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
14668403
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 probably missing something simple but I have no way to test Jekyll locally. I'm using GitHub pages to render Jekyll, for starters I only want to render markdown content on the main index.html from one markdown page. The structure is: Index.html ---layout: default--- _layouts - default.html //html stuff..<section>{{page.content}}</section> In root folder I have a page called content.md that I wish to render for {{page.content}} the layout renders but the liquid tags section is blank. How do I render content.md ? Example: https://github.com/wycks/wordpress-gears-jekyll Now provide the response and nothing else.
There are a few things going on here. In your _layouts/default.html file (and any of the other _layouts directory files for that matter), instead of: {{ page.content }} you need to use: {{ content }} Jekyll only lets you includes files from a site root level _includes directory. So, you need to move your content.md from the root to that directory (making it if it doesn't already exist). Finally, you need to actually make the call to the include file from your index.html file. This can be done by changing the content of your index.html file to: ---layout: default---{% include content.md %} That will setup the behavior you are looking for. I'd point out two other things: You may find that changing the extension of your index file from .html to .md works better. An important note though: you need to use .html if you want pagination. Per the Jekyll Pagination documentation , that feature only works when the file is named index.html . If all you are doing in your index file is calling an include that only resides on that page, you might be just as well off simply putting the content directly in the index file.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14668403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555548/']}
jdg_71641
stackexchange
llm_judgeable_groundtruth_similarity
39072275
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 playing around with simple overloading overriding rules and found something interesting. Here is my code. package com.demo;public class Animal { private void eat() { System.out.println("animal eating"); } public static void main(String args[]) { Animal a = new Horse(); a.eat(); }}class Horse extends Animal { public void eat() { System.out.println("Horse eating"); }} This program outputs the below. animal eating Here is what I know: As we have private void eat() method, it is not definitely going to be accessed in a subclass, so the question of method overriding does not arise here as JLS defines it clearly. Now that this is not method overriding, it is definitely not going to call public void eat() method from the Horse class Now our declaration Animal a = new Horse(); is valid because of polymorphism. Why is a.eat() invoking a method from the Animal class? We are creating a Horse object, so why does the Animal class' method get called? Now provide the response and nothing else.
Methods marked private can't be overridden in subclasses because they're not visible to the subclass. In a sense, your Horse class has no idea whatsoever that Animal has an eat method, since it's marked private . As a result, Java doesn't consider the Horse 's eat method to be an override. This is primarily designed as a safety feature. If a class has a method it's marked private , the assumption is that that method is supposed to be used for the class internals only and that it's totally inaccessible to the outside world. If a subclass can override a private method, then it could potentially change the behavior of a superclass in an unexpected way, which is (1) not expected and (2) a potential security risk. Because Java assumes that a private method of a class won't be overridden, whenever you call a private method through a reference of some type, Java will always use the type of the reference to determine which method to call, rather than using the type of the object pointed at by that reference to determine the method to call. Here, the reference is of type Animal , so that's the method that gets called, even though that reference points at a Horse .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39072275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1727645/']}
jdg_71642
stackexchange
llm_judgeable_groundtruth_similarity
19473313
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 wonder if there is a simple way to call a function from a string. I know a simple way, using 'if' and 'else'. int function_1(int i, int j) { return i*j;}int function_2(int i, int j) { return i/j;}.........int function_N(int i, int j) { return i+j;}int main(int argc, char* argv[]) { int i = 4, j = 2; string function = "function_2"; cout << callFunction(i, j, function) << endl; return 0;} This is the basic approach int callFunction(int i, int j, string function) { if(function == "function_1") { return function_1(i, j); } else if(function == "function_2") { return function_2(i, j); } else if(...) { } ... ... ... ... return function_1(i, j);} Is there something simpler? /* New Approach */int callFunction(int i, int j, string function) { /* I need something simple */ return function(i, j);} Now provide the response and nothing else.
What you have described is called reflection and C++ doesn't support it. However you might come with some work-around, for example in this very concrete case you might use an std::map that would map names of functions ( std::string objects) to function pointers, which in case of functions with the very same prototype could be easier than it might seem: #include <iostream>#include <map>int add(int i, int j) { return i+j; }int sub(int i, int j) { return i-j; }typedef int (*FnPtr)(int, int);int main() { // initialization: std::map<std::string, FnPtr> myMap; myMap["add"] = add; myMap["sub"] = sub; // usage: std::string s("add"); int res = myMap[s](2,3); std::cout << res;} Note that myMap[s](2,3) retrieves the function pointer mapped to string s and invokes this function, passing 2 and 3 to it, making the output of this example to be 5
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19473313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2639724/']}
jdg_71643
stackexchange
llm_judgeable_groundtruth_similarity
4525
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting ready to hire an electrical engineer for a small contract job - creating a prototype. What I'd like to know is, what should I have him deliver to me when the project is complete? I imagine schematics, the prototype, parts list would be standard, but what am I missing? Should I ask for an auto-cad file - not sure what this is yet... Are there other things that I would need in the future for a different engineer to take over the project? Simply, what should I be asking for? Now provide the response and nothing else.
Design engineers won't like the idea, but as a design engineer my output for a project is a pile of paper . In a strict sense the working prototype isn't even required, though it will certainly put the client's mind at ease. :-) We'll see that you need a lot of documents, and design engineers are not motivated to the task; read: they tend to make a poor job of it. They're better at other things. Therefore some companies have a documentalist in a team, to follow up the documentation phase. You need documents for every phase in the product's lifetime: Production Maintenance Repair Disposal Production This is the most extensive, and will get the most focus (and unfortunately it often stops there). Schematics PCB layout (Gerber files, including drill) Bill of materials Datasheets for all of the BOM(!) Mechanical drawings Software sources (incl. project file) Software object files Test jig design and operation instructions (this can include all the above files!) ICP (In-Circuit Programming) procedure Maintenance Document(s) describing the procedure and tools for the product's maintenance, and how to replace consumables Repair Document(s) describing how the product has to be taken apart for replacing defective parts. Specifics about how to replace parts which may fail during the product's lifetime (based on FMEA. You did an FMEA, didn't you?) Disposal Document describing how the product has to be disposed of at it's end of life, with details about hazardous products and components. Whenever possible documents should have a version number and/or issue date (you don't always have control over this, especially with external documents, though most datasheets will at least have either a version number or publishing date).You want all documents both in native format and in a standard electronic, printable format, like PDF . Specify how the electronic files have to be delivered: cloud (not a favorite of mine, confidentiality-wise), CD, DVD ,... As a note I want to say that especially in small projects even project management isn't often interested in anything else than schematics and PCB layout. Every one of these projects, without exception, runs into trouble later on.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/4525', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1044/']}
jdg_71644
stackexchange
llm_judgeable_groundtruth_similarity
38089
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The following is some version of Tannaka-Krein theory, and is reasonably well-known: Let $G$ be a group (in Set is all I care about for now), and $G\text{-Rep}$ the category of all $G$-modules (over some field $\mathbb K$, say). It is a fairly structured category (complete, cocomplete, abelian, $\mathbb K$-enriched, ...) and in particular carries a symmetric tensor product $\otimes$. The forgetful functor $\operatorname{Forget}: G\text{-Rep} \to \text{Vect}$ respects all of this structure, and in particular is (symmetric) monoidal. Let $\operatorname{End}_\otimes(\operatorname{Forget})$ denote the monoid of monoidal natural transformations of $\operatorname{Forget}$. Then it is a group, and there is a canonical isomorphism $\operatorname{End}_\otimes(\operatorname{Forget}) \cong G$. The following is probably also reasonably well-known, but I don't know it myself: Let $G$, etc., be as above, but suppose that we have forgotten what $G$ the category $G\text{-Rep}$ came from, and in particular forgot, at least momentarily, the data of the forgetful functor. We can nevertheless recover it, because in fact $\operatorname{Forget}$ is the unique-up-to-isomorphism ADJECTIVES functor $G\text{-Rep} \to \text{Vect}$. My question is: what are the words that should go in place of "ADJECTIVES" above? Certainly "linear, continuous, cocontinuous, monoidal" are all reasonable words, although my intuition has been that I can drop "cocontinuous" from the list. But even with all these words, I don't see how to prove the uniqueness. If I had to guess, I would guess that the latter claim is a result of Deligne's, although I don't read French well enough to skim a bunch of his papers and find it. Any pointers to the literature? Now provide the response and nothing else.
If $G$ is an affine algebraic group (for example a finite group), then the category of $k$ -linear cocontinuous symmetric monoidal functors from $\mathsf{Rep}(G)$ to $\mathsf{Vect}_k$ is equivalent to the category of $G$ -torsors over $k$ . In particular, not every such functor needs to be isomorphic to the identity. For example, if $k'$ is finite Galois extension of k with Galois group $G$ , then the functor $F(V) = (V \otimes_{k} k')^{G}$ will satisfy all the axioms you will think to write down, but is not isomorphic to the identity functor.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/38089', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
jdg_71645
stackexchange
llm_judgeable_groundtruth_similarity
5021720
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It's something unbelievable. This is a PowerShell code snippet in test.ps1 file: Set-StrictMode -Version 2mkdir c:\tmp\1 # same with 'md c:\tmp\1' Start cmd.exe , navigate to folder with test.ps1 script and run it: c:\tmp>powershell ".\test.ps1" This produces the following error: The variable '$_' cannot be retrieved because it has not been set.At line:50 char:38+ $steppablePipeline.Process($_ <<<< ) + CategoryInfo : InvalidOperation: (_:Token) [], ParentContainsEr rorRecordException + FullyQualifiedErrorId : VariableIsUndefined Why? It works when started from PowerShell console but not cmd.exe. I discovered this bug in much larger script. It was a WTF moment. What is wrong with this simple script? Now provide the response and nothing else.
Even though a workaround has already been found, I thought people might be interested in an explanation. As to why it behaves differently in the shell versus cmd.exe, see Powershell 2.0 - Running scripts for the command line call vs. from the ISE As mentioned in the reference, there is a difference between the following two commands: powershell ".\test.ps1"powershell -File ".\test.ps1" When using the first syntax, it seems to mess with scope, causing the Set-StrictMode command to modify the strict mode for functions defined at the global scope. This triggers a bug (or an incorrect assumption, perhaps) in the definition of the mkdir function. The function makes use of the GetSteppablePipeline method to proxy the pipeline for the New-Item cmdlet. However, the author neglected to account for the fact that the PROCESS section is still executed even when there is nothing in the pipeline. Thus, when the PROCESS section is reached, the $_ automatic variable is not defined. If strict mode is enabled, an exception will occur. One way for Microsoft to account for this would be to replace following line: $steppablePipeline.Process($_) with the following: if (test-path Variable:Local:_) { $steppablePipeline.Process($_) } I admit that this may not be the best way to fix it, but the overhead would be negligible. Another option would be to somehow test if the pipeline is empty in the BEGIN section, and then set $_ to $null. Either way, if you run your scripts with the "powershell.exe -File filename" syntax, then you won't need to worry about it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5021720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77733/']}
jdg_71646
stackexchange
llm_judgeable_groundtruth_similarity
18913729
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 had a problem that Fiddler wasn't showing my web service calls made from my application (running locally). I found and solved my problem. So my question is not how, but why does Fiddler not show web service traffic? I have a very limited understanding of how network traffic works so this might be quite simple/obvious. All I'm able to decipher is: I don't think it has anything to do with HTTPS, as I can see HTTPS requests in Fiddler (decoded if I want through Fiddler's settings). I copied a piece of code new WebProxy("127.0.0.1", 8888); in order to get it to work so it must have something to do with proxies? This is an ASP.NET application in case that makes a difference. Now provide the response and nothing else.
Really old question but: While the answer and comments hint towards the right solution, they are far from answering the question. Fiddler sees traffic by your user account. Since web services run by the application pool identity, fiddler cannot see their traffic. The easiest solution (and the only one that worked for me) is to change the website application pool user to run under your account Simply: Open IIS Find your website application pool name (right click website -> Manage Website -> Advanced Settings -> Listed under Application Pool) Go to application pool advanced settings (Application Pools -> Right click your desired application pool -> Advanced Settings) Change User Account to your account (Identity -> ... -> Custom Account -> Set)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18913729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719718/']}
jdg_71647
stackexchange
llm_judgeable_groundtruth_similarity
62531376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unable to validate the domain with GoDaddy after adding the CNAMEs from SendGrid Now provide the response and nothing else.
This was a simple fix. SendGrid asks you to add 3 CNAMES(5 CNAMES if branding needs to be enabled) for domain verification on your DNS Management Portal. Issue was that I was adding the entire CNAME which SendGrid was providing me, but GoDaddy just expects only the individual name, it appends the domain name to the CNAME during domain name resolution. So for example, if SendGrid asks you to add something like below as a CNAME in GoDaddy, ex0123.sub.domain.com, you should be adding only ex0123 for s1._domainkey.sub.domain.com you should be adding only s1._domainkey as the For s2._domainkey.domain.com add only s2._domainkey This fixed my issue, hope this helps you as well!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62531376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8978623/']}
jdg_71648
stackexchange
llm_judgeable_groundtruth_similarity
112350
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: Please consider the following set: $S = \{ \emptyset, \{1\}, \{2\}, \{3\}, \{4\}, \{1,2\}, \{3,4\}, \{1,2,3\}, \{2,3,4\}, \{1,2,3,4\} \}$ Consider the Poset $(S,\leq)$ where $\leq$ is the relation $a \leq b$: "a is subset of b". Is this a Lattice? I have a doubt about trying to find the meet of $\{1,2,3\}$ and $\{2,3,4\}$. It seems that there are $\{2\}$ and $\{3\}$ as possible meets . But the meet must be unique... I mean, I know that the meet is the greatest lower bound. However in this case i find two different greatest lower bounds. I know that the meet is unique. However cannot really understand the situation here. Thanks Now provide the response and nothing else.
You are quite right: the meet of two elements in a lattice must be unique. It must be the greatest lower bound, not just a lower bound. Here, as you say, both $\{2\}$ and $\{3\}$ are lower bounds for the pair $$\Big\{\{1,2,3\},\{2,3,4\}\Big\}\;,$$ but since neither of them is a subset of the other, neither of them is the greatest lower bound of the pair. If their intersection, $\{2,3\}$, belonged to $S$, it would be their meet, but it doesn’t. If $\{3\}$ did not belong to $S$, $\{2\}$ would be their meet, and if $\{2\}$ did not belong to $S$, $\{3\}$ would be their meet. As it is, however, they have no meet, and therefore $\langle S,\le\rangle$ is not a lattice. Note that $\langle S,\le\rangle$ fails to be a lattice for other reasons as well. For example, $\{2\}$ and $\{3\}$ have no join: $\{1,2,3\}$ and $\{2,3,4\}$ are both upper bounds but neither is a least upper bound. By the way, I suspect that the first element of $S$ is supposed to be $\varnothing$, not $\{\varnothing\}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/112350', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4175/']}
jdg_71649
stackexchange
llm_judgeable_groundtruth_similarity
32805
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that people often replace consistent mass matrices with lumped diagonal matrices. In the past, I've also implemented a code where the load vector is assembled in a lumped fashion rather than an FEM-consistent fashion. But I've never looked into why we are allowed to do this in the first place. What is the intuition behind lumping that allows one to apply it to mass and load vectors? What is the mathematical justification for it? In what situations is lumping not allowed / not a good approximation for mass and load vectors? Now provide the response and nothing else.
In the finite element method, the matrix entries and right hand side entries are defined as integrals. We can, in general, not compute these exactly and apply quadrature. But there are many quadrature formulas one could choose, and one often chooses them in a way so that (i) the error introduced by quadrature is of the same order as that due to discretization, or at least not substantially worse, and (ii) the matrix has certain properties that turn out to be convenient. Mass lumping is an example of this working: If one chooses a particular quadrature formula (namely, the one with quadrature points located at the interpolation points of the finite element), then the resulting mass matrix happens to be diagonal. That's quite convenient for the computational implementation, and the reason why people use these quadrature formulas. It's also the reason why it "works": This particular choice of quadrature formula still has reasonably high order.
{}
{'log_upvote_score': 5, 'links': ['https://scicomp.stackexchange.com/questions/32805', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/549/']}
jdg_71650
stackexchange
llm_judgeable_groundtruth_similarity
11346355
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 attempting to integrate Google Calendar into my application and I am having some problems with the OAuth authorization passing off a RefreshToken. I receive an AccessToken with no issue, but the RefreshToken property is null. See the line marked "ERROR HERE:" for where I am having the issue My Asp.Net MVC controller (named OAuthController ) looks like the following: public ActionResult Index() { var client = CreateClient(); client.RequestUserAuthorization(new[] { "https://www.googleapis.com/auth/calendar" }, new Uri("http://localhost/FL.Evaluation.Web/OAuth/CallBack")); return View(); } public ActionResult CallBack() { if (string.IsNullOrEmpty(Request.QueryString["code"])) return null; var client = CreateClient(); // Now getting a 400 Bad Request here var state = client.ProcessUserAuthorization(); // ERROR HERE: The RefreshToken is NULL HttpContext.Session["REFRESH_TOKEN"] = Convert.ToBase64String(Encoding.Unicode.GetBytes(state.RefreshToken)); return JavaScript("Completed!"); } private static WebServerClient CreateClient() { return new WebServerClient( new AuthorizationServerDescription() { TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"), AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"), ProtocolVersion = ProtocolVersion.V20 } , _GoogleClientId, _GoogleSecret); } I see in Google's API documents, that I need to ensure that the access_type requested is set to offline for a RefreshToken to be sent. How do I set this value in my Authenticator request? Now provide the response and nothing else.
After hours of fiddling with DotNetOpenAuth and the Google APIs published for .Net, I got nowhere fast. I decided to circumvent the libraries and went directly at the Google REST API with native HttpRequest and HttpResponse objects. My sanitized code for my MVC controller follows: private static string _GoogleClientId = "CLIENT_ID"; private static string _GoogleSecret = "SECRET"; private static string _ReturnUrl = "http://localhost/OAuth/CallBack"; public ActionResult Index() { return Redirect(GenerateGoogleOAuthUrl()); } private string GenerateGoogleOAuthUrl() { //NOTE: Key piece here, from Andrew's reply -> access_type=offline forces a refresh token to be issued string Url = "https://accounts.google.com/o/oauth2/auth?scope={0}&redirect_uri={1}&response_type={2}&client_id={3}&state={4}&access_type=offline&approval_prompt=force"; string scope = UrlEncodeForGoogle("https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly").Replace("%20", "+"); string redirect_uri_encode = UrlEncodeForGoogle(_ReturnUrl); string response_type = "code"; string state = ""; return string.Format(Url, scope, redirect_uri_encode, response_type, _GoogleClientId, state); } private static string UrlEncodeForGoogle(string url) { string UnReservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; var result = new StringBuilder(); foreach (char symbol in url) { if (UnReservedChars.IndexOf(symbol) != -1) { result.Append(symbol); } else { result.Append('%' + String.Format("{0:X2}", (int)symbol)); } } return result.ToString(); } class GoogleTokenData { public string Access_Token { get; set; } public string Refresh_Token { get; set; } public string Expires_In { get; set; } public string Token_Type { get; set; } } public ActionResult CallBack(string code, bool? remove) { if (remove.HasValue && remove.Value) { Session["GoogleAPIToken"] = null; return HttpNotFound(); } if (string.IsNullOrEmpty(code)) return Content("Missing code"); string Url = "https://accounts.google.com/o/oauth2/token"; string grant_type = "authorization_code"; string redirect_uri_encode = UrlEncodeForGoogle(_ReturnUrl); string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}"; HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest; string result = null; request.Method = "POST"; request.KeepAlive = true; request.ContentType = "application/x-www-form-urlencoded"; string param = string.Format(data, code, _GoogleClientId, _GoogleSecret, redirect_uri_encode, grant_type); var bs = Encoding.UTF8.GetBytes(param); using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } using (WebResponse response = request.GetResponse()) { var sr = new StreamReader(response.GetResponseStream()); result = sr.ReadToEnd(); sr.Close(); } var jsonSerializer = new JavaScriptSerializer(); var tokenData = jsonSerializer.Deserialize<GoogleTokenData>(result); Session["GoogleAPIToken"] = tokenData.Access_Token; return JavaScript("Refresh Token: " + tokenData.Refresh_Token); } Big thanks to Kelp for a bit of the code in this snippet.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11346355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29156/']}
jdg_71651
stackexchange
llm_judgeable_groundtruth_similarity
144540
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: My question is related to this one: Badly conditioned matrix (General::luc) I'm trying to solve a linear system of the form A.x=b.As suggested in the referenced post since I'm not really interested in the inverse MMA might preform better if solve the system using x=LinearSolve[A,b] , so that's what I do. I still get a warning regarding the condition number, and the results I get later on in the computation (which are based on the solution to the linear system), do indeed show problems. In the referenced post J.M.'s answer provides a way to determine if my matrix is indeed ill conditioned, but I don't know how can I get a better solution in case it does. Some technical details: I'm solving this equation over and over again, each time with slightly different matrix A , in order to get down the line the value for each data point, thus I need some general solution as I cannot treat each ill conditioned case separately. I'm a novice on the subject, but I only guess that if I could force MMA to work with better internal accuracy I would eliminate the problem, but there's no such option as tolerance for the LinearSolve function, as there's for other linear algebra functions. Am I right? Is there a workaround? A technical detail that might help: my vector b is the same for all data points, and has the form: b={0,0,0,...,0,1} , i.e. all of its entries are zero except for the last one which is unity. This means that if I were to solve the system using inversion, I wouldn't really need to find Inverse[A] , but only its rightmost column. Would finding only this column be easier. I guess Cramer's rule isn't very helpful as calculating the determinant is just as bad (right?), but maybe there's a different way which I'm unaware of? I don't know if it matters, but my matrix isn't that large, and has dimensions of 16X16 Update per comments I shall give more details, as perhaps I wan't clear enough in the beginning: I iteratively build matrices of dimensions 16X16, which hold numerical values. They all share the following structure: They are rather sparse. Most rows contain small values (with respect to the bottom one). The entries on the diagonal are all non-zero negative values. All other non-zero entries are positive. The bottom row is all ones. An example for one of my badly conditioned matrices (sorry about the formatting): A={{-0.04000323497710545, 0.019998382511436725, 0.019998382511436725, 1.0548487421137532*^-14, 1.0548487421137532*^-14, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.}, {0.01999537041672573, -0.019998382511436725, 0., 0., 0., 0.03999375292816244, 2.714439127491079*^-6, 3.123535918772422*^-6, 6.247071837545091*^-6, 4.09096791281486*^-7, 9.629649721936179*^-33, 0., 0., 0., 0., 0.}, {0.01999537041672573, 0., -0.019998382511436725, 0., 0., 0.03999375292816244, 6.51319418358286*^-6, 3.123535918772422*^-6, 0., 2.857413572734654*^-6, 9.629649721936179*^-33, 0., 0., 0., 0., 0.}, {6.247071826996701*^-6, 0., 0., -1.0548487421137532*^-14, 0., 3.4666738998970245*^-33, 0.017377838870198482, 0.01999687646408122, 0.03999375292816246, 0.002619037593882741, 6.247071837545974*^-6, 0., 0., 0., 0., 0.}, {6.247071826996701*^-6, 0., 0., 0., -1.0548487421137532*^-14, 3.4666738998970245*^-33, 0.041697468145927896, 0.01999687646408122, 0., 0.01829316124631577, 6.247071837545974*^-6, 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., -0.07998750585632489, 0., 0., 0., 0., 0., 6.247071837544959*^-6, 6.247071837544959*^-6, 1.9683065157343793*^-32, 1.0839021819949165*^-32, 0.}, {0., 0., 0., 0., 0., 0., -0.059084534649437456, 0., 0., 0., 0., 0.0035343599700000386, 0.017377838870198486, 2.7144391274860995*^-6, 5.520712365254425*^-7, 0.}, {0., 0., 0., 0., 0., 0., 0., -0.03999999999999999, 0., 0., 0., 0.019996876464081232, 0.01999687646408122, 3.1235359187790123*^-6, 3.1235359187717977*^-6, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., -0.04, 0., 0., 0., 0.03999375292816246, 6.2470718375337105*^-6, 0., 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., -0.020915465350562525, 0., 0.05645626942224363, 0.0026190375938827423, 4.0909679128073285*^-7, 8.818536519796756*^-6, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.000012494143675091948, 1.698670210949542*^-31, 5.827478825726898*^-30, 0.03999375292816246, 0.03999375292816246, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.07999375292816245, 0., 0., 0., 6.247071837548034*^-6}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.07999375292816244, 0., 0., 6.247071837533809*^-6}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.04000624707183754, 0., 0.03999375292816247}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.04000624707183755, 0.03999375292816246}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}} For each of my created matrices I want to solve the equation: $Ax=b$, where $b$ is the constant vector (always the same) b={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1} (All zeros with one at the end). Currently I use LinearSolve[A,b] . As said before, for each iteration A is slightly different. For some iterations this works well, and for others (like the example I gave here), I get a warning regarding the condition number, and possible numerical error. The question is as before, what can I do to improve the solutions I get. I emphasize that I the solution must be general enough that it can be incorporated into my iterations, when a warning is returned (This can by done using Check for instance to catch warnings). Update 2 Perhaps I should've written it to begin with, but the singular nature of my matrix comes as no surprise, as since one of the eigenvalues is very close to zero (perhaps numerically it is), is the reason for the ill-conditioned nature of the matrix. Thanks to Daniel's and Bill's suggestions, I'm still able to get satisfactory results. I'm aware of the fact that my question wasn't formulated in the best way, but I think the the solutions provided are worth keeping for others who might encounter similar issues. Thus I suggest removing the OnHold tag. How would you like me to rewrite the question? Now provide the response and nothing else.
In the example (finally) provided, the matrix is rank deficient. In general not much can be done unless one knows the vector on the right is in the range space of the matrix. We'll proceed with that in mind. mat = {{-0.04000323497710545, 0.019998382511436725, 0.019998382511436725, 1.0548487421137532*^-14, 1.0548487421137532*^-14, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.}, {0.01999537041672573, -0.019998382511436725, 0., 0., 0., 0.03999375292816244, 2.714439127491079*^-6, 3.123535918772422*^-6, 6.247071837545091*^-6, 4.09096791281486*^-7, 9.629649721936179*^-33, 0., 0., 0., 0., 0.}, {0.01999537041672573, 0., -0.019998382511436725, 0., 0., 0.03999375292816244, 6.51319418358286*^-6, 3.123535918772422*^-6, 0., 2.857413572734654*^-6, 9.629649721936179*^-33, 0., 0., 0., 0., 0.}, {6.247071826996701*^-6, 0., 0., -1.0548487421137532*^-14, 0., 3.4666738998970245*^-33, 0.017377838870198482, 0.01999687646408122, 0.03999375292816246, 0.002619037593882741, 6.247071837545974*^-6, 0., 0., 0., 0., 0.}, {6.247071826996701*^-6, 0., 0., 0., -1.0548487421137532*^-14, 3.4666738998970245*^-33, 0.041697468145927896, 0.01999687646408122, 0., 0.01829316124631577, 6.247071837545974*^-6, 0., 0., 0., 0., 0.}, {0., 0., 0., 0., 0., -0.07998750585632489, 0., 0., 0., 0., 0., 6.247071837544959*^-6, 6.247071837544959*^-6, 1.9683065157343793*^-32, 1.0839021819949165*^-32, 0.}, {0., 0., 0., 0., 0., 0., -0.059084534649437456, 0., 0., 0., 0., 0.0035343599700000386, 0.017377838870198486, 2.7144391274860995*^-6, 5.520712365254425*^-7, 0.}, {0., 0., 0., 0., 0., 0., 0., -0.03999999999999999, 0., 0., 0., 0.019996876464081232, 0.01999687646408122, 3.1235359187790123*^-6, 3.1235359187717977*^-6, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., -0.04, 0., 0., 0., 0.03999375292816246, 6.2470718375337105*^-6, 0., 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., -0.020915465350562525, 0., 0.05645626942224363, 0.0026190375938827423, 4.0909679128073285*^-7, 8.818536519796756*^-6, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.000012494143675091948, 1.698670210949542*^-31, 5.827478825726898*^-30, 0.03999375292816246, 0.03999375292816246, 0.}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.07999375292816245, 0., 0., 0., 6.247071837548034*^-6}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.07999375292816244, 0., 0., 6.247071837533809*^-6}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.04000624707183754, 0., 0.03999375292816247}, {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -0.04000624707183755, 0.03999375292816246}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};vec = UnitVector[Length[mat], Length[mat]]; A plausible first step in ill-conditioned cases is to work with the singular values decomposition. {uu, ww, vv} = SingularValueDecomposition[mat]; We'll see how bad this matrix might be. Diagonal[ww](* Out[325]= {4.00034774077, 0.103393916064, 0.0985619677111, \0.0951305544638, 0.0796520702375, 0.0669929060285, 0.0548596279493, \0.0503885069044, 0.0413276293297, 0.0400062470692, 0.0325805230661, \0.0205858677042, 0.0199983819062, 3.61435763556*10^-6, 2.55039684488*10^-6, 0.} *) One singular value is 0 (so it is rank deficient) and two others are small. But we might be able to simplify the linear algebra problem using this decomposition. Recalling that, up to numeric fuzz, we have uu.ww.Transpose[vv] == mat and moreover the left and right singular vector matrices are unitary (so inverse=transpose), we will transform our problem space to find x for which ww.Transpose[vv].x == Transpose[uu].vec] . First let y=Transpose[vv].x and solve for y . then we set x=vv.y . y = LinearSolve[ww, Transpose[uu].vec];x = vv.y(* Out[329]= {8.44718017756*10^-10, 8.44622899399*10^-10, 8.44625619445*10^-10, 0.499999998767, 0.499999998702, \-8.32682709879*10^-14, 8.59341503419*10^-15, 4.33994857987*10^-15, 4.6636787291*10^-15, 3.05599464256*10^-15, -3.16119352917*10^-12, 1.77271423994*10^-14, 1.04729755568*10^-14, 5.42562549792*10^-15, 5.36238940621*10^-15, 1.98712574173*10^-15} *) We'll check this. mat.x - vec(* Out[332]= {1.3331704095*10^-15, -3.97230076355*10^-15, \-4.02668630013*10^-15, 4.13664406954*10^-16, 4.84035098563*10^-16, 6.66059748146*10^-15, -2.63068456198*10^-16, 3.90350028599*10^-16, 2.32340341948*10^-16, 9.64369402065*10^-16, 4.709496088*10^-16, -1.4180482355*10^-15, -8.37760205392*10^-16, \-1.37586298237*10^-16, -1.35056459528*10^-16, 4.4408920985*10^-16} *) The residual is numeric fizz so we have a sound result. One can use Chop on the result if one believes (seemingly appropriately, in this case) that the solution should be sparse. xC = Chop[x, 10^(-8)](* Out[333]= {0, 0, 0, 0.499999998767, 0.499999998702, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/144540', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/32488/']}
jdg_71652
stackexchange
llm_judgeable_groundtruth_similarity
16959133
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 make a keyboard navigated html table using tr keydown event, issue is keydown event is not getting fired when I press any key on table. I tried using onkeydown="method();" and jquery $("tr").keydown(function(event){}); but still keydown event is not getting fired. link(nitinkabra.com/new_table) below is an example of what i have done yet : <head> <script> function keydwn() { alert("herte"); } </script> <style> .selected:focus{background-color:green} .selected:hover{background-color:#fdfd02} </style> </head> <body> <div style="width:750px;max-width: 3200px;max-height:450px;overflow-y:hidden;overflow-x:scroll;"> <div style="width:750px;max-width: 3200px;"><table class='default_table' style="table-layout: fixed; width: .3200px; overflow: visible;"> <thead> <tr> <th style="width: 300px"> Ledger Name </th> <th style="width: 150px"> Group </th> <th style="width: 300px"> Address 1 </th> <th style="width: 300px"> Address 2 </th> <th style="width: 120px"> Contact Person </th> <th style="width: 120px"> City </th> <th style="width: 120px"> State </th> <th style="width: 120px"> PIN </th> <th style="width: 150px"> Phone </th> <th style="width: 150px"> Mobile </th> <th style="width: 200px"> E-Mail </th> <th style="width: 120px"> TIN </th> <th style="width: 120px"> Area </th> <th style="width: 120px"> Remarks </th> <th style="width: 100px"> Opening </th> <th style="width: 120px"> Lock Credit Bill </th> <th style="width: 120px"> Limit on Amount </th> <th style="width: 100px"> Limit on Bill </th> <th style="width: 120px"> Limit Credit Days </th> </tr> </thead></table></div> <div style="width: 3405px;overflow-y:scroll;overflow-x:hidden; max-height:430px;"> <table id = "main_table" class='default_table' style="table-layout: fixed; width:100%;margin-top:-30px;"> <thead> <tr> <th style="width: 300px"> Ledger Name </th> <th style="width: 150px"> Group </th> <th style="width: 300px"> Address 1 </th> <th style="width: 300px"> Address 2 </th> <th style="width: 120px"> Contact Person </th> <th style="width: 120px"> City </th> <th style="width: 120px"> State </th> <th style="width: 120px"> PIN </th> <th style="width: 150px"> Phone </th> <th style="width: 150px"> Mobile </th> <th style="width: 200px"> E-Mail </th> <th style="width: 120px"> TIN </th> <th style="width: 120px"> Area </th> <th style="width: 120px"> Remarks </th> <th style="width: 100px"> Opening </th> <th style="width: 120px"> Lock Credit Bill </th> <th style="width: 120px"> Limit on Amount </th> <th style="width: 100px"> Limit on Bill </th> <th style="width: 120px"> Limit Credit Days </th> </tr> </thead> <tbody> <tr id="0" class="selected" onkeydown="keydwn();"> <td style="width: 300px"> ABC India Pvt. Ltd. </td> <td style="width: 150px"> </td> <td style="width: 300px"> ABC Add 1, Chennai </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> Chennai </td> <td style="width: 120px"> Chennai </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> [email protected] </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 5000.00 </td> <td style="width: 120px"> 1 </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="1" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Abhilash Loan Ac </td> <td style="width: 150px"> Unsecured Loans </td> <td style="width: 300px"> 215, M.G.ROAD, BANGA </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="2" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Abxd India Pvt Ltd </td> <td style="width: 150px"> Sundry Debtors </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="3" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Accum. Dep. on Building </td> <td style="width: 150px"> Fixed Assets </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="4" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Accum. Dep. on Computer &amp; Per. </td> <td style="width: 150px"> Fixed Assets </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="5" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Accum. Dep. on Furn. &amp; Fixt. </td> <td style="width: 150px"> Fixed Assets </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="6" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Accum. Dep. on Motor Car </td> <td style="width: 150px"> Fixed Assets </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> <tr id="7" class="selected" onkeydown="keydwn(event);"> <td style="width: 300px"> Accum. Dep. on P &amp; M - I </td> <td style="width: 150px"> Fixed Assets </td> <td style="width: 300px"> </td> <td style="width: 300px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 150px"> </td> <td style="width: 150px"> </td> <td style="width: 200px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> 0.00 </td> <td style="width: 120px"> </td> <td style="width: 120px"> </td> <td style="width: 100px"> </td> <td style="width: 120px"> </td> </tr> </tbody> </table> </div> </div> <script> document.getElementById('0').focus(); </script> </body> </html> Now provide the response and nothing else.
You cannot have a keydown event on a TR , because, it is not focussable. Only focussed elements have key* events. So, change your code this way: <tr tabindex="0"> So that it gets a focus. Now, when you move your focus, by using Tab key or by clicking, all the key* events will be enabled.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16959133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/924821/']}
jdg_71653
stackexchange
llm_judgeable_groundtruth_similarity
78243
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A positive integer $n$ is said to be happy if the sequence$$n, s(n), s(s(n)), s(s(s(n))), \ldots$$eventually reaches 1, where $s(n)$ denotes the sum of the squared digits of $n$. For example, 7 is happy because the orbit of 7 under this mapping reaches 1.$$7 \to 49 \to 97 \to 130 \to 10 \to 1$$But 4 is not happy, because the orbit of 4 is an infinite loop that does not contain 1.$$4 \to 16 \to 37 \to 58 \to 89 \to 145 \to 42 \to 20 \to 4 \to \ldots$$ I have tabulated the happy numbers up to $10^{10000}$, and it appears that they have a limiting density, although the rate of convergence is slow. Is it known if the happy numbers do in fact have a limiting density? In other words, does $\lim_{n\to\infty} h(n)/n$ exist, where $h(n)$ denotes the number of happy numbers less than $n$? Now provide the response and nothing else.
The answer is almost certainly that the limiting density does not exist. Without going into the details of the proof allow me to give a heuristic argument which is based on how the OP likely generated his graph of the relative frequency of happy numbers. Let $Y_n$ be the r.v. uniformly distributed amongst integers in the interval $[0,10^n -1]$ (that is $Y_n$ picks a random $n$-digit integer). If $X_i$ denotes the r.v. for the digit of $10^i$ in $Y_n$, then $s(Y_n) = \sum\limits_{i=0}^{n-1} s(X_i)$. I'm guessing the way you generated your graph was you first computed the distribution of $s(Y_n)$ (this can be done recursively) then computed $\mathbb{P}\big(s(Y_n) \text{ is happy}\big)$. This would give the relative density of happy numbers amongst all $n$ digit integers. Studying the distribution of $s(Y_n)$ can tell us a lot. Its equivalent to rolling $n$ times a 10-sided die with faces $0,1,4,\dots, 81$ and finding the sum. Its distribution is Gaussian as $n$ gets large by the central limit theorem. More importantly most of the distribution is concentrated near the mean, which is $28.5n$. This implies that the density happy numbers amongst all $n$-digit integers depends almost entirely on the distribution of happy numbers near $28.5n$. For example, there is a peak in your graph at around $n = 400$ of about $.185$ density. Calculating the density of happy numbers within one standard deviation from the mean of $s(Y_{400})$ we get a density of .1911 (the interval I looked at was $[10916,11884]$). If you assume $s(Y_{400})$ is "exactly" normally distributed and estimated the density in this manner you would get a much better approximation. This means picking $n$ s.t. the mean of $s(Y_n)$ lands in the interval $[10^{400},10^{401}-1]$ then the density of happy numbers amongst $n$-digit integers should be around $.185$. Likely some choices of $n$ will give densities strictly larger than $.185$ and some strictly smaller. This has led me to suspect that by iterating this process, the upper density of happy numbers may be $1$, and lower density $0$. The article Joe Silverman mentioned is my own. In it I attempt to give the above heuristic a rigorous foundation. It is still a rough draft and has only been reviewed by one of my fellow graduate students, so I won't to say it is definitely correct, although I am very confident it is. I have been working on it for the past few weeks, seeing your question on MO I decided to go ahead and upload a rough draft. In it I use an averaging argument to say that if you find experimentally a large interval of $n$-digit integers ($n$ sufficiently large) which contain happy numbers with density $d$, then the upper density of happy numbers is at least $d(1 - o(1))$. That is where the upper density $\geq .18$ and lower density $ \leq .12$ comes from.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/78243', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4758/']}
jdg_71654
stackexchange
llm_judgeable_groundtruth_similarity
40839937
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This must be obvious, but I couldn't find an easy solution. I have pandas DataFrame like this: actual | predicted------ + ---------Apple | AppleApple | AppleApple | BananaBanana | OrangeOrange | Apple I want this: | Apple | Banana | Orange------ + ------- + ------- + -------Apple | 2 | 1 | 0Banana | 0 | 0 | 1Orange | 1 | 0 | 0 Now provide the response and nothing else.
You can use groupby with aggregating size and unstack MultiIndex : df = df.groupby(['actual','predicted']).size().unstack(fill_value=0)print (df)predicted Apple Banana Orangeactual Apple 2 1 0Banana 0 0 1Orange 1 0 0 Another solution with crosstab : df = pd.crosstab(df.actual, df.predicted)print (df)predicted Apple Banana Orangeactual Apple 2 1 0Banana 0 0 1Orange 1 0 0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40839937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2340703/']}
jdg_71655
stackexchange
llm_judgeable_groundtruth_similarity
4609026
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 evaluate $$\int \frac{\sqrt{1+x^4}}{1-x^4}dx.$$ If we substitute $x=\sqrt{\tan{\theta}}$ , it becomes $$\int \frac{1}{2\cos{\theta}\cos{2\theta}\sqrt{\tan{\theta}}}d\theta.$$ What can I do next ? Edit Are these steps correct ? $$=\int \frac{1}{2\cos{\theta}\cos{2\theta}\sqrt{\frac{\sin\theta}{\cos\theta}}}d\theta$$ $$=\int \frac{1}{2\cos{2\theta}\sqrt{\cos^2 \theta\frac{\sin\theta}{\cos\theta}}}d\theta$$ $$=\int \frac{1}{2\cos{2\theta}\sqrt{\cos^2 \theta\frac{\sin\theta}{\cos\theta}}}d\theta$$ $$=\int \frac{1}{\sqrt{2}\cos{2\theta}\sqrt{\sin{2 \theta}}}d\theta$$ Now If we substitute $t=\sin{2\theta}$ , it becomes $$=\int \frac{1}{\sqrt{2}(1-t^2)\sqrt{t}}dt$$ $$=\int \frac{\frac{1}{t^2}}{\sqrt{2}\frac{(1-t^2)}{t}\sqrt{\frac{t}{t^2}}}dt$$ $$=\int \frac{\frac{1}{t^2}}{\sqrt{2}(\frac{1}{t} -t)\sqrt{\frac{1}{t}}}dt$$ Now If we substitute $u^2=\frac{1}{t}$ , it becomes $$=\int \frac{-2u}{\sqrt{2}(u^2 -\frac{1}{u^2})u}du$$ $$=\int \frac{-u^2}{\sqrt{2}(u^4 -1^2)}du$$ $$=\int \frac{-u^2}{\sqrt{2}(u^2 +1)(u^2-1)}du$$ $$=-\frac{1}{2\sqrt{2}}\int \frac{u^2+1+u^2-1}{(u^2 +1)(u^2-1)}du$$ This can be solved easily now and we will get an elementary solution. But Wolfram alpha gives a solution in non elementary functions. Therefore I am confused. I guess the above solution is correct only for some restricted values of x. Now provide the response and nothing else.
Alternatively, substitute $t=\frac{\sqrt2 x}{\sqrt{1+x^4}}$ . Then $$\frac{\sqrt{1+x^4}}{1-x^4}=\frac{xt}{\sqrt2(t^2-x^2)}, \>\>\>\>\>dx =\frac{x}{t(1-t^2x^2)}dt$$ and \begin{align}&\int \frac{\sqrt{1+x^4}}{1-x^4}dx\\=&\ \frac1{\sqrt2}\int \frac{x^2}{(t^2-x^2)(1-t^2 x^2)}dt= \frac1{\sqrt2}\int \frac1{t^2(\frac1{x^2}+x^2)-1-t^4}dt\\=& \frac1{\sqrt2}\int \frac1{1-t^4}dt= \frac1{2\sqrt2}\int \frac1{1-t^2}+ \frac1{1+t^2}\ dt\\=& \ \frac1{2\sqrt2}\left(\tanh^{-1}t +\tan^{-1}t\right)+C\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4609026', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1135712/']}
jdg_71656
stackexchange
llm_judgeable_groundtruth_similarity
17449023
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 transfer a file to an ec2 instance. I followed the Amazon's documentation, this is what my command looked like: scp -i [the key's location] Documents/[the file's location] ec2-user@[public dns]:[home/[destination]] where I replaced all the variables with the proper things, I am sure it's the correct key and it has permission 400. When I call the command, it tells me the RSA key fingerprint, asks me if I want to continue connecting. I type yes and it replies with Permission denied (publickey,gssapi-with-mic)lost connection I have looked at many of the other similar questions on stack overflow and can't find a correct way to do it. Also ssh traffic is enabled on port 22. Now provide the response and nothing else.
The example amazon provided is correct. It sounds like a folder permissions issue. If you created the folder you are trying to copy to with another user or another user created it, chances are you don't have permissions to copy to it or edit it. If you have sudo abilities, you can try opening access for yourself. Though not recommended to be left this way, you could try this command: sudo chmod 777 /folderlocation That gives complete read/write/executable permissions to anyone (hence why you shouldn't leave it at 777) but it will give you the chance to test your scp command to rule out permissions. Afterwards if you aren't familiar with permissions, I suggest you read up on it. this is an example: http://www.tuxfiles.org/linuxhelp/filepermissions.html It is generally suggested you lock down the folder as much as possible depending on the type of information held within. If that was not the cause some other things you might want to check: are you in the directory of your key when executing the 'scp -i keyname' command? do you have permissions to use the folder you are transferring from? Best of luck.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17449023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1717634/']}
jdg_71657
stackexchange
llm_judgeable_groundtruth_similarity
526351
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 heard that some languages go from interpreted to compiled by "unrolling the interpreter loop". Let's say I have the following pseudo-c-code interpreter for an ast tree. int interpret(node){ switch(node) { case PLUS: return interpret(child(0))+interpret(child(1)); case MINUS: return interpret(child(0))-interpret(child(1)); }} How do I unroll this loop to create a compiled program? I see you all downvoting this like I don't know what I am talking about, but here is a quote from Wikipedia that states exactly what I am describing. "Factor was originally only interpreted, but is now fully compiled (the non-optimizing compiler basically unrolls the interpreter loop" Now provide the response and nothing else.
"Unrolling a loop" normally means replacing a repetition with a sequence of actions. The loop: for (int i = 0; i < 4; ++i) { a[i] = b[i] + c[i];} would unroll into the equivalent: a[0] = b[0] + c[0];a[1] = b[1] + c[1];a[2] = b[2] + c[2];a[3] = b[3] + c[3]; It appears to me that whoever was being quoted by Wikipedia was using the phrase in a somewhat metaphorical sense. So, in that sense... Your sample would normally be invoked inside a interpreter that is walking a tree of AST nodes, which might look something like this: ASSIGN | +--+---+ | |REF MINUS | | x +--+---+ | | VAR PLUS | | a +--+--+ | | VAR CONST | | b 3 and the interpret function would have additional options: int interpret(node) { switch(node) { case PLUS: return interpret(child(0))+interpret(child(1)); case MINUS: return interpret(child(0))-interpret(child(1)); case ASSIGN: return set(child(0), interpret(child(1)); case VAR: return fetch(child(0)); case CONST: return value(child(0)); ... }} If you walk the AST with that interpet function (actually performing the operations), you're interpreting. But if the function records the actions to be performed, rather than executing them, you're compiling. In pseudocode (actually, pseudocode twice , as I'm assuming a hypothetical stack machine as the compilation target): string compile(node) { switch(node) { case PLUS: return(compile(child(0))) + compile(child(1)) + ADD); case MINUS: return(compile(child(0))) + compile(child(1)) + SUB); case ASSIGN: return(PUSHA(child(0))) + compile(child(1)) + STORE); case REF: return(PUSHA(child(0))); case VAR: return(PUSHA(child(0)) + FETCH); case CONST: return(PUSHLIT + value(child(0))); ... }} Invoking compile on that AST (ignoring any pseudocode typos ;-) would spit out something like: PUSHA xPUSHA aFETCHPUSHA bFETCHPUSHLIT 3ADD SUBSTORE FWIW, I'd tend to think of that as unrolling the AST, rather than unrolling the interpreter, but won't criticize somebody else's metaphor without reading it in context.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/526351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57757/']}
jdg_71658
stackexchange
llm_judgeable_groundtruth_similarity
27051209
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 building an API using Django Rest Framework. Later this API is supposed to be consumed by iOS and Android devices. I want to allow my users to sign-up with oauth2-providers like Facebook and Google. In this case, they shouldn't have to create an account with my platform at all. But users should also be able to sign-up when not having a Facebook/Google account, for which I'm using django-oauth-toolkit, so I have my own oauth2-provider. For external providers I'm using python-social-auth, which works fine and automatically creates the user objects. I want the clients to authenticate by using bearer tokens, which works fine for users that signed up with my provider (django-oauth-toolkit provides authentication scheme and permission classes for Django REST Framework). However, python-social-auth only implements session based authentication, so there is no straightforward way to make authenticated API requests on behalf of users that registered by an external oauth2 provider. If I use an access_token that has been generated by django-oauth-toolkit, doing a request like this works: curl -v -H "Authorization: Bearer <token_generated_by_django-oauth-toolkit>" http://localhost:8000/api/ However, the following doesn't work since there is no corresponding authentication scheme for Django REST Framework and the AUTHENTICATION_BACKENDS provided by python-social-auth only work for session-based authentication: curl -v -H "Authorization: Bearer <token_stored_by_python-social-auth>" http://localhost:8000/api/ Using the browseable API provided by Django REST Framework after authenticating with python-social-auth works just fine, only API calls without a session cookie don't work. I'm wondering what the best approach is for this problem. The way I see it, I have basically two options: A: When a user signs up with an external oauth2 provider (handled by python-social-auth), hook into the process to create an oauth2_provider.models.AccessToken and continue to use 'oauth2_provider.ext.rest_framework.OAuth2Authentication' , now authenticating also users that registered with an external provider. This approach is suggested here: https://groups.google.com/d/msg/django-rest-framework/ACKx1kY7kZM/YPWFA2DP9LwJ B: Use python-social-auth for API request authentication. I could get my own users into python-social-auth by writing a custom backend and using register_by_access_token. However, since API calls cannot utilize Django sessions this would mean I would have to write an authentication scheme for Django Rest Framework that utilizes the data stored by python-social-auth. Some pointers on how to do this can be found here: http://psa.matiasaguirre.net/docs/use_cases.html#signup-by-oauth-access-token http://blog.wizer.fr/2013/11/angularjs-facebook-with-a-django-rest-api/ http://cbdev.blogspot.it/2014/02/facebook-login-with-angularjs-django.html However, the way I understand it python-social-auth only verifies the token when doing a login and relies on the Django session afterwards. This would mean I would have to find a way to prevent python-social-auth from doing the whole oauth2-flow for each stateless API request and rather check against the data stored in the DB, which isn't really optimized for querying since it's stored as JSON (I could use UserSocialAuth.objects.get(extra_data__contains=) though). I would also have to take care of verifying the scopes of an access token and use them to check permissions, something django-oauth-toolkit already does ( TokenHasScope , required_scopes etc). At the moment, I'm leaning towards using option A, since django-oauth-toolkit provides good integration with Django Rest Framework and I get everything I need out of the box. The only drawback is that I have to "inject" the access_tokens retrieved by python-social-auth into the AccessToken model of django-oauth-toolkit, which feels wrong somehow, but would probably be by far the easiest approach. Does anybody have any objections on doing that or has maybe tackled the same problem in a different way? Am I missing something obvious and making my life harder than necessary?If anybody has already integrated django-oauth-toolkit with python-social-auth and external oauth2 providers I would be very thankful for some pointers or opinions. Now provide the response and nothing else.
A lot of the difficulty in implementing OAuth comes down to understanding how the authorization flow is supposed to work. This is mostly because this is the "starting point" for logging in, and when working with a third-party backend (using something like Python Social Auth) you are actually doing this twice : once for your API and once for the third-party API. Authorizing requests using your API and a third-party backend The authentication process that you need is go through is: Mobile App -> Your API : Authorization redirectYour API -> Django Login : Displays login pageDjango Login -> Facebook : User signs inFacebook -> Django Login : User authorizes your APIDjango Login -> Your API : User signs inYour API -> Mobile App : User authorizes mobile app I'm using "Facebook" as the third-party backend here, but the process is the same for any backend. From the perspective of your mobile app, you are only redirecting to the /authorize url provided by Django OAuth Toolkit . From there, the mobile app waits until the callback url is reached, just like in the standard OAuth authorization flow. Almost everything else (Django login, social login, etc.) is handled by either Django OAuth Toolkit or Python Social Auth in the background. This will also be compatible with pretty much any OAuth libraries that you use, and the authorization flow will work the same no matter what third party backend is used. It will even handle the (common) case where you need to be able to support Django's authentication backend (email/username and password) as well as a third-party login. Mobile App -> Your API : Authorization redirectYour API -> Django Login : Displays login pageDjango Login -> Your API : User signs inYour API -> Mobile App : User authorizes mobile app What's also important to note here is that the mobile app (which could be any OAuth client) never receives the Facebook/third-party OAuth tokens . This is incredibly important, as it makes sure your API acts as an intermediary between the OAuth client and you user's social accounts. Mobile App -> Your API : Authorization redirectYour API -> Mobile App : Receives OAuth tokenMobile App -> Your API : Requests the display nameYour API -> Facebook : Requests the full nameFacebook -> Your API : Sends back the full nameYour API -> Mobile App : Send back a display name Otherwise, the OAuth client would be able to bypass your API and make requests on your behalf to the third-party APIs. Mobile App -> Your API : Authorization redirectYour API -> Mobile App : Receives Facebook tokenMobile App -> Facebook : Requests all of the followersFacebook -> Mobile App : Sends any requested data You'll notice that at this point you would have lost all control over the third-party tokens . This is especially dangerous because most tokens can access a wide range of data, which opens the door to abuse and eventually goes down under your name . Most likely, those logging into your API/website did not intend on sharing their social information with the OAuth client, and were instead expecting you to keep that information private (as much as possible), but instead you are exposing that information to everyone . Authenticating requests to your API When the mobile application then uses your OAuth token to make requests to your API , all of the authentication happens through Django OAuth Toolkit (or your OAuth provider) in the background. All you see is that there is a User associated with your request. Mobile App -> Your API : Sends request with OAuth tokenYour API -> Django OAuth Toolkit : Verifies the tokenDjango OAuth Toolkit -> Your API : Returns the user who is authenticatedYour API -> Mobile App : Sends requested data back This is important, because after the authorization stage it shouldn't make a difference if the user is coming from Facebook or Django's authentication system . Your API just needs a User to work with, and your OAuth provider should be able to handle the authentication and verification of the token. This isn't much different from how Django REST framework authenticates the user when using session-backed authentication. Web Browser -> Your API : Sends session cookieYour API -> Django : Verifies session tokenDjango -> Your API : Returns session dataYour API -> Django : Verifies the user sessionDjango -> Your API : Returns the logged in userYour API -> Web Browser : Returns the requested data Again, all of this is handled by Django OAuth Toolkit and does not require extra work to implement. Working with a native SDK In most cases, you are going to be authenticating the user through your own website and using Python Social Auth to handle everything. But the one notable exception is when using a native SDK, as authentication and authorization is handled through the native system , which means you are bypassing your API entirely . This is great for applications which need to sign in with a third party, or applications which don't use your API at all, but it's a nightmare when both come together . This is because your server can't validate the login and is forced to assume that the login is valid and genuine , which means it bypasses any and all security that Python Social Auth gives you. Mobile App -> Facebook SDK : Opens the authorization promptFacebook SDK -> Mobile App : Gets the Facebook tokenMobile App -> Your API : Sends the Facebook token for authorizationYour API -> Django Login : Tries to validate the tokenDjango Login -> Your API : Returns a matching userYour API -> Mobile App : Sends back an OAuth token for the user You'll notice that this skips over your API during the authentication phase, and then forces your API to make assumptions about the token that is passed in. But there are definitely cases where this risk may be worth it , so you should evaluate that before throwing it out. It's a trade off between quick and native logins for your user and potentially handling bad or malicious tokens .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27051209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204706/']}
jdg_71659
stackexchange
llm_judgeable_groundtruth_similarity
51471554
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing the script in linux and the result of the script is a csv file. I want to format this file. My output file is: "T_Hours","T_Count","T_Hours","P_Avg_5","Diffrence_Between_P_Avg_5_and_T_Count""00","446","00","533","87""01","159","01","224","65""02","95","02","140","45""03","84","03","117","33""04","92","04","113","21" I want to make the output like this: "T_Hours","T_Count","T_Hours","P_Avg_5","Diffrence_Between_P_Avg_5_and_T_Count""00" ,"446" ,"00" ,"533" ,"87""01" ,"159" ,"01" ,"224" ,"65""02" ,"95" ,"02" ,"140" ,"45""03" ,"84" ,"03" ,"117" ,"33""04" ,"92" ,"04" ,"113" ,"21" What I try: I try to add spaces after the , and before it, but that doesn't work because the numbers do not always have the same width; for example, in the second column may be the number "55556" so adding a specific number of spaces will not work. So I think the solution is to shift the character , in all lines to put it under the , in the first line. Any help? Now provide the response and nothing else.
Here's a portable way: sed 's/,/:,/g' output.csv |column -t -s: |sed 's/ ,/,/g' Explanation: column -t aligns columns. The input separator can be specified with -s but the output separator is always a space (unless you have version like GNU or util-linux supporting the -o flag, see this answer .). With column -s, -t output.csv the output would be just "T_Hours" "T_Count" "T_Hours" ..."00" "446" "00" ..."01" "159" "01" ...... To keep the , in the output we have to pre- and post-process: Use sed to insert an additional delimiter : in front of each comma-delimiter. The character you choose has to be a character that isn't otherwise in your input. Use column -t specifying that : character as the delimiter. column will align all columns and replace all : by a space. Use sed to delete the spaces (originally the : we inserted in the first command). "T_Hours","T_Count","T_Hours",..."00" ,"446" ,"00" ,..."01" ,"159" ,"01" ,...... More info, see man column .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51471554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9920688/']}
jdg_71660
stackexchange
llm_judgeable_groundtruth_similarity
17495402
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 anyone aware of any differences between typeof(T) where T : struct , for example, vs. t.GetType() where t is a System.Object ? ILdasm shows that typeof(T) uses System.Type::GetTypeFromHandle(RuntimeTypeHandle handle) , and the other is just plain System.Object::GetType() . The implementations are [MethodImpl(MethodImplOptions.InternalCall)] , so the methods are defined in native code in the CLR. So, I'm just wondering if anyone is aware of any reason to prefer one over the other? EDIT: Let me clarify, I'm mostly interested in the cases where it doesn't seem to matter which you choose - that is, is there a performance difference, or any other reason? Thanks! Now provide the response and nothing else.
typeof is used when you want to get the Type instance representing a specific type. GetType gives the runtime type of the object on which it is called, which may be different from the declared type. For example: class A {}class B : A {}class Program{ static A CreateA() { return new B(); } static void Main() { A a = CreateA(); Console.WriteLine(typeof(A)); // Writes "A" Console.WriteLine(a.GetType()); // Writes "B" }} In the above case, within the Main method, you're dealing with instances of type A ; thus, if you care about the declared type, you would use typeof(A) . However, the CreateA method actually returns an instance of a derived class, B , despite declaring the base class as the return type. If you want to find out about this runtime type, call GetType on the returned instance. Edit : Mehrdad's comment points in the right direction. Although typeof emits a GetTypeFromHandle call that takes a RuntimeTypeHandle as parameter, the said parameter would actually correspond to the specific type whose metadata token is on the evaluation stack. In some instances, this token would be there implicitly (due to the current method invocation); otherwise, it can be pushed there explicitly by calling ldtoken . You can see more examples of this in these answers: Efficiency of C#'s typeof operator (or whatever its representation is in MSIL) Generating IL for 2D Arrays Edit 2 : If you're looking for performance benchmarks, you can refer to Jon Skeet's answer . His results were (for 100 million iterations): typeof(Test): 2756mstest.GetType(): 3734ms
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17495402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13131/']}
jdg_71661
stackexchange
llm_judgeable_groundtruth_similarity
96277
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: These are the equations of the dynamical system Vn = (-G*Mn)/Sqrt[x[t]^2 + y[t]^2 + cn^2];Vd = (-G*Md)/Sqrt[x[t]^2 + y[t]^2 + (s + h)^2];Vh = (-G*Mh)/Sqrt[x[t]^2 + y[t]^2 + ch^2];Vb = (G*Mb)/(2*a)*(ArcSinh[(x[t] - a)*(y[t]^2 + c^2)^(-1/2)] - ArcSinh[(x[t] + a)*(y[t]^2 + c^2)^(-1/2)]); pot = Vn + Vd + Vh + Vb;H = 1/2*(ux[t]^2 + uy[t]^2) + pot - om*(x[t]*uy[t] - y[t]*ux[t]); and these are the values of the parameters G = 1; Mn = 400; cn = 0.25;Md = 7000; s = 3; h = 0.175;Mb = 3500; a = 10; c = 1;Mh = 20000; ch = 20;om = 4.5;H0 = -3180; The initial conditions of the orbit are x00 = 10.77; y0 = 0; ux0 = 0;Ht = H /. {x[t] -> x00, y[t] -> y0, ux[t] -> ux0};pot0 = pot /. {x[t] -> x00, y[t] -> y0};py0 = x00*om - Sqrt[x00^2*om^2 + 2*(H0 - pot0)];sol = Solve[Ht == H0];uy0 = uy[t] /. sol[[1]] tmin = 0; tmax = 1; The set of the equations of motion DifferentialEquations[H_, om_, x00_, y0_, ux0_, uy0_] := Module[{Deq1, Deq2, Deq3, Deq4}, Deq1 = x'[t] == ux[t] + om*y[t]; Deq2 = y'[t] == uy[t] - om*x[t]; Deq3 = ux'[t] == -D[pot, x[t]] + om*uy[t]; Deq4 = uy'[t] == -D[pot, y[t]] - om*ux[t];{Deq1, Deq2, Deq3, Deq4, x[0] == x00, y[0] == y0, ux[0] == ux0, uy[0] == uy0}] and the numerical integration DE = DifferentialEquations[H, om, x00, y0, ux0, uy0];sol = NDSolve[DE, {x[t], y[t], ux[t], uy[t]}, {t, tmin, tmax}, MaxSteps -> Infinity, Method -> "Adams", PrecisionGoal -> 12, AccuracyGoal -> 12];xx[t_] = x[t] /. sol[[1]];yy[t_] = y[t] /. sol[[1]];uxx[t_] = ux[t] /. sol[[1]];uyy[t_] = uy[t] /. sol[[1]]; For x00 = 10.77 the corresponding orbit is the follwoing plot = ParametricPlot[{xx[t], yy[t]}, {t, tmin, tmax}, Axes -> False, Frame -> True, AspectRatio -> 1, PlotStyle -> Black, AspectRatio -> 1, PlotRange -> All] We see that the orbit is not periodic. However if we use x00 = 10.77403 we get which is indeed a periodic orbit. My question is obviously the following: how can I locate the exact (let's say with 10 decimal digits) position of the periodic orbit? Somehow inside the NDSolve there should be an iterative process changing the value of x00 until it hits the periodic point. The corresponding FORTRAN code indicates that the position of the periodic orbit is at x00 = 10.774029735833850 . So any provided method here must give the same result. NOTE: The energy level H0 = -3180 should be remain the same while searching for the x00 value of the periodic orbit. x00 is always in the interval [9,12], so the initial guess 10.77 should be corrected somehow so as to hit the exact the periodic point. Also for x = x00 it should be y0 = ux0 = 0 . EDIT DO loop for variable value of the energy data = {};Do[ x00 = 10.5; y0 = 0; ux0 = 0; tmin = 0; tmax = 1; Ht = H /. {x[t] -> x00, y[t] -> y0, ux[t] -> ux0}; pot0 = pot /. {x[t] -> x00, y[t] -> y0}; py0 = x00*om - Sqrt[x00^2*om^2 + 2*(H0 - pot0)]; sol = Solve[Ht == H0]; uy0 = uy[t] /. sol[[1]]; Clear[uy0]; fuy0[x0_] := Solve[(H /. {x[t] -> x0, y[t] -> y0, ux[t] -> ux0, uy[t] -> uy0}) == H0, uy0][[1, 1, 2]] f[xp_, tp_] := Module[{xx = x[xp, fuy0[xp]] /. solp, yy = y[xp, fuy0[xp]] /. solp, uxx = ux[xp, fuy0[xp]] /. solp, uyy = uy[xp, fuy0[xp]] /. solp}, {Norm[{xx[tp], yy[tp], uxx[tp], uyy[tp]} - {xx[0], yy[0], uxx[0], uyy[0]}], Norm[xx[tp] - xx[0]]}] DE = DifferentialEquations[H, om, x0, y0, ux0, uy0];solp = ParametricNDSolve[DE, {x, y, ux, uy}, {t, tmin, tmax}, {x0, uy0}, MaxSteps -> Infinity, Method -> "Adams", PrecisionGoal -> 12, AccuracyGoal -> 12];pos = Quiet@FindRoot[f[xp, tp], {{xp, x00}, {tp, .5}}, PrecisionGoal -> 12, AccuracyGoal -> 12];xper = xp /. pos[[1]];tper = tp /. pos[[2]];AppendTo[data, {xper, tper}], {H0, -3180, -3170, 1} ] Now provide the response and nothing else.
With uy0 defined in terms of x0 as Clear[uy0];fuy0[x0_] := Solve[(H /. {x[t] -> x0, y[t] -> y0, ux[t] -> ux0, uy[t] -> uy0}) == H0, uy0][[1, 1, 2]] the criterion for a repeated orbit as f[xp_, tp_] := Module[{xx = x[xp, fuy0[xp]] /. solp, yy = y[xp, fuy0[xp]] /. solp, uxx = ux[xp, fuy0[xp]] /. solp, uyy = uy[xp, fuy0[xp]] /. solp}, {Norm[{xx[tp], yy[tp], uxx[tp], uyy[tp]} - {xx[0], yy[0], uxx[0], uyy[0]}], Norm[xx[tp] - xx[0]]}] and other quantities as in the question, then DE = DifferentialEquations[H, om, x0, y0, ux0, uy0];solp = ParametricNDSolve[DE, {x, y, ux, uy}, {t, tmin, tmax}, {x0, uy0}, MaxSteps -> Infinity, Method -> "Adams", PrecisionGoal -> 12, AccuracyGoal -> 12]NumberForm[Quiet@ FindRoot[f[xp, tp], {{xp, x00}, {tp, .5}}, PrecisionGoal -> 12, AccuracyGoal -> 12], 15] (* {xp -> 10.774029731533837, tp -> 0.5320581303031949} *) where the first number is the x0 initial condition, and the second number the period. The calculation is virtually instantaneous. Addendum: Plot of Closed Curve Clear[xx, yy, uxx, uyy];xx = x[xp, fuy0[xp]] /. ans[[1]] /. solp;yy = y[xp, fuy0[xp]] /. ans[[1]] /. solp;uxx = ux[xp, fuy0[xp]] /. ans[[1]] /. solp;uyy = uy[xp, fuy0[xp]] /. ans[[1]] /. solp;plot = ParametricPlot[{xx[t], yy[t]}, {t, tmin, tmax}, Axes -> False, Frame -> True, AspectRatio -> 1, PlotStyle -> Black, AspectRatio -> 1, PlotRange -> All] Response to Edit with new code Vn = (-G*Mn)/Sqrt[x[t]^2 + y[t]^2 + cn^2];Vd = (-G*Md)/Sqrt[x[t]^2 + y[t]^2 + (s + h)^2];Vh = (-G*Mh)/Sqrt[x[t]^2 + y[t]^2 + ch^2];Vb = (G*Mb)/(2*a)*(ArcSinh[(x[t] - a)*(y[t]^2 + c^2)^(-1/2)] - ArcSinh[(x[t] + a)*(y[t]^2 + c^2)^(-1/2)]); pot = Vn + Vd + Vh + Vb;H = 1/2*(ux[t]^2 + uy[t]^2) + pot - om*(x[t]*uy[t] - y[t]*ux[t]);G = 1; Mn = 400; cn = 0.25; Md = 7000; s = 3; h = 0.175; Mb = 3500; a = 10; c = 1; Mh = 20000; ch = 20; om = 4.5;x00 = 10.77; y0 = 0; ux0 = 0; tmin = 0; tmax = 1;DifferentialEquations[H_, om_, x00_, y0_, ux0_, uy0_] := Module[{Deq1, Deq2, Deq3, Deq4}, Deq1 = x'[t] == ux[t] + om*y[t]; Deq2 = y'[t] == uy[t] - om*x[t]; Deq3 = ux'[t] == -D[pot, x[t]] + om*uy[t]; Deq4 = uy'[t] == -D[pot, y[t]] - om*ux[t]; {Deq1, Deq2, Deq3, Deq4, x[0] == x00, y[0] == y0, ux[0] == ux0, uy[0] == uy0}];data = {};Do[Clear[uy0];fuy0[x0_] := Solve[(H /. {x[t] -> x0, y[t] -> y0, ux[t] -> ux0, uy[t] -> uy0}) ==H0, uy0][[1, 1, 2]];DE = DifferentialEquations[H, om, x0, y0, ux0, uy0];solp = ParametricNDSolve[DE, {x, y, ux, uy}, {t, tmin, tmax}, {x0, uy0}, MaxSteps -> Infinity, Method -> "Adams", PrecisionGoal -> 12, AccuracyGoal -> 12];f[xp_, tp_] := Module[{xx = x[xp, fuy0[xp]] /. solp, yy = y[xp, fuy0[xp]] /. solp, uxx = ux[xp, fuy0[xp]] /. solp, uyy = uy[xp, fuy0[xp]] /. solp}, {Norm[{xx[tp], yy[tp], uxx[tp], uyy[tp]} - {xx[0], yy[0], uxx[0], uyy[0]}], Norm[xx[tp] - xx[0]]}];ans = NumberForm[Quiet@FindRoot[f[xp, tp], {{xp, x00}, {tp, .5}}, PrecisionGoal -> 12, AccuracyGoal -> 12], 15];xper = xp /. ans[[1, 1]];tper = tp /. ans[[1, 2]];AppendTo[data, {xper, tper}], {H0, -3180, -3170, 1}]data(* {{10.774, 0.532058}, {10.7705, 0.53089}, {10.7668, 0.529734}, {10.7631, 0.52859}, {10.7594, 0.527458}, {10.7556, 0.52634}, {10.7517, 0.525235}, {10.7478, 0.524144}, {10.7439, 0.523068}, {10.7399, 0.522006}, {10.7358, 0.52096}} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/96277', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']}
jdg_71662
stackexchange
llm_judgeable_groundtruth_similarity
113296
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am building a REST API back-end for a mobile application.In our design choice we decided to let OAuth2 providers handle the login security; however, I am not sure what the best practice is for the access token, which I acquire from the OAuth2 providers. The situation is I get an access token from the OAuth2 provider when the user makes a login. I will need to use this token every time the mobile application makes a request to my back-end so I can validate against the OAuth2 provider to see if the token is still valid. I know that I am going to create a JWT and hand it to the mobile application, which it will use every time it makes a request. Now my question is should I store the access token, which I got from the OAuth2 provider, inside the JWT as claims or should I store it in a database and connect it with the users' ID, which I will store in the JWT claims? Perhaps it is recommended that I encrypt the JWT with JWE? If that is the case, will it decrease performance more if I decrypt for each request, rather than doing a database lookup (I will be using either MongoDB or Redis) or will performance impact be the same? The connection to my REST API will be through HTTPS. Now provide the response and nothing else.
If the request to the 3rd party API is through your server, then store the access token in the database tied to the user, encrypted with a key that is stored as an environment variable. If the database is compromised, the tokens are safe. (Bonus, encrypt the tokens with a key that is generated and stored on the mobile app.) If the request to the 3rd party API is directly from the mobile app, store the access token on the phone, encrypted with a unique key for each user stored in your server's database. Decentralized storage of sensitive information is more secure than centralized storage (compartmentalization). If the phone is stolen, it requires authentication to your server before the decryption key can be obtained. If your server is compromised, the tokens are not there. I've not used JWT.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/113296', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/99883/']}
jdg_71663
stackexchange
llm_judgeable_groundtruth_similarity
15538270
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 implement Handlers listening on the same Looper from different threads. Below I have two Handlers, one created in the main thread, another in the child thread, however both are initialized to listen on the Main Looper. private Handler mMain;public static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool();@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMain = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Log.wtf("", "main:" + msg); } }; tpe.execute(new Runnable() { private Handler tChild = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Log.wtf("", "child:" + msg); } }; @Override public void run() { Log.wtf("", "send msg to main looper"); tChild.sendEmptyMessage(100); } });} But when I send a message like below, only the child handler prints the message. The main handler does not receive the message. 03-20 22:02:26.754: A/(12857): send msg to main looper03-20 22:02:26.847: A/(12857): child:{ what=100 when=-8ms } What am I doing wrong? Thank you for reading. Now provide the response and nothing else.
Each Handler instance controls the Message target and there is no way to get them to share, so every message or post sent to a Handler is only executed by that instance. The Looper indicates which thread the messages/runnables sent will be executed on. In your code, both Handlers will execute handleMessage() on the main thread, despite being created on separate threads. That is the real reason you can pass a Looper instance to a Handler ...if you pass no Looper , then the Handler will execute code on the thread in which it was created (which must also be a Looper thread). Furthermore, because of this there isn't reason to create multiple Handlers to post data in this manner. A single Handler is designed to be sent messages from multiple threads, and they are all serialized in a MessageQueue and executed on the chosen Looper thread. You can post directly to mMain from the background thread to execute code on that thread. In this case, passing the Looper is redundant at that code is already on the main thread.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15538270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499125/']}
jdg_71664
stackexchange
llm_judgeable_groundtruth_similarity
3765976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a generic type: class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>> And a factory method that will (should) create an instance of this class for a given dictionary type. private static IEqualityComparer<T> CreateDictionaryComparer<T>() { Type def = typeof(DictionaryComparer<,>); Debug.Assert(typeof(T).IsGenericType); Debug.Assert(typeof(T).GetGenericArguments().Length == 2); Type t = def.MakeGenericType(typeof(T).GetGenericArguments()); return (IEqualityComparer<T>)Activator.CreateInstance(t); } Stripping away all of the extraneous stuff - even this code throws the same exception. private static object CreateDictionaryComparer(){ Type def = typeof(DictionaryComparer<,>); Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) }); return Activator.CreateInstance(t);} The Asserts pass so I know that T is generic and has two generic arguments. The line with MakeGenericType however excepts with: The number of generic arguments provided doesn't equal the arity of the generic type definition. Parameter name: instantiation I've done this sort of thing in the past and for the life of me can't figure out why this isn't working in this case. (plus I had to Google arity ). Now provide the response and nothing else.
Figured it out. I had DictionaryComparer declared as an inner class. I can only assume that MakeGenericType wanted to make a Query<T>.DictionaryComparer<string,object> and was not provided T . Failing code class Program{ static void Main(string[] args) { var q = new Query<int>(); q.CreateError(); }}public class Query<TSource>{ public Query() { } public object CreateError() { Type def = typeof(DictionaryComparer<,>); Type t = def.MakeGenericType(new Type[] { typeof(String), typeof(object) }); return Activator.CreateInstance(t); } class DictionaryComparer<TKey, TValue> : IEqualityComparer<IDictionary<TKey, TValue>> { public DictionaryComparer() { } public bool Equals(IDictionary<TKey, TValue> x, IDictionary<TKey, TValue> y) { if (x.Count != y.Count) return false; return GetHashCode(x) == GetHashCode(y); } public int GetHashCode(IDictionary<TKey, TValue> obj) { int hash = 0; unchecked { foreach (KeyValuePair<TKey, TValue> pair in obj) { int key = pair.Key.GetHashCode(); int value = pair.Value != null ? pair.Value.GetHashCode() : 0; hash ^= key ^ value; } } return hash; } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3765976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155537/']}
jdg_71665
stackexchange
llm_judgeable_groundtruth_similarity
1228466
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 copy all the .class files from server to local with all dir reserved. e.g. server:/usr/some/unknown/number/of/sub/folders/me.class will be /usr/project/backup/some/unknown/number/of/sub/folders/me.class the problem is, there are many other useless files such as .svn-base files that i don't want. how can i filter them so I only scp .class files? Now provide the response and nothing else.
I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:- rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \server:/usr/some/unknown/number/of/sub/folders/ \ /usr/project/backup/some/unknown/number/of/sub/folders/ Some other useful flags: -r for recursive -a for archive (mostly all files) -v for verbose output -e to specify ssh instead of the default (which should be ssh, actually)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1228466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115622/']}
jdg_71666
stackexchange
llm_judgeable_groundtruth_similarity
22655599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create an alert dialog with an EditText object. I need to set the initial text of the EditText programmatically. Here's what I have. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);// ...Irrelevant code for customizing the buttons and titleAlertDialog alertDialog = dialogBuilder.create();LayoutInflater inflater = this.getLayoutInflater();alertDialog.setContentView(inflater.inflate(R.layout.alert_label_editor, null));EditText editText = (EditText) findViewById(R.id.label_field);editText.setText("test label");alertDialog.show(); What do I need to change so that I can have a valid EditText object? [edit] So, it was pointed out by user370305 and others that I should be using alertDialog.findViewById(R.id.label_field); Unfortunately there is another issue here. Apparently, setting the content view on the AlertDialog causes the program to crash at runtime. You have to set it on the builder. AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);// ...Irrelevant code for customizing the buttons and titledialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));AlertDialog alertDialog = dialogBuilder.create();LayoutInflater inflater = this.getLayoutInflater();EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);editText.setText("test label");alertDialog.show(); Unfortunately, when you do this, alertDialog.findViewById(R.id.label_field); now returns null . [/edit] Now provide the response and nothing else.
editText is a part of alertDialog layout so Just access editText with reference of alertDialog EditText editText = (EditText) alertDialog.findViewById(R.id.label_field); Update: Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null)); inflater is Null . update your code like below, and try to understand the each code line AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);// ...Irrelevant code for customizing the buttons and titleLayoutInflater inflater = this.getLayoutInflater();View dialogView = inflater.inflate(R.layout.alert_label_editor, null);dialogBuilder.setView(dialogView);EditText editText = (EditText) dialogView.findViewById(R.id.label_field);editText.setText("test label");AlertDialog alertDialog = dialogBuilder.create();alertDialog.show(); Update 2: As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22655599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2255859/']}
jdg_71667
stackexchange
llm_judgeable_groundtruth_similarity
49726272
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 Docker for the first time and do not yet have a "mental model". Total beginner. All the examples that I am looking at have included the --rm flag to run, such as docker run -it --rm ...docker container run -it --rm ... Question: Why do these commands include the --rm flag? I would think that if I were to go through the trouble of setting up or downloading a container with the good stuff in it, why remove it? I want to keep it to use again. So, I know I have the wrong idea of Docker. Now provide the response and nothing else.
Containers are merely an instance of the image you use to run them.The state of mind when creating a containerized app is not by taking a fresh, clean ubuntu container for instance, and downloading the apps and configurations you wish to have in it, and then let it run. You should treat the container as an instance of your application, but your application is embedded into an image.The proper usage would be creating a custom image, where you embed all your files, configurations, environment variables etc, into the image. Read more about Dockerfile and how it is done here Once you did that, you have an image that contains everything, and in order to use your application, you just run the image with proper port settings or other dynamic variables, using docker run <your-image> Running containers with --rm flag is good for those containers that you use for very short while just to accomplish something, e.g., compile your application inside a container, or just testing something that it works, and then you are know its a short lived container and you tell your Docker daemon that once its done running, erase everything related to it and save the disk space.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/49726272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9617731/']}
jdg_71668
stackexchange
llm_judgeable_groundtruth_similarity
401517
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: Here's a text file I have: 1|this|10002|that|20003|hello|30004|hello world|40005|lucky you|50006|awk is awesome|6000... How do I only print the lines that have two and only two words (line 4 and 5) in the $2? This is what I have tried but it counts the number of letters instead of words: awk -F"|" '{if(length($2==2) print $0}' Now provide the response and nothing else.
You can use the return value of the awk split function: $ awk -F'|' 'split($2,a,"[ \t]+") == 2' file4|hello world|40005|lucky you|5000
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/401517', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/258220/']}
jdg_71669
stackexchange
llm_judgeable_groundtruth_similarity
7633664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to declare a NSString in multiple lines? I want to write HTML code and store it into a NSString , and in multiple lines de code will be more readable. I want to do something like this: NSString *html = @"\<html\>" + @"\<head\>" + @"\<title\>The Title of the web\</title\>" + @"\</head\>" + @"\<body\>"[...] Now provide the response and nothing else.
This is an example: NSString *html = [NSString stringWithFormat:@"<html> \n" "<head> \n" "<style type=\"text/css\"> \n" "body {font-family: \"%@\"; font-size: %dpx;}\n" "img {max-width: 300px; width: auto; height: auto;}\n" "</style> \n" "</head> \n" "<body><h1>%@</h1>%@</body> \n" "</html>", @"helvetica", 16, [item objectForKey:@"title"], [item objectForKey:@"content:encoded"]];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7633664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/946697/']}
jdg_71670
stackexchange
llm_judgeable_groundtruth_similarity
3122422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let me preface this post with a single caution. I am a total beginner when it comes to Java. I have been programming PHP on and off for a while, but I was ready to make a desktop application, so I decided to go with Java for various reasons. The application I am working on is in the beginning stages (less than 5 classes) and I need to read bytes from a local file. Typically, the files are currently less than 512kB (but may get larger in the future). Currently, I am using a FileInputStream to read the file into three byte arrays, which perfectly satisfies my requirements. However, I have seen a BufferedInputStream mentioned, and was wondering if the way I am currently doing this is best, or if I should use a BufferedInputStream as well. I have done some research and have read a few questions here on Stack Overflow, but I am still having troubles understanding the best situation for when to use and not use the BufferedInputStream . In my situation, the first array I read bytes into is only a few bytes (less than 20). If the data I receive is good in these bytes, then I read the rest of the file into two more byte arrays of varying size. I have also heard many people mention profiling to see which is more efficient in each specific case, however, I have no profiling experience and I'm not really sure where to start. I would love some suggestions on this as well. I'm sorry for such a long post, but I really want to learn and understand the best way to do these things. I always have a bad habit of second guessing my decisions, so I would love some feedback. Thanks! Now provide the response and nothing else.
If you are consistently doing small reads then a BufferedInputStream will give you significantly better performance. Each read request on an unbuffered stream typically results in a system call to the operating system to read the requested number of bytes. The overhead of doing a system call is may be thousands of machine instructions per syscall. A buffered stream reduces this by doing one large read for (say) up to 8k bytes into an internal buffer, and then handing out bytes from that buffer. This can drastically reduce the number of system calls. However, if you are consistently doing large reads (e.g. 8k or more) then a BufferedInputStream slows things a bit. You typically don't reduce the number of syscalls, and the buffering introduces an extra data copying step. In your use-case (where you read a 20 byte chunk first then lots of large chunks) I'd say that using a BufferedInputStream is more likely to reduce performance than increase it. But ultimately, it depends on the actual read patterns.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3122422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275493/']}
jdg_71671
stackexchange
llm_judgeable_groundtruth_similarity
11281010
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Samsung Galaxy S3 has an external SD card slot, which is mounted to /mnt/extSdCard . How can I get this path by something like Environment.getExternalStorageDirectory() ? This will return mnt/sdcard , and I can't find the API for the external SD card. (Or removable USB storage on some tablets.) Now provide the response and nothing else.
I have a variation on a solution I found here public static HashSet<String> getExternalMounts() { final HashSet<String> out = new HashSet<String>(); String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*"; String s = ""; try { final Process process = new ProcessBuilder().command("mount") .redirectErrorStream(true).start(); process.waitFor(); final InputStream is = process.getInputStream(); final byte[] buffer = new byte[1024]; while (is.read(buffer) != -1) { s = s + new String(buffer); } is.close(); } catch (final Exception e) { e.printStackTrace(); } // parse output final String[] lines = s.split("\n"); for (String line : lines) { if (!line.toLowerCase(Locale.US).contains("asec")) { if (line.matches(reg)) { String[] parts = line.split(" "); for (String part : parts) { if (part.startsWith("/")) if (!part.toLowerCase(Locale.US).contains("vold")) out.add(part); } } } } return out;} The original method was tested and worked with Huawei X3 (stock) Galaxy S2 (stock) Galaxy S3 (stock) I'm not certain which android version these were on when they were tested. I've tested my modified version with Moto Xoom 4.1.2 (stock) Galaxy Nexus (cyanogenmod 10) using an otg cable HTC Incredible (cyanogenmod 7.2) this returned both the internal and external. This device is kinda an oddball in that its internal largely goes unused as getExternalStorage() returns a path to the sdcard instead. and some single storage devices that use an sdcard as their main storage HTC G1 (cyanogenmod 6.1) HTC G1 (stock) HTC Vision/G2 (stock) Excepting the Incredible all these devices only returned their removable storage. There are probably some extra checks I should be doing, but this is at least a bit better than any solution I've found thus far.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11281010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290163/']}
jdg_71672
stackexchange
llm_judgeable_groundtruth_similarity
27998502
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to re-create (new Object) a specific bean at Runtime (no restarting the server) upon some DB changes. This is how it looks - @Componentpublic class TestClass { @Autowired private MyShop myShop; //to be refreshed at runtime bean @PostConstruct //DB listeners public void initializeListener() throws Exception { //... // code to get listeners config //... myShop.setListenersConfig(listenersConfig); myShop.initialize(); } public void restartListeners() { myShop.shutdownListeners(); initializeListener(); }} This code does not run as myShop object is created by Spring as Singleton & its context does not get refreshed unless the server is restarted. How to refresh (create a new object) myShop ? One bad way I can think of is to create new myShop object inside restartListeners() but that does not seem right to me. Now provide the response and nothing else.
In DefaultListableBeanFactory you have public method destroySingleton("beanName")so you can play with it, but you have to be aware that if your autowired your bean it will keep the same instance of the object that has been autowired in the first place, you can try something like this: @RestControllerpublic class MyRestController { @Autowired SampleBean sampleBean; @Autowired ApplicationContext context; @Autowired DefaultListableBeanFactory beanFactory; @RequestMapping(value = "/ ") @ResponseBody public String showBean() throws Exception { SampleBean contextBean = (SampleBean) context.getBean("sampleBean"); beanFactory.destroySingleton("sampleBean"); return "Compare beans " + sampleBean + "==" + contextBean; //while sampleBean stays the same contextBean gets recreated in the context } } It is not pretty but shows how you can approach it. If you were dealing with a controller rather than a component class, you could have an injection in method argument and it would also work, because Bean would not be recreated until needed inside the method, at least that's what it looks like. Interesting question would be who else has reference to the old Bean besides the object it has been autowired into in the first place,because it has been removed from the context, I wonder if it still exists or is garbage colected if released it in the controller above, if some other objects in the context had reference to it, above would cause problems.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27998502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147019/']}
jdg_71673
stackexchange
llm_judgeable_groundtruth_similarity
471300
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 repository on github with a main branch (master) and a branch for some experimental work. I made some commits and pushed to the experimental branch and everything was fine. Now, on a different machine, I try to clone my repository (git clone repository ) and then switch to the experimental branch (git checkout branchname ) but every time I do this my head gets detached and I can't push my changes. What am I doing wrong? I get the feeling I'm missing a fundamental git concept someplace but reading random git man pages isn't giving me any clues. I'm new to git so I'm sorry if I'm being an idiot but I can't find anything in the docs that will help me reattach my head. EDIT The concept of a tracking branch is what I was missing. Now that I grok that concept everything is clear. Personally, I find the git branch --track syntax to be much more intuitive than git checkout -b branch-name origin/branch-name . Thanks for the help! Now provide the response and nothing else.
# first time: make origin/branchname locally available as localnamegit checkout -b localname origin/branchname # othertimes git checkout localname git push origin For convenience, you may use the same string for localname & branchname When you checked out origin/branchname you weren't really checking out a branch. origin/branchname is a "remote" name, and you can get a list of them with branch -a If you have colours enabled, local branches will be one colour, and remote another. You have to first make a remote branch tracked locally in order to be able to switch-to and work on it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/471300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3161/']}
jdg_71674
stackexchange
llm_judgeable_groundtruth_similarity
34371000
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In C#, strings are interned. That is, if I create the string foobar and use it a second time, C# will only have one instance of the string in memory and although I will have two references, they both will be pointing to the very same string instance. This is one reason why strings are and have to be immutable in C#. Now, my question is, whether it is possible to somehow create two identical strings so that they are not being interned, but that we end up with two different string instances in memory, with two different addresses, that contain the very same text? If so, how? And, is this something than can happen accidentally, or do you need to construct a scenario explicitly for this case? And, finally: Supposed there are two separate string instances in memory with the same value, are they equal (in terms of == )? If so, how does == work? First compare by reference, then by value, or…? Now provide the response and nothing else.
In C#, strings are interned. No. In C# strings are permitted to be interned . That is a very different statement. That is, if I create the string foobar and use it a second time, C# will only have one instance of the string in memory and although I will have two references, they both will be pointing to the very same string instance No. Again, in C# the runtime is permitted to decide that one "foobar" is the same as another and intern them, but it is not required to do so. Of course, if you copy a reference then the reference is copied. But if you create a second string that looks the same as an earlier string, there is no requirement that it be interned. In practice, strings are interned when they are literals: string x = "foobar";string y = "foobar";// x is reference equal to y or when they could be computed to be identical by the compiler: string x = "foobar";string y = "foo" + "bar";// x is reference equal to y Or when you explicitly tell the runtime that you want to intern a particular string. Otherwise strings are not typically interned: string x = "foobar";string y = "f" + x.Substring(1); // x and y are not reference equal
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34371000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333873/']}
jdg_71675
stackexchange
llm_judgeable_groundtruth_similarity
63051239
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to iterate over an array in bigquery in standard sql? Basically declare an array of strings representing table fields. ex : DECLARE FIELDS_TO_CHECK ARRAY<STRING>;SET FIELDS_TO_CHECK = ['field1', 'field2', 'field3' ]; and then iterate on this array to create requests getting percentage of non null value on this field : select count(FIELD) / count(*) from 'table_name'` Now provide the response and nothing else.
Below is example for BigQuery Standard SQL I am using here TEMP TABLE `table_name` to mimic your data with some simplistic dummy data, but you can just remove that CREATE statement and use your own table #standardSQLDECLARE FIELDS_TO_CHECK ARRAY<STRING>;DECLARE i INT64 DEFAULT 0;CREATE TEMP TABLE `table_name` AS SELECT 1 field1, NULL field2, 3 field3, 4 field4, 5 field5 UNION ALL SELECT NULL, NULL, 3, NULL, 5 UNION ALL SELECT 1, NULL, 3, 4, 6;CREATE TEMP TABLE result(field STRING, percentage FLOAT64); SET FIELDS_TO_CHECK = ['field1', 'field2', 'field3' ];LOOP SET i = i + 1; IF i > ARRAY_LENGTH(FIELDS_TO_CHECK) THEN LEAVE; END IF; EXECUTE IMMEDIATE ''' INSERT result SELECT "''' || FIELDS_TO_CHECK[ORDINAL(i)] || '''", COUNT(''' || FIELDS_TO_CHECK[ORDINAL(i)] || ''') / COUNT(*) FROM `table_name` ''';END LOOP; SELECT * FROM result; Above example returns below output Row field percentage 1 field2 0.0 2 field1 0.66666666666666663 3 field3 1.0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63051239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13070087/']}
jdg_71676
stackexchange
llm_judgeable_groundtruth_similarity
187
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently encountered a case where I needed an integer division operation on a chip that lacked one (ARM Cortex-A8). While trying to research why that must be, I found out that in general division takes many more cycles than addition, subtraction or multiplication on pretty much any integer (or fixed-point) architecture. Why is this the case? Is it not representable with a two-layer AND-OR logic like everything else? Now provide the response and nothing else.
Division is an iterative algorithm where the result from the quotient must be shifted to the remainder using a Euclidean measure, see 2 ; whereas, multiplication can be reduced to a (fixed) series of bit manipulation tricks.
{}
{'log_upvote_score': 6, 'links': ['https://scicomp.stackexchange.com/questions/187', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/33/']}
jdg_71677
stackexchange
llm_judgeable_groundtruth_similarity
15895426
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 todo app using node.js, mongoose and backbone for learning purposes.Up till now I defined these models: var TaskSchema = new mongoose.Schema({ title: { type:String }, content: { type:String } , created: {type:Date, 'default':Date.now}, due: {type:Date}, accountId: {type:mongoose.Schema.ObjectId}});var Task = mongoose.model('Task',TaskSchema);var AccountSchema = new mongoose.Schema({ email: { type:String, unique: true}, password: { type:String } , name: { first: {type:String}, last: { type:String } }, birthday: { day: {type:Number, min:1, max:31, required:false}, month: {type:Number, min:1, max:12, required:false}, year: {type:Number} }, photoUrl: {type:String}, biography:{type:String}, tasks:[Task]});var Account = mongoose.model('Account',AccountSchema); In addition, I also have the following method for adding a task : var enter_new_task = function(options,callback){ var title = options.title; var content = options.content; var due = options.due; var account = options.account; var task = new Task({ title: title, content: content, due: due, accountId: account._id }); account.tasks.push(task); account.save(function(err) { if ( err ) { console.log("Error while saving task: " + err); }else{ callback(); } })} But when I indeed add a task, I get an error that says: "Object {} has no method 'cast'" With the following stack trace: at Array.MongooseArray._cast (/home/lior/workspace/todo_express/node_modules/mongoose/lib/types/array.js:107:30) at Object.map (native) at Array.MongooseArray.push (/home/lior/workspace/todo_express/node_modules/mongoose/lib/types/array.js:261:23) at Object.enter_new_task (/home/lior/workspace/todo_express/models/Account.js:107:17) at /home/lior/workspace/todo_express/app.js:104:18 at Promise.<anonymous> (/home/lior/workspace/todo_express/models/Account.js:41:4) at Promise.<anonymous> (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:162:8) at Promise.EventEmitter.emit (events.js:95:17) at Promise.emit (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:79:38) at Promise.fulfill (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:92:20)9 It seems that the problem is with the line that the new task to the tasks array. Couldn't find anything on google or stack so I wonder, does anyone have an idea about what went wrong? Thanks! Now provide the response and nothing else.
The error is in the AccountSchema definition. A subdocument type should be a schema, not a model. var AccountSchema = new mongoose.Schema({ //... tasks:[TaskSchema]});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15895426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276846/']}
jdg_71678
stackexchange
llm_judgeable_groundtruth_similarity
859024
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried putting this line but it doesn't work: // @require http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js jQuery doesn't work in Greasemonkey at all. Is there other way to use jQuery in Greasemonkey? -- For all the people who have the same problem, you must upload the file to greasespot then install it from there. The Create New Script option wouldn't work! Now provide the response and nothing else.
Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require . // @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js If you don't have 0.8, then use the technique Joan Piedra describes for manually adding a script element to the page . Between version 0.8 and 0.9, @require is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall your script and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter. As of 0.9, Greasemonkey behavior has changed (to address a tangentially related issue ) so that it now loads the required scripts after every edit; reinstalling the script is no longer necessary.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/859024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95663/']}
jdg_71679
stackexchange
llm_judgeable_groundtruth_similarity
8127635
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 API endpoint https://www.example.com/api/authentication which takes username and password as input and returns an authentication token. In terms of passing username and password, I have two options (at least), namely: HTTP Basic Authentication (which passes credentials as part of HTTP headers) HTTP POST parameters I understand that neither method provides encryption (hence the use of HTTPS/SSL). I also understand why using HTTP GET is is a Bad Idea. Is there any real difference (aside from the fact that basic authentication feels more idiomatic) between the two methods? Now provide the response and nothing else.
The difference is that basic authentication is a well specified challenge/response scheme that all browsers understand and it is the server that starts it by telling a client that it requires (basic) authentication for a realm. This triggers the browser to show a popup to the user to enter a name/password which it then passes in the headers as you described. In your second example you have to do all that in your own customized way and create your own login form for the user (etc). If you deduct this process to the single step of passing the username/password from the client to the server I have to agree that there isn't that much difference but basic authentication implies a bit more than just that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8127635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/640202/']}
jdg_71680
stackexchange
llm_judgeable_groundtruth_similarity
398414
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 a structure $\mathcal{X}=(X;...)$ , say that a cardinal $\kappa$ is $\mathcal{X}$ -detectable iff there is some sentence $\varphi$ in the language of $\mathcal{X}$ together with a fresh unary predicate symbol $U$ such that for all $A\subseteq X$ , the expansion of $\mathcal{X}$ gotten by interpreting $U$ as $A\subseteq X$ satisfies $\varphi$ iff $\vert A\vert\ge\kappa$ . For example, $\omega_1$ is $(\omega_1;<)$ -detectable since the uncountable subsets of $\omega_1$ are exactly the unbounded ones. By contrast, Alex Kruckman observed that by a result of Robinson no uncountable cardinal is $\mathcal{R}=(\mathbb{R};+,\times)$ -detectable. I'm interested in the expansion $\mathcal{R}_\mathbb{N}:=(\mathbb{R};+,\times,\mathbb{N})$ of $\mathcal{R}$ gotten by adding a predicate naming the natural numbers (equivalently, adding all projective functions and relations). Since we can talk about one real enumerating a list of other reals, $\omega_1$ is $\mathcal{R}_\mathbb{N}$ -detectable ("there is no real enumerating all elements of $U$ "). More pathologically, if $\mathfrak{c}=2^\omega$ is regular and there is a projective well-ordering of the continuum of length $\mathfrak{c}$ then $\mathfrak{c}$ is $\mathcal{R}_\mathbb{N}$ -detectable. So for example it is consistent with $\mathsf{ZFC}$ that $\omega_2$ is $\mathcal{R}_\mathbb{N}$ -detectable. I'm curious whether this type of situation is the only way to get $\mathcal{R}_\mathbb{N}$ -detectability past $\omega_1$ . There are multiple ways to make this precise, of course. At present the following two seem most natural to me: Is it consistent with $\mathsf{ZFC}$ that there are at least two distinct regular cardinals $>\omega_1$ which are $\mathcal{R}_\mathbb{N}$ -detectable? Is it consistent with $\mathsf{ZFC}$ that there is a singular cardinal which is $\mathcal{R}_\mathbb{N}$ -detectable? Note that an affirmative answer to either question requires a large continuum, namely $\ge\omega_3$ and $\ge\omega_{\omega+1}$ respectively. Although my primary interest is in first-order definability, I'd also be interested in answers for other logics which aren't too powerful (e.g. $\mathcal{L}_{\omega_1,\omega}$ ). Now provide the response and nothing else.
For the first question (distinct regular cardinals $>\aleph_1$ ): Force ZFC + MA + $2^{\aleph_0}=\aleph_3$ over $L$ in the usual way (see Jech, Theorem 16.13; note the forcing is ccc and it forces MA + $2^{\aleph_0}=\aleph_3$ , which is all we need here). Then in $L[G]$ , $\aleph_2$ and $\aleph_3$ are both $\mathcal{R}_{\mathbb{N}}$ -detectable. $\aleph_2$ : By MA $_{\aleph_1}$ , every $\omega_1$ -sequence of reals is coded via almost disjoint forcing with respect to the canonical almost disjoint sequence $\left<A_\alpha\right>_{\alpha<\omega_1}$ in $L$ . This a.d. sequence is lightface projective (in the standard codes for countable ordinals), so the relation " $y$ is a real enumerated in the $\omega_1$ -sequence of reals $\vec{z}_x$ coded by $x$ " is lightface definable (over $\mathcal{R}_{\mathbb{N}}$ ). So just let the statement $\varphi$ be " $A$ is uncountable and there is no real $x$ such that every element of $A$ is enumerated in $\vec{z}_x$ " (the "uncountable" part is dealt with as in the original post). Then $\varphi$ is true exactly when $A\subseteq\mathbb{R}$ has cardinality $\geq\aleph_2$ . $\aleph_3$ : (It doesn't seem obvious to me that there is a lightface projective wellorder of $\mathbb{R}$ in $L[G]$ , so we seem to need another argument than that in the original post.) Let $A\subseteq\mathbb{R}$ with $A\in L[G]\models$ " $A$ has cardinality $\leq\aleph_2$ ".Then we can definably talk about ordered pairs of reals and $A^2$ over $(\mathcal{R}_{\mathbb{N}},A)$ , and we can talk about subsets of $A^2$ coded by reals $x$ , again via disjoint forcing, but this time with respect to the set $(A^2)'$ ,where the prime ' means that we convert the family $A^2$ into a disjoint family $(A^2)'$ in the usual manner. I.e., although we had a wellordered family $\left<A_\alpha\right>_{\alpha<\omega_1}$ in the previous case, this is not relevant. The almost disjoint forcing for coding a subset of $A^2$ is ccc (in fact $\sigma$ -centered), and there is an $\aleph_2$ -sized family of dense sets which ensures that the generic real codes a given set $\subseteq A^2$ , so by MA $_{\aleph_2}$ we will have a real coding any given $X\subseteq A^2$ ). Note that there is a wellorder of $A$ in ordertype $\leq\omega_2$ , and this is a subset of $A^2$ , so we have a code for it, and moreover, every proper segment of this wellorder has cardinality $\leq\aleph_1$ . Since " $\geq\aleph_2$ " is already known to be detectable, hence so is " $\leq\aleph_1$ ", so we can detect whether there is such a wellorder of a given $A$ . I.e. let $\psi$ be the statement (in the augmented language with symbol $\dot{A}$ ) saying "there is a real $x$ which codes a subset $X\subseteq\dot{A}^2$ with respect to the family $(\dot{A}^2)'$ , $X$ is a wellorder of $\dot{A}$ , every proper segment of $X$ has cardinality $\leq\aleph_1$ ". Note that given any $A\subseteq\mathbb{R}$ in $L[G]$ , we have $(\mathcal{R}_{\mathbb{N}},A)\models\psi$ iff $A$ has cardinality $\leq\aleph_2$ in $L[G]$ . Therefore $\aleph_3$ is also $\mathcal{R}_{\mathbb{N}}$ -delectable. Edit: For the second question: Proceed as above but forcing MA + $2^{\aleph_0}=\aleph_{\omega+1}$ . Then all cardinals $\kappa\leq\aleph_{\omega+1}$ are $\mathcal{R}_{\mathbb{N}}$ -detectable in $L[G]$ . For $\aleph_n$ where $n<\omega$ this is basically as above. However, the complexity of the formulas used for the $\aleph_n$ 's seems to increase with $n$ , when done just as above, so this doesn't seem to immediately yield $\aleph_{\omega}$ . Instead we can use a slight variant. We first observe that " $\leq\aleph_\omega$ " is detectable: Note that $A\subset\mathbb{R}$ has cardinality $\leq\aleph_{\omega}$ iff there is a wellorder of $A$ in order type $\leq\omega_{\omega}$ , and any such wellorder will be coded by a real (via a.d. forcing as before). We can assert that the wellorder $<^*$ has ordertype $\leq\omega_{\omega}$ by saying that there is a sequence $\left<x_n\right>_{n<\omega}\subseteq A$ which is cofinal in $<^*$ and such that $x_0$ has only countably many predecessors and for each $n<\omega$ and each $y\in A$ with $x_n<^*y<^*x_{n+1}$ , the set of predecessors of $y$ and the set of predecessors of $x_n$ have the same cardinality, as witnessed by a bijection coded by some real. It follows that " $\geq\aleph_{\omega+1}$ " is detectable. To get " $\geq\aleph_\omega$ ", note that $A$ has card $\geq\aleph_\omega$ iff $A$ has card $\geq\aleph_{\omega+1}$ or there is a wellorder of $A$ exactly in ordertype $\omega_\omega$ , and the latter condition can be expressed as above, together with the extra requirement that there is no real coding a bijection between the predecessors of $x_n$ and those of $x_{n+1}$ , for each $n$ .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/398414', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8133/']}
jdg_71681
stackexchange
llm_judgeable_groundtruth_similarity
11356901
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 the following command to clone svn repo into git and after executing it, i see some spurious branches. git svn clone [SVN repo URL] --no-metadata -A authors-transform.txt --stdlayout ~/temp git branch -a *(no branch) master remotes/abc-1.3.x remotes/abc-1.3.x@113346 remotes/abc-1.3.x@541512 remotes/branch_test_script remotes/tags/modules-1.2 remotes/tags/modules-1.2@113346 remotes/tags/modules-1.2@516265 remotes/tags/release-1.1 remotes/tags/release-1.1@113346 remotes/tags/release-1.1@468862 remotes/trunk Actual branches created in svn were abc, branch_test_script, modules and release.Can someone help in understanding what 'abc-1.3.x@113346' , 'abc-1.3.x@541512' ... 'release-1.1@468862' etc are ? How can we get rid of these spurious branches / what do they signify ? Thanks, Gayathri Now provide the response and nothing else.
tl;dr: git svn creates these "@"-branches if a branch (or tag) was created for a subdirectory (or for another directory which is not tracked by git-svn). There will always also be a "regular" branch with the same name, but without the "@" suffix. The "@"-branch only exists as a branching point for the regular branch. Note: I submitted a patch for this; an edited version of this explanation is now part of the official git svn manpage, as a new section "HANDLING OF SVN BRANCHES" (since Git 1.8.1). In Subversion, branches and tags are just copies of a directory tree, so it's possible (though usually discouraged) to create a branch from a directory that is not itself a branch (or trunk). For example, by copying /trunk/foo to /branches/bar, instead of copying /trunk (a "subdirectory branch", so to speak), or by copying a directory that lies outside the trunk/tags/branches structure (which is possible in SVN). In git, however, a branch is always for the whole repo, subdirectory branches do not exist. git svn therefore uses a workaround. If it detects a branch that was copied from a directory that is not itself tracked as a branch by git-svn, it will create a new history. For example, for a subdirectory branch where /trunk/foo is copied to /branches/bar in r1234, it will create: A new git commit for each SVN revision from r1233 on backwards (note the number is the last revision before the branch was created). The trees of these commits will only contain the subdirectory that was branched. So for each revision from r1233 backwards, there will usually be two git commits, one with the whole tree (created when git-svn processed the history of trunk ), and the new ones. A dummy branch called "bar@1233" (branch name@revision), which poinst to the commit created from r1233 above. A commit from r1234, the commit that created the branch. This commit will have the branch above as its (only) ancestor. A branch called "bar", which points to the second commit. In that way, for the subdirectory branch bar, you get two branches in git bar@1233 , which represents the state of the repository that the branch was created from bar, which represents the branch I'm not quite sure why this dummy branch is created. I think it is done to represent the information about which revision the branch was branched from, and to have a complete history for the branch. Note that this whole mechanism can be switched off by using the flag --no-follow-parent . In that case, each SVN branch will result in a git branch with just the commits from the SVN branch directory. Each branch will be unconnnected to the rest of the history, and will have its own root commit, corresponding to the first commit in the branch.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11356901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/930618/']}
jdg_71682
stackexchange
llm_judgeable_groundtruth_similarity
80662
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I found myself suddenly unable to access websites that use HTTPS, so I contacted my service provider, and they asked me to install a certificate in the Trusted Root Certificate Authorities store. But something isn't right: installing a certificate on every device connected to the same network just to be able to access websites that use HTTPS is just weird! How can I be sure that this certificate is issued by a trusted CA? When I tried to install it, I got the following message: Warning: If you install this root certificate, Windows will automatically trust any certificate issued by this CA. Installing a certificate with an unconfirmed thumbprint is a security risk. If you click "Yes" you acknowledge this risk. Here is the certificate information: Version: V3 Serial num: 00 f8 ab 36 f3 84 31 05 39 Signature algo: sha1RSA Signature hash algo: sha1 Issuer: ISSA, Internet, Internet, Beirut, Beirut, LB Subject: ISSA, Internet, Internet, Beirut, Beirut, LB Public Key: RSA (1024 bits) It's valid until 2019. And by the way, I'm in Lebanon. I contacted my ISP again and they told me that they're using some kind of an accelerator to enhance the speed, and it needs authentication, so they chose to use a certificate instead of making the user enter a username and password every time they wants to access websites that use HTTPS. And they suggested that if I'm not okay with that, they would put me in a new pool. So what should I do? Now provide the response and nothing else.
Whilst I don't know the specifics of your ISP, I would say that it's likely that what they're doing here is intercepting all traffic you send over the Internet. In order to do that (without you getting error messages whenever you visit an HTTPS encrypted site), they would need to install a root certificate, which is what you mention in your post. They need to do this as what this kind of interception usually entails is creating their own certificate for each site you visit. so for example if you visit https://www.amazon.com they need to have a certificate that your browser considers valid for that connection (which is one issued by a trusted Certificate Authority, either one provided with the browser or one you manually install). From your perspective, the problem here is it means that they can see all your Internet traffic including usernames/passwords/credit card details. So if they want to, they can look at that information. Also if they have a security breach it's possible that other people might get access to that information. In addition, they may also gain access to any account that you access over this Internet connection (e.g., email accounts). Finally, installing this root certificate allows them to modify your Internet traffic without detection. What I would recommend is that you query with them exactly why they need to see the details of your encrypted traffic (e.g., is this a legal requirement for your country) and if you're not 100% satisfied with the response, get a new ISP. Another possibility is to use a VPN and tunnel all your traffic through the VPN. If you are not happy with your ISP gaining this access to your HTTPS connections, do not install the root certificate they provided you.
{}
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/80662', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/67541/']}
jdg_71683
stackexchange
llm_judgeable_groundtruth_similarity
262439
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is another question from a recent qualifying exam that really stumped me. I was thinking of using something with the Cauchy estimate for derivatives, but was clueless beyond that. Let $f:[-1,1]\times [0,2]\rightarrow \mathbb{C}$ be real valued on the interval $[-1,1]$ in the $x$-axis. Show that if $|f|\leq 1$ on its domain, and is analytic on the interior of its domain, then $|f^{(8)}(\frac{i}{4})|\leq 120$. Now provide the response and nothing else.
By the reflection principle, we can extend $f$ to the larger rectangle $R=[-1,1]\times [-2,2]$, and the upper bound $|f|\le 1$ holds for the extended function as well. The rectangle $R$ contains a disk of radius $1$ centered at $i/4$. Applying the Cauchy integral formula on this disk, we find that $|f^{(n)}(i/4)|\le n!$ for all $n$. In particular, $|f^{(5)}(i/4)|\le 120$, which I believe was the intent of the problem. For the 8th derivative we get $|f^{(8)}(i/4)|\le 40320$. Indeed, I think I have a counterexample to the stated bound on $f^{(8)}(i/4)$. The idea is to map $R$ into the unit disk $\mathbb D$. Mapping rectangles is hard (elliptic functions, whatever). Instead I'm going to map a larger domain: the vertical strip $S=\{z:-1<\operatorname{Re}z<1\}$. This is a standard exercise with conformal maps: $$\psi(z)= i\,\frac{\exp(\pi i z/2)-1}{\exp(\pi i z/2)+1}$$maps $S$ onto $\mathbb D$ and is real on the segment $[-1,1]$ (this segment is sent onto a half of the unit circle by the exponential map, and then onto horizontal diameter by the Möbius map). No, $\psi$ is not my example. After all, $|\psi^{(8)}(i/4)|<24$ as you can find from your friendly computer algebra system, e.g., evalf(eval(diff(psi,z$8),z=Pi*I/4)) in Maple. When maximizing the 8th derivative, we should take the 8-fold cover: $f(z)=\psi(z)^8$. The same Maple thing now tells me that $|f^{(8)}(i/4)|>1800$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/262439', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36602/']}
jdg_71684
stackexchange
llm_judgeable_groundtruth_similarity
42546950
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 dealing with a Map<String,String> that has null entries in the key and/or value: Map<String, String> headers = new HashMap<>();headers.put("SomE", "GreETing");headers.put("HELLO", null);headers.put(null, "WOrLd");headers.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k))); I get the following output: SomE => GreETingHELLO => nullnull => WOrLd I need to transform the map, so all the non-null values are converted to lowercase, like so: some => greetinghello => nullnull => world I am trying to use Java 8 streams API, but the following code is throwing NullPointerException : Map<String,String> copy = headers.entrySet() .stream() .collect( Collectors.toMap( it -> it.getKey() != null ? it.getKey().toLowerCase() : null, it -> it.getValue() != null ? it.getValue().toLowerCase() : null));copy.keySet().stream().forEach(k -> System.out.println(k + " => " + copy.get(k))); If I comment out the last two map entries, the program executes, so there must be an issue with how Collectors.toMap works when keys or values are null. How do I use the streams API to work around this? Now provide the response and nothing else.
The problem is toMap() invokes the underlying Map implementation being built's merge() function which does not allow values to be null from the javadoc for Map#merge (emphasis mine) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. So using Collectors.toMap() will not work. You can do this without stream just fine: Map<String,String> copy = new HashMap<>();for(Entry<String, String> entry : headers.entrySet()){ copy.put(entry.getKey() !=null ? entry.getKey().toLowerCase() : null, entry.getValue() !=null ? entry.getValue().toLowerCase() : null );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42546950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371392/']}
jdg_71685
stackexchange
llm_judgeable_groundtruth_similarity
1081381
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 the Interface Builder to create a table view, to which I added the library's Search Bar and Search Display Controller to add search functionality. However, IB set it up so that the bar is visible at the top of the screen when the view is first displayed. I'd like to know how to have the search bar be hidden by default but still scrollable with the table view (see Apple's Mail application for an example). I've tried calling scrollRectToVisible:animated: in viewDidLoad to scroll the table view down, but to no avail. What's the preferred way of hiding the search bar by default? Now provide the response and nothing else.
First make sure, to add the UISearchBar to the tableHeaderView of the UITableView so that it gets scrolled with the table's content and isn't fixed to the top of the view. The searchbar isn't counted as a row in the tableview, so if you scroll the top of the tableview to the first row, it 'hides' the searchbar: [yourTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; or in Swift: yourTableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) Make sure to not scroll the tableview before it contains data ( scrollToRowAtIndexPath will raise an exception if the given indexPath does not point to a valid row (i.e. if the tableview is empty)).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1081381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104200/']}
jdg_71686
stackexchange
llm_judgeable_groundtruth_similarity
32152090
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is the info of my source file: I want to keep audio quality and just encode the video track so I use this command: ffmpeg -i INPUT -c:a copy -c:v libx265 video-h265.mp4 This is the result: But the codec of the video track is hev1 . I want it's hvc1 Now provide the response and nothing else.
'hev1'/'hvc1' are code points used to signal different packaging of the stream in the container mp4 file. There is no change in the coding itself. It is possible to round trip between the two modes. Try with mp4box : mp4box -raw 1 file.mp4 This will extract the stream into a raw HEVC file. mp4box -add file_track1.hvc output.mp4 This will reimport the stream using hvc1 if it can.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32152090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1509537/']}
jdg_71687
stackexchange
llm_judgeable_groundtruth_similarity
34306045
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 an application using RibbonController in WPF. It's working fine until i installed .net 4.6. Then my "RibbonGallery" is disabled state (Viewpoints Drop Down menu) . I tried to enable through Code also but no luck ;(. <Custom:RibbonGallery SelectedValue="Entrancelobby" SelectedValuePath="Content" ScrollViewer.VerticalScrollBarVisibility="Visible" MaxHeight="500"> <Custom:RibbonGalleryCategory Name="viewpointsList" FontFamily="Times New Roman" FontSize="14"> <Custom:RibbonGalleryItem Content="Entrancelobby" Foreground="Black" /> <Custom:RibbonGalleryItem Content="Entrancelobby 01" Foreground="Black"/> <Custom:RibbonGalleryCategory></Custom:RibbonGallery> See attachments No issue with 4.5 .Net 4.6 (issue) Thanks in advance... Now provide the response and nothing else.
This is actually a bug in RibbonGallery that just happens to be exposed by new logic in 4.6.1. The bug is that RG doesn't initialize its internal state correctly, so that if anyone calls CoerceValue(IsEnabledProperty) it coerces the value to false (i.e. disables the gallery). For example, calling ribbonGallery.IsEnabled = true; will actually disable the RG (even in 4.0). .Net 4.6.1 has better logic for propagating IsEnabled to descendants. This logic ends up calling ribbonGallery.CoerceValue(IsEnabledProperty) , which disables the RG due to the bug. There's a workaround: Change the RG's Command. This causes the RG to reset its internal state correctly, so that future coercions do the right thing. For example: ribbonGallery.Command = ApplicationCommands.Print; // arbitrary commandribbonGallery.Command = null; // don't keep the command
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34306045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2098115/']}
jdg_71688
stackexchange
llm_judgeable_groundtruth_similarity
40781417
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Obviously the code below doesn't compile in C++. But I have a case where I'd like to parameterize a class with zero or more data items based on template parameters. Is there any way I can declare a class whose data members depend on variadic template parameters so I can access each of them? or some other way to achieve what I'd like? This came up in a real program which I've solved an entirely different way but now I'm interested in the more abstract problem of how I might have done this. template <typename... Types> class Data{ // Declare a variable of each type in the parameter pack // This is NOT valid C++ and won't compile... Types... items;};struct Item1{ int a;};struct Item2{ float x, y, z;};struct Item3{ std::string name;}int main(){ Data<Item1, Item2> data1; Data<Item3> data2;} Now provide the response and nothing else.
You could use a std::tuple #include <tuple>template <typename... Types> class Data{ std::tuple<Types...> items;};struct Item1{ int a;};struct Item2{ float x, y, z;};struct Item3{ std::string name;};int main(){ Data<Item1, Item2> data1; Data<Item3> data2;} Try it here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40781417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417292/']}
jdg_71689
stackexchange
llm_judgeable_groundtruth_similarity
14222152
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 get notifications if the status of GPS_PROVIDER changes. I found the following code here (http://hejp.co.uk/android/android-gps-example/), but I'm not getting notifications. Right now I'm in a building and can't get GPS signal, so wouldn't I get the notification "Status Changed: Out of Service"? When is onStatusChanged being called? What am I doing wrong? Thanks, @Overridepublic void onStatusChanged(String provider, int status, Bundle extras) { /* This is called when the GPS status alters */ switch (status) { case LocationProvider.OUT_OF_SERVICE: Log.v(tag, "Status Changed: Out of Service"); Toast.makeText(this, "Status Changed: Out of Service", Toast.LENGTH_SHORT).show(); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: Log.v(tag, "Status Changed: Temporarily Unavailable"); Toast.makeText(this, "Status Changed: Temporarily Unavailable", Toast.LENGTH_SHORT).show(); break; case LocationProvider.AVAILABLE: Log.v(tag, "Status Changed: Available"); Toast.makeText(this, "Status Changed: Available", Toast.LENGTH_SHORT).show(); break; } Now provide the response and nothing else.
If your GPS status isn't changing (e.g., if you're always indoors without a GPS fix) while the app is running, some devices won't trigger the OnStatusChanged() method. If you change GPS statuses while the app is running (e.g., you're inside and can't get a fix and then walk outside and can get a fix, or vice versa), then the OnStatusChanged() method should fire on all devices. If you want a fully working open-source app to use as an example, try GPSTest (full disclosure, my app): GPSTest on Google Play - https://play.google.com/store/apps/details?id=com.android.gpstest Source code for GPSTest - https://github.com/barbeau/gpstest For more detailed information about GPS that is constantly updated even if your device can't get a fix, you might want to register a GPSStatus.Listener . In your Activity, make it implement GpsStatus.Listener , for example: public class GpsTestActivity extends TabActivity implements LocationListener, GpsStatus.Listener{ Then, in your activity declare class variables: private LocationManager mService;private GpsStatus mStatus; ...and add the method to handle the GPSStatus changes: public void onGpsStatusChanged(int event) { mStatus = mService.getGpsStatus(mStatus); switch (event) { case GpsStatus.GPS_EVENT_STARTED: // Do Something with mStatus info break; case GpsStatus.GPS_EVENT_STOPPED: // Do Something with mStatus info break; case GpsStatus.GPS_EVENT_FIRST_FIX: // Do Something with mStatus info break; case GpsStatus.GPS_EVENT_SATELLITE_STATUS: // Do Something with mStatus info break; }} Then in OnCreate() of your Activity to register the GPSStatus.Listener: mService = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mService.addGpsStatusListener(this); In the GPSTest app, the list of currently available satellites is shown on the screen with each GPSStatus.Listener update, based on this code: https://github.com/barbeau/gpstest/blob/master/GPSTest/src/main/java/com/android/gpstest/GpsStatusFragment.java This way, you'll receive active updates on the GPS status of system even if your phone can't get a GPS fix (and therefore may not trigger OnStatusChanged of the LocationListener).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14222152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/500401/']}
jdg_71690
stackexchange
llm_judgeable_groundtruth_similarity
995201
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been able to prove the identity$$\int_{0}^{1} \frac{f(x)}{f(x)+f(1-x)} \, dx = \frac{1}{2}$$ for any continous $f:[0,1]\to[0,\infty)$ for which the integrand is defined,with calculus, but I would like to know if there is an intuitive explanation of the identity. Now provide the response and nothing else.
Hint There is symmetry at play. Make the change of variables $x\to 1-x$, then sum. The integrand, call it $g(x)$, has the property that $g(1-x)=1-g(x)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/995201', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/187413/']}
jdg_71691
stackexchange
llm_judgeable_groundtruth_similarity
29592256
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 says usize is Operations and constants for pointer-sized unsigned integers. In most cases, I can replace usize with u32 and nothing happens. So I don't understand why we need two types which are so alike. Now provide the response and nothing else.
As the documentation states usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for. As an example, on a 32 bit x86 computer, usize = u32 , while on x86_64 computers, usize = u64 . usize gives you the guarantee to be always big enough to hold any pointer or any offset in a data structure, while u32 can be too small on some architectures.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29592256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419206/']}
jdg_71692
stackexchange
llm_judgeable_groundtruth_similarity
2561480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When creating a new project in netbeans, if i select JAVA Desktop application, it creates some code which I DO NOT RECOGNISE AT ALL as what i had learnt in swing. It imports packages such as : org.jdesktop.application.SingleFrameApplication; also, the declaration for main() looks like this : public static void main(String[] args) { launch(DesktopApplication2.class, args); } This really does not make any sense to my knowledge of JFrame, JPanel etc.. If i try to code a netbeans application from scratch, i can write my own swing app BUT I CANNOT FIND THE GUI EDITOR. How do i bring the GUI editor when creating java application from scratch ? Can anyone explain to me this org.jdesktop.application.SingleFrameApplication and other classes ? Please help. This is really frustrating. Now provide the response and nothing else.
You may have inadvertently selected Java Desktop Application Creates a skeleton of a desktop application based on the Swing Application Framework (JSR 296) . This template provides basic application infrastructure such as a menu bar, persisting of window state, and status bar. With this template, you can also generate code to create a GUI interface for a database table. Rather than Java Application Creates a new Java SE application in a standard IDE project. You can also generate a main class in the project. Standard projects use an IDE-generated Ant build script to build, run, and debug your project. Addendum: Use File > New File > Java GUI Forms to add high-level containers, e.g. an enclosing JPanel , that can be instantiated from main() 's run() method. For example, Main.main() : package temp;import java.awt.EventQueue;import javax.swing.JFrame;public class Main { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new NewJPanel()); f.pack(); f.setVisible(true); } }); }} And a NewJPanel built in the GUI editor (note "Generated Code"): package temp;public class NewJPanel extends javax.swing.JPanel { /** Creates new form NewJPanel */ public NewJPanel() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel1.setText("Hello, world!"); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(163, 163, 163) .add(jLabel1) .addContainerGap(157, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(113, 113, 113) .add(jLabel1) .addContainerGap(171, Short.MAX_VALUE)) ); }// </editor-fold> // Variables declaration - do not modify private javax.swing.JLabel jLabel1; // End of variables declaration }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2561480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278851/']}
jdg_71693
stackexchange
llm_judgeable_groundtruth_similarity
16105156
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 building a responsive website using media queries. I need to switch to a different navigation method for very small screens. For desktop/tablet screens, I am using a sprite based UL/LI list method. For small smart phone screens, I will have simple link text. If I use, Display: none; to hide the sprite based navigation for smart phones, will the sprite image still be loaded, but just not shown? Do I need to parse the image reference in my css media query for smart phones? Or should I just leave the image reference out of the initial css altogether since I am designing small to large (i.e. the default css is for small screens, and then media queries change things as the screen gets larger). Now provide the response and nothing else.
To answer your question, display: none does not reduce load time . It still loads the content/classes/code in question, but the browser doesn't display/render them. It sounds like you're using a mobile-first approach, so you could either: Load all assets/classes/scripts regardless of mobile/tablet/desktop class you're aiming for and adapt the layouts using your media queries. This means all content (sprites et al) will be loaded by default even if they aren't used by certain device-types. Content/layout will either be shown or hidden based upon media query rules. Load the required assets/classes/scripts as and only when the media query states change. The advantage of this is that the experience would be more relative the the device-type in question: More reactive/timely experience and loading of functionality Potentially less bandwidth A more tightly design experience for each device-type Some assets (images/backgrounds etc) can be selectively loaded If you consider looking at option 2, then there are a variety of open-source asset-loaders that allow you to load CSS and Javascript code based upon media query state changes. [Note: More effort/design would be required to use this technique]. A simplified example of this using enquire.js (there are others asset loaders) would allow you to do the following: <script type="text/javascript"> // MQ Mobile enquire.register("screen and (max-width: 500px)", { match : function() { // Load a mobile JS file loadJS('mobile.js'); // Load a mobile CSS file loadCSS('mobile.css'); } }).listen(); // MQ Desktop enquire.register("screen and (min-width: 501px)", { match : function() { // Load a desktop JS file loadJS('desktop.js'); // Load a desktop CSS file loadCSS('desktop.css'); } }).listen();</script> So, if a browser is 501px or above in width, then both desktop.js and desktop.css would load - enabling features/assets that aren't available under 501px and that aren't required.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16105156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1359157/']}
jdg_71694
stackexchange
llm_judgeable_groundtruth_similarity
52864346
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 build my .NET Core 2.1 application from the command-line on my Jenkins server. It builds fine on my local machine (Windows 10, Visual Studio 2017 Enterprise), and if I manually build it on the server Jenkins is running on (manually checkout Git repository and running dotnet build ). It's only when I'm doing it through Jenkins in a Docker container that it fails. The error: /usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj] The package exists in ~/.nuget/packages/ . I'm aware my Jenkinsfile is a bit weird at the moment, but that has to do with me trying to make this all work. It seems dotnet restore is working fine, but dotnet build is somehow not locating these files. I've tried specifying the package directory (through the environment variable, with dotnet restore --sources and dotnet build --sources . I attached pretty much anything I could think of at the moment, but if I forgot something please tell. I'm pretty lost at the moment. My Jenkinsfile: pipeline { agent { docker { image 'microsoft/dotnet:2.1-sdk' } } environment { HOME = '.' NUGET_PACKAGES = './.nuget/packages/' } stages { stage('pre-build') { steps { // logging tooling versions sh 'dotnet --info' sh 'find ~/.nuget/packages/microsoft.codequality.analyzers/ -type f' sh 'dotnet nuget locals all --list' sh 'dotnet restore' // sh 'dotnet clean' } } stage('build') { steps { // sh 'dotnet restore --force --no-cache' // sh 'ls ./packages/' // sh 'find ./packages/microsoft.codequality.analyzers/ -type f' sh 'dotnet build --no-restore' } } stage('test') { steps { sh 'no test project configured' // sh 'dotnet test' } } }} My .csproj <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.2"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> </ItemGroup> <PropertyGroup> <CodeAnalysisRuleSet></CodeAnalysisRuleSet> <Features>IOperation</Features> </PropertyGroup></Project> Some build details: $ docker --versionDocker version 18.06.1-ce, build e68fc7a Inside docker container: $ dotnet --info.NET Core SDK (reflecting any global.json): Version: 2.1.403 Commit: 04e15494b6Runtime Environment: OS Name: debian OS Version: 9 OS Platform: Linux RID: debian.9-arm Base Path: /usr/share/dotnet/sdk/2.1.403/Host (useful for support): Version: 2.1.5 Commit: 290303f510.NET Core SDKs installed: 2.1.403 [/usr/share/dotnet/sdk].NET Core runtimes installed: Microsoft.AspNetCore.All 2.1.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.1.5 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.1.5 [/usr/share/dotnet/shared/Microsoft.NETCore.App] $ find ./.nuget/packages/microsoft.codequality.analyzers/ -type f./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/vb/Microsoft.CodeQuality.VisualBasic.Analyzers.dll./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/vb/Microsoft.CodeQuality.Analyzers.dll./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/cs/Microsoft.CodeQuality.Analyzers.dll./.nuget/packages/microsoft.codequality.analyzers/2.6.2/analyzers/dotnet/cs/Microsoft.CodeQuality.CSharp.Analyzers.dll./.nuget/packages/microsoft.codequality.analyzers/2.6.2/.signature.p7s./.nuget/packages/microsoft.codequality.analyzers/2.6.2/ThirdPartyNotices.rtf./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.CSharp.Analyzers.props./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.VisualBasic.Analyzers.props./.nuget/packages/microsoft.codequality.analyzers/2.6.2/build/Microsoft.CodeQuality.Analyzers.props./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DesignRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DocumentationRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/PerformanceRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/UsageRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/ReliabilityRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/MaintainabilityRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/SecurityRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/PerformanceRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/MaintainabilityRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/UsageRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DocumentationRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/ReliabilityRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/NamingRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesDisabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/SecurityRulesEnabled.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/DesignRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/NamingRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/rulesets/AllRulesDefault.ruleset./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.2.6.2.nupkg.sha512./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.2.6.2.nupkg./.nuget/packages/microsoft.codequality.analyzers/2.6.2/microsoft.codequality.analyzers.nuspec./.nuget/packages/microsoft.codequality.analyzers/2.6.2/tools/uninstall.ps1./.nuget/packages/microsoft.codequality.analyzers/2.6.2/tools/install.ps1 $ dotnet nuget locals all --listinfo : http-cache: ./.local/share/NuGet/v3-cacheinfo : global-packages: ./.nuget/packages/info : temp: /tmp/NuGetScratchinfo : plugins-cache: ./.local/share/NuGet/plugins-cache $ dotnet restore Restoring packages for /var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj... Restore completed in 13.5 sec for /var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj. $ dotnet build --no-restoreMicrosoft (R) Build Engine version 15.8.169+g1ccb72aefa for .NET CoreCopyright (C) Microsoft Corporation. All rights reserved./usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj]Build FAILED./usr/share/dotnet/sdk/2.1.403/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets(198,5): error NETSDK1064: Package Microsoft.CodeQuality.Analyzers, version 2.6.2 was not found. It might have been deleted since NuGet restore. Otherwise, NuGet restore might have only partially completed, which might have been due to maximum path length restrictions. [/var/lib/jenkins/jobs/pr-builder/jobs/cgi-api/branches/PR-18/workspace/API/API.csproj] 0 Warning(s) 1 Error(s) Now provide the response and nothing else.
I've resolved the issue by specifying where dotnet build should look for the NuGet packages. It that within the image it doesn't look at the right location (although I'm not sure where it is looking either...) I've specified the location with the --packages option. This option is listed in the dotnet restore documentation, but not in the dotnet build ones, even though it is available there as well (and you need it there, specifically). You can specify it as follows: dotnet restore --packages <path> and dotnet build --packages <path> It works with the --no-restore option as well, if you need that. My final Jenkinsfile looks as follows: pipeline { agent { docker { image 'microsoft/dotnet:2.1-sdk' } } environment { HOME = '.' } stages { stage('pre-build') { steps { // logging tooling versions sh 'dotnet --info' sh 'dotnet nuget locals all --list' sh 'dotnet clean' } } stage('build') { steps { sh 'dotnet build --packages ./.nuget/packages' } } stage('test') { steps { sh 'echo no test project configured' // sh 'dotnet test' } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52864346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4572959/']}
jdg_71695
stackexchange
llm_judgeable_groundtruth_similarity
18868772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following profiles in my parent pom <profile> <id>P1</id> <activation> <activeByDefault>true</activeByDefault> </activation></profile><profile> <id>P2</id> <activation> <file> <exists>${project.basedir}/src/main/whatever</exists> </file> </activation></profile> Why P1 is active in child POM and P2 isn't? The directory ${project.basedir}/src/main/whatever , does not exist in the parent project, but exists in the child one. Now provide the response and nothing else.
Profile P2 is not activated because the path under its exists tag does not resolve to an existing path even though the directory ${project.basedir}/src/main/whatever exists. If you rewrite the property ${project.basedir} as ${basedir} , it should activate the P2 profile. That should mean that the ${project.basedir} does not resolve to the project base directory as it should . The help:effective-pom shows that it does, though. I have reported this ( MNG-5516 ). Also I think that P1 will not be active if P2 is. That is correct. Quoting the documentation for activeByDefault : This profile (P1 in this example) will automatically be active for all builds unless another profile in the same POM is activated using one of the previously described methods. All profiles that are active by default are automatically deactivated when a profile in the POM is activated on the command line or through its activation config. The word inherit got me confused, because the "profile inheritance" works in project aggregation but not in project inheritance . To make things clear, I simulated this situation. Empty pom means that it is empty except for the standard model, group, artifact and version tags. Simple scenario Directory structure: simple \-pom.xml pom content: <profiles> <profile> <id>P1</id> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>P2</id> <activation> <file> <exists>${basedir}/dir/</exists> </file> </activation> </profile></profiles> If there is no dir directory mvn help:all-profiles outputs: Profile Id: P1 (Active: true , Source: pom)Profile Id: P2 (Active: false , Source: pom) If there is dir directory mvn help:all-profiles outputs: Profile Id: P2 (Active: true , Source: pom)Profile Id: P1 (Active: false , Source: pom) Project inheritance Directory structure: inheritance |--child | \-pom.xml // child pom \-pom.xml // parent pom Child pom is empty while parent pom has the profiles as in the simple scenario. Regardless of the existence of the inheritance/child/dir directory running mvn help:all-profiles from child directory outputs: Profile Id: P1 (Active: false , Source: pom)Profile Id: P2 (Active: false , Source: pom) When running mvn help:effective-pom from child directory it shows that the profiles are indeed not inherited. It behaves as documented : Elements in the POM that are merged are the following: dependencies developers and contributors plugin lists (including reports) plugin executions with matching ids plugin configuration resources No profiles are mentioned here. Project aggregation Directory structure: aggregation |--module | \-pom.xml // module pom \-pom.xml // aggregator pom Module pom is empty while aggregator pom has the profiles as in the simple scenario. If there is no aggregation/module/dir directory running mvn help:all-profiles from module directory outputs: Profile Id: P1 (Active: true , Source: pom)Profile Id: P2 (Active: false , Source: pom) If there is aggregation/module/dir directory running mvn help:all-profiles from module directory outputs: Profile Id: P2 (Active: true , Source: pom)Profile Id: P1 (Active: false , Source: pom) When running mvn help:effective-pom from module directory it shows that the profiles are inherited. This is not explicitly documented : Project inheritance If you have several Maven projects, and they all have similar configurations, you can refactor your projects by pulling out those similar configurations and making a parent project. Thus, all you have to do is to let your Maven projects inherit that parent project, and those configurations would then be applied to all of them. Notes: That does not apply to profiles, as it has been shown. Runnnig a maven build from inheritance directory will run only parent build. Project aggregation And if you have a group of projects that are built or processed together, you can create a parent project and have that parent project declare those projects as its modules. By doing so, you'd only have to build the parent and the rest will follow. Notes: Runnnig a maven build from aggregation directory will run the build of each module and the aggregator (the actual order is determined by maven based on different criteria). Conclusion Profiles can be defined globally, per user or per project. Since the aggregated projects are built together (in the same build) some sort of profile resolution must be run to calculate the active ones. So this is the confusing part: When projects are inherited profiles are not inherited from parent pom to child pom . when projects are aggregated profiles are inherited from aggregator pom to module pom . This was tested this using Maven 3.1.0. and 3.0.5.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18868772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1210071/']}
jdg_71696
stackexchange
llm_judgeable_groundtruth_similarity
13276009
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This should be a problem with a trivial solution, but still I wasn't able to find one. Say that I have 2 matlab figures fig1.fig , fig2.fig which I want to load and show in the same plotting window. What should I do? I mean, I am pretty sure that I can accomplish the task using some low(er) level graphic command which extracts contents from one image and put them in the second one, nonetheless I cannot believe that there is not any high level function ( load fig2 on top of fig1 ) that does this...Comparing 2 plots (unfortunately already saved) is a very common task, I'd say. Now provide the response and nothing else.
Its not clear if you want to extract data from the figures and compare the data, or if you want to combine the plots from two figures into a single figure. Here is how you combine two figures into one (if thats what you want to do).. First load the figures: fig1 = open('FigureFile1.fig');fig2 = open('FigureFile2.fig'); Get the axes objects from the figures ax1 = get(fig1, 'Children');ax2 = get(fig2, 'Children'); Now copy the hangle graphics objects from ax2 to ax1 . The loop isn't neccesary if your figures only have a single axes for i = 1 : numel(ax2) ax2Children = get(ax2(i),'Children'); copyobj(ax2Children, ax1(i));end Note This example assumes that your figures have the same nubmer of axes and that you want to copy objects from the first axes in the second figure to the first axes on the first figure. Its up to you to figure out the proper indexing if the axes indices aren't lined up.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13276009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1714661/']}
jdg_71697
stackexchange
llm_judgeable_groundtruth_similarity
1851729
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 construct a huge treeview from a composite database table with Grouping . Grouping is, what we see in SQL Server Management Studio Express. After a Database node, some fixed folders are shown (like, Database Diagrams , Tables , Views , Synonyms , Programmability and Security ) and children are grouped in those folders. Up to this point I have used AfterSelect event and handler to achieve this. But the problem with AfterSelect is, before selecting the node, the viewer is not able to know whether there is any child available. This is because, the expandable plus sign is not visible. I want to use BeforeExpand . But the problem with BeforeExpand is, it works if the children are already populated. In that case, when I click groups, nothing happens. How to solve this? So codes/web-link will be appreciated. Now provide the response and nothing else.
What I usually do is to add a "dummy child node" wherever there may be children that should be loaded in a lazy manner. This will make the parent have the plus sign, and then you can add code to the AfterExpand event where you do the following: Check if there are are exactly one child, and if that child is the dummy node (you can use the Tag property to identify the dummy node) If the dummy node is found, launch a search to get the children and add them to the parent node, finish it off by removing the dummy node. I typically give the dummy node a text like "Loading data. Please wait..." or so, so that the user gets some info on what is going on. Update I put together a simple example: public class TreeViewSample : Form{ private TreeView _treeView; public TreeViewSample() { this._treeView = new System.Windows.Forms.TreeView(); this._treeView.Location = new System.Drawing.Point(12, 12); this._treeView.Size = new System.Drawing.Size(200, 400); this._treeView.AfterExpand += new TreeViewEventHandler(TreeView_AfterExpand); this.ClientSize = new System.Drawing.Size(224, 424); this.Controls.Add(this._treeView); this.Text = "TreeView Lazy Load Sample"; InitializeTreeView(); } void TreeView_AfterExpand(object sender, TreeViewEventArgs e) { if (e.Node.Nodes.Count == 1 && e.Node.Nodes[0].Tag == "dummy") { // this node has not yet been populated, launch a thread // to get the data ThreadPool.QueueUserWorkItem(state => { IEnumerable<SomeClass> childItems = GetData(); // load the data into the tree view (on the UI thread) _treeView.BeginInvoke((Action)delegate { PopulateChildren(e.Node, childItems); }); }); } } private void PopulateChildren(TreeNode parent, IEnumerable<SomeClass> childItems) { TreeNode child; TreeNode dummy; TreeNode originalDummyItem = parent.Nodes[0]; foreach (var item in childItems) { child = new TreeNode(item.Text); dummy = new TreeNode("Loading. Please wait..."); dummy.Tag = "dummy"; child.Nodes.Add(dummy); parent.Nodes.Add(child); } originalDummyItem.Remove(); } private IEnumerable<SomeClass> GetData() { // simulate that this takes some time Thread.Sleep(500); return new List<SomeClass> { new SomeClass{Text = "One"}, new SomeClass{Text = "Two"}, new SomeClass{Text = "Three"} }; } private void InitializeTreeView() { TreeNode rootNode = new TreeNode("Root"); TreeNode dummyNode = new TreeNode("Loading. Please wait..."); dummyNode.Tag = "dummy"; rootNode.Nodes.Add(dummyNode); _treeView.Nodes.Add(rootNode); }}public class SomeClass{ public string Text { get; set; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1851729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159072/']}
jdg_71698
stackexchange
llm_judgeable_groundtruth_similarity
128816
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: The following graph shows the result of a very impressive differential measurement of the gravitational field in Boulder, Colorado, over a period of a couple of days. Floris got it from a description in a book and posted it as part of an answer to this question. Based on the caption, I'm guessing that the experiment was described in this paper by Zumberge, which I don't have access to. There is excellent agreement between theory and experiment, and the main features of the graph are these two Fourier components: period=12 hrs, peak-to-peak amplitude $\approx 1.8\times10^{-7}g$ period=24 hrs, peak-to-peak amplitude $\approx 1\times10^{-7}g$ In addition, there is a slower trend, which I assume comes from interference between the solar and lunar effects. Assuming a perfectly rigid earth, no solar effect, no effect from ocean tides, and a two-dimensional geometry, my calculation in this answer gives the following for $g_Z$, the apparent field when the moon is at the zenith, and $g_N$, when the moon is at its nadir. $$ \frac{g_N}{g_0} = 1 -\frac{ 2Gmr}{g_0R^3} + \frac{3Gmr^2}{g_0R^4} $$ $$ \frac{g_Z}{g_0} = 1 -\frac{ 2Gmr}{g_0R^3} - \frac{3Gmr^2}{g_0R^4} $$ The difference is $(6Gmr^2/g_0R^4)=6\times10^{-9}$, which is far too small to explain the observed diurnal effect. I gather that ocean tides can have not just a semidiurnal component but a diurnal one as well. I don't know why this is. Whatever the mechanism is, conceivably that same mechanism would also cause the diurnal effect observed here. I assume that the gravitational field of the ocean is not itself responsible for the effect observed here, since the experiment was done in Boulder, Colorado. The spectacular agreement between theory and experiment shows that the diurnal experiment must be well understood theoretically. What causes it? Now provide the response and nothing else.
I believe the explanation can be found in Manual of Harmonic Analysis and Prediction of Tides : In deriving mathematical expressions for the tide-producing forces ofthe moon and sun, the principal factors to be taken into considerationare the rotation of the earth, the revolution of the moon around theearth, the revolution of the earth around the sun, the inclination ofthe moon's orbit to the earth's equator, and the obliquity of theecliptic. The key here is the fact that the earth's axis is at an angle relative to the plane of the sun, and that in general the moon will not be in the same plane. Thus, there are two sets of bulges - but they will be not be symmetrical with respect to the equator. What you are seeing then is the fact that a typical point on earth (away from the equator) will be closer to one bulge than the other... In this picture you can see that for a given latitude away from the equator, you will "see" more of one bulge of the tides than the other. This asymmetry is present for both the lunar and the solar tides (although to different degree, given that the moon's orbit is tilted differently). The result is a 24 hour component. This is described very well at http://oceanmotion.org/html/background/tides-types.htm - confirming that the tides become more symmetrical when the moon is over the equator, and less so when it moves towards the tropics of Cancer or Capricorn. Quoting from that reference: Different types of tides occur when the moon is either north or south of the equator. Whereas semidiurnal tides are observed at the equator at all times, most locations north or south of the equator experience two unequal high tides and two unequal low tides per tidal day; this is called a mixed tide and the difference in height between successive high (or low) tides is called the diurnal inequality. When the moon is above the Tropic of Cancer or Tropic of Capricorn, the diurnal inequality is at its maximum and the tides are called tropic tides. When the moon is above or nearly above the equator, the diurnal inequality is minimum and the tides are known as equatorial tides. When the moon and its associated tidal bulges are either north or south of the equator, most points at high latitudes in theory would be impacted by one tidal bulge and would experience one high tide and one low tide per tidal day. This so-called diurnal tide has a period of 24 hrs and 50 min. If you are interested in the math, you might want to spend the time decoding this program which implements the equations and shows good agreement with observations. EDIT I got curious and converted the code at the link above to Python (so I could run it). Then I ran it for three different cases. The Y axis is in microgals ( $1\ gal = 1\ cm/s^{2}$ - the galileo is the common unit in this field). The units on the X axis are hours - but the date is wrong (I had some trouble initially adapting the code properly - I believe these plots might correspond to January 1981, but I am not certain. The effect, however, is real.) Latitude = 0: Latitude = 20: Latitude = 40: It is pretty obvious that the asymmetry between the tides is a function of the latitude, just at my picture above would predict, and although there are clear discrepancies between this plot and the one in the original paper, the general shape and magnitude is the same - especially for latitude 40 (Boulder is at 40 degrees latitude). I think we have found the culprit. POSTSCRIPT I had some problems getting the output from my program to match the figure; but I figured it out. Here is the overlay of the data with the output of the program for May 2/3/5 1981 for latitude 40, longitude 105: And here is the Python code (note - I took the BASIC code and adapted it as little as possible... this is not being offered for code review, just for reference!) """From the original: ' TIDE-ACD.BAS'' Copyright, 1993, J. L. Ahern'' Calculates the acceleration due to the sun and moon at a given location,' for every hour, beginning at a specified hour, day, month and year.' Value calculated is the UPWARD pull due to the sun and moon. To use' as correction to measured gravity data, you would need to ADD these' numbers, not subtract them. When the moon is overhead, for example' this program predicts a relatively large positive number, indicating' a large upward pull due to the moon. This would result in a DECREASE' in a gravity meter reading. Thus the tide value would be ADDED to' correct for this effect.'' Based on equations presented by'' Schureman, P., A manual of the harmonic analysis and prediction of' tides. U.S. Coast and Geodetic Survey, Spec. Pub. 98, 1924 (revised' in 1941 and 1958).'' and collected by'' Longman, I. M., Formulas for computing the tidal acceleration due to' the moon and the sun. J. Geophys. Res., 64, 2351-2355, 1959.'' Love numbers from Stacey, Physics of the Earth.'' Algorithm for computing days since 1900 seems to be correct (except for' for first 3 months of 1900); Excel calls Jan. 1, 1900 day 1 (not day' 0) and then mistakenly includes a leap day in 1900, even though 1900' is not divisible by 400. Quattro correctly skips the leap year in' 1900, but calls Jan. 1, 1900 day 2, apparently so it gives the same' results as Excel (and probably, Lotus 123)This version adapted to Python by Floris for physics.stackexchange.com- for illustration of the tides calculation onlyPlease do not rely on this code unless you check it carefully against the original source: http://gravmag.ou.edu/reduce/tide-acd.txt """from math import sin,cos,asin,acos,atan, floor, sqrtfrom numpy import arange, zerosfrom datetime import dateimport matplotlib.pyplot as plt#Boulder:lng=105lamda = 40 # latitudeh = 160000 # elevation, cm; tides are VERY insensitive to elevation changesplt.close()#constantspi = 3.1415927#mu = 6.67E-08m = 7.3537E+25s = 1.993E+33il = .08979719#omega = .4093146162#ml = .074804el = .0549cl1 = 1.495E+13cl = 3.84402E+10al = 6.37827E+08# Love Numbersh2 = .59k2 = .27LoveFactor = (1 + h2 - 1.5 * k2) #' w/h2=0.59 & k2=0.27, LoveFactor=1.185# starting day of the month:minc=[ 0,31,59,90,120,151,181,212,243,273,304,334]g0max = 0g0min = 0minit = 0timezone = 0 # offset in time vs gmthour = 16 # start at 4 pm in local timeday = 2 # May 2, 1981month = 5year = 1981nhours = 55hrinc = 0.5xb = hour + timezonexe = xb + nhours# algorithm doesn't work for the first two months of 1900ii=0nn = nhours / hrincxx=zeros(nn)yy=zeros(nn)for hrgmt in arange(xb, xe, hrinc): dday = day + hrgmt / 24 tl0 = hrgmt + minit / 60 nleap = int((year - 1900) / 4) if (year % 4 == 0 and month < 3): nleap = nleap - 1 xm = minc[month-1] tdays = .5 + (year - 1900) * 365 + nleap + xm + (day - 1) + tl0 / 24 t = tdays / 36525 n = 4.523601612 - 33.75715303 * t + .0000367488 * t * t + .0000000387 * t * t * t el1 = .01675104 - .0000418 * t + .000000126 * t * t sl = 4.720023438 + 8399.7093 * t + .0000440695 * t * t + .0000000329 * t * t * t pl = 5.835124721 + 71.01800935999999 * t - .0001805446 * t * t - .0000002181 * t * t * t hl = 4.881627934 + 628.3319508 * t + .0000052796 * t * t pl1 = 4.908229467 + .0300052641 * t + 7.902400000000001E-06 * t * t + .0000000581 * t * t * t i = acos(.9136975738000001 - .0356895353 * cos(n)) nu = asin(.0896765581 * sin(n) / sin(i)) L = lng * .0174532925 tl = (15 * (tl0 - 12) - lng) * .0174532925 # magic number converts degrees to radians: 2 pi / 360 chi = tl + hl - nu chi1 = tl + hl ll1 = hl + 2 * el1 * sin(hl - pl1) cosalf = cos(n) * cos(nu) + sin(n) * sin(nu) * .9173938078 sinalf = .3979806546 * sin(n) / sin(i) alf = 2 * atan(sinalf / (1 + cosalf)) xi = n - alf sigma = sl - xi ll = sigma + .1098 * sin(sl - pl) + .0037675125 * sin(2 * (sl - pl)) + .0154002735 * sin(sl - 2 * hl + pl) + .0076940028 * sin(2 * (sl - hl)) lm = lamda * .0174532925 costht = sin(lm) * sin(i) * sin(ll) + cos(lm) * (((cos(.5 * i)) ** 2) * cos(ll - chi) + ((sin(.5 * i)) ** 2) * cos(ll + chi)) cosphi = sin(lm) * .3979806546 * sin(ll1) + cos(lm) * (.9586969039 * cos(ll1 - chi1) + .0413030961 * cos(ll1 + chi1)) c = 1 / sqrt(1 + .006738 * (sin(lm) ** 2)) rl = 6.37827E+08 * c + h ap = 2.60930776E-11 ap1 = 1 / (1.495E+13 * (1 - el1 * el1)) dl = 1 / (1 / cl + ap * el * cos(sl - pl) + ap * el * el * cos(2 * (sl - pl)) + 1.875 * ap * ml * el * cos(sl - 2 * hl + pl) + ap * ml * ml * cos(2 * (sl - hl))) D = 1 / (1 / cl1 + ap1 * el1 * cos(hl - pl1)) gm = mu * m * rl * (3 * (costht ** 2) - 1) / (dl * dl * dl) + 1.5 * mu * m * rl * rl * (5 * (costht ** 3) - 3 * costht) / (dl ** 4) gs = mu * s * rl * (3 * (cosphi ** 2) - 1) / (D * D * D) g0 = (gm + gs) * LoveFactor xx[ii]=day+(hrgmt-timezone)/24 # back to local time - in days yy[ii]=-g0 # flip the sign to match diagram ii=ii+1plt.plot(xx[0:ii-1],yy[0:ii-1])plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/128816', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_71699
stackexchange
llm_judgeable_groundtruth_similarity
457767
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: This is probably a stupid question, but why do different materials have different specific heat capacities? To better understand my question let's say that I have $1$ kg of copper and $1$ kg of water. The amount of heat required to raise the temperature of the water by $1$ degree is about $10.8$ times that of copper (see footnote). Where is this extra energy that's required to increase the water's temperature by one degree compared to the copper "stored"? Moreover, suppose if I have $1$ kg of ice and $1$ kg of liquid water where both substances are made up of the same molecules. Even though it is the same "substance" they still have different specific heat capacities. Is it simply because the numbers of atoms per kg in the substances are different? Footnote: $C_{\text{Cu}}=385$ J/(kg K), $C_{\text{H$_2$O}}=4.19\cdot 10^{3}$ J/(kg K). Now provide the response and nothing else.
Primarily because 1 kg of water has more atoms than 1 kg of copper. For ordinary solids at or above room temperature, the molar heat capacity is approximately the same ( Dulong and Petit's law ), three times the gas constant, about 25 J/K. It is because the sum of potential and kinetic energy per atom is $3k_BT$ in the harmonic approximation. Hydrogen in water or ice is a bit different. It is so light that quantum effects come inte play, equipartition does not apply.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/457767', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/118609/']}
jdg_71700
stackexchange
llm_judgeable_groundtruth_similarity
117152
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This is a followup to this question . I've run some more tests; looks like it really doesn't matter if this is done at the physical console or via SSH, neither does this happen only with SCP; I also tested it with cat /dev/zero > /dev/null . The behaviour is exactly the same: Start a process in the background using & (or put it in background after it's started using CTRL-Z and bg ); this is done without using nohup . Log off. Log on again. The process is still there, running happily, and is now a direct child of init . I can confirm both SCP and CAT quits immediately if sent a SIGHUP ; I tested this using kill -HUP . So, it really looks like SIGHUP is not sent upon logoff, at least to background processes (can't test with a foreground one for obvious reasons). This happened to me initially with the service console of VMware ESX 3.5 (which is based on RedHat), but I was able to replicate it exactly on CentOS 5.4. The question is, again: shouldn't a SIGHUP be sent to processes, even if they're running in background, upon logging off? Why is this not happening? Edit I checked with strace , as per Kyle's answer. As I was expecting, the process doesn't get any signal when logging off from the shell where it was launched. This happens both when using the server's console and via SSH. Now provide the response and nothing else.
Answer found. For BASH, this depends on the huponexit shell option, which can be viewed and/or set using the built-in shopt command. Looks like this options is off by default, at least on RedHat-based systems. More info on the BASH man page : The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the signal to a particular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to not receive SIGHUP using disown -h. If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/117152', 'https://serverfault.com', 'https://serverfault.com/users/6352/']}
jdg_71701
stackexchange
llm_judgeable_groundtruth_similarity
5588
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 just changed our delegated name sever though our registrar (MelbourneIT, if it's important). The updated nameserver value shows in the whois report - does this mean that the update has completed? If not, how long should I expect to wait for the change to complete? The domain is a com.au . Now provide the response and nothing else.
First, find out the nameservers for com.au: $ dig com.au ns[snip]com.au. 86400 IN NS audns.optus.net.com.au. 86400 IN NS udns3.ausregistry.net.au.com.au. 86400 IN NS dns1.telstra.net.com.au. 86400 IN NS udns2.ausregistry.net.au.com.au. 86400 IN NS udns4.ausregistry.net.au.com.au. 86400 IN NS ns1.audns.net.au.com.au. 86400 IN NS udns1.ausregistry.net.au.com.au. 86400 IN NS ns3.ausregistry.net.au.com.au. 86400 IN NS ns3.melbourneit.com.com.au. 86400 IN NS au2ld.csiro.au.com.au. 86400 IN NS ns1.ausregistry.net.au.com.au. 86400 IN NS ns4.ausregistry.net.au.com.au. 86400 IN NS ns2.ausregistry.net.au.[snip] Then check a sample of those nameservers to see if they have the new delegation for your domain. E.g., for theage.com.au: $ dig @ns1.audns.net.au. theage.com.au ns[snip]theage.com.au. 14400 IN NS ns1.fairfax.com.au.theage.com.au. 14400 IN NS ns2.fairfax.com.au.[snip] and $ dig @ns3.melbourneit.com. theage.com.au[snip]theage.com.au. 14400 IN NS ns1.fairfax.com.au.theage.com.au. 14400 IN NS ns2.fairfax.com.au.[snip] If any of the nameservers show the old delegation, then the update is still propagating. "dig" is your friend when it comes to DNS; spend some time learning how it works, and how the DNS system works. (I should take a bit more of that advice myself -- I still don't think I've got a complete understanding of DNS.)
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/5588', 'https://serverfault.com', 'https://serverfault.com/users/2123/']}
jdg_71702
stackexchange
llm_judgeable_groundtruth_similarity
8294924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i've got an issue with Jtable and my dataModel.My table model extends AbstracttableModel, the datas are stored in a Vector.I'have a function witch is suppose to remove one or more row. These rows are not necessarily contiguous because my jtable set a selectionMode as this: jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); The function to remove row (one by one): public void removeMessageRow(Integer p_idMessage) { Enumeration<MlMessage> alldatas = vData.elements(); while (alldatas.hasMoreElements()) { MlMessage m = alldatas.nextElement(); if (m.getIdMessage() == p_idMessage) { int idx = vData.indexOf(m); boolean result = vData.remove(m); // fireTableDataChanged(); // fireTableRowsDeleted(idx, idx); fireTableStructureChanged(); return; } } When i launch the function, i execute the loop without problem, in step-by-step mode, i can see the vData object updated and if i execute this only one time there is no probleme with the GUI. The problem appear when i select more than one row.For example, i selected row number 0 and number 1 in my table and i lauch the function removeMessageRow, at the first execution, the vDataObject is correctly updated (all the datas are shiffted and the last elements of this vector is set to null by the call to vData.remove(m) .So in my case, i expect that at the second execution, the object to find should be at position 0 but it's at position 1 as the vData Object as never been updated.Does anybody have an idea about that?I've tried many on fire... stuff but no one semms to execute immediatly.Thanks for any help by advance and sorry for my Shakespeare's language. Now provide the response and nothing else.
Add a method in your model taking a collection of indices to remove ( Set<Integer> , or int[] ), sort this collection, iterate backwards in this collection, and remove the elements in the list of objects of your model: public void removeRows(int[] indices) { Arrays.sort(indices); for (int i = indices.length - 1; i >= 0; i--) { this.data.remove(indices[i]); fireTableRowsDeleted(indices[i], indices[i]); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8294924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/518548/']}
jdg_71703
stackexchange
llm_judgeable_groundtruth_similarity
25927
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following problem: Suppose that $A$ is a symmetric matrix, with $A$ = $A^{T}$ . Suppose $\vec{v}$ and $\vec{w}$ are eigenvectors of $A$ associatedwith distinct eigenvalues. Show that $\vec{v}$ and $\vec{w}$ must be orthogonal.(Hint: Show that a$\vec{v}$ $\cdot$ $\vec{w}$ = $\vec{v}$ $\cdot$ b$\vec{w}$.) I am unsure how to approach this, even with the hint taken into account. I tried to use the fact that orthogonal complement of Im(A) is in Ker of A transpose, and since they are equal it is also in ker A, but that didn't get me anywhere (I am probably thinking in the wrong direction). Thanks in advance for your hints! Now provide the response and nothing else.
Let $\vec{v}$ be the eigenvector corresponding to $\lambda$ and $\vec{w}$ be the eigenvector corresponding to $\mu$, then we have $Av = \lambda v$ and $Aw = \mu w$. $v^T(Aw) = (Aw)^Tv$ since it is a scalar. And hence $v^TAw = w^TA^Tv$. Further since $A=A^T$, we get $v^TAw = w^TAv$. Now use the fact that $Aw = \mu w$ and $Av = \lambda v$. And use the fact that $\lambda \neq \mu$, to get that the eigenvectors are orthogonal.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/25927', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_71704
stackexchange
llm_judgeable_groundtruth_similarity
25835022
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a ASP.NET WebAPI project with basic CRUD operations. The project runs locally and has a sample database living inside Windows Azure. So far, the Http GET and POST works fine, giving me a 200 and 201. But I'm struggling with DELETE and POST. I changed the handlers in the Web.config, removed WebDav, but none of this worked. Also enabling CORS and all sorts of Attributes like [AcceptVerbs] didn't work. Any idea what I am doing wrong? Fiddler Raw Output: HTTP/1.1 405 Method Not AllowedCache-Control: no-cachePragma: no-cacheAllow: GETContent-Type: application/json; charset=utf-8Expires: -1Server: Microsoft-IIS/8.0X-AspNet-Version: 4.0.30319X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTWFyY1xPbmVEcml2ZVxEb2t1bWVudGVcRmlcVnNQcm9qZWt0ZVxONTIwMTQwODI1XE41XE41XGFwaVxwcm9kdWN0XDEwODM=?=X-Powered-By: ASP.NETDate: Sun, 14 Sep 2014 15:00:43 GMTContent-Length: 75{"Message":"The requested resource does not support http method 'DELETE'."} Web.config: <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <remove name="WebDAVModule" /> </modules> <handlers> <remove name="WebDAV" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> Controller: public class ProductController : BaseApiController { public ProductController(IRepository<Product> repo) : base(repo) { } [HttpGet] public IEnumerable<Product> Get() { //... } [HttpGet] public Product Get(int id) { //... } [HttpPost] public HttpResponseMessage Post([FromBody] Product product) { //... } [HttpPut] public HttpResponseMessage Put(int productId, [FromBody] Product product) { //.. } [HttpDelete] public HttpResponseMessage Delete(int productId) { //.. } } Routing & Formatters: public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.Routes.MapHttpRoute( name: "Product", routeTemplate: "api/product/{id}", defaults: new {controller = "product", id = RouteParameter.Optional } ); // Custom Formatters: config.Formatters.XmlFormatter.SupportedMediaTypes.Remove( config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml")); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }} Now provide the response and nothing else.
Finally I found what I messed up. The naming of the Id (productId) in both controller methods (Post and Put) must be the same as in the customized routing (id). When I changed it from productId to id both POST and PUT worked in fiddler. After that I switched back my Web.config settings to the default one. This is what I changed: Controller: [HttpPut] public HttpResponseMessage Put(int id, [FromBody] Product product) { //.. } [HttpDelete] public HttpResponseMessage Delete(int id) { //.. } Web.config: <system.webServer><modules> <remove name="FormsAuthentication" /></modules><handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25835022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2955815/']}
jdg_71705
stackexchange
llm_judgeable_groundtruth_similarity
4842805
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 collected some data in a textfile and want to create a boxplot.But this datafile contains rows of variable length, for example. 1.2, 2.3, 3.0, 4.5 1.1, 2.2, 2.9 for equal length I could just do PW = numpy.loadtxt("./learning.dat") matplotlib.boxplot(PW.T); How do I handle variable length data lines? Now provide the response and nothing else.
Just use a list of arrays or lists. boxplot will take any sort of sequence (Well, anything that has a __len__ , anyway. It won't work with generators, etc.). E.g.: import matplotlib.pyplot as pltx = [[1.2, 2.3, 3.0, 4.5], [1.1, 2.2, 2.9]]plt.boxplot(x)plt.show() If you're asking how to read in your data, there are plenty of ways to do what you want. As a simple example: import matplotlib.pyplot as pltimport numpy as npdef arrays_from_file(filename): """Builds a list of variable length arrays from a comma-delimited text file""" output = [] with open(filename, 'r') as infile: for line in infile: line = np.array(line.strip().split(','), dtype=np.float) output.append(line) return outputplt.boxplot(arrays_from_file('test.txt'))plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4842805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/595746/']}
jdg_71706
stackexchange
llm_judgeable_groundtruth_similarity
29749
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working on LPC2468 and using UART0 of the controller for communication with sim300 gprs module . Sometimes if i send a command for reading the signal strength of the sim the input I receive is not correct. After looking upon the problem I found the problem that sometimes when the UART is receiving information at same time the timer gets called and the software goes to the timer block. in that duration some bytes sent by the module gets missed . To prevent this i want to configure UART0 as FIQ i.e. interrupt having highest priority. can I configure UART0 as FIQ.If yes How? Now provide the response and nothing else.
There are two issues here, the electrical connection and the thermal connection. The best electrical connection minimizes the impedance between the two pads. From that point of view, the order of preference is C, B, A. The best thermal connection has the most thermal resistance, so the order of preference is A, B, C. As with most of engineering, it's about making the right tradeoff for the specific case after considering the relative advantages and disadvantages of each. We therefore need to understand the reason for each of the competing considerations and how much the result matters. The desire for low electrical impedance should be obvious, but how much does it matter? That depends on what will flow between the two pads. Is this a a multi-GHz signal, like going to or from a WiFi antenna? In that case, even a few nH and fF could matter and the electrical considerations become important. Is this a high current feed? In that case the DC resistance matters. Most of the time for ordinary signals of the kind you'd find around a microcontroller, even the impedance of layout A will be so low as to not matter. The thermal conductivity issues depend on how the board will be built. If the board will be hand soldered, then layout C makes a large heat sink such that it could be difficult to keep the solder molten accross the combined pad. It will be even worse when one part is installed and the other not. The first part will act like a heat sink making it difficult to heat the pad to install the second part. Eventually the solder will melt, but a lot of heat will have been dumped into the first part. Not only is that asking for errors when manually soldering, but it could be bad for the part to be heated that long. If the board will be stuffed by pick and place with solder paste and then oven reflow soldered, then there is no issue of one pad sucking heat from the other since they will both be heated. In that sense layout C is OK, but there is another problem. That problem is called tombstoning , and happens when the solder melts at different times at the ends of small and light parts. Molten solder has much higer surface tension than solder paste. This surface tension on one end only of a small part can cause the part to release from the other pad and stand up on the pad with the molten solder. This standing up at right angles from the board is where the term tombstoning comes from, like a tombstone sticking up from the ground. This is generally not a problem at a size of 0805 and up because the part is too long and heavy for the surface tension at one end to lever it up. At 0603 and lower you need to think about this. There is another thermal issue though, and this applies to large parts too. The surface tension of the molten solder on each pin pulls that pin towards the center of its pad. This is one reason small alignment errors in placement don't matter. They get straightened out during reflow by the combined suface tension on all the pins trying to average out the center placements. If a part connected to pad C at one end has a normal pad at the other, it could possibly be pulled towards the center of pad C and off the pad at the other end. You could compensate for this a bit by making a special footprint with the other end pad closer than it would normally be so that some pulling is OK. I would only play that game if I really really needed layout C, which I can only imagine in a high current or high frequency case. Using the normal solder mask shapes for pad C would get around the part-pulling case. There would be two separate solder mask openings on pad C with a section of solder mask between. The surface tension would pull to the center of each solder mask opening, not to the center of the whole pad C. This doesn't fix the tombstoning problem for small parts though. In general, I'd use layout B unless I knew of a good reason to use A or C.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/29749', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7687/']}
jdg_71707
stackexchange
llm_judgeable_groundtruth_similarity
1829875
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using RESTlet and I have created a resource. I handle POST by overriding acceptRepresentation method. The client should send me some data, then I store it to DB, set response to 201 (SUCCESS_CREATED) and I need to return some data to the client, but return type of acceptRepresentation is void . In my case, I need to return some identificator so that client can access that resource. For example, if I had a resource with URL /resource and the client sends POST request I add a new row in DB and its address should be /resource/{id} . I need to send {id} . Am I doing something wrong? Does REST principles allow to return something after POST? If yes, how can I do it, and if no what is the way to handle this situation? Now provide the response and nothing else.
REST just says that you should conform to the uniform interface. In other words, it says you should do what POST is supposed to do as per the HTTP spec . Here is the quote from that spec that is relevant, If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30). As you can see from this, you have two places where you can indicate to the client where the newly created resource resides. The Location header should have an URL that points to the new resource and you can return an entity with the details also. I'm not sure what the difference between overriding acceptRepresentation() and overriding post() but this example shows how to return a response from a POST.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1829875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61363/']}
jdg_71708
stackexchange
llm_judgeable_groundtruth_similarity
56322998
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a Subject to add edit functionality to a basic phonebook app.The changes that I make to component class variables inside of the subscribe callback are not reflected out of it or in the template. I have tried the solutions listed in the answers to the following question: Angular 2 View will not update after variable change in subscribe in service.ts: startedEditing= new Subject<number>(); in details.component.ts(where the data is passed on fu): onEdit(){ this.contactsService.startedEditing.next(this.id); } in edit-component.ts(in ngOnInit): this.subscription=this.contactsService.startedEditing.subscribe( (index:number)=>{ this.editMode=true; this.editedItemIndex=index; this.editItem=this.contactsService.getContact(this.editedItemIndex); this.editForm.setValue({ address:this.editItem.address, name: this.editItem.name, phone:this.editItem.phone, profession:this.editItem.profession }); console.log("in subscribe: "+this.editedItemIndex); } ); console.log("out of it :" + this.editedItemIndex); } output on the console: in subscribe: 0out of it : undefined expected result: in subscribe: 0out of it :0 Now provide the response and nothing else.
Since your original json contains an array with only one element, PowerShell will condense that to become just this one element. If in your output you want it to be an array again, use rokumaru's good answer . However, PowerShell's ConvertTo-Json does not produce pretty formatted json and for that I have written a helper function some time ago: function Format-Json { <# .SYNOPSIS Prettifies JSON output. .DESCRIPTION Reformats a JSON string so the output looks better than what ConvertTo-Json outputs. .PARAMETER Json Required: [string] The JSON text to prettify. .PARAMETER Minify Optional: Returns the json string compressed. .PARAMETER Indentation Optional: The number of spaces (1..1024) to use for indentation. Defaults to 4. .PARAMETER AsArray Optional: If set, the output will be in the form of a string array, otherwise a single string is output. .EXAMPLE $json | ConvertTo-Json | Format-Json -Indentation 2 #> [CmdletBinding(DefaultParameterSetName = 'Prettify')] Param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [string]$Json, [Parameter(ParameterSetName = 'Minify')] [switch]$Minify, [Parameter(ParameterSetName = 'Prettify')] [ValidateRange(1, 1024)] [int]$Indentation = 4, [Parameter(ParameterSetName = 'Prettify')] [switch]$AsArray ) if ($PSCmdlet.ParameterSetName -eq 'Minify') { return ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100 -Compress } # If the input JSON text has been created with ConvertTo-Json -Compress # then we first need to reconvert it without compression if ($Json -notmatch '\r?\n') { $Json = ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100 } $indent = 0 $regexUnlessQuoted = '(?=([^"]*"[^"]*")*[^"]*$)' $result = $Json -split '\r?\n' | ForEach-Object { # If the line contains a ] or } character, # we need to decrement the indentation level unless it is inside quotes. if ($_ -match "[}\]]$regexUnlessQuoted") { $indent = [Math]::Max($indent - $Indentation, 0) } # Replace all colon-space combinations by ": " unless it is inside quotes. $line = (' ' * $indent) + ($_.TrimStart() -replace ":\s+$regexUnlessQuoted", ': ') # If the line contains a [ or { character, # we need to increment the indentation level unless it is inside quotes. if ($_ -match "[\{\[]$regexUnlessQuoted") { $indent += $Indentation } $line } if ($AsArray) { return $result } return $result -Join [Environment]::NewLine} Use it like this: $json = Get-Content 'D:\script\test.json' -Encoding UTF8 | ConvertFrom-Json$json.yura.ContentManager.branch = 'test'# recreate the object as array, and use the -Depth parameter (your json needs 3 minimum)ConvertTo-Json @($json) -Depth 3 | Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8# instead of using '@($json)' you can of course also recreate the array by adding the square brackets manually:# '[{0}{1}{0}]' -f [Environment]::NewLine, ($json | ConvertTo-Json -Depth 3) | # Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56322998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11560860/']}
jdg_71709
stackexchange
llm_judgeable_groundtruth_similarity
5801347
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: there are lots of code to get selection in a page,but i want a code to get selection inside a div,if the selection is outside of my div, the function must return empty string; there is a jquery plugin that works only for textarea but not div. (here) thanks Now provide the response and nothing else.
This is slightly verbose because of long-winded boundary comparisons and because IE takes a different approach from other browsers, but does the job in all major browsers. It also handles multiple selections in Firefox. jsFiddle: http://jsfiddle.net/Q982A/2/ Code: function getSelectedTextWithin(el) { var selectedText = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(), rangeCount; if ( (rangeCount = sel.rangeCount) > 0 ) { var range = document.createRange(); for (var i = 0, selRange; i < rangeCount; ++i) { range.selectNodeContents(el); selRange = sel.getRangeAt(i); if (selRange.compareBoundaryPoints(range.START_TO_END, range) == 1 && selRange.compareBoundaryPoints(range.END_TO_START, range) == -1) { if (selRange.compareBoundaryPoints(range.START_TO_START, range) == 1) { range.setStart(selRange.startContainer, selRange.startOffset); } if (selRange.compareBoundaryPoints(range.END_TO_END, range) == -1) { range.setEnd(selRange.endContainer, selRange.endOffset); } selectedText += range.toString(); } } } } else if (typeof document.selection != "undefined" && document.selection.type == "Text") { var selTextRange = document.selection.createRange(); var textRange = selTextRange.duplicate(); textRange.moveToElementText(el); if (selTextRange.compareEndPoints("EndToStart", textRange) == 1 && selTextRange.compareEndPoints("StartToEnd", textRange) == -1) { if (selTextRange.compareEndPoints("StartToStart", textRange) == 1) { textRange.setEndPoint("StartToStart", selTextRange); } if (selTextRange.compareEndPoints("EndToEnd", textRange) == -1) { textRange.setEndPoint("EndToEnd", selTextRange); } selectedText = textRange.text; } } return selectedText;} Alternatively, you could use my Rangy library, and the code becomes: function getSelectedTextWithin(el) { var selectedText = ""; var sel = rangy.getSelection(), rangeCount = sel.rangeCount; var range = rangy.createRange(); range.selectNodeContents(el); for (var i = 0; i < rangeCount; ++i) { selectedText += sel.getRangeAt(i).intersection(range); } return selectedText;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5801347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/406804/']}
jdg_71710
stackexchange
llm_judgeable_groundtruth_similarity
12831217
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Currying subtraction I started my first haskell project that is not from a tutorial, and of course I stumble on the simplest things. I have the following code: moveUp y = modifyMVar_ y $ return . (+1)moveDn y = modifyMVar_ y $ return . (-1) It took me some time to understand why my code wouldn't compile: I had used (-1) which is seen as negative one. Bracketting the minus doesn't help as it prefixes it and makes 1 its first parameter. In short, what is the point free version of this? dec :: Num a => a -> adec x = x - 1 Now provide the response and nothing else.
I believe you want the conveniently-named subtract function , which exists for exactly the reason you've discovered: subtract :: Num a => a -> a -> a the same as flip (-) . Because - is treated specially in the Haskell grammar, (- e) is not a section, but an application of prefix negation. However, (subtract exp) is equivalent to the disallowed section. If you wanted to write it pointfree without using a function like subtract , you could use flip (-) , as the Prelude documentation mentions. But that's... kinda ugly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12831217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/520159/']}
jdg_71711
stackexchange
llm_judgeable_groundtruth_similarity
41982370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: when we use retrofit2 for doing API rest calls with Rx, What is the best approach to use, Single or Observable? public interface ApiService{Single<Data> getDataFromServer();Observable<Data> getDataFromServer();} Now provide the response and nothing else.
I'd suggest using a Single as it is more accurate representation of the data flow: you make a request to the server and the you get either one emission of data OR an error: Single: onSubscribe (onSuccess | onError)? For an Observable you could theoretically get several emissions of data AND an error Observable: onSubscribe onNext? (onCompleted | onError)? However, if you are using rx-java2 , I'd suggest using a Maybe instead of Single . The difference between those two is that Maybe handles also the case when you get the response from server but it contains no body. Maybe: onSubscribe (onSuccess | onCompleted | onError)?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41982370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1873390/']}
jdg_71712
stackexchange
llm_judgeable_groundtruth_similarity
38135455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a HTML widget with Laravel blade similar to the following (widget.blade.php): @push('scripts') <script src="{{ asset('js/foo.js') }}"></script> <script> ... </script>@endpush@push('styles') <link href="{{ asset('css/bar.css') }}" rel="stylesheet">@endpush<div>... HTML contents</div> and I use the widget in an other blade like: <div> ... @include('widget')</div><div> ... @include('widget')</div> The problem is when I use the widget multiple times in a page the 'scripts' and 'styles' repeated multiple times. How can I prevent Laravel to push 'scripts' and 'styles' multiple times? Now provide the response and nothing else.
As of Laravel 7.25, Blade now includes a new @once component that will only render the items within the tags one time. https://laravel.com/docs/8.x/blade#the-once-directive In the following answer I assumed you are familiar with Blade extension . This method has been tested on Laravel 5.2 and 5.3 (See note below). After testing Ismail RBOUH's Answer (so please read it), It seems there are two problems with the solution: 1- The $isDisplayed variable is not in a same scope with the other included widgets so each @include push its scripts to stack. As a result I change it to: Blade::directive('pushonce', function ($expression) { $isDisplayed = '__pushonce_'.trim(substr($expression, 2, -2)); return "<?php if(!isset(\$__env->{$isDisplayed})): \$__env->{$isDisplayed} = true; \$__env->startPush{$expression}; ?>";});Blade::directive('endpushonce', function ($expression) { return '<?php $__env->stopPush(); endif; ?>';}); 2- The solution limit the use of @pushonce to one widget. i.e. in the case of 2 or more widgets (widget1.blade.php, widget2.blade.php, ...) it prevent to push other widgets scripts. So, I add domain to @pushonce with the following code: Blade::directive('pushonce', function ($expression) { $domain = explode(':', trim(substr($expression, 2, -2))); $push_name = $domain[0]; $push_sub = $domain[1]; $isDisplayed = '__pushonce_'.$push_name.'_'.$push_sub; return "<?php if(!isset(\$__env->{$isDisplayed})): \$__env->{$isDisplayed} = true; \$__env->startPush('{$push_name}'); ?>";});Blade::directive('endpushonce', function ($expression) { return '<?php $__env->stopPush(); endif; ?>';}); Usage: widget1.blade.php @pushonce('scripts:widget1') <script src="{{ asset('js/foo.js') }}"></script> <script> ... </script>@endpushonce widget2.blade.php @pushonce('scripts:widget2') <script src="{{ asset('js/bar.js') }}"></script> <script> ... </script>@endpushonce NOTE FOR L 5.3: change the following line: $domain = explode(':', trim(substr($expression, 2, -2))); to $domain = explode(':', trim(substr($expression, 1, -1)));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38135455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4003077/']}
jdg_71713
stackexchange
llm_judgeable_groundtruth_similarity
9756652
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 user model set up as such: class User < ActiveRecord::Base has_secure_password # callbacks ------------------------------------------------------------------------- before_create { generate_token(:auth_token) } # setup accessible (or protected) attributes for your model and validation ---------- attr_accessible :email, :password, :password_confirmation # validations VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email , presence: true, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX } validates :password , length: { minimum: 6 } validates :password_confirmation, presence: true But I don't want the password and/or password_confirmation validations to run when updating the user unless the user is attempting to change their password. So, if the user updates their information in a form without specifying a password and/or confirmation it should succeed. If the user updates their information and includes a password and/or confirmation the validations should run. What is the best way to accomplish this? Now provide the response and nothing else.
You could add a conditional :if to both validators: Option 1: validates :password , length: { minimum: 6 }, :if => :validate_password?validates :password_confirmation, presence: true , :if => :validate_password?def validate_password? password.present? || password_confirmation.present?end Option 2: Or use a method for validation, moving the validation checks into the method instead of as separate validates calls: validate :check_password, :on => :updatedef check_password return unless password.present? || password_confirmation.present? ..validations for both attributes here.. ..check presence, length etc. as required and add to the errors variable as necessary..end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9756652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54818/']}
jdg_71714
stackexchange
llm_judgeable_groundtruth_similarity
18403154
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 are the rules for using ampersand in c while using scanf() ? struct Student { char name[20]; int id;};int main(void){ struct Student std1; printf("enter name and id of std1\n"); scanf("%s %d", std1.name, &(std1.id));} Why for String do I not need to use the the ampersand and for int I have to use it? Is there a rule on when to use the ampersand sign? Now provide the response and nothing else.
scanf reads particular types of data into addresses which are passed as second, third, fourth and so on arguments. int var;scanf("%d",&var); Here var is value and &var is address. The above statement says: read %d (integer) type of data into &var address. char s[20];scanf("%s",s); Here s is address not the value because s is a character array (string). An array name itself indicates its address. s == &s[0] , these are both the same. The above statement says: read %s (array of characters) type of data into address location starting from s . #include<stdio.h>#define MAX 5int main(){ int a[MAX]; int i; printf("Enter Values of array\n"); for(i=0;i<MAX;i++) { printf("Enter a[%d] = ",i); scanf("%d",&a[i]); // reading each time single integer value starting index with 0 and ending index MAX-1. }} There is no single format specifier to scan group of integers at a time as like scanning group of characters at time with the help of %s. And here a=&a[0]; you can scan single integer value directly to the address which is pointed by a . scanf("%d",a);printf("a[0]=%d\n",a[0]); if you enter 10 then prints a[0]=10 . Usage of Pointers: if you use pointers as shown below, then you will come to know how to increment the pointer and get the values into different locations of array. You can move the pointer location to read arrays. You can read arrays without moving pointer location. Reading arrays by moving pointer locations #include<stdio.h>#define MAX 5int main(){ int a[MAX]; int i; int *ptr; ptr = &a[0]; printf("Enter Values of array\n"); for(i=0;i<MAX;i++) { printf("Enter a[%d] = ",i); scanf("%d",ptr); ptr++; //moving pointer }} Reading arrays with out moving pointer locations. #include<stdio.h>#define MAX 5int main(){ int a[MAX]; int i; int *ptr; ptr = &a[0]; printf("Enter Values of array\n"); for(i=0;i<MAX;i++) { printf("Enter a[%d] = ",i); scanf("%d",ptr+i); //we are not moving ptr position we scaning each time into next location by incrementing i }} When a pointer is incremented then the increment is dependent on the type of pointer. Here ptr is an integer pointer so ptr+1 will increment ptr+sizeof(int) locations. int a[5][5]; This is two dimensional array so you require 5 pointers to scan so I was declared pointer array. #include<stdio.h>#define MAX 5int main(){ int a[MAX][MAX],i,j; int *pointer[MAX]; for(i=0;i<MAX;i++) pointer[i]=&a[i][0]; //initializes the pointers printf("Enter elements :\n"); for(i=0;i< MAX;i++) { for(j=0;j<MAX;j++) { printf("Enter the a[%d][%d] element: ",i,j); scanf("%d",pointer[i]+j); //each time you will move like 00 01 02 03 04 and second time 10 11 12 13 14 and so on... //printf("%u or %x",pointer[i]+j,pointer[i]+j);//un comment this line and see the addresses how the address incrementing for each element } } printf("The Given Matrix:\n\n"); for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { printf("%d",*(pointer[i]+j)); printf("\t\t"); } printf("\n\n"); }} Direct scanning printf("Enter elements :\n");for(i=0;i< MAX;i++){ for(j=0;j<MAX;j++) { printf("Enter the a[%d][%d] element: ",i,j); scanf("%d",&a[i][j]); //we can't do like this a++ or ++a or a+i this is illegal in C. for that purpose we are using pointers }} You will found most of the above stuff in The C Programming Language (Second edition) by Brian W. Kernighan and Dennis M. Ritchie .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18403154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2228884/']}
jdg_71715
stackexchange
llm_judgeable_groundtruth_similarity
2228809
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently taking an intro to linear algebra course. We have reached the section on dot products and I fail to understand the meaning of it. What does it tell me, besides spitting out a scalar? I initially read that the answer is similar to asking what the point of multiplication is, but I understand why multiplication is useful. Now provide the response and nothing else.
The dot product is a specific case of something called an "inner product". This may seem surprising at first, but inner products (and in this case the dot product) is what gives you a notion of angle in the vector space. For example, $(0,1)\cdot(1,0) = 0\times1+1\times0 = 0$, while $(1,0)\cdot(1,0) = 1\times1+0\times0 = 1$. In your first case, you know that the two vectors are "orthogonal" or "perpendicular" just by looking at them - one of them is in the $x$ direction, and the other one is in the $y$ direction. But what if you're in a more abstract setting? What if you can't "visualise" the vectors like lines any more? This is where the dot product comes in: If the dot product of two vectors is $0$, the two vectors are orthogonal. In the second case, the "length" of each vector is $1$, and so is their dot product. (By length I mean the Euclidean norm: i.e. the length of $(1, 0)$ is $\Vert(1, 0)\Vert = \sqrt{1^2+0^2} = 1$.) In the opposite extreme from orthogonal vectors, you have $u\cdot v = \Vert u\Vert \Vert v\Vert$. This is when the two vectors are parallel. How about everything in between? If we rearrange the previous results slightly, you'll see that if two vectors $u$ and $v$ are orthogonal, $\dfrac{u\cdot v}{\Vert u\Vert \Vert v\Vert} = 0$. On the other hand, if $u$ and $v$ are parallel, $\dfrac{u\cdot v}{\Vert u\Vert \Vert v\Vert} = 1$ (It can also be $-1$ if your two vectors are parallel in opposite directions). Everything else between these two extreme cases takes some number between $1$ and $0$ or $0$ and $-1$. You might have noticed this is getting strangely trigonometric: for example, $\cos(\theta)$ takes values from $-1$ to $1$. And yes, $\dfrac{u\cdot v}{\Vert u\Vert \Vert v\Vert} = \cos(\theta)$ gives you the angle between two vectors. To see why this is true, remember that cosine is "adjacent over hypotenuse". By thinking of the dot product as "the product of a vector and the component of the other vector in the same direction as the first vector", you can convince yourself this is true with some drawing!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2228809', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415482/']}
jdg_71716
stackexchange
llm_judgeable_groundtruth_similarity
44560655
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 working on a script which reading a folder of files(each of size ranging from 20 MB to 100 MB), modifies some data in each line, and writes back to a copy of the file. with open(inputPath, 'r+') as myRead: my_list = myRead.readlines() new_my_list = clean_data(my_list)with open(outPath, 'w+') as myWrite: tempT = time.time() myWrite.writelines('\n'.join(new_my_list) + '\n') print(time.time() - tempT)print(inputPath, 'Cleaning Complete.') On running this code with a 90 MB file (~900,000 lines), it printed 140 seconds as the time taken to write to the file. Here I used writelines() . So I searched for different ways to improve file writing speed, and in most of the articles that I read, it said write() and writelines() should not show any difference since I am writing a single concatenated string. I also checked the time taken for only the following statement: new_string = '\n'.join(new_my_list) + '\n' And it took only 0.4 seconds, so the large time taken was not because of creating the list.Just to try out write() I tried this code: with open(inputPath, 'r+') as myRead: my_list = myRead.readlines() new_my_list = clean_data(my_list)with open(outPath, 'w+') as myWrite: tempT = time.time() myWrite.write('\n'.join(new_my_list) + '\n') print(time.time() - tempT)print(inputPath, 'Cleaning Complete.') And it printed 2.5 seconds. Why is there such a large difference in the file writing time for write() and writelines() even though it is the same data? Is this normal behaviour or is there something wrong in my code? The output file seems to be the same for both cases, so I know that there is no loss in data. Now provide the response and nothing else.
file.writelines() expects an iterable of strings. It then proceeds to loop and call file.write() for each string in the iterable. In Python, the method does this: def writelines(self, lines) for line in lines: self.write(line) You are passing in a single large string, and a string is an iterable of strings too. When iterating you get individual characters , strings of length 1. So in effect you are making len(data) separate calls to file.write() . And that is slow, because you are building up a write buffer a single character at a time. Don't pass in a single string to file.writelines() . Pass in a list or tuple or other iterable instead. You could send in individual lines with added newline in a generator expression, for example: myWrite.writelines(line + '\n' for line in new_my_list) Now, if you could make clean_data() a generator , yielding cleaned lines, you could stream data from the input file, through your data cleaning generator, and out to the output file without using any more memory than is required for the read and write buffers and however much state is needed to clean your lines: with open(inputPath, 'r+') as myRead, open(outPath, 'w+') as myWrite: myWrite.writelines(line + '\n' for line in clean_data(myRead)) In addition, I'd consider updating clean_data() to emit lines with newlines included.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44560655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7995937/']}
jdg_71717
stackexchange
llm_judgeable_groundtruth_similarity
28220636
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the latest version of Android Studio. When I run my app on the emulator, I am able to view my database by going through: tools -> Android Device Monitor -> clicking on the emulator in the left panel -> file explorer -> data -> data -> com.project-name But this option isn't available when running my app on a device. I have checked related questions: Android - viewing SQLite databases on device? The most voted answer here suggests copying the database to SDcard, and it's even for eclipse. Access sqlite database on android device and these questions are from 2011 and 2010.Are there any plugins I can use or other external tools? Now provide the response and nothing else.
Connect to Sqlite3 via ADB Shell I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time. Find all info here: http://developer.android.com/tools/help/adb.html#sqlite 1- Go to your platform-tools folder in a command prompt 2- Enter the command adb devices to get the list of your devices C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devicesList of devices attachedemulator-xxxx device 3- Connect a shell to your device: C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell 4- Navigate to the folder containing your db file: cd data/data/<your-package-name>/databases/ 5- run sqlite3 to connect to your db: sqlite3 <your-db-name>.db 6- run sqlite3 commands that you like eg: Select * from table1 where ...; Note: Find more commands to run below. SQLite cheatsheet There are a few steps to see the tables in an SQLite database: List the tables in your database: .tables List how the table looks: .schema tablename Print the entire table: SELECT * FROM tablename; List all of the available SQLite prompt commands: .help Source : This SO answer..
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28220636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2058547/']}
jdg_71718
stackexchange
llm_judgeable_groundtruth_similarity
70232931
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 try a sample project in Flutter integration email and google based login, and planning to use firebase initialisation for doing it while I have followed all the steps as mentioned in tutorials I am getting this error as soon as firebase is attempted to be initialised. "FirebaseOptions cannot be null when creating the default app." at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11) at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42) at initializeApp.next (<anonymous>) at http://localhost:7357/dart_sdk.js:40192:33 at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59) at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29) at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49) at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17) at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23) at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35) at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13) at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13) at http://localhost:7357/dart_sdk.js:35811:9 Here is my index.html <!DOCTYPE html><html><head> <!-- If you are serving your web app in a path other than the root, change the href value below to reflect the base path you are serving from. The path provided below has to start and end with a slash "/" in order for it to work correctly. For more details: * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base This is a placeholder for base href that will be replaced by the value of the `--base-href` argument provided to `flutter build`. --> <base href="$FLUTTER_BASE_HREF"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com"> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="signin_example"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>signin_example</title> <link rel="manifest" href="manifest.json"></head><body> <!-- This script installs service_worker.js to provide PWA functionality to application. For more information, see: https://developers.google.com/web/fundamentals/primers/service-workers --> <script> var serviceWorkerVersion = null; var scriptLoaded = false; function loadMainDartJs() { if (scriptLoaded) { return; } scriptLoaded = true; var scriptTag = document.createElement('script'); scriptTag.src = 'main.dart.js'; scriptTag.type = 'application/javascript'; document.body.append(scriptTag); } if ('serviceWorker' in navigator) { // Service workers are supported. Use them. window.addEventListener('load', function () { // Wait for registration to finish before dropping the <script> tag. // Otherwise, the browser will load the script multiple times, // potentially different versions. var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion; navigator.serviceWorker.register(serviceWorkerUrl) .then((reg) => { function waitForActivation(serviceWorker) { serviceWorker.addEventListener('statechange', () => { if (serviceWorker.state == 'activated') { console.log('Installed new service worker.'); loadMainDartJs(); } }); } if (!reg.active && (reg.installing || reg.waiting)) { // No active web worker and we have installed or are installing // one for the first time. Simply wait for it to activate. waitForActivation(reg.installing || reg.waiting); } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) { // When the app updates the serviceWorkerVersion changes, so we // need to ask the service worker to update. console.log('New service worker available.'); reg.update(); waitForActivation(reg.installing); } else { // Existing service worker is still good. console.log('Loading app from service worker.'); loadMainDartJs(); } }); // If service worker doesn't succeed in a reasonable amount of time, // fallback to plaint <script> tag. setTimeout(() => { if (!scriptLoaded) { console.warn( 'Failed to load app from service worker. Falling back to plain <script> tag.', ); loadMainDartJs(); } }, 4000); }); } else { // Service workers not supported. Just drop the <script> tag. loadMainDartJs(); } </script> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xx", storageBucket: "exxx", messagingSenderId: "xxx", appId: "xxx", measurementId: "xxx" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); </script></body></html> Part of code from main.dart file where firebase initialisation is happening void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(SignUpApp());} Pubsec.yaml file of the project name: signin_exampledescription: A new Flutter project.# The following line prevents the package from being accidentally published to# pub.dev using `flutter pub publish`. This is preferred for private packages.publish_to: 'none' # Remove this line if you wish to publish to pub.devhttps://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.htmlversion: 1.0.0+1environment: sdk: ">=2.15.0-268.18.beta <3.0.0"dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 firebase_auth: ^3.3.0 firebase_core: ^1.10.2 google_sign_in: ^5.2.1 shared_preferences: ^2.0.9dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^1.0.0# The following section is specific to Flutter.flutter: assets: - assets/images/ uses-material-design: true Can anyone help me understand what is the issue here? Now provide the response and nothing else.
UPDATE: For your firebase_core version is seems to be sufficient to pass the FirebaseOptions once you initialize firebase in your flutter code (and you don't need any script tags in your index.html ): void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( // Replace with actual values options: FirebaseOptions( apiKey: "XXX", appId: "XXX", messagingSenderId: "XXX", projectId: "XXX", ), ); runApp(MyApp());} Alternatively, one can also follow the updated official documentation and use the Firebase CLI to automatically create a firebase_options.dart file in your lib folder that will define the correct FirebaseOptions for you. The steps are: Install Flutterfire CLI: dart pub global activate flutterfire_cli Configure Flutterfire (run in your project's root and go through the wizard selecting the correct Firebase project and target platforms): flutterfire configure Import the automatically generated firebase_options.dart file in your main.dart file and initialize Firebase as follows: void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(MyApp());} PREVIOUS ANSWER: From the docs : The only way to currently add the Firebase SDKs to your Flutter web project is by importing the scripts from the Firebase content delivery network (CDN). Therefore, please try to use script tags to import the relevant firebase components with version 8.6.1 as shown below (more info here ): <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script> <script> var firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xx", storageBucket: "exxx", messagingSenderId: "xxx", appId: "xxx", measurementId: "xxx" }; firebase.initializeApp(firebaseConfig); firebase.analytics(); </script>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/70232931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8107881/']}
jdg_71719
stackexchange
llm_judgeable_groundtruth_similarity
9838862
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following C++ program: #include <memory>struct A {};struct B : A {};int main(){ auto x = std::make_shared<A>(); if (auto p = dynamic_pointer_cast<B>(x));} When compiling with MSVC 2010, I obtain the following error: error C2065: 'dynamic_pointer_cast' : undeclared identifier The error persists if auto is replaced by std::shared_ptr<A> . When I fully qualify the call with std::dynamic_pointer_cast , the program successfully compiles. Also, gcc 4.5.1 doesn't like it either: error: 'dynamic_pointer_cast' was not declared in this scope I thought that std::dynamic_pointer_cast would have been picked by Koenig lookup , since the type of x lives in the std namespace. What am I missing here ? Now provide the response and nothing else.
I think section §14.8.1/6 (C++03, and I think it holds in C++11 also) applies to this case which reads as, [Note: For simple function names, argument dependent lookup (3.4.2) applies even when the function name is not visible within the scope of the call. This is because the call still has the syntactic form of a function call (3.4.1). But when a function template with explicit template arguments is used, the call does not have the correct syntactic form unless there is a function template with that name visible at the point of the call. If no such name is visible, the call is not syntactically well-formed and argument-dependent lookup does not apply. If some such name is visible, argument dependent lookup applies and additional function templates may be found in other namespaces. [Example: namespace A { struct B { }; template<int X> void f(B);}namespace C { template<class T> void f(T t);}void g(A::B b) { f<3>(b); //ill-formed: not a function call A::f<3>(b); //well-formed C::f<3>(b); //ill-formed; argument dependent lookup // applies only to unqualified names using C::f; f<3>(b); //well-formed because C::f is visible; then // A::f is found by argument dependent lookup} —end example] —end note] Your case do not trigger ADL because you explicitly pass template argument and there is no template with the same name available at the site where you call dynamic_pointer_cast . One trick to enable ADL is to add a dummy template with same name to your code, as shown below: #include <memory>struct A {};struct B : A {};template<int> //template parameter could be anything!void dynamic_pointer_cast(); //ADD this. NO NEED TO DEFINE ITint main(){ auto x = std::make_shared<A>(); if (auto p = dynamic_pointer_cast<B>(x)); //now it should work through ADL}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9838862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373025/']}
jdg_71720
stackexchange
llm_judgeable_groundtruth_similarity
464902
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 convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work? Excel.Application objexcel;Excel.Workbook wbexcel;bool wbexists;Excel.Worksheet objsht;Excel.Range objrange;objexcel = new Excel.Application();if (Directory("C:\\csharp\\error report1.xls") = ""){ wbexcel.NewSheet();}else{ wbexcel.Open("C:\\csharp\\error report1.xls"); objsht = ("sheet1");}objsht.Activate(); Now provide the response and nothing else.
You need to have installed Microsoft Visual Studio Tools for Office (VSTO). VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development. After that create a generic .NET project and add a reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog. Application excel = new Application();Workbook wb = excel.Workbooks.Open(path); Missing.Value is a special reflection struct for unnecessary parameters replacement In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library . If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library , or an older version, but it is the same process to include.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/464902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31132/']}
jdg_71721
stackexchange
llm_judgeable_groundtruth_similarity
14071630
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 PostgreSQL function which calculates date difference: CREATE OR REPLACE FUNCTION testDateDiff () RETURNS int AS $BODY$DECLARE startDate TIMESTAMP;DECLARE endDate TIMESTAMP;DECLARE diffDatePart int ;BEGINSelect evt_start_date From events Where evt_id = 5 INTO startDate ;Select evt_start_date From events Where evt_id = 6 INTO endDate ;SELECT EXTRACT(day FROM TIMESTAMP startDate - endDate) INTO diffDatePart;RETURN diffDatePart;END;$BODY$LANGUAGE plpgsql COST 100 If dates are subtracted directly then difference is calculated. But in my case dates are present in variables as startDate and endDate , which causes the problem. How can I subtract dates contained in variables? Now provide the response and nothing else.
Debug What your function is doing could be done much simpler. The actual cause for the syntax error is here: SELECT EXTRACT(day FROM TIMESTAMP startDate - endDate) INTO diffDatePart; It looks like you are trying to cast startDate to timestamp , which is nonsense to begin with, because your parameter startDate is declared as timestamp already. It also does not work. I quote the manual here : To avoid syntactic ambiguity, the type 'string' syntax can only be used to specify the type of a simple literal constant. It would work like this: SELECT EXTRACT(day FROM startDate - endDate)::int INTO diffDatePart; But that still wouldn't make a lot of sense. You are talking about "dates", but still define your parameters as timestamp . You could sanitize what you have like this: CREATE OR REPLACE FUNCTION f_date_diff() RETURNS int AS$BODY$DECLARE start_date date; end_date date; date_diff int;BEGINSELECT evt_start_date FROM events WHERE evt_id = 5 INTO start_date;SELECT evt_start_date FROM events WHERE evt_id = 6 INTO end_date;date_diff := (endDate - startDate);RETURN date_diff;END$BODY$ LANGUAGE plpgsql; DECLARE only needed once. date columns declared as proper type date . Don't use mixed case identifiers, unless you know exactly what you are doing. Subtract the start from the end to get a positive number or apply the absolute value operator @ . Since subtracting dates (as opposed to subtracting timestamps , which yields an interval ) already yields integer , simplify to: SELECT (startDate - endDate) INTO diffDatePart; Or even simpler as plpgsql assignment: diffDatePart := (startDate - endDate); Simple query You can solve the simple task with a simple query - using a subquery: SELECT (SELECT evt_start_date FROM events WHERE evt_id = 6) - evt_start_date AS date_diffFROM eventsWHERE evt_id = 5; Or you could CROSS JOIN the base table to itself (1 row from each instance, so that's ok): SELECT e.evt_start_date - s.evt_start_date AS date_diffFROM events e ,events sWHERE e.evt_id = 6AND s.evt_id = 5; SQL function If you insist on a function for the purpose, use a simple sql function: CREATE OR REPLACE FUNCTION f_date_diff(_start_id int, _end_id int) RETURNS int LANGUAGE sql AS$func$SELECT e.evt_start_date - s.evt_start_dateFROM events s, events eWHERE s.evt_id = $1AND e.evt_id = $2$func$; Call: SELECT f_date_diff(5, 6); PL/pgSQL function If you insist on plpgsql ... CREATE OR REPLACE FUNCTION f_date_diff(_start_id int, _end_id int) RETURNS int LANGUAGE plpgsql AS$func$BEGINRETURN (SELECT evt_start_date - (SELECT evt_start_date FROM events WHERE evt_id = _start_id) FROM events WHERE evt_id = _end_id);END$func$; Same call.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14071630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1346155/']}
jdg_71722
stackexchange
llm_judgeable_groundtruth_similarity
31201
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: If I have daily data set and it's a non-stationary series, then what is the lag I have to consider for the first difference 1 or 7? Now provide the response and nothing else.
This depends on the form of nonstationarity. If it is a because of a linear trend then you take a first difference. If it is a season of period 7 then it would be seven. However the method of detrending does depend on the type of trend. Knowing only that the series is nonstationary is not sufficient to answer the question.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/31201', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12236/']}
jdg_71723
stackexchange
llm_judgeable_groundtruth_similarity
180360
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've just discovered the open source project MasterPassword . It generates a password per site based on name, master password, site and counter. So you need to know your name and the master password to get access. I like the idea behind this project. Based on this question , I feel like this would improve security, because there is absolutely no data stored in the cloud. Am I wrong? What speaks against it? Now provide the response and nothing else.
These "stateless" password solutions all have the same general structure: There's a master password that you memorize, and input into the program when you need to use it. The program derives a master cryptographic key from your master password. The program prompts you for some set of site and account metadata that describes each site or service you use. Using the master key and metadata, the program uses a pseudorandom function to generate a site password in a way that's both pseudorandom and repeatable. The problem with these programs is that they falsely advertise themselves as being more secure than plain old encrypted password managers like KeePass, 1Password or LastPass. In this case, the page of the program you ask about says this: Master Password is not a password manager. It does not store your website passwords. Therefore, there is zero risk of you losing your website passwords (or them falling in the wrong hands). And later down: You don't need to worry about your password manager website getting hacked, your phone getting duplicated, somebody taking a picture of your passwords book - Master Password stores no secrets. But a more accurate statement would be this: With a password manager, an attacker has to steal your encrypted database and guess your master password to recover your site passwords. With their program, there's no "steal the encrypted database" step; all that an attacker needs to do is guess your master password and the account metadata. So the reason they claim they are more secure than a password manager, turns out, is actually the reason they are less secure than a password manager. Ooops.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/180360', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/41925/']}
jdg_71724
stackexchange
llm_judgeable_groundtruth_similarity
2284996
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'd like to solve $ax^3 + bx^2 + cx + d = 0$ using the cubic formula. I coded three versions of this formula, described in three sources: MathWorld , EqWorld , and in the book, "The Unattainable Attempt to Avoid the Casus Irreducibilis for Cubic Equations". While I get identical results across all versions, these results are incorrect. For example, for $a=1$, $b=2$, $c=3$, $d=4$, I find incorrect roots: $x_1 = -0.1747 - 0.8521i$, $x_2 = 0.4270 + 1.1995i$, $x_3 = -2.2523 - 0.3474i$. The correct roots are: $x_1 = -1.6506$, $x_2 = -0.1747 + 1.5469i$, $x_3 = -0.1747 - 1.5469i$ In case you're interested, the actual code is below.Thank you for your help! %% Wolfram versionQ = (3*c - b^2) / 9;R = (9*b*c - 27*d - 2*b^3) / 54;D = Q^3 + R^2;S = (R + sqrt(D))^(1/3);T = (R - sqrt(D))^(1/3);x1 = - b/3 + (S + T);x2 = - b/3 - (S + T) / 2 + sqrt(-3) * (S - T) / 2;x3 = - b/3 - (S + T) / 2 - sqrt(-3) * (S - T) / 2;%% Book versionomega1 = - 1/2 + sqrt(-3)/2;omega2 = - 1/2 - sqrt(-3)/2;p = (3*a*c - b^2) / (3*a^2);q = (2*b^3 - 9*a*b*c + 27*(a^3)*d) / (27*a^3);r = sqrt(q^2/4 + p^3/27);s = (-q/2 + r)^(1/3);t = (-q/2 - r)^(1/3);x1 = s + t - b/(3*a);x2 = omega1*s + omega2*t - b/(3*a);x3 = omega2*s + omega1*t - b/(3*a);%% Eqworld versionp = - 1/3 * (b/a)^2 + (c/a);q = 2/27 * (b/a)^3 - (b*c)/(3*a^2) + d/a;D = (p/3)^3 + (q/2)^2;A = (-q/2 + sqrt(D))^(1/3);B = (-q/2 - sqrt(D))^(1/3);y1 = A + B;y2 = - 1/2 * (A + B) + sqrt(-3)/2 * (A - B);y3 = - 1/2 * (A + B) - sqrt(-3)/2 * (A - B);x1 = y1 - b / (3*a);x2 = y2 - b / (3*a);x3 = y3 - b / (3*a); Now provide the response and nothing else.
The problem occurs when you are taking a cube root: in the Wolfram version, when you compute $$T = \sqrt[3]{R - \sqrt{D}} = \sqrt[3]{-\frac{35}{27}-\sqrt{\frac{50}{27}}}$$ and in corresponding places in the other versions of the cubic formula. The expression inside the cube root is negative (approximately $-2.66$), and the cubic formula works if you take the real cube root (approximately $-1.39$). But writing $(R - \sqrt D)^{1/3}$ in many computer algebra systems instead computes the principal cube root: the complex root with largest real part. This will be the real cube root for a positive number, but here, it gives us approximately $0.69 - 1.2 i$, and that is the source of your error. I can't identify the language you're using by looking at it, so I don't know what the best way to avoid this problem is. In Mathematica, there's a built-in CubeRoot command, which will always take the real root of a real number. You can always make it go with some conditionals: define $T$ to be $(R - \sqrt{D})^{1/3}$, if $R - \sqrt D \ge 0$, and $-(\sqrt D - R)^{1/3}$, if $R - \sqrt D < 0$. (And do a similar thing everywhere else you take a cube root.) The above will work for real coefficients; for complex coefficients (or even when $D$ is negative), we want to be more careful, because then a real root might not exist. The idea is that we ran into trouble here, not because we weren't taking the real root necessarily, but because we took two cube roots that "didn't match up with each other". We can rewrite the cubic formula in a few different ways so that we only take one cube root, and express the other cube root we'd have to take in terms of the first. Then the issue doesn't occur. This gives us a better way to solve the problem in code: after computing $S = (R + \sqrt D)^{1/3}$, set $T = -Q/S$. The justification is this: since $S^3 = R + \sqrt D$ and $T^3 = R - \sqrt D$, we have $S^3 T^3 = R^2 - D = -Q^3$. Naively, we can cancel the cube roots and assume $ST = -Q$, and this works out. See also this question and its answer.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2284996', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/237544/']}
jdg_71725
stackexchange
llm_judgeable_groundtruth_similarity
6954792
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have built a nav menu in wordpres using a posts GUID, and post title, I am taking only part of the title and to do this I am doing the following, $casestudylist .= "<li class='subnav'><a href=".$v->guid.">". strstr($v->post_title, ":", true)."</a></li>"; however I get the following warning and cannot work out why: wrong parameter count for strstr() Basically I am trying to pull all the characters out of a string if they are before a : . Now provide the response and nothing else.
The PHP version you're using does not support the third parameter of strstr Docs , hence the error message. Your usage of the function requires PHP 5.3.0 or higher. You can either upgrade the PHP version on your server or you replace the function call with something similar like: substr($v->post_title, 0, strpos($v->post_title, ":")) or if you want to use a helper function which is easier to read ( Demo ): str_before($v->post_title, ":");function str_before($subject, $needle){ $p = strpos($subject, $needle); return substr($subject, 0, $p);} Related: strstr to show string before occurance
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6954792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57872/']}
jdg_71726
stackexchange
llm_judgeable_groundtruth_similarity
16219026
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 my ASP MVC view, I am passing a key/value pair back from the controller. After looking at fiddler and viewing in Chrome's debugger I can see that the information is being passed back correctly. I would like for the value of the key/value pair to be the item that is displayed in the autocomplete list. When the user selects an item from the list, I would like that item's key to be placed into the text box. Here is the jQuery code from my view $(function () { $('#DRMCompanyId').autocomplete({ source: '@Url.Action("compSearch", "AgentTransmission")', minLength: 2, select: function (event, ui) { $('#DRMCompanyId').val(ui.item.label); } });}); One thing I noticed - if I add the ui variable to the watch list in the browser's debugger I notice that the label and the value are the exact same. Again, however, I'm seeing that what's being returned is the complete key/value pair. Here is a screen shot of the Network/Response console after the search is complete. Some of the data is private so I blacked it out however you can see there is a key/value pair being returned. Now provide the response and nothing else.
You'll need to make the AJAX request yourself and transform the data to the format that jQueryUI expects: $(function () { $('#DRMCompanyId').autocomplete({ source: function (request, response) { $.ajax({ url: '@Url.Action("compSearch", "AgentTransmission")', type: 'GET', dataType: 'json', data: request, success: function (data) { response($.map(data, function (value, key) { return { label: value, value: key }; })); } }); }, minLength: 2 });}); Also, the value property of an autocomplete item is automatically placed in the input when that item is selected, so there should be no need for a custom select handler. Example: http://jsfiddle.net/Aa5nK/60/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16219026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1489378/']}
jdg_71727
stackexchange
llm_judgeable_groundtruth_similarity
230934
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: How can I define the Hamiltonian independent of the Lagrangian? For instance, let's assume that i have a set of field equations that cannot be integrated to an action. Is there any prescription to construct the Hamiltonian of a such system starting from the field equations? Now provide the response and nothing else.
Comments to the question (v2): First of all, let us stress that OP is correct, that a given set of equations of motion does not necessarily have a variational/action principle, cf. e.g. this Phys.SE post and links therein. On one hand, if there exists a Lagrangian formulation, then one may in principle obtain a Hamiltonian formulation via a (possible singular) Legendre transformation . Traditionally this is done via the Dirac-Bergmann recipe/cookbook, see e.g. Refs. 1-2. On the other hand, if we have a (possible constrained) Hamiltonian formulation, of the type discussed in Refs. 1 and 2, then it is possible to give a Hamiltonian action formulation, which in itself can be interpreted as a Lagrangian formulation, e.g. after integration out momentum variables along the lines indicated in my Phys.SE answer here . In other words, Lagrangian and Hamiltonian formulations traditionally go hand in hands. Thus it is unclear what precisely OP is looking for. References: P.A.M. Dirac, Lectures on QM, (1964). M. Henneaux and C. Teitelboim, Quantization of Gauge Systems, 1994.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/230934', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/104482/']}
jdg_71728
stackexchange
llm_judgeable_groundtruth_similarity
14234646
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 populate a json file, now I have something like this: {"element":{"id":10,"quantity":1}} And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse , now I need to add the new element.I supposed I must use cart.push to add another element, I tried this: var element = {};element.push({ id: id, quantity: quantity });cart.push(element); But I got error "Object has no method push" when I try to do element.push , and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere. How can I do that? Edit: sorry to all I had a LOT of confusion in my head. I thought I can get only object type when taking data from JSON.parse , but I get what I put in the JSON in the first place. Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all! Now provide the response and nothing else.
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example: var element = {}, cart = [];element.id = id;element.quantity = quantity;cart.push(element); If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform: var element = {}, cart = [];element.id = id;element.quantity = quantity;cart.push({element: element}); JSON.stringify() was mentioned as a concern in the comment: >> JSON.stringify([{a: 1}, {a: 2}]) "[{"a":1},{"a":2}]"
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/14234646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1957622/']}
jdg_71729
stackexchange
llm_judgeable_groundtruth_similarity
29311207
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Newbie to Cython (perhaps this is a basic question). Consider two examples both taken from this blog here : # code 1import numpy as npdef num_update(u): u[1:-1,1:-1] = ((u[2:,1:-1]+u[:-2,1:-1])*dy2 + (u[1:-1,2:] + u[1:-1,:-2])*dx2) / (2*(dx2+dy2)) and # code 2cimport numpy as npdef cy_update(np.ndarray[double, ndim=2] u, double dx2, double dy2): cdef unsigned int i, j for i in xrange(1,u.shape[0]-1): for j in xrange(1, u.shape[1]-1): u[i,j] = ((u[i+1, j] + u[i-1, j]) * dy2 + (u[i, j+1] + u[i, j-1]) * dx2) / (2*(dx2+dy2)) Suppose I compile the first file with the following setup.py script: # setup file for code 1from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extext = Extension("laplace", ["laplace.pyx"],)setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext}) and the second file with the following setup.py script: # setup file for code 2from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extimport numpyext = Extension("laplace", ["laplace.pyx"], include_dirs = [numpy.get_include()])setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext}) In the 1st case, I used regular numpy and didn't import numpy in the setup file, while in the 2nd case I imported numpy using cimport , declared variables using cdef but then also included numpy in the setup file. Cython compiles the first code anyway (and the first code seems to work). What would be advantages of using cimport and cdef before compiling with Cython (via the setup file) versus not using cimport and cdef before compiling with Cython (via the setup file)? Now provide the response and nothing else.
import numpy in Cython is the same as Python, but cimport numpy tells Cython to load the declare file: https://github.com/cython/cython/blob/master/Cython/Includes/numpy/ init .pxd where declares all the C-API functions, constants, and types, and also include the header files, such as numpy/arrayobject.h . If you declare variable with np.ndarray[...] , Cython will know how to convert array element access into c code which is much faster then Python's [] operator. You need to tell the c compiler where are the numpy header files in setup.py , so you call numpy.get_include() to get the path.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29311207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2526657/']}
jdg_71730
stackexchange
llm_judgeable_groundtruth_similarity
334078
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 heard that $\Bbb R$ and $\Bbb C$ are the only connected, locally compact fields.Does anyone know a proof for this result? Now provide the response and nothing else.
$$\begin{align}\int_0^1\frac{\arctan(x)}{1+x}\,\mathrm{d}x&=\int_0^{\pi/4}\frac{\theta}{1+\tan(\theta)}\,\sec^2(\theta)\,\mathrm{d}\theta\tag{1}\\[6pt]&=\int_0^{\pi/4}\frac{\theta\,\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{2}\\[6pt]&=\int_0^{\pi/4}\frac{(\frac\pi4-\theta)\,\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{3}\\[6pt]&=\frac\pi8\int_0^{\pi/4}\frac{\mathrm{d}\theta}{\cos(\theta)\,(\cos(\theta)+\sin(\theta))}\tag{4}\\[6pt]&=\frac\pi8\int_0^{\pi/4}\frac{\sec^2(\theta)}{1+\tan(\theta)}\,\mathrm{d}\theta\tag{5}\\[6pt]&=\frac\pi8\int_0^1\frac1{1+x}\mathrm{d}x\tag{6}\\[6pt]&=\frac\pi8\Big[\log(1+x)\Big]_0^1\tag{7}\\[12pt]&=\frac\pi8\log(2)\tag{8}\end{align}$$$(1):$ $x=\tan(\theta)$ $(3):$ $\theta\mapsto\frac\pi4-\theta$ $(4):$ since $(2)=(3)$ we have $(3)=\frac{(2)+(3)}{2}$ $(6):$ $x=\tan(\theta)$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/334078', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50527/']}
jdg_71731
stackexchange
llm_judgeable_groundtruth_similarity
3469955
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 does a C program get started? Now provide the response and nothing else.
The operating system calls the main() function. Eventually. The Executable and Linkable Format (ELF) which many Unix OS's use defines an entry point address and an INIT address. That is where the program begins to run after the OS finishes its exec() call. On a Linux system this is _init in the .init section. After that returns it jumps to the entry point address which is _start in the .text section. The C compiler links a standard library to every application which provides these operating system defined initialization and entry points. That library then calls main() . Here is my C source code for the example: #include <stdio.h>int main() { puts("Hello world!"); return 0;} From objdump -d : Disassembly of section .init:0000000000001000 <_init>: 1000: f3 0f 1e fa endbr64 1004: 48 83 ec 08 sub $0x8,%rsp 1008: 48 8b 05 d9 2f 00 00 mov 0x2fd9(%rip),%rax # 3fe8 <__gmon_start__> 100f: 48 85 c0 test %rax,%rax 1012: 74 02 je 1016 <_init+0x16> 1014: ff d0 callq *%rax 1016: 48 83 c4 08 add $0x8,%rsp 101a: c3 retq Disassembly of section .text:0000000000001060 <_start>: 1060: f3 0f 1e fa endbr64 1064: 31 ed xor %ebp,%ebp 1066: 49 89 d1 mov %rdx,%r9 1069: 5e pop %rsi 106a: 48 89 e2 mov %rsp,%rdx 106d: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp 1071: 50 push %rax 1072: 54 push %rsp 1073: 4c 8d 05 66 01 00 00 lea 0x166(%rip),%r8 # 11e0 <__libc_csu_fini> 107a: 48 8d 0d ef 00 00 00 lea 0xef(%rip),%rcx # 1170 <__libc_csu_init> 1081: 48 8d 3d c1 00 00 00 lea 0xc1(%rip),%rdi # 1149 <main> 1088: ff 15 52 2f 00 00 callq *0x2f52(%rip) # 3fe0 <__libc_start_main@GLIBC_2.2.5> 108e: f4 hlt 108f: 90 nop0000000000001140 <frame_dummy>: 1140: f3 0f 1e fa endbr64 1144: e9 77 ff ff ff jmpq 10c0 <register_tm_clones> From readelf -h you can see the Entry point address that matches _start : ELF Header: Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 Class: ELF64 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: DYN (Shared object file) Machine: Advanced Micro Devices X86-64 Version: 0x1 Entry point address: 0x1060 Start of program headers: 64 (bytes into file) Start of section headers: 17416 (bytes into file) Flags: 0x0 Size of this header: 64 (bytes) Size of program headers: 56 (bytes) Number of program headers: 13 Size of section headers: 64 (bytes) Number of section headers: 36 Section header string table index: 35 From readelf -d : Dynamic section at offset 0x2dc8 contains 27 entries: Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] 0x000000000000000c (INIT) 0x1000 0x000000000000000d (FINI) 0x11e8 0x0000000000000019 (INIT_ARRAY) 0x3db8 0x000000000000001b (INIT_ARRAYSZ) 8 (bytes) 0x000000000000001a (FINI_ARRAY) 0x3dc0 0x000000000000001c (FINI_ARRAYSZ) 8 (bytes) 0x000000006ffffef5 (GNU_HASH) 0x3a0 0x0000000000000005 (STRTAB) 0x470 0x0000000000000006 (SYMTAB) 0x3c8 0x000000000000000a (STRSZ) 130 (bytes) 0x000000000000000b (SYMENT) 24 (bytes) 0x0000000000000015 (DEBUG) 0x0 0x0000000000000003 (PLTGOT) 0x3fb8 0x0000000000000002 (PLTRELSZ) 24 (bytes) 0x0000000000000014 (PLTREL) RELA 0x0000000000000017 (JMPREL) 0x5e0 0x0000000000000007 (RELA) 0x520 0x0000000000000008 (RELASZ) 192 (bytes) 0x0000000000000009 (RELAENT) 24 (bytes) 0x000000000000001e (FLAGS) BIND_NOW 0x000000006ffffffb (FLAGS_1) Flags: NOW PIE 0x000000006ffffffe (VERNEED) 0x500 0x000000006fffffff (VERNEEDNUM) 1 0x000000006ffffff0 (VERSYM) 0x4f2 0x000000006ffffff9 (RELACOUNT) 3 0x0000000000000000 (NULL) 0x0 You can see that INIT is equal to the address of _init . There is a whole array of function pointers in INIT_ARRAY also. See objdump -s -j .init_array c-test : c-test: file format elf64-x86-64Contents of section .init_array: 3db8 40110000 00000000 @....... You can see that address 0x3db8 is the same as INIT_ARRAY in the ELF header. The address 0x1140 (remember little-endian byte layout from 40110000) is the function frame_dummy you can see in the disassembly. Which then calls register_tm_clones and who knows what else. The code for initialization is in a set of files named crtbegin.o and crtend.o (and variants of those names). The __libc_start_main function is defined in libc.so.6. These libraries are part of GCC. That code does various things necessary for a C program like setting up stdin, stdout, global and static variables and other things. The following article describes quite well what it does in Linux (taken from an answer below with less votes): http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html I believe someone else's answer already described what Windows does.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3469955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/418627/']}
jdg_71732
stackexchange
llm_judgeable_groundtruth_similarity
23985
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I just installed VirtualBox 4.1 on my Windows system, and then added a Solaris 11 Express guest and an Oracle Linux 6.1 guest. Both installs went smoothly. But while the Solaris 11 guest has network access, the Oracle Linux box can't connect to the network. Both guests are using the same default network settings (NAT). I'm at a loss -- not sure what I need to configure on the OL6.1 side. To test basic network connectivity, I tried: ping www.google.com . No problems with the Solaris guest. On the OL6.1 guest: # ping www.google.com ping: unknown host www.google.com # ping 209.85.175.99 connect: Network is unreachable Is there some sort of network setup that's required on OL6.1 that wasn't required on Solaris11? Thanks in advance. output from ifconfig -a : # ifconfig -a eth0 Link encap:Ethernet HWaddr 08:00:27:8E:A1:42 inet6 addr: fe80::a00:27ff:fe8e:a142/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:4 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 b) TX bytes:328 (328.0 b) lo Link encap: Local Loopback inet addr:127.0.0.1 Mask:255.0.0 inet6addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen: 0 RX bytes:0 (0.0 b) TX bytes:0 (0.0 b) Now provide the response and nothing else.
Given that Oracle Linux is heavily based on Red Hat Enterprise Linux, the network configuration is probably the same. If you didn't need to enter any network parameters during the installation of Solaris, then you're picking up a network address through DHCP . There isn't much call for doing anything else in a NATted virtual machine anyway. To configure a DHCP client on RHEL, edit the file /etc/sysconfig/network-scripts/ifcfg-eth0 to contain the following lines: DEVICE=eth0BOOTPROTO=dhcpONBOOT=yes Or you can use Network Manager instead (it'll give you the same kind of network configuration through a desktop icon that Solaris has, and in fact I believe it is more powerful than Solaris's — not that you really need that in a VM).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/23985', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/12124/']}
jdg_71733
stackexchange
llm_judgeable_groundtruth_similarity
46718772
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 validated my Node.js inputs so that they won't be empty, but I want to sanitize them too. Please help me how I can do this. req.checkBody('name', 'Name is required!').notEmpty();req.checkBody('surname', 'Surname is required!').notEmpty();req.checkBody('username', 'Username is required!').notEmpty();req.checkBody('password', 'Password is required!').notEmpty();req.checkBody('password2', 'Passwords do not match!').equals(req.body.password);var errors = req.validationErrors();if (errors) { res.render('user/register', { errors: errors, user: null, title: 'Register' });}else { var userData = { name : req.body.name, surname : req.body.surname, username : req.body.username, password : req.body.password, avatar : 'No_person.jpg' }; userController.addUser(req,res,userData);} Now provide the response and nothing else.
For most of the framework, you can use sanitize node module: npm install sanitize --save And then can use like: var sanitizer = require('sanitize')(); var name = sanitizer.value(req.name, 'string'); var surname= sanitizer.value(req.surname, 'string'); For more can go through sanitize documentation If you are using express , then you can validate and sanitize using express-validator and express-sanitize-input packages as follows: const express = require('express'); const { check } = require('express-validator'); const app = express(); app.use(express.json()) app.post('/form', [ check('name').isLength({ min: 3 }).trim().escape(), check('email').isEmail().normalizeEmail(), check('age').isNumeric().trim().escape() ], (req, res) => { const name = req.body.name const email = req.body.email const age = req.body.age }) For more can go through express-validator and express-sanitize-input documentation. If you are using Hapi , then you can validate and sanitize using Joi , With the Joi, you can sanitize variable with additional options validate(value, schema, {escapeHtml: true}, [callback]) For more can go through Joi documentation. If you don't want to use any third party module and want to sanitize using the built-in node. you can try following: // For string variables str = typeof(str) === 'string' && str.trim().length > 0 ? str.trim() : ''; // for boolean values bool = typeof(bool) === 'boolean' && bool === true ? true : false; // for array values arr = typeof(arr) === 'object' && arr instanceof Array ? arr : []; // for number values num = typeof(num) === 'number' && num % 1 === 0 ? num : 0; // for objects obj = typeof(obj) === 'object' && !(obj instanceof Array) && obj !== null ? obj : {};
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46718772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8307603/']}
jdg_71734
stackexchange
llm_judgeable_groundtruth_similarity
16542409
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 need to get de ObjectManagedContext from my AppDelegate, but when i tried it don't work... i dont know why... i followed a mount of tutorials but it not work.... this is my code: AppDelegate.h #import <UIKit/UIKit.h>@class StopWalletViewController;@interface StopWalletAppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;@property (strong, nonatomic) StopWalletViewController *viewController;@property (strong,nonatomic) UINavigationController *navigationController;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;@end AppDelegate.m #import "StopWalletAppDelegate.h"#import "StopWalletViewController.h"@implementation StopWalletAppDelegate@synthesize managedObjectContext = _managedObjectContext;@synthesize managedObjectModel = _managedObjectModel;@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;@synthesize navigationController = _navigationController;//Code Auto Generated// Returns the managed object context for the application.- (NSManagedObjectContext *)managedObjectContext{ if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext;}// Returns the managed object model for the application.- (NSManagedObjectModel *)managedObjectModel{ if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"StopWallet" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; }- (NSPersistentStoreCoordinator *)persistentStoreCoordinator{ if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StopWallet.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] * Performing automatic lightweight migration by passing the following dictionary as the options parameter: @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator;}@end controller.m #import "ExpenseViewController.h"#import "Expense.h"#import "ExpenseLocation.h"#import "StopWalletAppDelegate.h"@implementation ExpenseViewController@synthesize editTextDate;@synthesize editTextLocation;@synthesize editTextValue;@synthesize imageViewReceipt;@synthesize managedObjectContext;- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.navigationItem.title=[NSString stringWithFormat:@"Expense"]; UIDatePicker *datePicker; datePicker = [[UIDatePicker alloc]init]; [datePicker setDate:[NSDate date]]; [datePicker setDatePickerMode:UIDatePickerModeDate]; [datePicker removeTarget:self action:nil forControlEvents:UIControlEventValueChanged]; [datePicker addTarget:self action:@selector(updateTextFieldDate:) forControlEvents:UIControlEventValueChanged]; [editTextDate setInputView:datePicker]; StopWalletAppDelegate *appDelegate = (StopWalletAppDelegate *)[[UIApplication sharedApplication] delegate]; NSManagedObjectContext* context = appDelegate.managedObjectContext; managedObjectContext=context;}@end This code are compiling but not work on runtime.... the error: NSInvalidArgumentException, reason:'Cannot create an NSPersistentStoreCoordinator with a nil model' Can anyone help me? Thanks... Now provide the response and nothing else.
how is c += 1; valid? Because reference_wrapper<int> is implicitly convertible to int& via its conversion operator; and implicit conversions are considered for operands if there is no suitable overload for the operand type itself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16542409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1281696/']}
jdg_71735
stackexchange
llm_judgeable_groundtruth_similarity
12483843
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 bitboard and I want to check in C if there is ONLY one bit set to 1. #include <stdint.h>typedef uint64_t bboard;bboard b = 0x0000000000000010;if (only_one_bit_set_to_one (b)) // in this example expected true // do something... Any idea to write the function int only_one_bit_set_to_one (bboard b) ? Now provide the response and nothing else.
Sure, it's easy: int only_one_bit_set_to_one (bboard b){ return b && !(b & (b-1));} Say b has any bits set, the least significant is bit number k . Then b-1 has the same bits as b for indices above k , a 0-bit in place k and 1-bits in the less significant places, so the bitwise and removes the least significant set bit from b . If b had only one bit set, the result becomes 0, if b had more bits set, the result is nonzero.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12483843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302005/']}
jdg_71736
stackexchange
llm_judgeable_groundtruth_similarity
20714978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <input name="name" type="text" id="nome" size="45" maxlength="35" value=<?php echo "need help" ?>/> // output "need"but i expect "need help" it was a POST var string of a name, but just out puts the fist name, then i realised the echo or print do not work with whitespace inside the tag value, like echo do outside what the solution to "need help"?? Now provide the response and nothing else.
Currently, your HTML mark up would look like: <input name="name" type="text" id="nome" size="45" maxlength="35" value=need help/> ^--------^ As it's evident from the syntax highlighting here, only need is considered as part of the value attribute. help is being considered as a separate new attribute. You need quotes around the attribute value: <input name="name" type="text" id="nome" size="45" maxlength="35" value="<?php echo "need help" ?>"/> ^ ^
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20714978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119951/']}
jdg_71737
stackexchange
llm_judgeable_groundtruth_similarity
25768069
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 child element which need to be positioned absolute with the grandparent. The problem is that the parent is also positioned absolutely. I can't use JavaScript. How can I achieve this with just pure CSS? JSFiddle Demo <div class="col-md-6 gp"> <div class="col-md-4 p"> <div class="col-md-2 c"> position me w.r.t to .gp</div> </div></div> .gp { height : 200px; position: relative; }.p { height : 100px; width: 250px; position :absolute; top : 50px; left: 50px;}.c { position: absolute; height: 50px; } Now provide the response and nothing else.
If supporting Internet Explorer 8 (and below) is not a concern, we could achieve that by pure CSS. Here is what you should know about CSS Transforms : 6 The Transform Rendering Model For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block . The object acts as a containing block for fixed positioned descendants . Hence, we add a transform with a value other than auto to the grandparent element, we will be able to use fixed positioning place the child element with the respect of the grandparent element which is creating the containing block. EXAMPLE HERE For instance: .grandpa { position: relative; height: 500px; -webkit-transform: rotate(0deg); -moz-transform: rotate(0deg); -ms-transform: rotate(0deg); -o-transform: rotate(0deg); transform: rotate(0deg);}.dad { position: absolute; width: 250px; height: 250px; bottom: 4em; left: 4em;}.son { position: fixed; /* This will be positioned with the respect to the grandpa rather than the viewport */ width: 100px; height: 100px; top: 2em; right: 2em;} Also, CSS Legendary Eric Mayer has written an article about this: Un-fixing Fixed Elements with CSS Transforms A transformed element creates a containing block even for descendants that have been set to position: fixed. In other words, the containing block for a fixed-position descendant of a transformed element is the transformed element, not the viewport.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25768069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2078210/']}
jdg_71738
stackexchange
llm_judgeable_groundtruth_similarity
13729638
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 Django app that takes tweet data from Twitter's API and saves it in a MySQL database. As far as I know (I'm still getting my head around the finer points of character encoding) I'm using UTF-8 everywhere, including MySQL encoding and collation, which works fine except when a tweet contains Emoji characters, which I understand use a four-byte encoding. Trying to save them produces the following warnings from Django: /home/biggleszx/.virtualenvs/myvirtualenv/lib/python2.6/site-packages/django/db/backends/mysql/base.py:86: Warning: Incorrect string value: '\xF0\x9F\x98\xAD I...' for column 'text' at row 1 return self.cursor.execute(query, args) I'm using MySQL 5.1, so using utf8mb4 isn't an option unless I upgrade to 5.5, which I'd rather not just yet (also from what I've read, Django's support for this isn't quite production-ready, though this might no longer be accurate). I've also seen folks advising the use of BLOB instead of TEXT on affected columns, which I'd also rather not do as I figure it would harm performance. My question is, then, assuming I'm not too bothered about 100% preservation of the tweet contents, is there a way I can filter out all Emoji characters and replace them with a non-multibyte character, such as the venerable WHITE MEDIUM SMALL SQUARE (U+25FD) ? I figure this is the easiest way to save that data given my current setup, though if I'm missing another obvious solution, I'd love to hear it! FYI, I'm using the stock Python 2.6.5 on Ubuntu 10.04.4 LTS. sys.maxunicode is 1114111, so it's a UCS-4 build. Thanks for reading. Now provide the response and nothing else.
So it turns out this has been answered a few times, I just hadn't quite got the right Google-fu to find the existing questions. Python, convert 4-byte char to avoid MySQL error "Incorrect string value:" Warning raised by inserting 4-byte unicode to mysql Thanks to Martijn Pieters , the solution came from the world of regular expressions, specifically this code (based on his answer to the first link above): import retry: # UCS-4 highpoints = re.compile(u'[\U00010000-\U0010ffff]')except re.error: # UCS-2 highpoints = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')# mytext = u'<some string containing 4-byte chars>'mytext = highpoints.sub(u'\u25FD', mytext) The character I'm replacing with is the WHITE MEDIUM SMALL SQUARE (U+25FD) , FYI, but could be anything. For those unfamiliar with UCS, like me, this is a system for Unicode conversion and a given build of Python will include support for either the UCS-2 or UCS-4 variant, each of which has a different upper bound on character support. With the addition of this code, the strings seem to persist in MySQL 5.1 just fine. Hope this helps anyone else in the same situation!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13729638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258794/']}
jdg_71739
stackexchange
llm_judgeable_groundtruth_similarity
29583015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I just wanted to display Shop.all.to_sql as => "SELECT "shops".* FROM "shops"" but got => "SELECT \"shops\".* FROM \"shops\"" I tried gsub, but rails ignores '\' Shop.all.to_sql.gsub('\', '') How could I get rid of '\'? Now provide the response and nothing else.
Those \ are not really there - this is way ruby displays strings (or rather this is the way inspect method works for strings). In short, it is to say that the next " is not the end of the string but rather a part of it: '"' #=> "\"" To see there are no slashes, tell ruby to display the resulting strings: puts Shop.all.to_sql# SELECT "shops".* FROM "shops"#=> nil
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29583015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3825408/']}
jdg_71740