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
17037937
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 painfully analyzed all of yesterday if I had another apache/web-server instance running, with all of these commands ps auxps -elsof netstat tunap I DO NOT have another instance of Apache or ANY OTHER server running at port 8080. Yet, XAMPP gives me this: XAMPP: Another web server daemon is already running What should I do? I also edited httpd.conf to LISTEN to port 9876, and still the same. Now provide the response and nothing else.
If: lsof -Pi |grep 8080 returns no resultsnetstat -na |grep 8080 returns no resultsps -ef shows no web server processes Then maybe there's a lockfile lying around that the startup is checking against? Those are typically found under /var/run but don't necessarily have to. At this point I would usually run strace to see what's going on: strace -e read=all -e write=all -f -o strace.out your_startup_command Then open up strace.out, search for the "..is already running" string in the output, and starting looking at lines above it to see what is failing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17037937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2358206/']}
jdg_73241
stackexchange
llm_judgeable_groundtruth_similarity
181263
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a polygon given by poly = Polygon[ {{2437.21, 166.705}, {2437.38,166.856}, {2440.37,163.438}, {2435.84,159.581}, {2442.18,152.113}, {2431.45,142.989}, {2420.63,153.885}, {2428.72,160.067}, {2418.95,168.237}, {2435.2,183.216}, {2446.11,174.504}, {2437.21,166.705}}] which looks good when rendered: Graphics[poly] However, this shape cannot be used for Region -related operations as it is "ill-defined" with an interior line: Graphics[ { FaceForm[None], EdgeForm[Black], poly, Red, PointSize[Medium], Point@@poly }, Frame->True] whose zoomed-in view is like this: Graphics[ { FaceForm[None], EdgeForm[Black], poly, Red, PointSize[Medium], Point@@poly }, Frame->True, PlotRange->{{2437, 2438}, {166, 168}}, PlotRangeClipping->True] My question is: How can I detect such "ill-defined" polygons and fix them? Edit: As more people are concerning about the definition of a valid polygon, I just cite that used by the python package shapely here : Rings of a valid Polygon may not cross each other, but may touch at a single point only. Also, I have very little expertise in computational geometry; my intention was to use Region -related functions (e.g., RegionMeasure ) with these polygons, where I came across the kernel crash and then discovered such "ill-defined" polygons. Now provide the response and nothing else.
I expect there's a simpler way to do this, but here is a possibility. FIrst, discretize the polygon, and then find the boundary: boundary = RegionBoundary @ DiscretizeRegion @ poly Simplify the boundary using an undocumented, internal function: boundary = Region`Mesh`MergeCells @ boundary Notice the defect is gone. Convert the output to a BoundaryMesh and extract the polygon: simple = MeshPrimitives[ BoundaryMeshRegion[MeshCoordinates[boundary], MeshCells[boundary, 1]], 2] {Polygon[{{2440.37, 163.438}, {2437.38, 166.855}, {2446.11, 174.504}, {2435.2, 183.216}, {2418.95, 168.237}, {2428.72, 160.067}, {2420.63, 153.885}, {2431.45, 142.989}, {2442.18, 152.113}, {2435.84, 159.581}}]} The fixed polygon: Graphics[{FaceForm[None], EdgeForm[Black], simple}] And finally, here are the above steps packages as a function: fixPolygon[poly_Polygon] := With[ {boundary = Region`Mesh`MergeCells @ RegionBoundary @ DiscretizeRegion @ poly}, MeshPrimitives[ BoundaryMeshRegion[MeshCoordinates[boundary], MeshCells[boundary, 1]], 2 ]] Another example using a polygon from the comments: fixPolygon @ Polygon @ {{3, 3}/2, {3, 3}, {0,1}, {3, 1}, {2, 2},{3, 3}/2} {Polygon[{{3., 3.}, {0., 1.}, {3., 1.}, {2., 2.}}]}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/181263', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/260/']}
jdg_73242
stackexchange
llm_judgeable_groundtruth_similarity
10363188
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Some compilers failed on non-ASCII characters in JavaDoc and source code comments. What is the current (Java 7) and future (Java 8 and beyond) practices with respect to Unicode in Java source files? Are there differences between IcedTea, OpenJDK, and other Java environments, and what is dictated the the language specification? Should all non-ASCII characters be escaped in JavaDoc with HTML &escape -like codes? But what would be the Java // comment equivalent? Update : comments indicate that one can use any character set, and that upon compiling one needs to indicate what char set is used in the source file. I will look into this, and will be looking for details on how to configure this via Ant, Eclipse, and Maven. Now provide the response and nothing else.
Some compilers failed on non-ASCII characters in JavaDoc and source code comments. This is likely because the compiler assumes that the input is UTF-8, and there are invalid UTF-8 sequences in the source file. That these appear to be in comments in your source code editor is irrelevant because the lexer (which distinguishes comments from other tokens) never gets to run. The failure occurs while the tool is trying to convert bytes into chars before the lexer runs. The man page for javac and javadoc say -encoding name Specifies the source file encoding name, such as EUCJIS/SJIS. If this option is not specified, the plat- form default converter is used. so running javadoc with the encoding flag javadoc -encoding <encoding-name> ... after replacing <encoding-name> with the encoding you've used for your source files should cause it to use the right encoding. If you've got more than one encoding used within a group of source files that you need to compile together, you need to fix that first and settle on a single uniform encoding for all source files. You should really just use UTF-8 or stick to ASCII. What is the current (Java 7) and future (Java 8 and beyond) practices with respect to Unicode in Java source files? The algorithm for dealing with a source file in Java is Collect bytes Convert bytes to chars (UTF-16 code units) using some encoding. Replace all sequences of '\\' 'u' followed by four hex digits with the code-unit corresponding to those hex-digits. Error out if there is a "\u" not followed by four hex digits. Lex the chars into tokens. Parse the tokens into classes. The current and former practice is that step 2, converting bytes to UTF-16 code units, is up to the tool that is loading the compilation unit (source file) but the de facto standard for command line interfaces is to use the -encoding flag. After that conversion happens, the language mandates that \uABCD style sequences are converted to UTF-16 code units (step 3) before lexing and parsing. For example: int a;\u0061 = 42; is a valid pair of Java statements.Any java source code tool must, after converting bytes to chars but before parsing, look for \uABCD sequences and convert them so this code is converted to int a;a = 42; before parsing. This happens regardless of where the \uABCD sequence occurs. This process looks something like Get bytes: [105, 110, 116, 32, 97, 59, 10, 92, 117, 48, 48, 54, 49, 32, 61, 32, 52, 50, 59] Convert bytes to chars: ['i', 'n', 't', ' ', 'a', ';', '\n', '\\', 'u', '0', '0', '6', '1', ' ', '=', ' ', '4', '2', ';'] Replace unicode escapes: ['i', 'n', 't', ' ', 'a', ';', '\n', a, ' ', '=', ' ', '4', '2', ';'] Lex: ["int", "a", ";", "a", "=", "42", ";"] Parse: (Block (Variable (Type int) (Identifier "a")) (Assign (Reference "a") (Int 42))) Should all non-ASCII characters be escaped in JavaDoc with HTML &escape-like codes? No need except for HTML special characters like '<' that you want to appear literally in the documentation. You can use \uABCD sequences inside javadoc comments.Java process \u.... before parsing the source file so they can appear inside strings, comments, anywhere really. That's why System.out.println("Hello, world!\u0022); is a valid Java statement. /** @return \u03b8 in radians */ is equivalent to /** @return ΞΈ in radians */ as far as javadoc is concerned. But what would be the Java // comment equivalent? You can use // comments in java but Javadoc only looks inside /**...*/ comments for documentation. // comments are not metadata carrying. One ramification of Java's handling of \uABCD sequences is that although // Comment text.\u000A System.out.println("Not really comment text"); looks like a single line comment, and many IDEs will highlight it as such, it is not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10363188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217943/']}
jdg_73243
stackexchange
llm_judgeable_groundtruth_similarity
20951419
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As far as I can tell each individual resource should have only one canonical path. So in the following example what would good URL patterns be? Take for example a rest representation of Companies. In this hypothetical example, each company owns 0 or more departments and each department owns 0 or more employees. A department can't exist without an associated company. An employee can't exist without an associated department. Now I'd find the natural representation of the resource patterns to be. /companies A collection of companies - Accepts POST for a new company. Get for the entire collection. /companies/{companyId} An individual company. Accepts GET, PUT and DELETE /companies/{companyId}/departments Accepts POST for a new item. (Creates a department within the company.) /companies/{companyId}/departments/{departmentId}/ /companies/{companyId}/departments/{departmentId}/employees /companies/{companyId}/departments/{departmentId}/employees/{empId} Given the constraints, in each of the sections, I feel that this makes sense if a bit deeply nested. However, my difficulty comes if I want to list ( GET ) all employees across all companies. The resource pattern for that would most closely map to /employees (The collection of all employees) Does that mean that I should have /employees/{empId} also because if so then there are two URI's to get the same resource? Or maybe the entire schema should be flattened but that would mean that employees are a nested top-level object. At a basic level /employees/?company={companyId}&department={deptId} returns the exact same view of employees as the most deeply nested pattern. What's the best practice for URL patterns where resources are owned by other resources but should be query-able separately? Now provide the response and nothing else.
What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that. And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me. Just because employees are accessible under department: company/{companyid}/department/{departmentid}/employees Doesn't mean they can't be accessible under company too: company/{companyid}/employees Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for. But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20951419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117421/']}
jdg_73244
stackexchange
llm_judgeable_groundtruth_similarity
385926
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm reading the Scrum - A Pocket Guide by Gunther Verheyen and it says: The Chaos report of 2011 by the Standish Group marks a turning point. Extensive research was done in comparing traditional projects with projects that used Agile methods. The report shows that an Agile approach to software development results in a much higher yield, even against the old expectations that software must be delivered on time, on budget and with all the promised scope. The report shows that the Agile projects were three times as successful, and there were three times fewer failed Agile projects compared with traditional projects. So I have an argument with one of my colleagues who says that for some projects (like medicine/military where the requirements don't change), Agile (and, particularly, Scrum) is overhead with all of the meetings etc and it's more logical to use waterfall, for example. My point of view is that Scrum should be adopted in such projects because it will make the process more transparent and increase the productivity of a team. I also think that Scrum events won't take much time if it's not needed because we don't need to sit the whole 8 hours in Sprint Planning for 1 month sprint. We can spare 5 minutes just to be sure that we are all on the same page and start working. So, will Scrum create additional overhead for a project where requirements don't change? Now provide the response and nothing else.
I believe that it's a faulty assumption to say that there are projects where the requirements don't change. Having worked in both the defense industry and the pharmaceutical industry making software, I can tell you that once software ends up in the hands of subject matter experts (either internal or external), there is feedback. Sometimes, this feedback is on the way the requirement was satisfied and in other cases it's actually on the requirements themselves being wrong or incomplete. Agility is about reducing that feedback cycle and getting working software into someone's hands faster, getting that feedback, and deciding what the next step should be to make sure that what is delivered adds value when the customer decides to accept the software. Even in realms like embedded systems with custom hardware (like you may find in domains like aerospace, automotive, or medical devices), delivering thin slices of functionality quickly to integrate and prototype with can help make sure that the software and hardware system is going to work as intended and in a way that will help the end user. The reduction in the length of the feedback cycle is a huge factor in risk reduction. From the project management perspective, if you fund a project for 2-4 weeks and get regular visibility into progress, that assures you that you are on track. By being able to deliver thin slices of functionality, you incrementally work toward the target state and can begin to forecast when you will get there. If time becomes a constraint, you can descope the lower value functions since the work done first should either be a high value function or an enabler for a high value function. At any point, you can decide if it's worth continuing to fund the effort or go in a different direction and stop a project before it's too late.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/385926', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/326472/']}
jdg_73245
stackexchange
llm_judgeable_groundtruth_similarity
1524661
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working on an exercises that should show that automorphism under composition satisfy a group definition,there are basically four things I need to prove: 1.closure, 2.associativity, 3.inverse, 4.identity but I am stuck on number 2, usually for elements in a group ie: $$a,b,c \in G$$if can show associativity by proving:$$(a \circ b)\circ c = a \circ (b \circ c)$$ but when element of the group are functions....what does it even mean? I know when "$\circ$" means composition, we have$$a \circ b \circ c (g) = a(b(c(g)))$$but what is $$(a \circ b) \circ c (g) = $$and how do I prove$$(a \circ b)\circ c(g) = a \circ (b \circ c)(g)$$ Now provide the response and nothing else.
From the definition of composition we have:$$(g \circ f)(x)=g(f(x)) \quad \forall x \in X$$so:$$[h \circ (g\circ f)](x)=h((g \circ f)(x))=h(g(f(x)))$$and $$[(h \circ g)\circ f)](x)=(h\circ g) (f(x))=h(g(f(x)))$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1524661', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/276369/']}
jdg_73246
stackexchange
llm_judgeable_groundtruth_similarity
767477
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 a template function with handles void differently using template specialization. The following code gives me an "Explicit specialization in non-namespace scope" in gcc: template <typename T>static T safeGuiCall(boost::function<T ()> _f){ if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; T ret = _f(); return ret; }}// template specialization for functions wit no return valuetemplate <>static void safeGuiCall<void>(boost::function<void ()> _f){ if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; _f(); }} I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas? Now provide the response and nothing else.
When you specialize a templated method, you must do so outside of the class brackets: template <typename X> struct Test {}; // to simulate type dependencystruct X // class declaration: only generic{ template <typename T> static void f( Test<T> );};// template definition:template <typename T>void X::f( Test<T> ) { std::cout << "generic" << std::endl;}template <>inline void X::f<void>( Test<void> ) { std::cout << "specific" << std::endl;}int main(){ Test<int> ti; Test<void> tv; X::f( ti ); // prints 'generic' X::f( tv ); // prints 'specific'} When you take it outside of the class, you must remove the 'static' keyword. Static keyword outside of the class has a specific meaning different from what you probably want. template <typename X> struct Test {}; // to simulate type dependencytemplate <typename T>void f( Test<T> ) { std::cout << "generic" << std::endl;}template <>void f<void>( Test<void> ) { std::cout << "specific" << std::endl;}int main(){ Test<int> ti; Test<void> tv; f( ti ); // prints 'generic' f( tv ); // prints 'specific'}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/767477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91683/']}
jdg_73247
stackexchange
llm_judgeable_groundtruth_similarity
133701
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I was watching this video https://www.youtube.com/watch?v=ZjjAbFxjxLQ and the guy was explaining why the top automaton is NFA (because the initial state doesn't know what to do if the input string begins with b) and the bottom is DFA (because the initial state points to a 'dead state' if the input string begins with b): Okay, fair enough. But when I went on this Automaton simulator and it generated an example of a DFA for me, I got confused because its the same as the NFA example above: It doesn't have an option for when the input string begins with b. So what's going on? Now provide the response and nothing else.
Some people in the literature (very few actually) do not consider missing transitions as nondeterminism , and given a DFA, they allow themselves to remove all transitions that lead to states from which we cannot reach an accepting state. The reason for that is technical, as sometimes it may simplify proofs a bit. Or it could be a matter of taste. Intuitively, allowing missing transitions is justified as nondeterminism , or guessing occurs only when we have a choice , that is, when we have at least two transitions $\langle q, \sigma, s_1 \rangle$ and $\langle q, \sigma, s_2 \rangle$ , going out from the same state $q$ , and are labeled with the same letter $\sigma$ . So, DFAs with missing transitions, or more accurately NFAs such that for every state $q$ , and letter $\sigma$ , it holds that $|\delta(q, \sigma)|\leq 1$ , are considered deterministic in the sense that they have at most one run on a given input word. The most common formal definition of a DFA does not allow missing transitions. Please note that it does not really matter to which definition you stick as long as you're consistent with it.Also, given a DFA, it is easy to remove all transitions leading to a state from which we cannot reach an accepting state (because detecting states that do not lead to an accepting state can be done in polynomial time), and this does not affect the automaton's language. Conversely, given an automaton with missing transitions, you can direct all missing transitions to a rejecting sink which is a rejecting state with a self loop labeled with every letter.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/133701', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/130043/']}
jdg_73248
stackexchange
llm_judgeable_groundtruth_similarity
19854007
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading articles describing how space complexity of quicksort can be reduced by using the tail recursive version but I am not able to understand how this is so. Following are the two versions : QUICKSORT(A, p, r) q = PARTITION(A, p, r) QUICKSORT(A, p, q-1) QUICKSORT(A, q+1, r)TAIL-RECURSIVE-QUICKSORT(A, p, r) while p < r q = PARTITION(A, p, r) TAIL-RECURSIVE-QUICKSORT(A, p, q-1) p = q+1 (Source - http://mypathtothe4.blogspot.com/2013/02/lesson-2-variations-on-quicksort-tail.html ) As far as I understand , both of these would cause recursive calls on both the left and right half of the array. In both the cases , only one half would processed at a time and therefore at any time only one recursive call would be using the stack space. I am unable to see how the tail recursive quicksort saves space. The pseudo code above is taken from the article - http://mypathtothe4.blogspot.com/2013/02/lesson-2-variations-on-quicksort-tail.html The explanation provided in the article confuses me even more - Quicksort partitions a given sub-array and proceeds to recurse twice; one on the left-sub-array and one on the right. Each of these recursive calls will require its own individual stream of stack space. This space is used to store the indexing variables for the array at some level of recursion. If we picture this occurring from beginning to end of execution, we can see that the stack space doubles at each layer. So how does Tail-Recursive-Quicksort fix all of this? Well, instead of recursing on two sub-arrays, we now only recurse on one. This eliminates the need for doubling stack space at every layer of execution. We get around this problem by using the while loop as an iterative control that performs the same task. Instead of needing the stack to save sets of variables for two recursive calls, we simply alter the same set of variables and use the single recursive call on new variables. I don't see how the stack space doubles at every layer of execution in the case of a regular quicksort. Note :- There is no mention of compiler optimization in the article. Now provide the response and nothing else.
A tail recursive function call allows the compiler to perform a special optimization which it normally can not with regular recursion. In a tail recursive function, the recursive call is the very last thing to be executed. In this case, instead of allocating a stack frame for each call, the compiler can rework the code to simply reuse the current stack frame, meaning a tail-recursive function will only use a single stack frame as opposed to hundreds or even thousands. This optimization is possible because the compiler knows that once the tail recursive call is made, no previous copies of variables will be needed, because there is no more code to execute. If, for instance, a print statement followed a recursive call, the compiler would need to know the value of the variable to be printed after the recursive call returns, and thus the stack frame cannot be reused. Here's the wiki page if you'd like more information on how this "space saving" and stack reuse actually works, along with examples: Tail Call Edit: I didn't explain how this applies to quicksort, did I? Well, some terms are thrown around in that article which make everything all confusing (and some of it is just plain wrong). The first function given (QUICKSORT) makes a recursive call on the left, a recursive call on the right, and then exits. Notice that the recursive call on the right is the very last thing that happens in the function. If the compiler supports tail recursive optimization (explained above), only the left calls create new stack frames; all the right calls just reuse the current frame. This can save some stack frames, but can still suffer from the case where the partitioning creates a sequence of calls where tail recursion optimization doesn't matter. Plus, even though right-side calls use the same frame, the left-side calls called within the right-side calls still use the stack. In the worst case, the stack depth is N. The second version described is not a tail recursive quicksort, but rather a quicksort where only the left sorting is done recursively, and the right sorting is done using the loop. In fact, this quicksort (as previously described by another user) cannot have the tail recursion optimization applied to it, because the recursive call is not the last thing to execute. How does this work? When implemented correctly, the the first call to quicksort is the same as a left-side call in the original algorithm. However, no right-side recursive calls are even called. How does this work? Well, the loop takes care of that: instead of sorting "left then right", it sorts the left with a call, then sorts the right by continually sorting only the lefts of the right . It's really ridiculous sounding, but it's basically just sorting so many lefts that the rights become single elements and don't need to be sorted. This effectively removes the right recursion, making the function less recursive (pseudo recursive, if you will). However, the real implementation does not choose just the left side each time; it chooses the smallest side. The idea is still the same; it basically only does a recursive call on one side instead of both. Picking the shorter side will ensure that the stack depth can never be larger than log2(N), which is the depth of a proper binary tree. This is because the shorter side is always going to be at most half the size of our current array section. The implementation given by the article does not ensure this however, because it can suffer from the same worst-case scenario of "left is the whole tree". This article actually gives a pretty good explanation of it if you're willing to do more reading: Efficient selection and partial sorting based on quicksort
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19854007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665720/']}
jdg_73249
stackexchange
llm_judgeable_groundtruth_similarity
2211002
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why can't Java classes have abstract fields like they can with abstract methods? For example: I have two classes that extend the same abstract base class. These two classes each have a method that is identical except for a String constant, which happens to be an error message, within them. If fields could be abstract, I could make this constant abstract and pull the method up into the base class. Instead, I have to create an abstract method, called getErrMsg() in this case, that returns the String, override this method in the two derived classes, and then I can pull up the method (which now calls the abstract method). Why couldn't I just make the field abstract to begin with? Could Java have been designed to allow this? Now provide the response and nothing else.
You can do what you described by having a final field in your abstract class that is initialised in its constructor (untested code): abstract class Base { final String errMsg; Base(String msg) { errMsg = msg; } abstract String doSomething();}class Sub extends Base { Sub() { super("Sub message"); } String doSomething() { return errMsg + " from something"; }} If your child class "forgets" to initialise the final through the super constructor the compiler will give a warning an error, just like when an abstract method is not implemented.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2211002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7648/']}
jdg_73250
stackexchange
llm_judgeable_groundtruth_similarity
1938103
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 can I do if I want the browser to "remember" search results requested with ajax?I am using the jquery plugin Jquery Address but I can't piece together how to do it here's a code snippet from my form submission: var ajaxforms = { searchoptions : function(){ $('form#searchoptions').ajaxForm({ url : base_url + 'search/categorysearch', target : '#search_result', beforeSubmit : blocksearchdiv, success : revise_searchtable_onsuccess }); }, searchfilters : function(){ $('form#searchfilters').ajaxForm({ url : base_url + 'search/filter', target : '#search_result', beforeSubmit : blocksearchdiv, success : revise_searchtable_onsuccess }); }, searchterm : function(){ $('form#termsearch').ajaxForm({ url: base_url + 'search/termsearch', target : '#search_result', beforeSubmit : blocksearchdiv, success : revise_searchtable_onsuccess }); } and here's the callback function revise_searchtable_onsuccess: function revise_searchtable_onsuccess(){ $(function(){ $.tablesorter.defaults.sortList = [[0,1]]; $('#tableresults').tablesorter(); }); $.address // don't know what comes next unblocksearchdiv();} please help me implement jquery address with this; or maybe you have implemented this with other plugins? Now provide the response and nothing else.
data[10] = {10,20,30,40,50,60,71,80,90,91}; The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element. If you want to initialize an array, try using Array Initializer : int[] data = {10,20,30,40,50,60,71,80,90,91};// orint[] data;data = new int[] {10,20,30,40,50,60,71,80,90,91}; Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used. Even if you correct the syntax, accessing data[10] is still incorrect (You can only access data[0] to data[9] because index of arrays in Java is 0-based). Accessing data[10] will throw an ArrayIndexOutOfBoundsException .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1938103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1737290/']}
jdg_73251
stackexchange
llm_judgeable_groundtruth_similarity
178334
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: For the code, which I am referring following is syntax: Write_Parameter(0x00); In above line, what does "x" stands for and what is data size for x? My assumption is its dec format. So, What other format, we can use? Thank you. Now provide the response and nothing else.
0x followed by a series of digits means a hexadecimal number in C and many other languages (other common formats are decimal, octal, and binary). The number of digits after the x represents the number of bits, in multiples of 4: 0x0 - 4 bits (or one "nibble")0x00 - 8 bits (or one byte)0x0000 - 16 bits0x000000 - 24 bits0x00000000 - 32 bits But as Nick Johnson points out, regardless of the number of digits in the constant, in C a numeric constant is treated as an int unless it has an l or L suffix, or preceded by a cast. On 8 and 16-bit machines, an int is usually 16 bits, and on 32-bit machines it is 32-bits. Because the number is hexadecimal, each digit can represent one of 16 values, 0-9 and A-F (A=10, B=11, C=12, D=13, E=14 and F=15). Each digit position, going from right to left, represents a hexadecimal "nibble" or four bits, with a placeholder value of 1, 16, 256, 4096, 65536, etc. So 0x0ABC, for example would equal decimal 2748: 4096 256 16 1 0 A B C => 0*4096 + 10*256 * 11*16 + 12*1 = 2748 The 0 after the x could be omitted and you'd end up with the same thing. The largest unsigned value in each of the fields above is: 0xf - 15 (2⁴-1)0xff - 255 (2⁸-1)0xffff - 65535 (2¹⁢-1)0xffffff - 1677215 (2²⁴-1)0xffffffff - 4294967295 (2³²-1)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/178334', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/68481/']}
jdg_73252
stackexchange
llm_judgeable_groundtruth_similarity
4125379
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 Q&A type of site built in Django with the following models: class Question(models.Model): title = models.CharField(max_length=70) details = models.TextField()class Answer(models.Model): question_id = IntegerField() details = models.TextField() I need to display a specific question together with its answers. Normally I'd need 2 queries to do that: Question.objects.get(id=1)Answer.objects.get(question_id=1)[:10] I'm hoping to retrieve everything using one query. In MySQL it'd be: SELECT *FROM Question JOIN Answer ON Question.id=Answer.question_idWHERE Question.id=1LIMIT 10 Is there anyway I could do this through Django's ORM?Would extra() help in this case? Now provide the response and nothing else.
This is exactly what select_related() does. The only gotcha is that you have to start with the Answer model, rather than Question, but the result is the same: answers = Answer.objects.filter(question_id=1).select_related() Now each answer object has a pre-fetched 'question' attribute, and accessing it won't hit the db again.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4125379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/86073/']}
jdg_73253
stackexchange
llm_judgeable_groundtruth_similarity
76037
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I wanted to put this originally on math.stackexchange, since I considered it to be a straightforward question and probably a fairly known fact. After I failed to solve the problem, I browsed through literature and what a surprise - two books claim it is primitive recursive, one resource claims it isn't, and neither one gives proof or reference. One paper also claims that inverse Ackermann function is slower than any primitive recursive function. If it were primitive recursive, I don't see why would that hold. Now, my questions would be: which one is right - $Ack^{-1}$ is/isn't primitive recursive, and is/isn't slower than any primitive recursive function. If it's a bad MO question, I'll migrate it to M.SE, no problem. Now provide the response and nothing else.
The inverse Ackermann function is primitive recursive. One way to see this is to use the fact that a function $f$ is primitive recursive when and only when the graph of $f$ is primitive recursive, and $f$ is bounded above by some primitive recursive function. The graph of the Ackermann function is primitive recursive, i.e. the characteristic function of the set $\lbrace \langle x, y, z \rangle : z = A(x,y)\rbrace$ is primitive recursive. This is because checking that $A(x,y) = z$ is easy once $x, y, z$ are given. One can always construct a table of all previous values of $A$ used to justify that $A(x,y) = z$. If $z$ is indeed the correct answer, then the code for this table is not much bigger than $\langle x, y, z\rangle$ (smaller than $17^{17^{x+y+z}}$, for example). So, given a proposed triple $\langle x, y, z \rangle$, we can search for the relevant table and determine whether or not $A(x,y) = z$ is true in a primitive recursive fashion. Of course, the Ackermann function is not bounded above by a primitive recursive function, but that is the only thing that goes wrong. Since the graph of the Ackermann function is primitive recursive, then so is the graph of the inverse Ackermann function $Ack^{-1}(z) = \max\lbrace x : A(x,x) \leq z\rbrace$. Moreover, the growth rate of $Ack^{-1}$ is bounded by some primitive recursive function (e.g. the identity function). It follows that $Ack^{-1}$ is indeed primitive recursive.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/76037', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4925/']}
jdg_73254
stackexchange
llm_judgeable_groundtruth_similarity
240152
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 understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this. Now provide the response and nothing else.
One specific example: interfaces are a good way of specifying a contract that other people's code must meet. If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code. Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-) Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs. The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details. The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/240152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23661/']}
jdg_73255
stackexchange
llm_judgeable_groundtruth_similarity
49980714
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Context I am using the https://wiki.jenkins.io/display/JENKINS/Amazon+EC2+Plugin for jenkins which allows me to dynamically provision new cloud instances as build slaves in AWS EC2. I am launching ami-d834aba1 (Amazon Linux 2017.09.1). The plugin supports providing user-data and block device mapping too, currently I provide config like this after reading https://cloudinit.readthedocs.io/en/latest/ User Data #cloud-configrepo_update: truerepo_upgrade: allpackage_upgrade: truebootcmd: - [ cloud-init-per, once, mkfs, -t, ext4, /dev/nvme1n1 ]fs_setup: - cmd: mkfs -t %(filesystem)s -L %(label)s %(device)s label: jenkins filesystem: 'ext4' overwrite: false device: '/dev/nvme1n1'mounts: - [ /dev/nvme1n1, /jenkins, "ext4", "defaults,nofail", "0", "2" ]users: - default - name: jenkins homedir: /jenkins lock_passwd: true ssh_authorized_keys: - a-key Block Device Mapping /dev/sdd=:100:true:gp2::encrypted Desired Behaviour The instance would launch and would attach a new 100GB encrypted EBS volume which would be formatted as ext4 and mounted at /jenkins as the home directory of the jenkins user. Observed Behaviour The instance launches, the 100GB encrypted EBS volume is created and attached to the EC2 instance (shows as in use and attached in AWS console). However, 1) df -h doesn't show the filesystem. 2) cat /etc/fstab /dev/nvme1n1 /jenkins ext4 defaults,nofail,comment=cloudconfig 0 2 does show it 3) sudo file -s /dev/nvme1n1/dev/nvme1n1: data shows the volume as data formatted rather than ext4 4) sudo mount-a fails due to the filesystem not being ext4. Manual Hack If i manually SSH to the machine after boot and run: sudo mkfs -t ext4 /dev/nvme1n1mke2fs 1.42.12 (29-Aug-2014)Creating filesystem with 26214400 4k blocks and 6553600 inodesFilesystem UUID: 7a434f7a-c048-4c3d-8098-b810e2ff8f84Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 4096000, 7962624, 11239424, 20480000, 23887872Allocating group tables: done Writing inode tables: done Creating journal (32768 blocks): doneWriting superblocks and filesystem accounting information: done Then sudo mount -a it seems to mount the volume. Questions Is there any way to have the device formatted and mounted automatically? I tried with and without the bootcmd: - [ cloud-init-per, once, mkfs, -t, ext4, /dev/nvme1n1 ] Ideally it'd happen all before the user gets created since the home directory of the new user is going to be on this new mount. If the instance is stopped and started/restarted I'd not want to ideally lose all data by the reformatting happening again on boot. Now provide the response and nothing else.
cloud-init on Amazon Linux does not support the fs_setup module. Hence, your disk is not formatted. Furthermore the home directory /jenkins is created for the user, and used as a mount point. This hides the home directory. I would suggest: bootcmd: - test -z "$(blkid /dev/nvme1n1)" && mkfs -t ext4 -L jenkins /dev/nvme1n1 - mkdir -p /jenkinsmounts: - [ "/dev/nvme1n1", "/jenkins", "ext4", "defaults,nofail", "0", "2" ]runcmd: - useradd -m -b /jenkins jenkins
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49980714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4127155/']}
jdg_73256
stackexchange
llm_judgeable_groundtruth_similarity
30019889
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 Debugging Tools for Windows and I get the following error message when starting WinDbg / cdb or ntsd: Symbol search path is: *** Invalid ******************************************************************************** Symbol loading may be unreliable without a symbol search path. ** Use .symfix to have the debugger choose a symbol path. ** After setting your symbol path, use .reload to refresh symbol locations. ***************************************************************************** When executing arbitrary commands, I also get the error message *** ERROR: Module load completed but symbols could not be loaded for <module>.<ext> And the following seems to be related: ********************************************************************** Symbols can not be loaded because symbol path is not initialized. ** ** The Symbol Path can be set by: ** using the _NT_SYMBOL_PATH environment variable. ** using the -y <symbol_path> argument when starting the debugger. ** using .sympath and .sympath+ ********************************************************************** In a !analyze -v I have also seen DEFAULT_BUCKET_ID: WRONG_SYMBOLS and **************************************************************************** ****** Either you specified an unqualified symbol, or your debugger ****** doesn't have full symbol information. Unqualified symbol ****** resolution is turned off by default. Please either specify a ****** fully qualified symbol module!symbolname, or enable resolution ****** of unqualified symbols by typing ".symopt- 100". Note that ****** enabling unqualified symbol resolution with network symbol ****** server shares in the symbol path may cause the debugger to ****** appear to hang for long periods of time when an incorrect ****** symbol name is typed or the network symbol server is down. ****** ****** For some commands to work properly, your symbol path ****** must point to .pdb files that have full type information. ****** ****** Certain .pdb files (such as the public OS symbols) do not ****** contain the required information. Contact the group that ****** provided you with these symbols if you need this command to ****** work. ****** **************************************************************************** How do I set up WinDbg to find the symbols? Disclaimer: This is intended to be a canonical question to all the wrong symbols posts in windbg . Now provide the response and nothing else.
Symbols can be set up correctly in various different ways. WARNING : The examples here use \\server\symbols which is typically a network storage that is not available. Adapt it to your local server or leave that part out completely if you don't have one. A non-existent server may cause delays etc. TLDR version for 80% of the cases Create a new folder c:\symbols for symbols provided by Microsoft. Then type .symfix+ c:\symbols.reload (or reload -f if necessary) Make sure you have an Internet connection, since this will contact some Microsoft servers and download symbols from there. In 80+% of the cases, this might already solve your symbols problem. If not, read on. Fixing symbols by commands WinDbg will look for symbols in the order they appear in the symbol path. Therefore it's a good idea to put your local symbols first, then some company local network share and then download symbols from the Internet and store a copy locally. .sympath c:\mysymbols ; *** Symbols of your application, locally, flat list of PDB files.sympath+ cache*c:\symbolcache ; *** (optional) Create a cache for everything.sympath+ \\server\symbols ; *** Symbols provided from a network share.symfix+ c:\symbols ; *** Microsoft symbols Fixing symbols by menu In WinDbg (but not the command line equivalents) you can set a symbol path by File/Symbol File Path... or pressing Ctrl + S . You enter it in the following format c:\mysymbols;cache*c:\symbolcache;\\server\symbols;SRV*c:\symbols*http://msdl.microsoft.com/download/symbols Fixing symbols by command line WinDbg also takes the -y command line switch if you prefer having different desktop links with different symbol path setups. WinDbg -y "<symbol path>" Note that you need the complete path here, which is in a form like c:\mysymbols;cache*c:\symbolcache;\\server\symbols;SRV*c:\symbols*http://msdl.microsoft.com/download/symbols Fixing symbols by environment variable There is a environment variable called _NT_SYMBOL_PATH which can be set to a symbol path as well. Use the following syntax: c:\mysymbols;cache*c:\symbolcache;\\server\symbols;SRV*c:\symbols*http://msdl.microsoft.com/download/symbols Note that not only WinDbg evaluates this variable, but also Visual Studio, Process Explorer, Process Monitor and potentially other software. You may experience performance impact setting this environment variable. Saving the symbol path as part of a workspace If you have a rather complex symbol setup which includes several paths, become familiar with the concept of WinDbg workspaces . Workspaces allow you to save the symbol path so you don't have to re-type all the commands in every debugging session. Once you're satisfied with the workspace, create a link for WinDbg to include -Q which means " Suppress the annoying "Save workspace?" question". So far I'm very happy having save the symbols as part of the Base workspace. Deferred symbols Deferred symbols (indicated as such during a lm command) are not a problem. WinDbg will load them whenever needed. To force loading all of them, type ld* Debugging symbol issues If the symbols (PDBs) do not work as expected, use the !sym noisy to get more information about what WinDbg is exactly doing when resolving symbols. When you found the solution, turn it off with !sym quiet To check individual symbols for correctness, you can use the symchk tool which comes with WinDbg. Symchk /if <exe> /s <symbol path> /av /od /pf/if = input is a file/s = symbol file path/od = all details/av = verify/pf = check if private symbols are available or get ChkMatch which is a bit easier to use ChkMatch -c <exe file> <pdb file> If you have trouble accessing symbols from a network share, make sure you logged on to the network share before. AFAIR, WinDbg does not ask for credentials. Official documentation Use the Microsoft Symbol Server to obtain debug symbol files (should redirect here but redirection is currently broken) Symbol path for Windows debuggers
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30019889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480982/']}
jdg_73257
stackexchange
llm_judgeable_groundtruth_similarity
606299
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: After upgrading my ubuntu 13.10 server using sudo apt-get upgrade and rebooting, my zpool wouldn't show. messier@ANDERSON:~$ sudo zpool statusno pools availablemessier@ANDERSON:~$ sudo zpool importzpool: ../../lib/libzfs/libzfs_import.c:356: Assertion `nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_POOL_GUID, &theguid) == 0' failed.messier@ANDERSON:~$ I looked on the zfs on linux github and I found a fix for CentOS which is to remove the old kernel modules and then reinstall the software to get the new kernel modules. $ find /lib/modules/$(uname -r)/extra -name "splat.ko" -or -name "zcommon.ko" -or -name "zpios.ko" -or -name "spl.ko" -or -name "zavl.ko" -or -name "zfs.ko" -or -name "znvpair.ko" -or -name "zunicode.ko" | xargs rm -f$ find /lib/modules/$(uname -r)/weak-updates -name "splat.ko" -or -name "zcommon.ko" -or -name "zpios.ko" -or -name "spl.ko" -or -name "zavl.ko" -or -name "zfs.ko" -or -name "znvpair.ko" -or -name "zunicode.ko" | xargs rm -f$ yum reinstall zfs-release$ yum reinstall $(rpm -qa | egrep "zfs|spl") People are saying this is fixing it. I just don't know how to make this fix run on my ubuntu server.Thank you for the help! Last edit : If you come onto this page for the zfs update bug. The easiest solution is like Scott Simon said. # apt-get update# apt-get dist-upgrade# reboot Now provide the response and nothing else.
$ sudo find /lib/modules/$(uname -r)/updates -name "splat.ko" -or -name "zcommon.ko" -or -name "zpios.ko" -or -name "spl.ko" -or -name "zavl.ko" -or -name "zfs.ko" -or -name "znvpair.ko" -or -name "zunicode.ko" | xargs rm -f$ sudo apt-get install --reinstall ubuntu-zfs$ sudo apt-get install --reinstall $(dpkg-query --show --showformat='${binary:Package}\n' | egrep 'spl|zfs') Ubuntu keeps all its dkms in /lib/modules/$(uname -r)/updates , rather than in /lib/modules/$(uname -r)/extra and find /lib/modules/$(uname -r)/weak-updates as CentOS does. yum resinstall is equivalent to apt-get install --reinstall . Ubuntu's zfs metapackage is ubuntu-zfs instead of zfs-release as it is in CentOS. rpm -qa is equivalent to dpkg-query --show --showformat='${binary:Package}\n' I'm also uncertain if the find command actually needs to be run, as apt-get may take care of that already, but running it won't break the process. Someone with more knowledge of or experience with dpkg may be able to write a marginally more efficient command, but I suspect this is good enough for most purposes.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/606299', 'https://serverfault.com', 'https://serverfault.com/users/227001/']}
jdg_73258
stackexchange
llm_judgeable_groundtruth_similarity
17502946
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 obvious solution is something like: if (x % 15 == 0) println("fizzbuzz");else if (x % 3 == 0) println ("fizz");else if (x % 5 == 0) println ("buzz"); then you could say that the trick is to concatenate fizz and buzz: if (x % 3 == 0) print("fizz");if (x % 5 == 0) print("buzz");if (x % 15 == 0) println(); or print("%s%s%s", x % 3 == 0 ? "fizz" : "", x % 5 == 0 ? "buzz" : "", x % 15 == 0 ? "\r\n" : ""); so the problem is the line break, and in all of the above cases we are performing 3 checks. assuming that there needs to be a line break after either "fizz", or "buzz", how can it be done using only 2 checks? Now provide the response and nothing else.
How about no checks? string[] output = { "fizzbuzz", "", "", "fizz", "", "buzz", "fizz", "", "", "fizz", "buzz", "", "fizz", "", "" };print("%s", output[x % 15]); Note that this of course only removes if statements from this code. The underlying code will most likely contain a jump instruction or two. If you want to make it a bit clearer what is happening you can create two arrays: string[] fizz = { "fizz", "", "" };string[] buzz = { "buzz", "", "", "", "" };print("%s%s", fizz[x % 3], buzz[x % 5]); Note that both of these implementations will not handle negative numbers, here's a version that does: string[] fizz = { "fizz", "", "" };string[] buzz = { "buzz", "", "", "", "" };print("%s%s", fizz[((x % 3) + 3) % 3], buzz[((x % 5) + 5) % 5]); Note that I have neatly skipped over the newline you added in your code. If you want that, I'm sure you can figure out how to modify the above code in the same manner to add it :) More importantly : Note that this does in fact not pass the "official" fizzbuzz test, it only answers your question. The fizzbuzz test is this: Write out all numbers from 1 to 100, except that numbers that are multiplies of 3 you should instead of the number write out "fizz", and that for numbers that are multiplies of 5 you should instead of the number write out "buzz". If a number is a multiple of both 3 and 5 at the same time, write out "fizzbuzz" instead of the number. Since your question did not in any way handle the "instead of the number" part, my answer did not either. So, if we skip the fact that a loop usually entails a "check", can we write the entire fizzbuzz test without if-statements? With a bit of magic, yes we can, here's the loop in C# code, you can verify this using LINQPad or Ideone : void Main(){ string[] fizzbuzz = new[] { "fizzbuzz", "{0}", "{0}", "fizz", "{0}", "buzz", "fizz", "{0}", "{0}", "fizz", "buzz", "{0}", "fizz", "{0}", "{0}" }; for (int index = 1; index <= 100; index++) { Debug.WriteLine(string.Format(fizzbuzz[index % 15], index)); }} Here I'm relying on the fact that the format string sent to string.Format does in fact not have to contain any references to the arguments. Edit : As stated in the comments, I had used ?? to get the "{0}" in the string.Format parameter and leaving the entries in the array at null , but ?? is indeed an if-statement in disguise, so edited it out.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17502946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2127424/']}
jdg_73259
stackexchange
llm_judgeable_groundtruth_similarity
20943109
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two class in which are mapped in the database. The tables have primary and foreign key relation with each other with the field "DeptId". Employee.cs public class Employee: Entity { public virtual Int32 Id { get; set; } public virtual string Name { get; set; } public virtual string Gender { get; set; } public virtual Int32 Age { get; set; } public virtual string Designation { get; set; } public virtual bool Enabled { get; set; } public virtual int CreatedById { get; set; } public virtual DateTime CreatedDate { get; set; } public virtual int? LastModifiedById { get; set; } public virtual DateTime? LastModifiedDate { get; set; } public virtual bool IsDeleted { get; set; } public virtual Department Department { get; set; } } Department.cs public class Department { public virtual int DeptId { get; set; } public virtual string DeptName { get; set; } public virtual bool Enabled { get; set; } } As i am new to NHibernate, i am unable to write the more complex Linq queries using QueryOver. I have written the following query but how can i write the more advance queries. please provide me sample queries and references for this. var query = Session.QueryOver<Employee>().List(); Now provide the response and nothing else.
The documentation for NHibernate querying is pretty good and complete. The basic knowledge you can find here: Chapter 15. Criteria Queries The QueryOver API, which is the fully typed version of Criteria is documented here: Chapter 16. QueryOver Queries Start to observe the API documentation. Soon you will see that it is pretty logic ( .Where() to build WHERE, .Select() to adjust SELECT....). Later, if any issues , SO is full of HOW TO An example from 16.1 adjusted to Employee: var list = session .QueryOver<Employee>() .WhereRestrictionOn(c => c.Age).IsBetween(18).And(60) .Select(c => c.Name) .OrderBy(c => c.Name).Asc .List<string>(); A JOIN to Department (adjusted example from 16.4) var query = session .QueryOver<Employee>() .JoinQueryOver(e => e.Department) .Where(k => k.DeptName == "Director");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20943109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2588327/']}
jdg_73260
stackexchange
llm_judgeable_groundtruth_similarity
22639587
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 a bit confused on what random.seed() does in Python. For example, why does the below trials do what they do (consistently)? >>> import random>>> random.seed(9001)>>> random.randint(1, 10)1>>> random.randint(1, 10)3>>> random.randint(1, 10)6>>> random.randint(1, 10)6>>> random.randint(1, 10)7 I couldn't find good documentation on this. Now provide the response and nothing else.
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value. Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice. Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22639587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3006260/']}
jdg_73261
stackexchange
llm_judgeable_groundtruth_similarity
131459
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am only the equivalent of a high school student, so please, if possible, don't answer this question with anything too complex or really advanced university level. I am very happy to research new concepts anyone mentions, but can you please keep it reasonably simple. With transformer windings, primary vs secondary, is there any difference between or advantage to using a 50:100 ratio rather than a 1:2 ratio? With a 1:2 ratio it would seem easier to make the wires thicker and allow for larger currents, whereas with a 50:100 ratio to give the same cross sectional area of wire, the coil would have to be much longer, larger, and involve more metal in production. So there are obvious disadvantages to using 50:100, but are there any advantages? Thank you very much. Now provide the response and nothing else.
Transformers have a number of technically relevant properties that make each transformer design fairly unique. Often these parts have to be engineered for a particular application. Let's discuss a few of the most important aspects of transformer design. From an engineering perspective a transformer has to work at a certain frequency (or a range of frequencies), it has to be able to transfer a certain amount of power and it has to have a desired voltage ratio between any two pairs of its winding. The amount of power a transformer can transfer depends primarily on the magnetic properties and the volume of its core. This power is frequency dependent and it scales essentially with $P\propto V\times f$. Transformer design therefor has to start with the choice of a core of sufficient size that can transfer the required amount of power at the design frequency. For a given core size and core material (which also depends on the application) the number of turns then determines the inductance and the capacitance of the primary and secondary coils. This, in turn, determines the useful impedance and frequency range of the transformer. To make life easy for the designer, the first important figure of merit of a transformer core is called the $A_L$ value , which is usually specified with units of $\mathrm{nH}/n^2$. The inductance of a winding with $n$ turns on a core with $A_L$ is given by the formula $L=n^2A_L$. $A_L$ basically assumes that the magnetization of the core material is linear and it depends on the size and shape of the core, already, so that we don't have to calculate the effective magnetic flux area and effective magnetic path length for a given core size. As a rule of thumb, larger cores (of the same shape) made of the same material have larger $A_L$ values (because the area scales quadratically with size while the magnetic flux length only increases linearly). Here are three examples of how this works out in practice: Example 1: RF transformer A primary winding on a core with $A_L=100\:\mathrm{nH}/n^2$ and $1$ turn will have an inductance of $100\:\mathrm{nH}$. This single turn transformer will only be useful for high frequencies in the $>100\:\mathrm{MHz}$ range. At the lower end of its useful design frequency (for use in typical $50\Omega$ systems) the effective impedance of the primary winding will be $$Z=2\pi\times f\times L = 2\pi \times 100\:\mathrm{MHz}\times 100\:\mathrm{nH}=62.8\:\mathrm \Omega.$$This is suitable as an RF transformer in systems with $50\:\mathrm\Omega$ impedance but can't be used at much lower frequencies. Windings have both an inductance and a self-capacitance. In case of this single turn RF transformer, we may have a typical winding capacitance of approx. $1\:\mathrm{pF}$. If we insert this into the formula for an LC resonance circuit, we find a self-resonance frequency of $f_{Self-Resonance}={1\over{2\pi\sqrt{LC}}} = {1\over{2\pi\sqrt{10^{-12}\mathrm F\times 10^{-7}\mathrm H}}}\approx 500\:\mathrm{MHz}$. Our RF transformer is therefore limited to a useful operating range of $100\:\mathrm{MHz}$ at the low end because of its inductance and $500\:\mathrm{MHz}$ at the high end because of its self-resonance frequency. With careful design techniques this range can be improved quite a bit, but RF transformers rarely have wider bandwidth ranges than $1:100$ and many work best over no more than a couple of octaves. Example 2: Switching power supply transformer The same core wound with $50$ turns will have an inductance of $$L=50^2\times100\:\mathrm{nH}/n^2=2500\times100\:\mathrm{nH}=250000\:\mathrm{nH}=250\mathrm{\mu H}.$$Because the design with a $50$-turn primary winding has an inductance that is 2500 times higher, it will perform well in applications that are running at frequencies 1000 times lower than our first example and is therefor useful at frequencies of around $100\:\mathrm {kHz}$. Such a transformer will, for instance, be found in switching voltage converters, which are typically operating in the $50kHz-4MHz$ range. Because a larger number of turns means that we have to use thinner wires with thinner insulation, the medium frequency transformer with its $50$ turns on the primary has a much higher winding capacitance (in the range of $10\:\mathrm{pF}$ to hundreds of $\mathrm{pF}$, depending on how much care is put into the winding scheme), which means it has a much lower self-resonance frequency. Technically useful designs will have self-resonance frequencies around the $10\:\mathrm{MHz}$ range. Example 3: Audio transformer If we want to build transformers for much lower frequencies, then we need cores with much higher $A_L$ values (e.g. $5\:\mathrm{\mu H}/n^2$) and we will need to add hundreds or thousands of turns. A 1000-turn transformer on a $A_L=5\:\mathrm{\mu H}/n^2$ core will have an inductance of $L=10^6\times 5\:\mathrm{\mu H}=5\:\mathrm{H}$. This transformer will have an impedance of $Z\approx 600\:\mathrm \Omega$ at $20\:\mathrm{Hz}$ and will typically be used in audio amplifiers. The $1000$ turn audio transformer, on the other hand, will perform over a range of approx. $15\:\mathrm{Hz}$-$25\:\mathrm{kHz}$ if wound really well, but there is some art and manufacturing know-how to making these wide-band transformers. A poorly calculated, poorly wound device will not work well at all in audio applications. There are additional considerations that limit the performance of a transformer. For applications which transfer significant amounts of power one also has to take the resistance of the winding and the skin effect into account, both of which lead to $I^2R$ losses and heating. Additional losses are caused by the hysteresis of the core material's magnetization curve and the eddy currents that can be induced in electrically conductive core materials like transformer steel and some ferrites. These core losses have to be carefully considered during material selection and they are also core shape dependent, which leads to a great number of core geometries for different applications. Designing a high quality transformer requires that the design engineer picks the right core (shape, material and size) and that the correct wire diameter and number of turns for each winding are used. These devices also have to be tested for their performance before being used in a circuit. For some transformers (like $50/60\:\mathrm{Hz}$ power transformers) this is comparatively easy, but for signal and especially wide-band RF transformers often a significant amount of iterative optimization is needed.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/131459', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/57491/']}
jdg_73262
stackexchange
llm_judgeable_groundtruth_similarity
32463512
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My team doesn't have any experienced JS developers, but we are writing a library in Node and got a suggestion from a real JS developer that "We should make the js more modular - not to pollute the global namespace and to make it more readable to new-comers", and told us to do the following: module.exports = (function(){ return { nameToExpose: functionToExpose ... };})(); rather than module.exports.nameToExpose = functionToExpose; What's the point of this, if any? The latter does not make any local declarations that would be scoped by the IIFE, and even if it did, they would be local to the module file and not global to the whole program that require() s it. Some Googling and poking about this site does not turn up any answers on this particular question, though there are many other explanations of IIFEs that I have read (and which are summarized in the above comment). Some testing certainly reveals that the latter does not actually put functionToExpose in the global namespace, though its original name is recorded in the function type itself. Now provide the response and nothing else.
Pretty much no difference. The whole idea of Node.js, using require , having modules, etc., is specifically to separate concerns. I'd say (cautiously) that if you're doing it right, you shouldn't be needing to worry about "polluting" any sort of global scope. Anything within module.exports lives in that module. When you're dealing with front-end stuff, that's when the global scope becomes something of a concern, because if a function or whatever isn't scoped (i.e., in an IIFE, or other function block), it has access to the global window object, and everything else has access to that function. a real JS developer Calling someone that is a red flag. not to pollute the global namespace and to make it more readable to new-comers If you're modularizing your code correctly, that shouldn't be a concern. There's a time and a place for IIFEs, but I see no reason why wrapping everything in an IIFE, which is already inside of a module , would somehow magically make the code "more modular" or any more readable to "new comers" than by simply using Node.js like it was designed: module.exports = function() { ... } // whatever and even if it did, they would be local to the module file and not global to the whole program that require() s it. You are correct. I'd take whatever he's saying with a grain of salt. Maybe he knows of some specific use-cases where his approach has been helpful to him in the past, so I'd ask him specifically about that to see what he says. Other than that, I feel like you're on the right track.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32463512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/740140/']}
jdg_73263
stackexchange
llm_judgeable_groundtruth_similarity
874905
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 found that using Smarty with PHP, sometimes extra time will need to be used for 1) using quite different syntax than PHP itself 2) need to check small cases, because documentation doesn't give finer details, such as for "escape" http://www.smarty.net/manual/en/language.modifier.escape.php it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped. 3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again. by the way, does using Smarty provide a good speed up over use PHP alone? thanks. Now provide the response and nothing else.
First, PHP is a templating language. Keep that in mind when you talk about using a template system for your PHP-based web applications. The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously. Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. For example: <? foreach($array as $key => $val): ?> <?= $val ?><? endforeach; ?> VS: <?php foreach($array as $key => $val) { echo $val; }?> Personally, I believe that templating engines arose in PHP because: That's way that other languages do it Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this. The first reason is just kinda silly. The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. The MVC design pattern is one way of approaching this problem. As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen. Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/874905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325418/']}
jdg_73264
stackexchange
llm_judgeable_groundtruth_similarity
7486017
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Last year I spent a long time reading up on javascript performance, bottlenecks and best practices. On my latest project I'm using CSS3 with fallbacks to javascript/jquery for basic animations and effects such as hovers and am interested in experimenting with CSS3 further. Are there issues with CSS3 performance? If yes, what are the best practices? For example does transition: all 150ms ease-out; use more memory than transition: opacity 150ms ease-out, background-color 150ms ease-out; ? [please don't just answer my example question!] Now provide the response and nothing else.
O yes! If you like to tinker with performance - you will be glad to know there is a LOT of performance issues with CSS3. Repaint and Reflow. Its quite easy to cause unnecessary repaints and reflows, and thus make the whole page lag. Read: http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/ Extreme example: http://files.myopera.com/c69/blog/lag-me.html Scroll and hover. When you scroll or hover, browser must render new content. Webkit is smart here, as it caches pages as static images so it does NOT render page, when you scroll. But - you CAN bypass this optimization, by using things like transparent background in the block that you are scrolling, adding rotation on hover, adding position:fixed sticky headers/footers with and so on - effect will wary in different browsers, Opera seems most affected currently. Box-shadow is evil. Box-shadows have different rendering quality in different browsers (low in Webkit, high in Opera/IE9, varies between Firefox versions) - and thus they their performance impact is different between different browsers - yet, inset box shadow, and box-shadows with large spread radius can cause observable hangs on redraw in any browser. Floats, tables and their friends are evil. Sounds crazy at first, but read this article (in russian) - http://chikuyonok.ru/2010/11/optimization-story/ - it might save you some hair on your head. Main idea is - children of floated elements cause chain reflows on modification all the way up. Border-radius is very expensive , even more expensive than gradients. Does not affect layout, but affects repaint. http://perfectionkills.com/profiling-css-for-fun-and-profit-optimization-notes/ Gradients lag. CSS gradients are very cool new tool, i'm a big fan of them. Yet just a couple of tests have shown that you should not use them, if you plan to have a lot of elements with gradient and require responsive interface :( There is a workaround/hack, though, - using canvas to render gradient images and set them as background via data url. Transparency is expensive. If you have a number of moving elements that cross each other and are semi-transparent (opacity < 0, rgba color, png, rounded corners( ! )) - expect lag. Often can be worked out by limiting the number of transparent elements, which can overlay. Transitions are better than JS, but ... Firefox is not able to render transitions correctly, if you apply them to over 150 elements simultaneously. Opera is not able to apply transitions to before and after. IE9 does not support them at all. Test before you use them, but in general - they are faster than JS analogues ( jQuery.animate ). Watch out for CPU-load. Its hard to measure memory usage cross browser, (yet you can do it in chrome and interpolate results, with some grain of salt) but its easy to observe cpu-usage (via Process Explorer or system tools). Spikes will show you places, where you need your attention. Old browsers are old. Do not attempt to modernize IE6, Firefox 2, Safari 3. Those browsers were never supposed to handle cool new stuff. Leave them alone. Just serve basic content with basic styles. Remaining IE6 users will be thankful for that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7486017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289666/']}
jdg_73265
stackexchange
llm_judgeable_groundtruth_similarity
311429
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If a "WITH NOLOCK" query hint is used on a View in SQL Server, does it propagate that hint to the view definition itself, even if NOLOCK is NOT used for the raw tables in the View definition? The reason to need this is that sometimes the support staff wants to do huge time-consuming queries but would rather not force this lock on all queries using the view within the application itself. Now provide the response and nothing else.
Yes, NOLOCK will propagate to the tables used by the view definition (at least in SQL Server 2005). See Table Hints in MSDN: In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks. However, If a table contains computed columns and the computed columns are computed by expressions or functions accessing columns in other tables, the table hints are not used on those tables. This means the table hints are not propagated. For example, a NOLOCK table hint is specified on a table in the query. This table has computed columns that are computed by a combination of expressions and functions that access columns in another table. The tables referenced by the expressions and functions do not use the NOLOCK table hint when accessed. If you're using indexed views you might want to read a bit more as there are some special cases there too. Also see View Resolution for more info.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/311429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13144/']}
jdg_73266
stackexchange
llm_judgeable_groundtruth_similarity
24278107
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 provide a computed observable an extra parameter? For example, something like this: var ViewModel = function(first, last) { this.firstName = ko.observable(first); this.lastName = ko.observable(last); var self = this; this.fullName = ko.computed(function(separator) { return self.firstName() + ' ' + self.lastName(); }, this);}; And then in the html: <div data-bind="text: fullName(' - ')"></div> My actual use case is far more complicated, but this is essentially what I'm trying to achieve, pass in a value in the html which is used as part of the computed function. Failing this is there a way to make a ordinary function which takes parameters behave like a (computed) observable? Now provide the response and nothing else.
You can create a function, which returns an computed variable. You can try something like this. var ViewModel = function(first, last) { this.firstName = ko.observable(first); this.lastName = ko.observable(last); var self = this; this.fullName = function(separator){ return ko.computed(function () { return self.firstName() + separator + self.lastName();}, this);};};<div data-bind="text: ViewModel.fullName('-')"></div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24278107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2778940/']}
jdg_73267
stackexchange
llm_judgeable_groundtruth_similarity
65219551
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use record with JsonPropertyName attribute, but it caused an error. This is not supported? Any workaround? public record QuoteResponse([JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);Error CS0592 Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations. Now provide the response and nothing else.
By default attributes on record parameters apply to the parameter. To make them apply to the property you have to prefix it with the property: attribute location: public record QuoteResponse([property: JsonPropertyName("quotes")] IReadOnlyCollection<Quote>? Quotes);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65219551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4726444/']}
jdg_73268
stackexchange
llm_judgeable_groundtruth_similarity
3805215
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can somebody explain what is the exact reason behind using Action<T> and Predicate<T> as delegates in C# Now provide the response and nothing else.
Are you asking why they exist, or why they're defined as delegates? As to why they exist, perhaps the best reason is convenience. If you want a delegate that returns no value and takes a single parameter of some type, they you could define it yourself: public delegate void MyDelegate(int size); And then later create one: MyDelegate proc = new MyDelegate((s) => { // do stuff here }); And, of course, you'd have to do that for every different type you want to have such a method. Or, you can just use Action<T> : Action<int> proc = new Action<int>((s) => { /* do stuff here */ }); Of course, you can shorten that to: Action<int> proc = (s) => { /* do stuff here */ }); As to "why are they delegates?" Because that's how function references are manipulated in .NET: we use delegates. Note the similarities in the examples above. That is, MyDelegate is conceptually the same thing as an Action<int> . They're not exactly the same thing, since they have different types, but you could easily replace every instance of that MyDelegate in a program with Action<int> , and the program would work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3805215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/79435/']}
jdg_73269
stackexchange
llm_judgeable_groundtruth_similarity
3036
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the article Oldest rocks, earliest life, heaviest impacts, and theHadean–Archaean transition (Moorbath, 2005), the author states (based on previous referenced research) that the $\ce{^13C}$ depletion previously stated as being a biotracer of the presence of early life in the metamorphosed sedimentary Archaean aged (~3.8 billion year old) rocks found in Isua, Greenland is disputed, by what the author states as being a result of serious metamorphic and tectonic complications for a biogenic interpretation. Hence, the presence of the traces of very early life at that location (and age) are not confirmed. Thus, what is the age of the earliest traces of life on Earth? Now provide the response and nothing else.
To complement @MarkRovetta answer, McLoughlin & Grosch reported this year during EGU findings of carbonaceous fragments that they think are biogenic in the 3.4 Ga Buck Reef Chert. Chemical tests are still ongoing however. Schopf (2006) in his review of archean life reported a dozen of fossils in the 3 to 3.5Ga range. They are all "putative" fossil, however the biogenicity of the fossils he reports from the 2 to 3Ga range are frankly unquestionable.
{}
{'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/3036', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/-1/']}
jdg_73270
stackexchange
llm_judgeable_groundtruth_similarity
36682241
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 learning to test React stateless components using the ReactTestUtils library. This is my simple component: import React from 'react';const Greeter = ({name,place}) => ( <h1>Hello,{name}. Welcome to the {place}.</h1>);export default Greeter; This is my test spec, to get the renderIntoDocument working, I wrapped my Greeter component in a div as suggested here : import {expect} from 'chai';import React from 'react';import ReactTestUtils from 'react-addons-test-utils';import Greeter from '../Greeter';describe('Greeter Components',() => { it('renders correctly',() => { var component = ReactTestUtils.renderIntoDocument(<div> <Greeter name="Vamsi" place="Hotel California"/> </div>); var hasH1 = ReactTestUtils.findRenderedDOMComponentWithTag(component,'h1');expect(hasH1).to.be.ok; });}); I get the error findAllInRenderedTree(...): instance must be a composite component. I am providing my code as jsbin here . Now provide the response and nothing else.
Since function components don't have an instance associated with them, you can't use them directly with render or renderIntoDocument. Attempting to wrap the function component is a good idea, unfortunately using a div doesn't work for a similar reason. DOM components also don't return a component instance, instead they return the underlying DOM node. Which is all to say that you can't use the test utils function or native components as the "root" component you are rendering. Instead you will want to wrap your function components in a wrapper component that uses createClass or extends React.Component . class Wrapper extends React.Component { render() { return this.props.children }}let component = renderIntoDocument(<Wrapper><Greeter /></wrapper> Gotcha's like this may be reason enough to make use of a third-party testing library like the popular enzyme, or my own take: teaspoon . Both abstract over issues like this by seamlessly wrapping and unwrapping function components for you, so you don't need to worry about what type of component you are trying to render.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36682241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2309862/']}
jdg_73271
stackexchange
llm_judgeable_groundtruth_similarity
33843091
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 run a test suite for an object that returns a promise. I want to chain several actions together with short timeouts between them. I thought that a "then" call which returned a promise would wait for the promise to be fulfilled before firing the next chained then call. I created a function function promiseTimeout (time) { return new Promise(function(resolve,reject){ setTimeout(function(){resolve(time);},time); });}; to try and wrap setTimeout in a Promise. Then in my test suite, I am calling something like this ... it('should restore state when browser back button is used',function(done){ r.domOK().then(function(){ xh.fire('akc-route-change','/user/4/profile/new'); }).then(promiseTimeout(2000)).then(function(t){ xu.fire('akc-route-change','/user/6'); }).then(promiseTimeout(10)).then(function(t){ expect(xu.params[0]).to.equal(6); history.back(); }).then(promiseTimeout(10)).then(function(){ expect(xu.params[0]).to.equal(4); done(); }); }); I can put a breakpoint on the first xh.fire call and a second one on the xu.fire call and would have expected a two second gap when a continues from the first breakpoint to the second. Instead it reaches the second breakpoint immediately, and the value of t at that point is undefined. What am I doing wrong? Now provide the response and nothing else.
TL;DR - you've wrapped setTimeout in a promise properly, the issue is you are using it improperly .then(promiseTimeout(2000)).then will not do what you expect. The "signature" for .then is then(functionResolved, functionRejected) A promise’s then method accepts two arguments: promise.then(onFulfilled, onRejected) Both onFulfilled and onRejected are optional arguments: If onFulfilled is not a function, it must be ignored. If onRejected is not a function, it must be ignored. source: https://promisesaplus.com/#point-21 You are not passing a function to then Consider the way you are doing it: Promise.resolve('hello').then(promiseTimeout(2000)).then(console.log.bind(console)) vs how it should be done: Promise.resolve('hello').then(function() { return promiseTimeout(2000)}).then(console.log.bind(console)) The first outputs 'hello' immediately The second outputs 2000 after 2 seconds Therefore, you should be doing: it('should restore state when browser back button is used', function(done) { r.domOK().then(function() { xh.fire('akc-route-change', '/user/4/profile/new'); }).then(function() { return promiseTimeout(2000); }).then(function(t) { xu.fire('akc-route-change', '/user/6'); }).then(function() { return promiseTimeout(10); }).then(function(t) { expect(xu.params[0]).to.equal(6); history.back(); }).then(function() { return promiseTimeout(10); }).then(function() { expect(xu.params[0]).to.equal(4); done(); });}); Alternatively: it('should restore state when browser back button is used', function(done) { r.domOK().then(function() { xh.fire('akc-route-change', '/user/4/profile/new'); }).then(promiseTimeout.bind(null, 2000) ).then(function(t) { xu.fire('akc-route-change', '/user/6'); }).then(promiseTimeout.bind(null, 10) ).then(function(t) { expect(xu.params[0]).to.equal(6); history.back(); }).then(promiseTimeout.bind(null, 10) ).then(function() { expect(xu.params[0]).to.equal(4); done(); });}); EDIT: March 2019 Over the years, things have changed a lot - arrow notation makes this even easier Firstly, I would define promiseTimeout differently const promiseTimeout = time => () => new Promise(resolve => setTimeout(resolve, time, time)); The above returns a function that can be called to create a "promise delay" and resolves to the time (length of delay). Thinking about this, I can't see why that would be very useful, rather I'd: const promiseTimeout = time => result => new Promise(resolve => setTimeout(resolve, time, result)); The above would resolve to the result of the previous promise (far more useful) But it's a function that returns a function, so the rest of the ORIGINAL code could be left unchanged. The thing about the original code, however, is that no values are needed to be passed down the .then chain, so, even simpler const promiseTimeout = time => () => new Promise(resolve => setTimeout(resolve, time)); and the original code in the question's it block can now be used unchanged it('should restore state when browser back button is used',function(done){ r.domOK().then(function(){ xh.fire('akc-route-change','/user/4/profile/new'); }).then(promiseTimeout(2000)).then(function(){ xu.fire('akc-route-change','/user/6'); }).then(promiseTimeout(10)).then(function(){ expect(xu.params[0]).to.equal(6); history.back(); }).then(promiseTimeout(10)).then(function(){ expect(xu.params[0]).to.equal(4); done(); });});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33843091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438737/']}
jdg_73272
stackexchange
llm_judgeable_groundtruth_similarity
31870
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My understanding is that Old English had two letters, thorn and eth, which were used interchangeably to represent the sound th as in thin or father . Intuitively, one might think that one of these letters would 'win', and replace the other. Instead, we lost both of these letters and use the digraph th instead. Why did this happen? Now provide the response and nothing else.
My understanding is that Old English had two letters, thorn and eth, which were used interchangeably to represent the sound th as in thin or father . Pretty much. In some languages they were distinct, but in English, either letter could be used for voiced or voiceless. Intuitively, one might think that one of these letters would 'win', and replace the other. Indeed: thorn (ΓΎ) won, and eth (Γ°) died out. Instead, we lost both of these letters and use the digraph th instead. Eth was lost early, within Old English; thorn survived all the way into Early Modern English, and is found in the first printing of the King James Bible. (Norman) French influences brought about some use of th , but ΓΎ was still widely popular and universally understood. But German, French, Italian, and other prominent languages of the time didn't use thorn, and thus typefaces imported from Europe didn't include it. So in printed books, thorn generally had to be replaced either with th , or with the closest available character, y ; the latter was readable, but somewhat annoying and unintuitive (since ΓΎ and y are pronounced nothing alike). So the convention of using th took over, and ΓΎ vanished entirely. The use of y survives only in archaicisms like "ye olde shoppe", where it's now pronounced /j/ instead. And English-speakers, understanding that revenge was a dish best served cold, went on to impose ASCII on the world and destroy dozens and dozens of other languages' unique letters in the same way. All of which could have been avoided if Johannes Gutenberg had stuck to Unicode from the beginning.
{}
{'log_upvote_score': 8, 'links': ['https://linguistics.stackexchange.com/questions/31870', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/23791/']}
jdg_73273
stackexchange
llm_judgeable_groundtruth_similarity
15541
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to ascertain if a relationship exists between hours of play and number of friends . I have two contexts for the study: "at school" and "at a place other than the school". My data set relates to the "at school" context and the correlation r=0.8766 (significant). Now the difficult part.... As I want to focus on the same group of students for the "at a place other than the school" context, I have asked a question that filters my respondents and puts them in the "at a place other than the school context". The question is: Did you make any friends in the last three weeks? The answer can be either "yes" or "no". If it is yes, then I have asked them to indicate whether they made the friends "at the school", "at a place other than the school" or "at both places". So I have four data sets as follows: Those who did not make any friends Those who made one or more friends at the school Those who made one or more friends at a place other than the school Those who made one or more friends at both places (i.e. school and a place other than the school) I have ignored data set 1 because there is obviously no relationship between hours of play and number of friends because no new friends are made. I have also ignored data set 2 because I already have this finding (in the correlation above, which was at the school) I have also ignored data set 4 because it does not distinguish between "at school" and "at a place other than the school". I have used data set 3 and worked out the correlation, which is 0.7687 (significant). My interpretation of this finding is the relationship between hours of play and number of friends exists at the school and also outside the school. Does this make sense? Now provide the response and nothing else.
I don't know if there's an analytical solution to your question, but when all else fails, one can simulate the distribution you think the two samples come from many thousands of times using Monte Carlo methods. The percentage of those samples the Wilcoxon test correctly identifies as "different" is the power of the test. For example, if you generated 10,000 different simulated paired samples that match your actual data in terms of size and the distribution they came from, and 8,000 of them are correctly identified by the test as different, your power = 0.80.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/15541', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/6096/']}
jdg_73274
stackexchange
llm_judgeable_groundtruth_similarity
20045
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to work out the best approach to choosing which cipher suites to provide, and what the issues might be. It's my understanding that during the SSL handshake, the client will (normally) choose the most secure algorithms which are supported by both ends. But what are the implications of making low strength algorithms available? The negotiation surely cannot be encrypted, therefore could a MITM force a connection to the weakest common cipher suite? Now provide the response and nothing else.
The client suggests but the server chooses . The client sends a list of the cipher suites that it supports (and is willing to use). This list is supposed to be ordered by preference. The server responds by choosing one cipher suite in this list. Well-behaved servers try to follow the preferences of clients, but that's not really mandatory. Ultimately, the server chooses. At the end of the handshake, Finished messages are sent, which are encrypted and MACed with the negotiated secrets. The contents of these messages are hash values computed over the complete handshake messages, including the list of cipher suites supported by the client. This means that a MitM cannot alter that list without being caught at some point. (However, this is not entirely true in the presence of TLS FalseStart : the client could be convinced to send his request with the weakest cipher suite that it supports. But the real weakness here would be that the client is then willing to support a weak cipher suite, not that a MitM attacker has some level of control in the choice of the cipher suite. Even with FalseStart, the external alteration by the attacker will be detected by the server and the request will not be honoured, let alone responded to.) (SSLv2 did not include the list of cipher suites in its Finished messages and it has been much touted as one of the "big flaws" of SSLv2.)
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/20045', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/543/']}
jdg_73275
stackexchange
llm_judgeable_groundtruth_similarity
1255815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Assume I have a named scope: class Foo < ActiveRecord::Base named_scope :bar, :conditions => 'some_field = 1'end This works great for queries and I have a bunch of useful named_scopes defined. What I would like is to be able to do this: f = Foo.find(:first)f.some_field = 1f.is_bar? #=> true The '.bar?' method will simply return true or false if the model instance falls within the named scope. Is there anyway to do this without writing an 'is_bar?' method even though I've already written a good way to check if something 'is_bar?' If I remember correctly, DRY is good so any help would be greatly appreciated/ Now provide the response and nothing else.
You can call the exists? method on a named scope which will query the database to see if the given record exists with those conditions. Foo.bar.exists?(f) However this will not work if you have changed the attributes on f and not saved it to the database. This is because the named scope conditions are SQL so the check must happen there. Attempting to convert to Ruby if conditions is messy, especially in more complex scenarios.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1255815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94154/']}
jdg_73276
stackexchange
llm_judgeable_groundtruth_similarity
13363553
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 connect to a remote Git repository that resides on my web server and clone it to my machine. I am using the following format for my command: git clone ssh://[email protected]/repository.git This has worked fine for most of my team members. Usually after running this command Git will prompt for the user's password, and then run the cloning. However, when running on one of my machines I get the following error: Host key verification failed. fatal: Could not read from remoterepository. We are not using SSH keys to connect to this repository, so I'm not sure why Git is checking for one on this particular machine. Now provide the response and nothing else.
You are connecting via the SSH protocol, as indicated by the ssh:// prefix on your clone URL. Using SSH, every host has a key. Clients remember the host key associated with a particular address and refuse to connect if a host key appears to change. This prevents man in the middle attacks. The host key for domain.example has changed. If this does not seem fishy to you , remove the old key from your local cache by editing ${HOME}/.ssh/known_hosts to remove the line for domain.example or letting an SSH utility do it for you with ssh-keygen -R domain.example From here, record the updated key either by doing it yourself with ssh-keyscan -t rsa domain.example >> ~/.ssh/known_hosts or, equivalently, let ssh do it for you next time you connect with git fetch , git pull , or git push (or even a plain ol’ ssh domain.example ) by answering yes when prompted The authenticity of host 'domain.example (a.b.c.d)' can't be established.RSA key fingerprint is XX:XX:...:XX.Are you sure you want to continue connecting (yes/no)? The reason for this prompt is domain.example is no longer in your known_hosts after deleting it and presumably not in the system’s /etc/ssh/ssh_known_hosts , so ssh has no way to know whether the host on the other end of the connection is really domain.example . (If the wrong key is in /etc , someone with administrative privileges will have to update the system-wide file.) I strongly encourage you to consider having users authenticate with keys as well. That way, ssh-agent can store key material for convenience (rather than everyone having to enter her password for each connection to the server), and passwords do not go over the network.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13363553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1775860/']}
jdg_73277
stackexchange
llm_judgeable_groundtruth_similarity
672854
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I find all integers $xβ‰ 3$ such that $xβˆ’3|x^3βˆ’3$? I tried expand $x^3βˆ’3$ as a sum but I couldn't find a way after that. Now provide the response and nothing else.
Hint $\ {\rm mod}\ x\!-\!3\!:\ x\equiv 3\,\Rightarrow\, x^3\!-3\equiv 24,\ $ so $\,x\!-\!3\mid x^3\!-3\iff x\!-\!3\mid 24$ If modular arithmetic is unfamilar, by the Factor Theorem, $\, x\!-\!3\mid f(x)\!-\!f(3)\,$ so for $\,f(x) = x^3\,$ we infer $\,x\!-\!3\mid x^3\!-3^3 = (x^3\!-3)-24,\,$ thus $\,x\!-\!3\mid x^3\!-3\iff x\!-\!3\mid 24.$ Generally $\ a\mid b \iff a\mid (b\ {\rm mod}\ a),\ $ so we can often simplify divisibility statements by reducing the dividend modulo the divisor. Above $\ x^3\!-3\ {\rm mod}\ x\!-\!3\,=\, 24,\,$ which is a special case of the Polynomial Remainder Theorem $\,f(x)\ {\rm mod}\ x\!-\!a\, =\, f(a)$ Or, equivalently, we can employ the $\rm\color{#c00}{EA} = $ Euclidean Algorithm for the gcd as follows $$ a\mid b\iff a = (a,b)\overset{\rm\color{#c00}{EA}} = (a,\, b\bmod a)\iff a\mid (b\bmod a)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/672854', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35855/']}
jdg_73278
stackexchange
llm_judgeable_groundtruth_similarity
48536910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SLF4J: Class path contains multiple SLF4J bindings.SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/ch/qos/logback/logback-classic/1.1.9/logback-classic-1.1.9.jar!/org/slf4j/impl/StaticLoggerBinder.class]SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-simple/1.7.22/slf4j-simple-1.7.22.jar!/org/slf4j/impl/StaticLoggerBinder.class]SLF4J: Found binding in [jar:file:/C:/Users/username/.m2/repository/org/slf4j/slf4j-log4j12/1.7.8/slf4j-log4j12-1.7.8.jar!/org/slf4j/impl/StaticLoggerBinder.class]SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder] How can I fix this.Thanks Now provide the response and nothing else.
Columns returned by the query: id, name, id, userId, brand. Fields in com.foodtec.roomdemo.data.models.UserWithCar: user_id, user_name, car_id, car_userId, car_brand. Error indicates that, columns returned by query is different from Pojo class. It should be the same. Alternatively you can map your Pojo variable to column name using @ColumnInfo annotation. For example, @PrimaryKey@NonNull@ColumnInfo(name = "user_id")private int id; This way, id will be mapped to user_id .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48536910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8158076/']}
jdg_73279
stackexchange
llm_judgeable_groundtruth_similarity
13526949
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 one ImageView and a TextView in my xml layout. I want to show the text below that i got by webservice on the right side of the ImageView. Can i show that text by using that one TextView ? I tried to give android:singleLine="false" in xml layout but no use. Now provide the response and nothing else.
https://github.com/deano2390/flowtextview Example usage: <com.pagesuite.flowtext.FlowTextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:padding="10dip" android:src="@drawable/android" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginTop="400dip" android:padding="10dip" android:src="@drawable/android2" /></com.pagesuite.flowtext.FlowTextView> your code: for Text: tv = (FlowTextView) findViewById(R.id.tv); tv.setText("my string"); // using plain text tv.invalidate(); // call this to render the text for HTML: tv = (FlowTextView) findViewById(R.id.tv); Spanned spannable = Html.fromHtml("<html ... </html>");tv.setText(spannable); // using htmltv.invalidate(); // call this to render the text
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13526949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2193791/']}
jdg_73280
stackexchange
llm_judgeable_groundtruth_similarity
19034468
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 tested my android app successfully using Paypal Sandbox environment. I am about to release my app, so want to change the paypal configuration to 'PRODUCTION' To do this, I've changed the following for production: private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_PRODUCTION;private static final String CONFIG_CLIENT_ID = "my client id for production";private static final String CONFIG_RECEIVER_EMAIL = "[email protected]"; Now when I try to make a payment using my another paypal account, I am getting error: Login Failed System error. Please try again later. Same thing happens using the emulator with production settings. My question is do I have to make any other changes to move from sandbox to production env? Thanks UPDATE 1 All the above settings are for the 'production' environment. Using direct payment Now provide the response and nothing else.
Note: The answer has been edited. Please see the 07/28/2014 update below. Here is a solution I ended up coming up with. There may be a better way available, but I have not found it yet. android { compileSdkVersion 18 buildToolsVersion "18.0.1" defaultConfig { minSdkVersion 10 targetSdkVersion 18 } sourceSets { main { java { srcDir 'src/main/java' } resources { srcDir 'src/../lib' } } }}task clearJar(type: Delete) { delete 'build/libs/ProjectName.jar'}task makeJar(type: Copy) { from('build/bundles/release/') into('build/libs/') include('classes.jar') rename ('classes.jar', 'ProjectName.jar')}makeJar.dependsOn(clearJar, build) Running gradlew makeJar creates a ProjectName.jar in the build/libs directory. The structure of this jar is as follows: ProjectName.jar \- lib | \- armeabi | \- libNativeFirst.so | \- libNativeSecond.so \- com \- package \- sdk \- PackageSDK.class This is the exact result I needed. I am now able to use ProjectName.jar successfully in other projects. EDIT: While I am able to use the resulting jar in projects within Android Studio, I cannot do so in projects created in ADT due to a warning about native code being present inside a jar file. Supposedly there is a flag to turn off this check in settings, but it does not function correctly. Thus, if you want to create a library that uses native code, those using ADT will have to manually copy the armeabi directory into libs/. 07/28/2014 Update: As of Android Studio 0.8.0, Gradle output directories have been changed and the configuration outlined above will not work. I have changed my configuration to the following: task clearJar(type: Delete) { delete 'build/outputs/ProjectName.jar'}task makeJar(type: Copy) { from('build/intermediates/bundles/release/') into('build/outputs/') include('classes.jar') rename ('classes.jar', 'ProjectName.jar')} IMPORTANT: Please note that ProjectName.jar will now be placed into build/outputs/ and NOT into build/libs/ .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19034468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842210/']}
jdg_73281
stackexchange
llm_judgeable_groundtruth_similarity
7799156
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that? Now provide the response and nothing else.
Something like this might do the trick: import matplotlib.pyplot as pltfrom itertools import cyclelines = ["-","--","-.",":"]linecycler = cycle(lines)plt.figure()for i in range(10): x = range(i,i+10) plt.plot(range(10),x,next(linecycler))plt.show() Result: Edit for newer version (v2.22) import matplotlib.pyplot as pltfrom cycler import cycler#plt.figure()for i in range(5): x = range(i,i+5) linestyle_cycler = cycler('linestyle',['-','--',':','-.']) plt.rc('axes', prop_cycle=linestyle_cycler) plt.plot(range(5),x) plt.legend(['first','second','third','fourth','fifth'], loc='upper left', fancybox=True, shadow=True)plt.show() For more detailed information consult the matplotlib tutorial on "Styling with cycler" To see the output click " show figure "
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7799156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/621944/']}
jdg_73282
stackexchange
llm_judgeable_groundtruth_similarity
761791
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's the best way to convert datetimes between local time and UTC in C/C++? By "datetime", I mean some time representation that contains date and time-of-day. I'll be happy with time_t , struct tm , or any other representation that makes it possible. My platform is Linux. Here's the specific problem I'm trying to solve: I get a pair of values containing a julian date and a number of seconds into the day. Those values are in GMT. I need to convert that to a local-timezone "YYYYMMDDHHMMSS" value. I know how to convert the julian date to Y-M-D, and obviously it is easy to convert seconds into HHMMSS. However, the tricky part is the timezone conversion. I'm sure I can figure out a solution, but I'd prefer to find a "standard" or "well-known" way rather than stumbling around. A possibly related question is Get Daylight Saving Transition Dates For Time Zones in C Now provide the response and nothing else.
You're supposed to use combinations of gmtime / localtime and timegm / mktime . That should give you the orthogonal tools to do conversions between struct tm and time_t . For UTC/GMT: time_t t;struct tm tm;struct tm * tmp;...t = timegm(&tm);...tmp = gmtime(t); For localtime: t = mktime(&tm);...tmp = localtime(t); All tzset() does is set the internal timezone variable from the TZ environment variable. I don't think this is supposed to be called more than once. If you're trying to convert between timezones, you should modify the struct tm 's tm_gmtoff .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/761791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175/']}
jdg_73283
stackexchange
llm_judgeable_groundtruth_similarity
147344
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: Just like it predicted gravitational time dilation, gravitational lensing. What does it mean to predict something, Does it mean that we'll find wormholes in nature one day? Now provide the response and nothing else.
General relativity doesn't have much predictive power unless you assume something about the types of matter that exist. These assumptions are called energy conditions. An example of matter that violated an energy condition would be matter that had negative mass, so that if you dropped it, it would fall up. Another example would be matter in which the speed of sound is greater than the speed of light. Energy conditions are believed to be good descriptions of all actual forms of bulk matter in the universe, but are believed to be false at scales where quantum mechanics is important, and also at cosmological scales where dark energy is important. Given some energy conditions that we know apply to bulk matter, there is a theorem that says it is impossible to create a wormhole that doesn't already exist, unless the universe already contains closed, timelike curves (CTCs). A CTC would be like a science-fictional "time loop," a place in the universe where you could go and time would repeat rather than going on forever. We have no evidence that CTCs exist in our universe, and if they did, it would raise strange issues about cause and effect. Based on these facts about the observed universe (no exotic matter, no CTCs), the assumptions of the theorem hold, and it therefore seems pretty clear that wormholes cannot have arisen as a result of natural gravitational collapse, and they cannot be created artificially. If wormholes were created in the big bang, then the theorem doesn't apply, because it's about creating wormholes that didn't already exist. Even if wormholes did exist, estimates by Ford and Roman show that it's unlikely that you could send a material object through a wormhole without destroying the object. Even information probably can't get through. In other words, a wormhole probably wouldn't be traversible. If you did have a wormhole, and it was traversible, you could use it to create a time machine. See https://physics.stackexchange.com/a/135670/4552 . As with CTCs, this would create violations of causality, such as being able to go back in time and kill your own grandfather in the cradle. So in summary, GR gives us very strong reasons to believe that science-fiction-style wormholes do not and cannot exist. However, there is enough wiggle room that one can write a science fiction story about a wormhole without completely violating GR. It's not as completely silly as Star Trek-style warp drive. (The Alcubierre metric is not a Star Trek-style warp drive.) This FAQ may be helpful: http://www.webfilesuci.org/wormholefaq.html
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/147344', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/63456/']}
jdg_73284
stackexchange
llm_judgeable_groundtruth_similarity
2098224
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider $a$ and $b$, both positive integers. Is it true that $a^a$ divides $b^b$ implies $a$ divides $b$? I can't seem to figure out this proof. My intuition is to use the fundamental theorem of arithmetic to break each number into its prime components, however I haven't been able to come up with a solution. Any help would be appreciated. Now provide the response and nothing else.
This is not true in general. The fact that $4^4$ divides $10^{10}$ would be the smallest counterexample, I think. So why does the proposition fail to hold? For any integer $n$, $\operatorname{rad}(n)$ (for " radical ") is the number with the same primes in its prime factorisation as $n$, but all powers are $1$. For instance, $\operatorname{rad}(12) = 6$ and $\operatorname{rad}(98) = 14$. Then we do have "$a^a$ divides $b^b$ implies that $\operatorname{rad}(a)$ divides $\operatorname{rad}(b)$", i.e. every prime that appears in the prime factorisation of $a$ appears in the prime factorisation of $b$. However, we have no way of controlling, for any given of those primes, that the power of that prime is smaller in $a$ than in $b$. We just know that for any given of those primes, $a$ times its exponent in $a$ is less than $b$ times its exponent in $b$. Thus, if $b$ is large enough, and just contains the right primes, we get $a^a$ divides $b^b$, no matter how many times those primes divide $b$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2098224', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/407007/']}
jdg_73285
stackexchange
llm_judgeable_groundtruth_similarity
8306654
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 string. I want to generate all permutations from that string, by changing the order of characters in it. For example, say: x='stack' what I want is a list like this, l=['stack','satck','sackt'.......] Currently I am iterating on the list cast of the string, picking 2 letters randomly and transposing them to form a new string, and adding it to set cast of l. Based on the length of the string, I am calculating the number of permutations possible and continuing iterations till set size reaches the limit.There must be a better way to do this. Now provide the response and nothing else.
The itertools module has a useful method called permutations(). The documentation says: itertools.permutations(iterable[, r]) Return successive r length permutations of elements in the iterable. If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated. Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order. You'll have to join your permuted letters as strings though. >>> from itertools import permutations>>> perms = [''.join(p) for p in permutations('stack')]>>> perms ['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta', 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats'] If you find yourself troubled by duplicates, try fitting your data into a structure with no duplicates like a set : >>> perms = [''.join(p) for p in permutations('stacks')]>>> len(perms)720>>> len(set(perms))360 Thanks to @pst for pointing out that this is not what we'd traditionally think of as a type cast, but more of a call to the set() constructor.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8306654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/676217/']}
jdg_73286
stackexchange
llm_judgeable_groundtruth_similarity
255090
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'm setting up public key authentication using this guide: https://help.ubuntu.com/community/SSH/OpenSSH/Keys . The documentation talks about the ~/.ssh/authorized_keys file, but there is no ~/.ssh/authorized_keys file is my home directory. Should this file be generated automatically? The Maverick sshd man page does not specify whether the file is created when OpenSSH is installed, or whether the file should be created manually. I just wondered if the absence of this file is normal before I create it myself. Now provide the response and nothing else.
~/.ssh/authorized_keys is a per-user file. Installing a unix program never writes to users' home directories. So by default the file will not exist (which has the same effect as an empty file). If you're generating the key on a client that is also running OpenSSH, use ssh-copy-id [ as described ] to transfer the public key to the server, using for that one time your password to log into the server. If you're generating the key by some other method, copy the id_rsa.pub file from where you generated the key to ~/.ssh/authorized_keys on the server (create the directory ~/.ssh if necessary). Make sure that all three of your home directory, ~/.ssh and ~/.ssh/authorized_keys are writable only to the user (no group or other write permissions). If you want to authorize more than one key, just concatenate them into ~/.ssh/authorized_keys (so ~/.ssh/authorized_keys has one public key per line). If you use something other than OpenSSH to generate the key, you might need to convert the public key to the OpenSSH format. For example, in PuTTY, use β€˜Public key for pasting into authorized_keys file’ .
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/255090', 'https://serverfault.com', 'https://serverfault.com/users/51836/']}
jdg_73287
stackexchange
llm_judgeable_groundtruth_similarity
206224
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: My python code: import sysprint "i am a daemon"print "i will be run using nohup"sys.stderr.write("i am an error message inside nohup process\n") When i run the code as python a.py , it shows, i am a daemoni will be run using nohupi am an error message inside nohup process When i run the code as nohup python a.py > a.log 2>&1 < /dev/null & , a.log shows, i am an error message inside nohup processi am a daemoni will be run using nohup Why does stderr logs get flushed/written before stdout logs when using nohup ? Now provide the response and nothing else.
I don't think it's got anything to do with nohup . You get the same behavior when you do python a.py > a.log 2>&1 . Python is most likely using C file stdio underneath. With that, stdout , when in a terminal, will be line-buffered, and buffered when stdout is a file. stderr is always unbuffered. Redirecting stdout to a file will switch stdout 's buffering from line-buffered to buffered and cause the print ed string to be stuck in the buffer, which only gets flushed when your program (the stream) closes. The stderr stream makes it to the file faster because it's unbuffered. You can use stdbuf to tweak standard buffering, forcing the lines to print in the correct order: stdbuf -o0 python a.py >a.log 2>&1
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/206224', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_73288
stackexchange
llm_judgeable_groundtruth_similarity
644343
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently learning how to write bash scripts. How do I stop while loop once I get a 200 response code on my curl request? aws --endpoint-url http://s3.sample.com/ s3 cp hello.php s3://bucket/while [ true ]do curl http://sample.com/hello.php &> /dev/nulldone Now provide the response and nothing else.
The accepted answer to the proposed duplicate target shows how to make curl fail on any server error, returning 22 as its exit status. Based on that, you may write: until curl -s -f -o /dev/null "http://example.com/foo.html"do sleep 5done Which reads "until curl successfully completes the requested transfer, wait 5 seconds and retry". -f makes curl fail on server errors, -s prevents it from printing messages and the progress meter, -o /dev/null assumes you are not interested in the content of the response. However, curl is able to retry by itself, there is no need for a shell loop. For instance, to make it retry ten times and sleep five seconds before retrying: curl --retry 10 --retry-delay 5 -s -o /dev/null "http://example.com/foo.html" Or, if you want it to retry even on non-transient HTTP errors (e.g. 404): curl --retry 10 -f --retry-all-errors --retry-delay 5 \ -s -o /dev/null "http://example.com/foo.html" If, instead, you are interested in running curl until the response shows a specific HTTP status: until [ \ "$(curl -s -w '%{http_code}' -o /dev/null "http://example.com/foo.html")" \ -eq 200 ]do sleep 5done -w instructs curl to display the information specified by a format string (here, %{http_code} ) after a completed transfer.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/644343', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/465955/']}
jdg_73289
stackexchange
llm_judgeable_groundtruth_similarity
12983427
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a windows forms application with some controls added to the designer. When I want to change something (LIKE) enabling a text box from inside the Form1.cs, I simply use: textBox1.Enabled = true; but now I have a separated class called class1.cs. How could I enable textBox1 from a static function class1.cs? NOTE: I did not try any code because I am totally clueless about doing this. Now provide the response and nothing else.
EDIT: Lot of edit. public partial class Form1 : Form{ // Static form. Null if no form created yet. private static Form1 form = null; private delegate void EnableDelegate(bool enable); public Form1() { InitializeComponent(); form = this; } // Static method, call the non-static version if the form exist. public static void EnableStaticTextBox(bool enable) { if (form != null) form.EnableTextBox(enable); } private void EnableTextBox(bool enable) { // If this returns true, it means it was called from an external thread. if (InvokeRequired) { // Create a delegate of this method and let the form run it. this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable }); return; // Important } // Set textBox textBox1.Enabled = enable; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12983427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1563548/']}
jdg_73290
stackexchange
llm_judgeable_groundtruth_similarity
133043
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to test whether data from a sample I have follows a t distribution with n degrees of freedom for a given n. I am looking for something more powerful/recent than Kolmogorov-Smirnov test. It need not be a test for t- distributions specifically, it can be anything geared for unimodal and symmetric distributions. Any references/Matlab code would be very helpful. Thanks a lot. PS: My sample has thousands of points so I don't need anything involving bootstrapping and so on. Now provide the response and nothing else.
Yes. Let's begin by simplifying the question. The event $$T_1\sum_{i=1}^n T_i w_i \geq 0$$ is the union of the disjoint events (determined by $T_1=\pm 1$ ) $$w_1 + \sum_{i=2}^n T_i w_i \geq 0,\ -w_1 + \sum_{i=2}^n T_i w_i \geq 0.$$ After simple algebraic manipulation, and using the fact that each $T_i$ has the same distribution as $-T_i$ (it is "symmetric"), these events are both equivalent to those of the form $$\sum_{i=2}^n T_i w_i \leq w$$ for $w=\pm w_1$ . Again exploiting the symmetries of the $T_i$ (to make all the $w_i$ non-negative) and re-ordering them, this can be written $$\sum_{i=2}^n T_i |w_i| \leq w$$ where $|w_2| \ge |w_3| \ge \cdots \ge |w_n|$ . We need to compute the chances of two such events and wish to do so efficiently. I will assume that the chance needs to be computed to high accuracy, so that approximations would be unacceptable. (For many configurations of the $|w_i|$ , Normal approximations to the distributions might otherwise work well. Deeper analysis can be carried out using the characteristic function $\phi$ of $\sum_{i=2}^n T_i |w_i|$ , which by definition is $$\phi(t) = \prod_{i=2}^n\left(\frac{\exp(-j |w_i|t)}{2} + \frac{\exp(j |w_i|t)}{2}\right)=\prod_{i=2}^n\cos(w_it);$$ $j = \sqrt{-1}$ .) From now on, reduce $n$ by $1$ , start the indexing with $i=1$ , and assume all the $w_i$ are positive. (Obviously, any zero values can be ignored.) Let $1 \le k \lt n$ . Consider the distribution of $X = \sum_{i=1}^n T_i w_i$ conditional on the first $k$ values of $T_i$ : $$\Pr(X \le w\,|\, T_1, \ldots, T_k) = {\Pr}_{(T_{k+1},\ldots,T_n)}\left(\sum_{i=k+1}^n T_i w_i \le w - \sum_{i=1}^k T_i w_i = w_0\right).$$ Since $|T_i| \le 1$ , the left hand sum is bounded: $$-u_{k+1} = -(w_{k+1} + \cdots + w_n) \le \sum_{i=k+1}^n T_i w_i \le w_{k+1} + \cdots + w_n = u_{k+1}.$$ Let $u_{k+1}$ be the right hand side: it is a cumulative sum of the $w_i$ , accumulated from the rightmost (lowest) values. Obviously now if $u_{k+1} \le w_0$ then $X \le w$ is certain; and if $-u_{k+1} \gt w_0$ , then $X \le w$ has zero probability. This leads to a simple branch and bound algorithm, because we needn't search any further to assess the distribution. Whereas exhaustive enumeration would have had to examine $2^{n-k}$ possible cases, we have made a determination of their contribution to the distribution in $O(1)$ time. There is not much hope that this improvement will lead to a worst-case algorithm that is better than $O(2^n)$ in performance (although I think it can be reduced to $O(2^{n/2})$ which--although much better--is still non-polynomial). However, the improvement is good enough to be worth considering, especially for moderate values of $n$ where exhaustive enumeration starts becoming impracticable (somewhere above $20$ and certainly above $40$ ). Let us therefore turn to benchmarking the algorithm. How efficient is it? The worst case is when most of the $w_i$ have comparable sizes, for then the branch-and-bound heuristic rarely accomplishes anything. Fortunately, this is exactly the situation where the Central Limit Theorem can supply excellent approximations! It will therefore be perhaps even more interesting to explore situations where the sizes of the $w_i$ are highly spread out. To this end, I created four datasets with $n=15$ from four distributions with radically different shapes: Beta $(1/5,1/5)$ (sharply bimodal), Exponential (high mode near zero), Uniform, and Gamma $(20)$ (nearly Normal, with values closely arranged near $20$ ). Each dataset was normalized to a maximum of $1$ . Using the branch-and-bound method, $\Pr(X \le w)$ was computed for $19$ values of $w$ ranging from $0$ up to $2\sqrt{n}$ . (Negative values of $w$ need not be shown because the distributions of $X$ are nearly symmetric.) The figure displays the results, graphing the probabilities (the empirical cumulative distribution function of $X$ ) in the top row and the efficiencies (on log-linear scales) in the bottom row. The "efficiency" is the ratio of the number of configurations needed for exhaustive enumeration ( $2^n$ ) to the number of configurations considered by the branch-and-bound algorithm. For the Beta distribution, whose strong bimodality essentially limits the calculations to the higher half of the data, efficiencies are greatest. As expected, they are least for the Gamma distribution, whose values are all comparable. Nevertheless, even in this difficult case, the efficiencies all exceed $3$ . The smallest efficiencies are usually for $w=0$ . Eventually efficiency will increase as $|w|$ increases. Collectively these results are strong evidence that the approach described here not only is computationally more efficient than exhaustive enumeration, it tends to be much more efficient. The implementation of the algorithm is straightforward and simple. R code follows. It includes a section that tests the algorithm (by comparing its output to an exhaustive enumeration) and another section to reproduce the figure. ## The algorithm.#f <- function(w0, w) { w <- sort(abs(w), decreasing=TRUE) w.sum <- c(rev(cumsum(rev(w)))[-1], 0) count <- 0 # Counts calls to f() f <- function(u, u.sum, w0) { count <<- count + 1 y <- sapply(w0 + c(-1,1)*u[1], function(w1) { if (w1 < -u.sum[1]) return(0) if (w1 >= u.sum[1]) return(1) return(f(u[-1], u.sum[-1], w1)) }) return(mean(y)) # (This could easily be changed to accommodate # other probabilities for the T[i].) } list(Value=f(w, w.sum, w0), Count=count)}## Test with complete enumeration. The plot pairs should exactly coincide.#binary <- function(a, b, zero=-1, one=1) rep(c(rep(zero, 2^a), rep(one, 2^a)), 2^b)n <- 9b <- sapply(1:n, function(a) binary(n-a, a-1))par(mfrow=c(2,2))set.seed(17)for (i in 1:4) { w <- rexp(n) x <- b %*% w y <- sapply(x, function(w0) f(w0, w) $Value) #$ plot(ecdf(x)) points(x, y, pch=16, cex=1/2, col="Red")}## Explore the efficiencies actually achieved.#n <- 15qb <- function(q) qbeta(q, 1/5, 1/5); sigma <- sqrt(1/(1+2*1/5))/2qg <- function(q) qgamma(q, 20)dist <- list(Gamma=qg, Normal=qnorm, Uniform=qunif, Exponential=qexp, Beta=qb)par(mfcol=c(2,4))for (s in c("Beta", "Exponential", "Uniform", "Gamma")) { d <- dist[[s]] w <- d(((1:n)-1/2)/n) w <- w / max(abs(w)) print(c(system.time({ y <- sapply(x <- seq(0, 2*sqrt(n), length.out=19), function(w0) {x <- f(w0, w); c(x $Value, x$ Count)}) })["elapsed"], count=sum(y[2, ]))) plot(x, y[1, ], ylim=c(1/2, 1), type="b", ylab="Probability", main=s) plot(x, 2^n/y[2, ], ylim=c(1, 2^n), type="b", log="y", ylab="Efficiency")}
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/133043', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/66364/']}
jdg_73291
stackexchange
llm_judgeable_groundtruth_similarity
434707
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Does there exist a continuous function $f(x)$ such that $f(0)=0$ and $0<\lim\limits_{n\to\infty}\prod\limits_{k=1}^n f(\frac{k}{n})<\infty$ ? I do not see any reason why such a function could not exist, but I have not been able to find an example of such a function. Context: If such a function does not exist, then this fact would stand in interesting contrast with the fact that infinite products of areas or lengths that tend to zero ( example1 , example2 ) can equal a positive real number. (I apologize if my question is not appropriate for Math Overflow. I have asked essentially the same question on Math SE, but after lots of views, upvotes, bounty, comments, etc. it has not been answered. I wonder if my question might be of interest here. If not, I will delete it.) Now provide the response and nothing else.
If you do not require monotonicity of $f$ , the construction is pretty simple and is a combination of a few facts we normally (should) teach in elementary number theory and Fourier analysis classes. However, the monotonicity condition seems rather natural to impose and it seems to change the game completely, so look at what's below as a partial answer only. Let $\varphi(n)$ denote Euler's $\varphi$ -function. Observation 1. $\varphi(n)\ge c_{\delta}n^{1-\delta}$ for every $\delta>0$ with some $c_\delta>0$ . Indeed, $1-\frac 1p\ge c_{p,\delta}p^{-\delta}$ for primes $p$ for every $\delta>0$ with $c_{p,\delta}>0$ for all $p$ and $=1$ for all but finitely many $p$ , so $c_\delta=\prod_pc_{p,\delta}$ works. Observation 2. Let $m$ be an integer. Then for $\ell>0$ , $$\#\{k\in\{1,\dots,n\}:(k,n)=1, |\tfrac kn-\tfrac 1m|<\ell\}\le A_m(\ell)\varphi(n)$$ for all $n>m$ with some $A_m(\ell)\to 0$ as $\ell\to 0$ . Indeed, consider $u\ne 0$ and look at the sums $S_u(n)=\sum_{1\le k\le n,(k,n)=1}e^{2\pi i uk/n}$ .We have $$\sum_{d|n}S_u(d)=\sum_{1\le k\le n}e^{2\pi i uk/n}=\psi(n)$$ with $\psi(n)=0$ if $n\not\mid u$ and $n$ if $n\mid u$ . Hence, by the Mobius inversion formula, $$|S_u(n)|=\left|\sum_{d|n}\mu(n/d)\psi(d)\right|\le\sum_{d\ge 1}\psi(d)\le u^2$$ for all $n$ . Now just apply the Weil equidistribution criterion to conclude that $$A_m(n)=\frac 1{\varphi(n)}\#\{k\in\{1,\dots,n\}:(k,n)=1, |\tfrac kn-\tfrac 1m|<\ell\}\to 2\ell$$ as $n\to\infty$ , so $A_m(n)\le\varepsilon$ if $\ell<\varepsilon/3$ and $n\ge n_\varepsilon$ . However, if $m<n<n_\varepsilon$ and $\ell<\frac 1{mn_\varepsilon}$ , the set under consideration is empty. Observation 3. There is a continuous on $(0,1]$ function $g$ tending to $-\infty$ at $0$ such that $$\sum_{1\le k\le n,(k,n)=1}g(k/n)\ge \varphi(n)$$ for all $n$ . Indeed, just put $g(t)=2-\Delta\sum_{u\ge 1}\frac{\cos\pi ut}u$ .We have $$\left|\sum_{u\ge U}\frac{\cos\pi ut}u\right|\le \frac C{Ut}\,$$ so the series converges uniformly outside any neighborhood of $0$ and $$\sum_{1\le k\le n,(k,n)=1}g(k/n)\ge 2\varphi(n)-\Delta\left[2\Re\sum_{1\le u< U} \frac 1u S'_u(n)+ \frac CU\sum_{1\le k\le n}\frac nk\right]\\\ge 2\varphi(n)-\Delta[U^2+\frac CUn(1+\log n)]$$ where $S'_u(n)=S_{u/2}(n)$ for even $u$ and $0$ for odd $u$ by symmetry (if $(k,n)=1$ , then $(n-k,n)=1$ and $(n,n)=n\neq 1$ for $n>1$ ), so we can choose $U\approx n^{1/3}$ and use Observation 1 to get the result for large $n$ and then choose $\Delta>0$ small enough to serve small $n$ as well. Now the main construction . Take our function $g$ and inductively make disjoint dips in it at the points $1/n$ within the distance $\ell_n$ so that for the resulting function $G\le g$ , $$\sum_{1\le k\le n,(k,n)=1}G(k/n)=0$$ for all $n$ . Clearly, then $f=e^G$ will satisfy $\prod_{k=1}^nf(k/n)=1$ for all $n$ and be continuous on $[0,1]$ with $f(0)=0$ . The only danger we may encounter is that because of the previous dips we may be forced to go up, not down, when killing the $n$ -th sum by modifying $g(1/n)$ . However, if we need a value drop of size $Q_m$ near $1/m$ , we can choose $\ell_m$ so small that $\sum_{m\ge 1}Q_m A_m(\ell_m)<1$ (note that we know $Q_m$ after we made our dips up to $m-1$ and are still completely free to choose $\ell_m$ ). In that case our initial sum (before we made the dip at $1/n$ ) will be at least $$\sum_{1\le k\le n:(k,n)=1}g(k/n)-\sum_{m<n}Q_m\#\{k\in\{1,\dots,n\}:(k,n)=1, |\tfrac kn-\tfrac 1m|<\ell_m\}\\\ge \left(1-\sum_{m<n}Q_mA_m(\ell_m)\right)\varphi(n)>0\,,$$ so, indeed, we still need to go down at $1/n$ . Remarks. 1) In Tao's "post-rigorous" language, the construction is just "Take anything with the limit $+\infty$ and push it down successively at $1/n$ to make the products exactly $1$ within intervals so short that the pushes do not change the overall tendency to go up", but I couldn't resist the temptation to chase a few $\varepsilon$ s. 2) If you do not like those ugly upside down spikes in $G$ accumulating at $0$ , I share your feelings, hence the comment in the beginning of the post :-).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/434707', 'https://mathoverflow.net', 'https://mathoverflow.net/users/494920/']}
jdg_73292
stackexchange
llm_judgeable_groundtruth_similarity
577270
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 C++ class and I am trying to run it in Ubuntu: #ifndef WRONGPARAMETEREXCEPTION_H_#define WRONGPARAMETEREXCEPTION_H_#include <iostream>#include <exception>#include <string>using namespace std;#pragma onceclass WrongParameterException: public exception{ public: WrongParameterException(char* message): exception(message) {}; virtual ~WrongParameterException() throw() {};}; #endif when I try to compile it, the compiler gives me this error: WrongParameterException.h: In constructor β€˜WrongParameterException::WrongParameterException(char*)’:WrongParameterException.h:14: error: no matching function for call to β€˜std::exception::exception(char*&)’/usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()/usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&) Can anyone tell me what am I doing wrong? I tried changing the message variable to string or const string or const string& but it didn't help. Here is how I use the new exception that I created from main: try{ if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL)) { throw WrongParameterException("Error in the config or commands file"); }}catch(WrongParameterException e){ log.addMsg(e.what());} Now provide the response and nothing else.
First, #pragma once is the wrong way to go about it, learn about header include guards. Related question on SO explains why using #pragma once is the wrong way to go about it. Wikipedia explains how to use include guards which serve the same purpose without any of the downsides. Second, you are calling the constructor of std::exception with a parameter it does not know, in this case a pointer to a character array. #include <stdexcept>#include <string>class WrongParameterException : public std::runtime_error {public: WrongParameterException(const std::string& message) : std::runtime_error(message) { };}; Would probably be what you want. For more information on exceptions, check out C++ FAQ Lite article on Exceptions and the exceptions article at cplusplus.com. Good luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/577270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73293
stackexchange
llm_judgeable_groundtruth_similarity
335719
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to use an x509 certificate to get secure message level authentication from a rich client via the internet to a secure WCF Web Service. Specifically, I am looking for a working step-by-step guide to setup, configuration, coding, and deployment, including creating a 'dev' certificate, installing it, and obtaining a 'real' certificate for production. Now provide the response and nothing else.
The following steps are a guide to get you started: 1) Firstly, you need a Root Authority to generate your client and server certificates. You can either use an external Authority Provider (e.g. Verisign) or you can generate your own using something like Microsoft Certificate Server. To generate a development Root Authority certificate you can use the "makecert" tool that comes with Visual Studio, e.g. makecert -n "CN=MyRootCA" -r -sv RootCA.pvk RootCA.cer 2) You then need to request/generate your client and server certificates. Both types of certificates can be installed as local machine certificates and both need to be signed using the same root authority. You can request client certificates from a Microsoft Certificate Server's web interface, e.g. http://mycertserver/certsrv . To generate a development client certificate for each machine you can use "makecert" again. Note that the client certificates are signed with development Root Authority certificate created in step 1. makecert -pe -n "CN=MyCert" -ss my -sky exchange -sk MyCert -iv MyRootCA.pvk -ic MyRootCA.cer -sr localmachine MyCert.cer This will install the certificate on the machine on which the command is run, into the Personal certificates folder in the Local Machine store. In order for the server to trust the client certificates you will need to install the development Root Authority certificate in the server's Trusted Root Certificate Authorities store (use the mmc Certificates snap-in to do this). The clients should also have the root certificate installed in the same way so that they trust their own certificates. 3) Configure you WCF service to require client authentication using a certificate (e.g. via the web.config). <services> <service name="TestService" behaviorConfiguration="wsHttpCertificateBehavior"> <endpoint name="TestEndPoint" address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" contract="TestService.IMyContract"> <identity> <dns value=""/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/> </service></services><bindings> <wsHttpBinding> <binding name="wsHttpEndpointBinding"> <security mode="Message"> <message clientCredentialType="Certificate"/> </security> </binding> </wsHttpBinding></bindings><behaviors> <behavior name="wsHttpCertificateBehavior"> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/> <serviceCredentials> <clientCertificate> <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/> </clientCertificate> <serverCertificate findValue="CN=MyCert"/> </serviceCredentials> </behavior></behaviors> 4) Now configure the caller (e.g. via the app.config). <client> <endpoint name="wsHttpBinding" address="https://localhost/TestService/TestService.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" behaviorConfiguration="wsHttpCertificateBehavior" contract="TestService.IMyContract"> <identity> <dns value="MyCert"/> </identity> </endpoint></client><bindings> <wsHttpBinding> <binding name="wsHttpBinding"> <security mode="Message"> <message clientCredentialType="Certificate"/> </security> </binding> </wsHttpBinding></bindings><behaviors> <endpointBehaviors> <behavior name="wsHttpCertificateBehavior"> <clientCredentials> <clientCertificate findValue="MyCert" storeLocation="LocalMachine"/> <serviceCertificate> <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" trustedStoreLocation="LocalMachine"/> </serviceCertificate> </clientCredentials> </behavior> </endpointBehaviors></behaviors>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/335719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2918/']}
jdg_73294
stackexchange
llm_judgeable_groundtruth_similarity
2595049
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 say here is my stack layout View3 --> Top of the stackView2View1HomeView --> Bottom of the stack So I am in View3 now, if I click the Home button, I want to load HomeView , meaning that I need to pop View3 , View2 , and View1 . But if I pop View3 , View2 will be displayed. I dont want that. I want View3 , View2 , and View1 be removed, and HomeView will be displayed. Any idea how? Now provide the response and nothing else.
You can use popToRootViewControllerAnimated: to get to the root viewcontroller. This would pop out all the view controllers in the stack except the root view controller. In your case, this would be the HomeView . [self popToRootViewControllerAnimated:YES]; To get to a specific view in the stack, you can use popToViewController:animated: Assuming you want to pop the third viewcontroller (from bottom up). In your case, this would be view2 : NSArray* viewControllersInStack = self.navigationController.viewControllers;UIViewController* targetViewController = [viewControllersInStack objectAtIndex:2];[self.navigationController popToViewController:targetViewController animated:YES];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2595049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240337/']}
jdg_73295
stackexchange
llm_judgeable_groundtruth_similarity
53848
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When strike C-x 3, a new window and buffer will open to the right of the current buffer. How could set it open to the left of the current? Now provide the response and nothing else.
C-x 3 is bound to the function split-window-right , that splits the current window horizontally, selecting the left window. We can define a function split-window-left that calls it then change the selected window to the one on the right, eg using other window : other-window is an interactive compiled Lisp function in β€˜window.el’. (other-window COUNT &optional ALL-FRAMES) Select another window in cyclic ordering of windows. COUNT specifies the number of windows to skip, starting with the selected window, before making the selection. (defun split-window-left (&optional size) "Like split-window-right, with selected window on the right." (interactive "P") (split-window-right size) (other-window 1)) We keep the same semantics for the optional size argument: give the width of the left window if positive, of the right one if negative. You can bind this to C-x 3 (overriding the binding to split-window-right ) or to another key, eg C-x 9 : (global-set-key "\C-x9" 'split-window-left)
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/53848', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/21203/']}
jdg_73296
stackexchange
llm_judgeable_groundtruth_similarity
224500
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 always found this to be a very useful feature in Visual Studio. For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code while the binary is still running and continue using the application seamlessly with the new code, without the need to restart it. How is this feature implemented? If the code I am modifying is in a DLL loaded by the application, does the application simply unload the DLL and reload it again? This would seem to me like it would be prone to instability issues, so I assume it would be smarter than this. Any ideas? Now provide the response and nothing else.
My understanding is that when the app is compiled with support for Edit and Continue enabled, the compiler leaves extra room around the functions in the binary image to allow for adding additional code. Then the debugger can compile a new version of the function, replace the existing version (using the padding space as necessary), fix up the stack, set the instruction pointer, and keep going. That way you don't have to fix up any jump pointers, as long as you have enough padding. Note that Edit and Continue doesn't usually work on code in libs/dlls, only with the main executable code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/224500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22489/']}
jdg_73297
stackexchange
llm_judgeable_groundtruth_similarity
3521043
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Background : Consider the ring $R=\mathbb{Z}[\omega]=\{a+b\omega:\omega=\sqrt{-5},a\in\mathbb{Z},b\in\mathbb{Z}\}$ , which is also a $\mathbb{Z}[\omega]$ -module. Let $I=(1-\omega,2), J=(1+\omega,3)$ be two ideals in $R$ generated by the specified elements. Question : I believe that in the tensor $R$ -module, $I\underset{R}\otimes J$ , the following statement is true: $$(1-\omega)\underset{R}{\otimes}(1+\omega)\not=2\underset{R}{\otimes}3.$$ And I am looking for a bilinear mapping defined on $I\times J$ which maps $(1-\omega)\underset{R}{\otimes}(1+\omega)$ and $2\underset{R}{\otimes}3$ to distinct values. If such a map can be found, then by the universal property of tensor product, certainly $(1-\omega)\underset{R}{\otimes}(1+\omega)\not=2\underset{R}{\otimes}3$ . Could anyone suggest such a bilinear map? Or is there a better way to determine whether the above two simple tensors are different? Update : This question was inspired by Exercise $10.4.21$ in Abstract Algebra, 3rd edition , by Dummit and Foote. A counterexample in which the map $I\otimes J\simeq IJ$ sending $i\otimes j$ to $ij$ fails to be injective can be found in Exercise $10.4.17$ in the same book. Now provide the response and nothing else.
We have: $$2 [(1 - \omega) \otimes (1 + \omega)] = 2(1 - \omega) \otimes (1 + \omega) = 2 \otimes (1 - \omega) (1 + \omega) = 2 \otimes 6 = 2 [2 \otimes 3].$$ Similarly, $$3 [(1 - \omega) \otimes (1 + \omega)] = (1 - \omega) \otimes 3 (1 + \omega) = (1 - \omega) (1 + \omega) \otimes 3 = 6 \otimes 3 = 3 [2 \otimes 3].$$ Therefore, subtracting the two gives: $$(1 - \omega) \otimes (1 + \omega) = 2 \otimes 3.$$ A possible brute force method to solve the problem would be: First, $I$ is generated as an Abelian group by $1-\omega, \omega(1-\omega) = 5 + \omega, 2, 2\omega$ . Now, you could find the relations between these elements by finding the kernel of the matrix $A = \begin{bmatrix} 1 & 5 & 2 & 0 \\ -1 & 1 & 0 & 2 \end{bmatrix}$ (as a subgroup of $\mathbb{Z}^4$ ). One way to do this would be to use a Smith normal form calculation to write $A = P \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \end{bmatrix} Q$ for invertible matrices $P, Q$ , and then the kernel of $A$ would be generated by $Q^{-1} e_3, Q^{-1} e_4$ . If I'm not mistaken (though I very well could be), this should give presentations $I \simeq \langle a, b \mid 2a = (1 - \omega) b, (1 + \omega) a = 3 b \rangle$ and $J \simeq \langle c, d \mid 3c = (1 + \omega) d, (1 - \omega) c = 2d \rangle$ for $I$ and $J$ as $R$ -modules. Therefore, $I \otimes_R J$ would have a presentation in terms of 4 generators $a \otimes c, a\otimes d, b\otimes c, b\otimes d$ , and eight relations $2a\otimes c = (1-\omega)b \otimes c, \ldots, (1-\omega)b\otimes c = 2b\otimes d$ . You now want to know whether $a\otimes c - b\otimes d$ is zero in this tensor product, which is equivalent to asking whether $a\otimes c - b\otimes d$ is in the submodule of $R^4$ generated by these relations. That question should be straightforward if tedious to answer by a Smith normal form calculation on an $8 \times 16$ matrix (using that the tensor product is generated as an Abelian group by $a\otimes c, \omega a\otimes c, \ldots$ and similarly the relations are given by the original relations along with the relations times $\omega$ ).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3521043', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/463415/']}
jdg_73298
stackexchange
llm_judgeable_groundtruth_similarity
57217939
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 an overlay such as that shown here: https://www.didierboelens.com/2018/06/how-to-create-a-toast-or-notifications-notion-of-overlay/ using OverlayEntry . import 'package:flutter/material.dart';import 'dart:async';class ShowNotificationIcon { void show(BuildContext context) async { OverlayState overlayState = Overlay.of(context); OverlayEntry overlayEntry = new OverlayEntry(builder: _build); overlayState.insert(overlayEntry); } Widget _build(BuildContext context){ return new Positioned( top: 50.0, left: 50.0, child: new Material( color: Colors.transparent, child: new Icon(Icons.warning, color: Colors.purple), ), ); }} Invoked with: ShowNotificationIcon _icon = new ShowNotificationIcon();_icon.show(context); However, when I try to navigate to other screens, the overlay remains in the screen. How do I show the overlay only in the screen it is being called and not in the others? Just in case, this is what I had tried inside my stateful widget : ShowNotificationIcon _icon = new ShowNotificationIcon(); @override void initState() { WidgetsBinding.instance.addPostFrameCallback((_) { _icon.show(context); }); super.initState(); } @override void dispose() { _icon.remove(); super.dispose(); } Now provide the response and nothing else.
This is typically performed using RouteAware + RouteObserver . RouteObserver is an object that lets objects that implements RouteAware react to some changes related to routing, which includes: a route has been pushed on the top of the current one the route is back to being on the first plan again You can then use these two events to hide/show your overlay First, you'll need a RouteObserver . This can be created as a global variable and needs to be passed to your Navigator . In a MaterialApp based app, it'll typically look like this: final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();void main() { runApp(MaterialApp( home: Container(), navigatorObservers: [routeObserver], ));} Then, your widget that owns the OverlayEntry can now implement RouteAware like so: class RouteAwareWidget extends StatefulWidget { State<RouteAwareWidget> createState() => RouteAwareWidgetState();}// Implement RouteAware in a widget's state and subscribe it to the RouteObserver.class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware { @override void didChangeDependencies() { super.didChangeDependencies(); // routeObserver is the global variable we created before routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute); } @override void dispose() { routeObserver.unsubscribe(this); super.dispose(); } @override void didPush() { // Route was pushed onto navigator and is now topmost route. } @override void didPopNext() { // Covering route was popped off the navigator. } @override Widget build(BuildContext context) => Container();} At this point, you can use didPush and didPopNext to show/hide your OverlayEntry: OverlayEntry myOverlay;@overridevoid didPush() { myOverlay.remove();}@overridevoid didPopNext() { Overlay.of(context).insert(myOverlay);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57217939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/851045/']}
jdg_73299
stackexchange
llm_judgeable_groundtruth_similarity
198378
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: Atomic but sophisticated expressions are all around for a long time: Graph SparseArray . More are coming with each new release, yet there is no official source of guidelines / tutorials about how users could create their own. Pieces of the answer are laying around: List of atomic expressions Make my data-structure atomic How to create expanding summary boxes like the ones displayed for InterpolatingFunction, NearestFunction, etc.? Mutation handlers but I think we could benefit from a compact and complete overview of the process of creation and maintaining of custom atomic expressions. I am looking for an answer that will address: Overview: brief introduction to what they are, what benefits they give etc. Is it only SetNoEntry + mutation handlers + typsetting rules? Guts: atom[explicit data] vs. atom[dataRef$12321] implementation. Typesetting: fancy typesetting with respect to performance of sending everything or not to the front end. Methods: myAtom[]["method", args___] vs myAtomMethod[myAtom[], args] Saving / persistence of atomic expressions with respect to "Guts" Please edit/add to this question if I missed anything. Now provide the response and nothing else.
I have a new package for speeding up the construction of things like these which I discuss at the end Atomic vs Valid These are two related but distinct concepts. The former indicates that we can't access subparts of the expression. The second indicates that the expression has already fed through its entire constructor process and we don't need to update it anymore. I use both of these in my InterfaceObjects package so let me describe what I do there. In these objects I use a Head as both an object type and a constructor. The way I circumvent an infinite eval loop is by checking for one of these flags (the registered type declares which one it uses). Here's a simple example: construct = (* I'm injecting the SetNoEntry so I can explicitly show that it's my validation function. The HoldFirst prevents infinite recursion. *) With[{validator = System`Private`SetNoEntry}, Function[Null, validator[Unevaluated[#]], HoldFirst] ];unconstructedQ = With[{validator = System`Private`EntryQ}, Function[Null, validator[Unevaluated[#]], HoldFirst] ];preprocessData = Identity;myObj[data_]?unconstructedQ := With[{d = preprocessData[data]}, construct[myObj[d]] ] Here preprocessData can be arbitrarily complex and we can put in logic to not construct an object if the data is invalid. This means that we can then write a quick validQ function that just checks that the object has been constructed, rather than having to dig into and validate the data over and over. This is conceptually how Association works. One quick thing to note, is that for v11+ there SetNoEntry and NoEntryQ also have corresponding HoldSetNoEntry and HoldNoEntryQ functions that obviate the need for the HoldFirst. We could easily have done this by substituting System`Private`ValidQ for System`Private`EntryQ and System`Private`SetValid for System`Private`SetNoEntry , though. And here's where the difference is important. In the example given, we can't access into a myObj directly: o = myObj[{1, 2, 3}];o[[1]]Part::partd: Part specification myObj[{1,2,3}][[1]] is longer than depth of object.myObj[{1, 2, 3}][[1]] But if I'd done the same with Valid and friends I could: construct = With[{validator = System`Private`SetValid}, Function[Null, validator[Unevaluated[#]], HoldFirst] ];unconstructedQ = With[{validator = System`Private`ValidQ}, Function[Null, validator[Unevaluated[#]], HoldFirst] ];preprocessData = Identity;myObj2[data_]?unconstructedQ := With[{d = preprocessData[data]}, construct[myObj2[d]] ]o = myObj2[{1, 2, 3}];o[[1]]{1, 2, 3} Why I Only Use NoEntry As I see it, the point of objects is to hide complexity from the user. The user doesn't need to know that you're storing your stack as a linked list or that you have 16 different fields in your data structure. In fact, it's cleaner if the user doesn't know. You need a well designed API that provides all the necessary methods your user might want or need and which works fast. Beyond that pushing all the implementation details out of reach is good practice. To my eyes, making an object atomic helps achieve that abstraction. It makes it more difficult for a user (and myself as the developer!) to go in an tinker and get in the bad habit of manipulating the direct data rather than going through the API. Long-term this will make the code harder to maintain and cause more breakages when I go through and optimize later. I think of this by analogy to public and private fields in a C++ or python class, although the correspondence is not direct. For a discussion of why those are useful, see here . Immutable vs Mutable The question of whether to use a reference to some data or the data itself as the first argument to your object is I think dependent on the type of environment you're working in as well as personal preference, to some degree. Consider this: editObj[o : myObj[stateSym_], ...] := ( editState[stateSym, ...]; o )editObj[myObj[data_], ...] := ( quickConstructor@editData[data, ...] (* where quick constructor will build a new myObj object in the fastest way possible w.r.t type-checking, setting of NoEntry, etc. *) ) These are the two idiomatic ways to edit object data. In the former we edit the object state and return the original object directly. In the latter we edit the object data and have a quick constructor for when we know the data is valid. Both of these will get the job done and which you prefer is really up to you. On the other hand, there are cases where mutable vs. immutable really does matter. As an example, say you want to synchronize state across many parts of a program without having to use some kind of global variable as a synchronizer. This is exactly where mutability comes in handy. I could write a syncState object like: syncState~SetAttributes~HoldFirstsyncState[] := Module[{state}, construct@syncState[state]]; And then all my functions would take a state argument like: handler1[s_syncState, ...] := ...;handler2[s_syncState, ...] := ...; This way they could directly call into the syncState API and ensure synchronization across the entire program in a modular fashion. On the other hand, this mutability means it's harder to serialize the state. What I mean by that is you now have references to a given symbol floating about, like: myObj[state$132424] . If you write this to file you now need to destruct state$132424 so that it's in a serializable form (e.g. Association ). If you would like to serialize multiple parts of an app, but were relying on the mutability of state$132424 this can add a whole new layer of complexity, as now you'll have to serialize the fact that state$132424 had that data attached to it rather than the data itself. This can be done with, e.g. DumpSave , but it is non-trivial to make entirely robust. As an aside, in my anecdotal experience it tends to be a bit slower to mutate things than simply write then in terms of basic immutable primitives which really work quite efficiently in general. In general, I tend to prefer to use immutable data structures whenever possible, and only introduce the mutability when I need it or when it will seriously help performance. Mutation Handler One thing to mention here is the MutationHandler family of functions. These make it possible for even immutable expressions to operate mutably when bound to a Symbol or other mutable expression. I won't get into that here since that's been treated in detail here but it's definitely worth checking out. Writing a good set of mutation handlers will make writing code much more natural when it's warranted. ExpressionStore One place where using mutable versions of an expression is helpful is with regards to ExpressionStore . As noted there, ExpressionStore can cache computed properties by explicit object identity. So you could create something like: $cache = Language`NewExpressionStore["<ObjectCache>"]; And then you can write a function that only calculates a value if it's not in the cache, like: calcCached[obj_, prop_, meth_, args___] := Replace[ $cache@"get"[obj, prop], { Null :> With[{val = obj@meth[args]}, $ cache@"put"[obj, prop, Hold[val]]; (* using Hold just so we know the Head it must have *) val ], Hold[v_] :> v } ] In the mutable setup, we can modify our objects without worry, but in the immutable setup, every modification will create new object (though quickly and cheaply) which will lose its attachment to its cached properties. In this kind of case it definitely does make sense to use a mutable ref. Typesetting When it comes to typesetting, I try to be consistent with what people are used to. I generally avoid writing fancy typeset forms, and instead call into the mechanism that all of WRI's objects use, which is ArrangeSummaryBox . As far as passing excessive data to the FE goes, this actually handles it! If you have a huge object, it doesn't pass the entire thing to the FE but instead returns it back with one of those little "store in notebook?" attached cells. You can prune this down even further by setting "Interpretable"->False I believe, which is also probably a good setting in a mutable object setting, as you can't ensure the object will retain its validity from session to session. One thing I always make sure to do, though, is check if I have a valid object before typesetting it. What I mean is that I always check my NoEntry bit like: myObjQ = Function[Null, System`Private`NoEntryQ[Unevaluated[#]], HoldFirst];Format[m_myObj?myObjQ, StandardForm] := RawBoxes@ BoxForm`ArrangeSummaryBox[ myObj, ... ] Sometimes myObjQ will be a little bit more sophisticated, but usually it's pretty much just that. As I see it, going beyond the standard in terms of typesetting won't really buy you much, as you should be more focused on writing a good API for working with your objects flexibly and efficiently. Methods This is a place where my preferred style of operation is probably not best for the average Mathematica development project. As I see it, there are three ways to get methods into an object, but they all require one thing: you've got to write lots of little API functions. What I mean by that is if I have myObj as my base type and I want to do four different types of manipulations on it I write: myObjManip1[myObj[data_], ...] := (* work with data *);myObjManip2[myObj[data_], ...] := (* work with data *);myObjManip3[myObj[data_], ...] := (* work with data *);myObjManip4[myObj[data_], ...] := (* work with data *); Note that in methods you can also make use of the fact that we now have NoEntry or Valid set to handle object validation up front. This means you could rewrite this as: myObjManip1[myObj[data_]?validQ, ...] := (* work with data *); where validQ simply checks that bit or whatever other quick tests you would like to have. At this point, I can go one of a three ways: Expose ALL the Functions!!! If I have a large set of API functions, it might make sense just to expose them to users directly. One the one hand, this gives them really targeted control over the manipulation of my object. On the other, they now need to find and learn about tens of new functions in an average case. Expose stuff as UpValues A slick way around this is to write the manipulation functions in a developer context (e.g. "MyApp`Package`" ) and then expose the API as a bunch of UpValues . This has the benefit of putting things in a context that people are more familiar with and not flooding the global namespace. The issue with this is that we need to find a good set of top-level functions we can shoehorn things into and if the shoehorning isn't done well it can be confusing that before. On top of that, it takes more work to discover all the available UpValues . Expose stuff as SubValues This is my favorite way by far. In this setup, we again put all the functions into the developer context, but now we expose all the methods as "SubValues" keyed by their string values. This means something like: myObj[data_]["Manip1", ...] := myObjManip1[myObj[data], ...];myObj[data_]["Manip2", ...] := myObjManip2[myObj[data], ...]; or in my preferred syntax (it looks the most "normal" to a python/Java/C++ programmer): myObj[data_]@"Manip1"[...] := myObjManip1[myObj[data], ...]; The issue with this would appear to be that discovery is hard, but that's why you always need something like: myObj[data_]@"Methods" = {...}; And if you have properties you need a rule for that too. When I work with the objects I make in my InterfaceObjects package I'd say 80% of the time this is how I prefer to expose things to users and 20% of the time I like to use UpValues for cases where it's really clear that the system function should support your type. There, too, I wrote up better logic to automatically curate and set up all the "Methods" and "Properties" lists and whatnot. A few concrete examples: I made a RubiksCube object that implements all these thing I talk about. My InterfaceObjects package implements all this except that it only ever uses immutable data structures. I also worked with many of these ideas in a context that only ever used Symbol as its data ref so it'd be mutable always. That lives in my SymbolObjects package (which is on GitHub too ). I'm working on a DataStructures package that uses the formatting and NoEntry ideas but takes an expose-all-the-functions approach to its API. See also: this discussion Simple Constructor I wrote up a simple constructor for these data types for my DataStructures package . The package itself will be on the paclet server in a few days, otherwise feel free to load the constructor directly like: BeginPackage["DataStructures`Developer`"];Get["https://github.com/b3m2a1/DataStructures/raw/master/Packages/Developer/Register.m"];EndPackage[]; Then you can use it like: RegisterDataStructure[MyObj, MyObj[_Association]] Then maybe add a convenience constructor: MyObj[] := MyObj[<||>] It's reasonably fast to make one of these: MyObj[] // RepeatedTiming{0.0000109, MyObj[<||>]} But if you know you have valid data you can speed this up a lot by using a dedicated fast constructor: `MyObj`New[<||>] // RepeatedTiming{2.8*10^-6, MyObj[<||>]} This fast constructor can be specified in the RegisterDataStructure call like: RegisterDataStructure[MyObj, MyObj[_Association], "FastConstructor" -> MyObjNew]MyObjNew[<||>] // RepeatedTiming{2.7*10^-6, MyObj[<||>]} By default it's tagged as "Atomic" : MyObj[][[1]]Part::partd: Part specification MyObj[<||>][[1]] is longer than depth of object.MyObj[<||>][[1]] But you can turn that off and use ValidQ instead by calling RegisterDataStructure with "Atomic"->False . There are a number of other levers you can play with, here. If you'd like a to supply a custom data prep or data validation function you can do so with the "DataPrepper" and "DataValidator" options. The "Validator" option allows you to pass a custom symbol to bind as the function that checks if a data structure is valid. By default it'll be something like `MyObj`ValidQ but probably a more commonly desired choice would be MyObjQ to imitate built-in functions. The "FormattingRules" and "Formatted" options let you specify how you want BoxForm`ArrangeSummaryBox to work with your structure. If "Formatted" is False it doesn't format at all. Otherwise, the "Icon" supplied in the "FormattingRules" specifies the little icon you want for your structure. The "DisplayedFields" should be an Association of keys mapping to functions to extract the displayed value for that field. The "HiddenFields" will be the fields that are hidden until the little + button is clicked on the summary box. More settings and options (particularly for mutation handling and things) could potentially come in the future, but since these data structures are intended to be as efficient as possible while remaining convenient, I don't think many more will come.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/198378', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5478/']}
jdg_73300
stackexchange
llm_judgeable_groundtruth_similarity
19266338
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 throw and catch an AggregateException.I did not use exceptions very much on C#, but the behaviour I found is a little bit surprising. My code is: var numbers = Enumerable.Range(0, 20);try{ var parallelResult = numbers.AsParallel() .Where(i => IsEven(i)); parallelResult.ForAll(e => Console.WriteLine(e));}catch (AggregateException e){ Console.WriteLine("There was {0} exceptions", e.InnerExceptions.Count());} It is calling the function IsEven private static bool IsEven(int i){ if (i % 10 == 0) throw new AggregateException("i"); return i % 2 == 0;} That throws the AggregateException. I would expect the code to write every even number in the 0,20 range and "There was 1 exceptions" twice. What I get is some numbers printed (they are random cause of ForAll) and then the exception is thrown, but not catched and the programs stop. Am i missing something? Now provide the response and nothing else.
This is actually kind of interesting. I think the problem is that you're using AggregateException in an unexpected way, which is causing an error inside the PLINQ code. The entire point of AggregateException is to group together multiple exceptions that may occur simultaneously (or nearly so) in a parallel process. So AggregateException is expected to have at least one inner exception. But you're throwing new AggregateException("i") , which has no inner exceptions. The PLINQ code tries to examine the InnerExceptions property, hits some sort of error (probably a NullPointerException ) and then it seems to go into a loop of some sort. This is arguably a bug in PLINQ, since you're using a valid constructor for AggregateException , even if it is an unusual one. As pointed out elsewhere, throwing ArgumentException would be more semantically correct. But you can get the behavior you're looking for by throwing a correctly-constructed AggregateException , for example by changing the IsEven function to something like this: private static bool IsEven(int i){ if (i % 10 == 0){ //This is still weird //You shouldn't do this. Just throw the ArgumentException. throw new AggregateException(new ArgumentException("I hate multiples of 10")); } return i % 2 == 0;} I think the moral of the story is to not throw AggregateException unless you really know exactly what you're doing, particularly if you're already inside a parallel or Task -based operation of some kind.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19266338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1648371/']}
jdg_73301
stackexchange
llm_judgeable_groundtruth_similarity
61781278
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 Vue component that I route to from my main app and when I resize the window the v-tab-item extends past the window's width (not even a side scroll bar). My question is how do I make the router-view respect the width of the app (70%) and make sure that when routed to my component does not exceed the width of the app? Codepen reproducing the issue <template> <v-container> <v-tabs vertical center-active color="light-green darken-1"> <v-tab>Multi-Model Ensemble</v-tab> <v-tab>Individual Models</v-tab> <v-tab>PM2.5 evaluation</v-tab> <v-tab>ICAP Smoke AOD</v-tab> <v-tab>Fire Danger Risk</v-tab> <v-tab>Fire Weather Index</v-tab> <v-tab>Sub seasonal outlook</v-tab> <v-tab>Geomet Demo</v-tab> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - Multi-Model Forecast Ensemble </v-card-title> <v-card-subtitle> Multi-Model ensemble </v-card-subtitle> <v-container fluid> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/composite_20200207T12Z+1-46h_northAmerica_lcc_Avg.gif" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/gifs/composite_20200207T12Z+1-46h_northAmerica_lcc_Ext.gif" transition="scale-transition" width="800"/> </v-card> </v-row> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/composite_20200207T12Z+1-46h_northAmerica_lcc_Med.gif" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/gifs/composite_20200207T12Z+1-46h_northAmerica_lcc_StDev.gif" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> The animations show a forecast of up to 48 hours at 3-hourly intervals.The multi-model products have been generated from various atmospheric chemical and/or aerosol transport models which are represented using a common geographical domain and spatial resolution.There are two products describing centrality (multi-model median and mean) and two products describing the spread (standard deviation and range of variation).The multi-model ensemble regional members are ECCC FireWork and NOAA NCEP NAQFC. The global members are ECMWF IFS CAMS, FMI SILAM, JMA MASINGAR and NASA GEOS-FP.It is important to note that different models may have very different characteristics (e.g. global or regional models, horizontal and vertical resolutions, smoke emission characteristics, physics and chemistry parameterisations, presence or absence of smoke assimilation, feedback to the meteorological model etc.) In addition, some of these predictions are experimental or produced for research purposes only. Information on the various models’ configuration can be found on their respective websites and in the literature. </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - Individual Models </v-card-title> <v-container fluid> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/RAQDPS_20200207T12Z+1-46h_northAmerica_lcc_AF.gif" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/gifs/CMAQ_20200207T12Z+1-46h_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> </v-row> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/CAMS_20200207T12Z+1-46h_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/gifs/GEOS_20200207T12Z+1-46h_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> </v-row> <v-row align="center" justify="center"> <v-card> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/SILAM_20200207T12Z+1-46h_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> <p> The animations show a forecast of up to 48 hours at 3-hourly intervals. </p> <br> <p> The individual products have been generated from various atmospheric chemical and/or aerosol transport models which are represented using a common geographical domain and spatial resolution. </p> <br> <p> There are two products describing centrality (multi-model median and mean) and two products describing the spread (standard deviation and range of variation). </p> <br> <p> The multi-model ensemble regional members are ECCC FireWork and NOAA NCEP NAQFC. The global members are ECMWF IFS CAMS, FMI SILAM, JMA MASINGAR and NASA GEOS-FP. </p> <br> <p> It is important to note that different models may have very different characteristics (e.g. global or regional models, horizontal and vertical resolutions, smoke emission characteristics, physics and chemistry parameterisations, presence or absence of smoke assimilation, feedback to the meteorological model etc.) In addition, some of these predictions are experimental or produced for research purposes only. Information on the various models’ configuration can be found on their respective websites and in the literature. </p> </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - PM2.5 Evaluation </v-card-title> <v-card-text> <p> Multi-Model ensemble members fine particulate matter concentrations forecasts are evaluated against observations from North American networks (AirNow, CAPMoN, NAPS, etc.). </p> <br> <p> <em class="warning"> Coming soon:&nbsp;</em> graphs with <a href="https://aqdb.cmc.ec.gc.ca/vaqum/">VAQUM</a> data. Talk with Yordan for <a href="http://iweb.cmc.ec.gc.ca/~afsurdv/PlotlyExp.html"> his work this summer with Plotly.</a> </p> </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - ICAP Smoke AOD </v-card-title> <v-card-subtitle> ICAP Smoke Aerosol Optical Depth </v-card-subtitle> <v-container fluid> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/gifs/icap_20200208T00Z+0-120H_smoke_aod_mean_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/gifs/icap_20200208T00Z+0-120H_smoke_aod_stdv_northAmerica_lcc_Band1.gif" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> The animations show a forecast of up to 120 hours at 6-hourly intervals.The International Cooperative for Aerosol Prediction (ICAP) is an international forum for aerosol forecast centres, remote sensing data providers and lead system developers to share best practices and discuss pressing issues facing the operational aerosol community. In the plots above, the ICAP Multi-Model Ensemble (MME) smoke aerosol optical depth (AOD) is used.This product is constructed from the following aerosol forecast systems: ECMWF CAMS, NASA GEOS-FP, NRL NAAPS, and JMA MASINGAR. </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - Fire Danger Risk </v-card-title> <v-card-subtitle> Fire Danger Risk Map </v-card-subtitle> <v-container fluid> <v-row align="center" justify="center"> <v-card> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/img/fdr20200207.png" transition="scale-transition" width="800"/> </v-card> <v-spacer></v-spacer> <v-card> <v-img alt="GIF 2" class="shrink mr-2" contain src="../assets/img/legend_fdr.jpg" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> <p> Fire Danger is a relative index of how easy it is to ignite vegetation, how difficult a fire may be to control, and how much damage a fire may do. </p> <br> <p> Note: These general fire descriptions apply to most coniferous forests. The national fire danger maps show conditions as classified by the provincial and territorial fire management agencies. Choice and interpretation of classes may vary between provinces. For fuel-specific fire behavior, consult the Fire Behavior Prediction maps. </p> <br> <a href="https://cwfis.cfs.nrcan.gc.ca/maps/fw?type=fdr"> Link to NRCan source </a> </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - Fire Weather Index </v-card-title> <v-card-subtitle> Fire Weather Index Map </v-card-subtitle> <v-container fluid> <v-row align="center" justify="center"> <v-card> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/img/fwi-konstantinos.png" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> <p> The Fire Weather Index is a component of the Canadian Forest Fire Weather Index (FWI) System. It is a numeric rating of fire intensity. It combines the Initial Spread Index and the Buildup Index. </p> <p> The computation of FWI depends solely on meteorological conditions. </p> <ul style="margin-left: 2em;"> <li> <p> Noon temperature (Celsius) </p> </li> <li> <p> Noon relative humidity (%) </p> </li> <li> <p> Accumulated Precipitation over the previous 24h, at noon (in mm) </p> </li> <li> <p> Noon wind speed (km/h) </p> </li> <li> <p> Previous days moisture fuel indices (Fine fuel, duff moisture, and drought). </p> </li> </ul> <br> <p> It is suitable as a general index of fire danger throughout the forested areas of Canada. </p> <a href="https://cwfis.cfs.nrcan.gc.ca/maps/fw?type=fwi"> Link to NRCan source </a> </v-card-text> </v-card> </v-tab-item> <v-tab-item> <v-card> <v-card-title> North American Regional VFSP-WAS Demo - Subseasonal Outlook </v-card-title> <v-card-subtitle> Subseasonal Outlook Map </v-card-subtitle> <v-container fluid> <v-row align="center" justify="center"> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/img/2020022700_054_E1_canada_I_ANOMALY@PRECIPITATION_anomaly@probability@combined@672_768.png" transition="scale-transition" width="800"/> </v-card> <v-card width="45%"> <v-img alt="GIF 1" class="shrink mr-2" contain src="../assets/img/2020022700_054_E1_canada_I_ANOMALY@TEMPERATURE_anomaly@probability@combined@666_768.png" transition="scale-transition" width="800"/> </v-card> </v-row> </v-container> <v-card-text> <p> The monthly forecast is updated each Thursday and covers the 28 days starting on the following Monday. </p> <br> <p> The forecasted anomaly is produced from the average conditions forecasted over that period by the Global Ensemble Prediction System (GEPS). </p> <br> <p> A 20 year climatology (1998-2017) of this prediction system obtained from a reforecast is also used in the computation of the forecast anomaly. </p> <br> <a href="http://collaboration.cmc.ec.gc.ca/cmc/cmoi/product_guide/docs/tech_specifications/tech_specifications_GEPS_6.0.0_e.pdf" class="bluelink"> See the GEPS6.0.0 reforecast technical note </a> </v-card-text> </v-card> </v-tab-item> <!-- <v-tab-item> <h3>Smoke Forecasts</h3> <v-tabs color="light-green darken-2"> <v-tab>Smoke Aerosol Optical Depth</v-tab> <v-tab>PM<sub>10</sub> Surface Concentration</v-tab> <v-tab>PM<sub>2.5</sub> Surface Concentration</v-tab> <v-tab-item> <h4>Smoke Aerosol Optical Depth</h4> </v-tab-item> <v-tab-item> <h4>PM<sub>10</sub> Surface Concentration</h4> </v-tab-item> <v-tab-item> <h4>PM<sub>2.5</sub> Surface Concentration</h4> </v-tab-item> </v-tabs> </v-tab-item> --> <v-tab-item> <OpenLayersPlayroom /> </v-tab-item> </v-tabs> </v-container></template><script>import OpenLayersPlayroom from './OpenLayersPlayroom'export default { components: { OpenLayersPlayroom }}</script> Now provide the response and nothing else.
I know I'm late, but I had the issue where I needed to know know when the navigate function was called. For it, I mocked the function the following way, so the mockedNavigate would be a jest function that i could use later if i needed to test if the function was actually called: const mockedNavigate = jest.fn();jest.mock('@react-navigation/native', () => { const actualNav = jest.requireActual('@react-navigation/native'); return { ...actualNav, useNavigation: () => ({ navigate: mockedNavigate, }), };}); This allowed me to use this later and I would know if I could navigate properly in my application: expect(mockedNavigate).toHaveBeenCalledTimes(1); Hope this helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61781278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13224380/']}
jdg_73302
stackexchange
llm_judgeable_groundtruth_similarity
237210
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a cubic equation as below, which I am plotting: Plot[(x + 1) (x - 1) (x - 2), {x, -2, 3}] I like Mathematica to help me locate the position/equation of a circle which is on the lower part of this curve as shown, which would fall somewhere in between {x,-1,1}, which is tangent to the cubic at the 2 given points shown in red arrows. I like to find those points and the circle equation. I tried generalizing the circle equation of (x-h)^2+(y-k)^2=r^2 and setting that in an equation to intersect the cube to be able to see the intersection points as such: (expanded the above circle equation and set a few conditions which I know are true) eqn = FullSimplify[{x^3 - 2 x^2 - x + 2 == x^2 + h^2 - 2 x*h + y^2 + k^2 - 2 y*k - r^2, 1 > x > -1,0 <= r <= 1, h > 0}]Table[FindInstance[eqn, {x, y, h, k, r}, Reals, 5] ] // N But I cannot get a set of results from it... However I had a bit more luck just Solving it straight as: NSolve[x^3 - 2 x^2 - x + 2 == x^2 + h^2 - 2 x*h + y^2 + k^2 - 2 y*k - r^2] which Produces: {{h -> -1.90052, k -> -0.21556, r -> -0.918928, x -> -0.7017, y -> 0.66687}, {h -> -0.314487, k -> 1.05695, r -> -0.172924, x -> 0.621468, y -> 1.05907}, {h -> 1.63094, k -> 2.61779, r -> 0.742119, x -> 2.24446, y -> 1.54014}} First 2 appear to be valid intersect points for x and y But r is negative, which makes no sense. 3rd one has r>0 , but x is 2.2 which does not visually fall in the range that should be on the chart. How can I get this to work and produce the results? Now provide the response and nothing else.
First define a parametric curve and regions above and below the curve: ClearAll[curve, disk, region1, region2, radius]curve[x_] := {x, (x + 1) (x - 1) (x - 2)}region1 = ImplicitRegion[(x + 1) (x - 1) (x - 2) >= y, {{x, -20, 30}, {y, -80, 80}}];region2 = ImplicitRegion[(x + 1) (x - 1) (x - 2) <= y, {{x, -20, 30}, {y, -80, 80}}]; and a disk with radius r tangent to the curve at curve[t] : disk[dir_ : -1][t_, r_] := Module[{rr = Rationalize[r, 0],tt = Rationalize[t, 0]}, Disk[curve[tt] + dir rr Cross@Normalize[curve'[tt]], rr]] For given input region reg and parameter value t find the maximal radius r such that the disk with radius r tangent to the curve at curve[t] stays within reg : radius[reg_, dir_ : -1][t_?NumericQ] := NMaxValue[{r, RegionWithin[reg, disk[dir][t, r]]}, r] Examples: radius[region1][-1] 0.992403 radius[region1][3/2] 2.29173 radius[region2, 1][1] 0.555255 pp = ParametricPlot[curve[x], {x, -2, 3}, ImageSize -> Medium, PlotRange -> {{-5, 5}, {-6, 5}}];frames = Table[Show[pp, Graphics @ {PointSize[Large], Red, Point[curve[t]], FaceForm[], EdgeForm[Red], disk[][t, radius[region1][t]]}], {t, -3/2, 3/2, 1/100}];Export["diskoncurve.gif", frames] ParametricPlot[curve[x], {x, -2, 3}, AspectRatio -> Automatic, Epilog -> {FaceForm[], EdgeForm[Red], disk[][1 + 5/10, radius[region1][1 + 5/10]], EdgeForm[Green], disk[][1, radius[region1][1]], EdgeForm[Orange], disk[][1/5, radius[region1][1/5]], EdgeForm[{Dashed, Red}], disk[1][1 + 5/10, radius[region2, 1][1 + 5/10]], EdgeForm[{Dashed, Green}], disk[1][1, radius[region2, 1][1]], EdgeForm[{Dashed, Orange}], disk[1][1/5, radius[region2, 1][1/5]]}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/237210', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/69429/']}
jdg_73303
stackexchange
llm_judgeable_groundtruth_similarity
37728555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a Subject (or something similar) that can: Could receive items and hold them in a queue or buffer if there are no subscribers Once we have a subscriber all items are consumed and never emitted again I can subscribe/unsubscribe to/from Subject BehaviorSubject almost would do the job, but it retains last observed item. UPDATE Based on accepted answer I worked out similar solution for single observed item. Also added unsubscription part to avoid memory leaks. class LastEventObservable private constructor( private val onSubscribe: OnSubscribe<Any>, private val state: State) : Observable<Any>(onSubscribe) { fun emit(value: Any) { if (state.subscriber.hasObservers()) { state.subscriber.onNext(value) } else { state.lastItem = value } } companion object { fun create(): LastEventObservable { val state = State() val onSubscribe = OnSubscribe<Any> { subscriber -> just(state.lastItem) .filter { it != null } .doOnNext { subscriber.onNext(it) } .doOnCompleted { state.lastItem = null } .subscribe() val subscription = state.subscriber.subscribe(subscriber) subscriber.add(Subscriptions.create { subscription.unsubscribe() }) } return LastEventObservable(onSubscribe, state) } } private class State { var lastItem: Any? = null val subscriber = PublishSubject.create<Any>() }} Now provide the response and nothing else.
I achieve the expected result creating a customized Observable that wraps a publish subject and handles emission cache if there's no subscribers attached. Check it out. public class ExampleUnitTest { @Test public void testSample() throws Exception { MyCustomObservable myCustomObservable = new MyCustomObservable(); myCustomObservable.emit("1"); myCustomObservable.emit("2"); myCustomObservable.emit("3"); Subscription subscription = myCustomObservable.subscribe(System.out::println); myCustomObservable.emit("4"); myCustomObservable.emit("5"); subscription.unsubscribe(); myCustomObservable.emit("6"); myCustomObservable.emit("7"); myCustomObservable.emit("8"); myCustomObservable.subscribe(System.out::println); }}class MyCustomObservable extends Observable<String> { private static PublishSubject<String> publishSubject = PublishSubject.create(); private static List<String> valuesCache = new ArrayList<>(); protected MyCustomObservable() { super(subscriber -> { Observable.from(valuesCache) .doOnNext(subscriber::onNext) .doOnCompleted(valuesCache::clear) .subscribe(); publishSubject.subscribe(subscriber); }); } public void emit(String value) { if (publishSubject.hasObservers()) { publishSubject.onNext(value); } else { valuesCache.add(value); } }} Hope that it helps! Best Regards.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37728555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385219/']}
jdg_73304
stackexchange
llm_judgeable_groundtruth_similarity
42940507
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I merge two different dataframes, keeping all rows from each dataframe while filling in the blanks? DF1 Name Addr Num Parent Parent_AddrMatt 123H 8 James 543FAdam 213H 9 James 543FJames 321H 10 Mom 654FAndrew 512F 10 Dad 665FFaith 555A 7 None 657F DF2 Name Parent Parent_Num Parent_AddrMatt James 10 543FAdam James 10 543FJames Mom 12 654FNone Ian 13 656FNone None None 1234 Expected output Name Addr Num Parent Parent_Num Parent_Addr Matt 123H 8 James 10 543FAdam 213H 9 James 10 543FJames 321H 10 Mom 12 654FAndrew 512F 10 Dad None 665FFaith 555A 7 None None 657FNone None None Ian 13 656FNone None None None None 1234 I am attempting to merge and keep all data from both dataframes. Any help would be greatly appreciated. THank you. Now provide the response and nothing else.
You need to merge on all the common columns and use outer join pd.merge(df1, df2, on = ['Name', 'Parent', 'Parent_Addr'], how = 'outer') Name Addr Num Parent Parent_Addr Parent_Num0 Matt 123H 8 James 543F 101 Adam 213H 9 James 543F 102 James 321H 10 Mom 654F 123 Andrew 512F 10 Dad 665F NaN4 Faith 555A 7 None 657F NaN5 None NaN NaN Ian 656F 136 None NaN NaN None 1234 None
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42940507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6916973/']}
jdg_73305
stackexchange
llm_judgeable_groundtruth_similarity
42133107
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 looking at Accelerate to compute mean and standard deviation of arrays in Swift. I can do the mean. How do I do the standard deviation? let rr: [Double] = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]var mn: Double = 0.0vDSP_meanvD(rr, 1, &mn, vDSP_Length(rr.count))print(mn) // prints correct mean as 45.6250// Standard Deviation should be 22.3155 Now provide the response and nothing else.
You can compute the standard deviation from the mean value andthe mean square value (compare https://en.wikipedia.org/wiki/Standard_deviation#Identities_and_mathematical_properties and https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance ): import Acceleratelet rr: [Double] = [ 18.0, 21.0, 41.0, 42.0, 48.0, 50.0, 55.0, 90.0 ]var mn: Double = 0.0 // mean valuevDSP_meanvD(rr, 1, &mn, vDSP_Length(rr.count))var ms: Double = 0.0 // mean square valuevDSP_measqvD(rr, 1, &ms, vDSP_Length(rr.count))let sddev = sqrt(ms - mn * mn) * sqrt(Double(rr.count)/Double(rr.count - 1))print(mn, sddev)// 45.625 22.315513501982 Alternatively (for iOS 9.0 and later or macOS 10.11 and later), use vDSP_normalizeD : var mn = 0.0var sddev = 0.0vDSP_normalizeD(rr, 1, nil, 1, &mn, &sddev, vDSP_Length(rr.count))sddev *= sqrt(Double(rr.count)/Double(rr.count - 1))print(mn, sddev)// 45.625 22.315513501982
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42133107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7421242/']}
jdg_73306
stackexchange
llm_judgeable_groundtruth_similarity
30862
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There were no unclean animals in the garden of Eden.This is why the phrase "You are cursed more than all cattle" strikes me. Genesis 3:14 (NKJV) So the LORD God said to the serpent: "Because you have done this, You are cursed more than all cattle, And more than every beast of the field; On your belly you shall go, And you shall eat dust All the days of your life. If the serpent is cursed "More than all" cattle and "More than everybeast", are some other animals under less severe curses byimplication? (i.e "more" for the serpent and "less" for some other animals) Does this phrase have any implications as regarding theclean/unclean distinction that existed between animals after theexpulsion from Eden? Now provide the response and nothing else.
The curse on the snake in Genesis 3:14 has no connection with the snake being an unclean animal. The implication that other animals might have been cursed to a lesser degree cause by the translation "more than all" is a translation artifact . It does not exist in the MT, and this is the reason that I tagged this question with the "Hebrew" tag. The Hebrew expression translated as "more than all" in the NKJV is ΧžΦ΄Χ›ΦΌΦΈΧœ , micol , which uses the prepositional "all of", Χ›Χœ , with the prefix מ , "from". So the simple translation, as well as the plain meaning in Hebrew, is " from all of " not "more than all". This is a superlative form in OT Hebrew that indicates that the snake is severely cursed, in a way that no other animal will ever be cursed, but with no implication that any other animal is or will be cursed . Note that the KJV, AKJV and a plurality of the other translations use "above" rather than the NKJV "more than" to translate the micol superlative in Genesis 3:14. Using "above" avoids the implication that the other animals might have been cursed to a lesser degree, and preserves the quirky Hebrewism of the MT albeit at the cost of a loss in clarity (what does it mean " above all cattle and above all animals of the field"?), and is a better translation than the more literal "You are cursed from all of the cattle, and from all of the beasts of the field". The micol or "from all of" superlative in the OT is formed by: a subject noun an adjective ΧžΧ›Χœ , micol , "from all of" the name of some specific group or class of which the subject noun is a member The name of the group or class provides the context for the superlative as well as the necessary subject of for the prepositional phrase "all of...". In the MT the verse is: Χ•Φ·Χ™ΦΌΦΉΧΧžΦΆΧ¨ Χ™Φ°Χ”ΦΉΧ•ΦΈΧ” ΧΦ±ΧœΦΉΧ”Φ΄Χ™Χ א֢ל-הַנָּחָשׁ Χ›ΦΌΦ΄Χ™ Χ’ΦΈΧ©Χ‚Φ΄Χ™ΧͺΦΈ זֹּאΧͺ אָרוּר אַΧͺΦΌΦΈΧ” ΧžΦ΄Χ›ΦΌΦΈΧœ -Χ”Φ·Χ‘ΦΌΦ°Χ”Φ΅ΧžΦΈΧ” Χ•ΦΌ ΧžΦ΄Χ›ΦΌΦΉΧœ Χ—Φ·Χ™ΦΌΦ·Χͺ Χ”Φ·Χ©ΦΌΧ‚ΦΈΧ“ΦΆΧ” גַל-Χ’ΦΌΦ°Χ—ΦΉΧ Φ°ΧšΦΈ Χͺ֡ל֡ךְ Χ•Φ°Χ’ΦΈΧ€ΦΈΧ¨ ΧͺΦΌΦΉΧΧ›Φ·Χœ Χ›ΦΌΦΈΧœ-Χ™Φ°ΧžΦ΅Χ™ Χ—Φ·Χ™ΦΌΦΆΧ™ΧšΦΈ Later historical levels of the Hebrew language, following western languages, developed the superlative form b'yoter , Χ‘Χ™Χ•ΧͺΧ¨, which is adjectival and not prepositional and therefore does not require the identification of a group or class context, which is left unspecified or implied by subject noun's implied class membership. This superlative form completely avoids the implied comparative. To end this post with a blessing rather than a curse, note that in the OT, the micol superlative is sometimes contracted to just the letter מ , mi , "from", dropping the col , "all of", as in Judges 5:14 (KJV): Blessed above women shall Jael the wife of Heber the Kenite be, blessed shall she be above women in the tent for which the MT is: ΧͺΦΌΦ°Χ‘ΦΉΧ¨Φ·ΧšΦ° מִ נָּשִׁים Χ™ΦΈΧ’Φ΅Χœ א֡שׁ֢Χͺ Χ—ΦΆΧ‘ΦΆΧ¨ Χ”Φ·Χ§ΦΌΦ΅Χ™Χ Φ΄Χ™ מִ נָּשִׁים Χ‘ΦΌΦΈΧΦΉΧ”ΦΆΧœ ΧͺΦΌΦ°Χ‘ΦΉΧ¨ΦΈΧšΦ° In this verse, as well as in Genesis 3:14, there is no implication that other women are are necessarily blessed, but if any of them are, then Jael is the most blessed. This form of expression is peculiarly Hebrew and Jewish.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/30862', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/20490/']}
jdg_73307
stackexchange
llm_judgeable_groundtruth_similarity
29100380
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 long series like the following: series = pd.Series([[(1,2)],[(3,5)],[],[(3,5)]])In [151]: seriesOut[151]:0 [(1, 2)]1 [(3, 5)]2 []3 [(3, 5)]dtype: object I want to remove all entries with an empty list. For some reason, boolean indexing does not work. The following tests both give the same error: series == [[(1,2)]]series == [(1,2)]ValueError: Arrays were different lengths: 4 vs 1 This is very strange, because in the simple example below, indexing works just like above: In [146]: pd.Series([1,2,3]) == [3]Out[146]:0 False1 False2 Truedtype: bool P.S. ideally, I'd like to split the tuples in the series into a DataFrame of two columns also. Now provide the response and nothing else.
You could check to see if the lists are empty using str.len() : series.str.len() == 0 and then use this boolean series to remove the rows containing empty lists. If each of your entries is a list containing a two-tuple (or else empty), you could create a two-column DataFrame by using the str accessor twice (once to select the first element of the list, then to access the elements of the tuple): pd.DataFrame({'a': series.str[0].str[0], 'b': series.str[0].str[1]}) Missing entries default to NaN with this method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29100380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992687/']}
jdg_73308
stackexchange
llm_judgeable_groundtruth_similarity
879775
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do we evaluate the integral $$I=\displaystyle\int_{\mathbb{R}} \dfrac{x\sin {(\pi x)}}{(1+x^2)^2}$$ I have wasted so much time on this integral, tried many substitutions $(x^2=t, \ \pi x^2=t)$. Wolfram alpha says $I=\dfrac{e^{-\pi} \pi^2}{2}$, but I don't see how. How do I calculate it using any of the methods taught in real analysis, and not complex analytical methods? Now provide the response and nothing else.
Consider $$\mathcal{I}(y,t)=\int_{-\infty}^{\infty}\frac{\cos xt}{x^2+y^2}\ dx=\frac{\pi e^{-yt}}{y}\quad;\quad\text{for}\ t>0.\tag1$$ Differentiating $(1)$ with respect $t$ and $y$ yields\begin{align}\frac{\partial^2\mathcal{I}}{\partial y\partial t}=\int_{-\infty}^{\infty}\frac{2xy\sin xt}{(x^2+y^2)^2}\ dx&=\pi te^{-yt}\\\int_{-\infty}^{\infty}\frac{x\sin xt}{(x^2+y^2)^2}\ dx&=\frac{\pi te^{-yt}}{2y}.\tag2\end{align}Putting $y=1$ and $t=\pi$ to $(2)$ yields$$\large\color{blue}{\int_{-\infty}^{\infty}\frac{x\sin\pi x}{(x^2+1)^2}\ dx=\frac{\pi^2 e^{-\pi}}{2}}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/879775', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157130/']}
jdg_73309
stackexchange
llm_judgeable_groundtruth_similarity
390248
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 totally understand that --dig-holes creates a sparse file in-place. That is, if the file has holes --dig-holes options removes those holes: Let's take it in a very simplified way, let's say we have a huge file named non-sparse: non-sparse: aaaaaaaaaaaaaaaaaaaaaaaaaaaa\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bbbbbbbbbbbbbbbbbbbbbbbbbbbb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00cccccccccccccccccccccccccccc non-sparse has many zeros in it, assume that the interleaving zeros are in Gigabytes. fallocate --dig-holes de-allocates the space available for the zeros (holes) where the actual file size remains the same (preserved). Now, there's --punch-hole what does it really do? I read the man page, still don't understand: -p, --punch-hole Deallocates space (i.e., creates a hole) in the byte range starting at offset and continuing for length bytes. Within the specified range, partial filesystem blocks are zeroed, and whole filesystem blocks are removed from the file. After a successful call, subsequent reads from this range will return zeroes. Creating hole, that's the opposite of --dig-hole option it seems like that, and how come that digging a hole isn't the same as creating a hole?! Help! we need a logician :). The naming of the two options are synonymous linguistically which perhaps makes confusion. What's the difference between --dig-holes and --punch-holes operationally (not logically or linguistically please!)? Now provide the response and nothing else.
--dig-holes doesn’t change the file’s contents, as determined when the file is read: it just identifies runs of zeroes which can be replaced with holes. --punch-hole uses the --offset and --length arguments to punch a hole in a file, regardless of what the file contains at that offset: it works even if the file contains non-zeroes there, but the file’s contents change as a result. Considering your example file, running fallocate --punch-hole --offset 2 --length 10 would replace ten a characters with zeroes, starting after the second one.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/390248', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/233788/']}
jdg_73310
stackexchange
llm_judgeable_groundtruth_similarity
35361426
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I'm adding an HTML URL into email body, it is not redirecting to the preferred location. This is the snippet, please tell me what am I doing wrong. #location variable contains the URLStringBuffer body = new StringBuffer("<html><body>Hi, <br/><br/>");body.append("<p>"+cmts+"</p>");#both the ways are not working, how to construct proper URL body.append("<br/><br/><a href=\"+location+\">" + location + "</a><br/>");body.append("<br/><br/><a href="+location+">" +location + "</a><br/>");#this is working as link only in OUTLOOK, but in other mail client it shows as plain textbody.append("<br/><br/>"+location); URL: http://host:port/weebApp/report/viewer.html#%2Fpublic%2FSamples%2FDashboards%2_FSample_report Now provide the response and nothing else.
Lambda return type deduction uses the auto rules, which normally would have deduced std::initializer_list just fine. However, the language designers banned deduction from a braced initializer list in a return statement ([dcl.spec.auto]/7): If the deduction is for a return statement and the initializer is a braced-init-list ([dcl.init.list]), the program is ill-formed. The reason for this is that std::initializer_list has reference semantics ( [dcl.init.list]/6 ). []() -> std::initializer_list<int> { return {1, 2}; } is every bit as bad as []() -> const int & { return 1; } . The lifetime of the backing array of the initializer_list object ends when the lambda returns, and you are left with a dangling pointer (or two). Demo : #include <vector>struct Noisy { Noisy() { __builtin_printf("%s\n", __PRETTY_FUNCTION__); } Noisy(const Noisy&) { __builtin_printf("%s\n", __PRETTY_FUNCTION__); } ~Noisy() { __builtin_printf("%s\n", __PRETTY_FUNCTION__); }};int main(){ auto foo = []() -> std::initializer_list<Noisy> { return {Noisy{}, Noisy{}}; }; std::vector<Noisy> bar{foo()};} Output: Noisy::Noisy()Noisy::Noisy()Noisy::~Noisy()Noisy::~Noisy()Noisy::Noisy(const Noisy&)Noisy::Noisy(const Noisy&)Noisy::~Noisy()Noisy::~Noisy() Note how the copy constructors are called after all the Noisy objects created so far have been destroyed already.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35361426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4732576/']}
jdg_73311
stackexchange
llm_judgeable_groundtruth_similarity
39948489
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two inline ul li a lists. One is what I would expect and the other has a space between the a items. ul { list-style: none; margin: 0; padding: 0}li { display: inline;}a { border: 1px solid black; font-size: 1rem;} <br><nav> <ul> <li><a href="#">ONE</a> </li> <li><a href="#">TWO</a> </li> <li><a href="#">THREE</a> </li> </ul></nav><br><nav> <ul> <li> <a href="#"> ONE </a> </li> <li> <a href="#"> TWO </a> </li> <li> <a href="#"> THREE </a> </li> </ul></nav> What I get is two inline navigation sets one without a space between the items and another with a space. Here is an image of the resulting code:Why? Now provide the response and nothing else.
Every Python object can have its truthiness evaluated with PyObject_IsTrue , and you should use this in preference to direct PyTrue / PyFalse singleton checking unless you absolutely know, for certain, that the object is a PyBool . Usage is: int truthy = PyObject_IsTrue(someobj);if (truthy == -1) return APPROPRIATEERRORRETURN;if (truthy){ /* it's true! */ }else{ /* it's false */ } You can just test someobj == Py_True if you know it's definitely a bool, or use PyNumber_AsSsize_t to convert any logical integer type (anything implementing __index__ , and bool is a subclass of int , so it's also logically an integer) to a signed size_t value (if __index__ returns a number that doesn't fit in signed size_t , it will return -1 with exception set). The reason not to do someobj == Py_True in general is because it's like doing if someobj is True: at the Python layer. If someobj is 1 , or an non-empty str , that will treat it as false, when Pythonic code is rarely concerned about being True or False , but rather, "truthiness" and "falsiness". In addition, this: PyObject *b = Py_RETURN_TRUE; is flat wrong. That will incref PyTrue and return it; none of the subsequent code will execute. You'd want: PyObject *b = Py_True; for a borrowed reference, adding a subsequent: Py_INCREF(b); to make it an owned reference if you intended to return it later (since it's a singleton that won't go away, using a borrowed reference is fine unless you know it will be DECREF ed later, e.g. because you returned it and passed ownership to a caller who can't know it's a borrowed reference).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39948489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1807480/']}
jdg_73312
stackexchange
llm_judgeable_groundtruth_similarity
5596874
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 is my first day to perl, and I find this warning very confusing. Parentheses missing around "my" list at ./grep.pl line 10. It seems open FILE, $file; works fine. What is wrong with open my $fh, $file; Thanks! #!/usr/bin/perluse strict;use warnings;sub grep_all { my $pattern = shift; while (my $file = shift) { open my $fh, $file; while (my $line = <$fh>) { if ($line =~ m/$pattern/) { print $line; } } } }grep_all @ARGV; Now provide the response and nothing else.
I've been hacking Perl for more than 15 years, and I admit this warning caused me to scratch my head for a minute because almost every example call to open in the standard Perl documentation and nearly every Perl tutorial in existence contains open with no parentheses, just like you wrote it. You wrote this question on your first day with Perl, but you're already enabling the strict and warnings pragmata! This is an excellent start. False starts An easy but dumb way to β€œfix” the warning is to disable all warnings. This would be a terrible move! Warnings are meant to help you. NaΓ―ve ways to squelch the warning are abandoning the lexical filehandle in favor of the bad old way with a bareword open FH, $file; using explicit parentheses with open open(my $fh, $file); making my 's parentheses explicit open my($fh), $file; using circumscribed parentheses (open my $fh, $file); or using 3-argument open . open my $fh, "<", $file; I recommend against using any of these by themselves because they all have a severe omission in common. The best approach In general, the best way to silence this warning about missing parentheses involves adding no parentheses! Always check whether open succeeds, e.g. , open my $fh, $file or die "$0: open $file: $!"; To disable Perl's magic open and treat $file as the literal name of a fileβ€”important, for example, when dealing with untrusted user input β€”use open my $fh, "<", $file or die "$0: open $file: $!"; Yes, both shut up the warning, but the much more important benefit is your program handles inevitable errors rather than ignoring them and charging ahead anyway. Read on to understand why you got the warning, helpful hints about your next Perl program, a bit of Perl philosophy, and recommended improvements to your code. Finally, you'll see that your program doesn't require an explicit call to open ! Write helpful error messages Notice the important components of the error message passed to die : the program that complained ( $0 ) what it tried to do ( "open $file" ) why it failed ( $! ) These special variables are documented in perlvar . Develop the habit now of including these important bits in every error message that you'll seeβ€”although not necessarily those that users will see. Having all of this important information will save debugging time in the future. Always check whether open succeeds! Once again, always check whether open and other system calls succeed! Otherwise, you end up with strange errors: $ ./mygrep pattern no-such-fileParentheses missing around "my" list at ./mygrep line 10.readline() on closed filehandle $fh at ./mygrep line 11. Explanation of Perl's warnings Perl's warnings have further explanation in the perldiag documentation , and enabling the diagnostics pragma will look up explanations of any warning that perl emits. With your code, the output is $ perl -Mdiagnostics ./mygrep pattern no-such-file Parentheses missing around "my" list at ./mygrep line 10 (#1) (W parenthesis) You said something like my $foo, $bar = @_; when you meant my ($foo, $bar) = @_; Remember that my , our , local and state bind tighter than comma. readline() on closed filehandle $fh at ./mygrep line 11 (#2) (W closed) The filehandle you're reading from got itself closed sometime before now. Check your control flow. The -Mdiagnostics command-line option is equivalent to use diagnostics; in your code, but running it as above temporarily enables diagnostic explanations without having to modify your code itself. Warning #2 is because no-such-file does not exist, but your code unconditionally reads from $fh . It's puzzling that you see warning #1 at all! This is the first time I recall ever seeing it in association with a call to open . The 5.10.1 documentation has 52 example uses of open involving lexical filehandles, but only two of them have parentheses with my . It gets curiouser and curiouser: $ perl -we 'open my $fh, $file'Name "main::file" used only once: possible typo at -e line 1.Use of uninitialized value $file in open at -e line 1. Parentheses are missing, so where's the warning?! Adding one little semicolon, however, does warn about missing parentheses: $ perl -we 'open my $fh, $file;'Parentheses missing around "my" list at -e line 1.Name "main::file" used only once: possible typo at -e line 1.Use of uninitialized value $file in open at -e line 1. Let's look in perl's source to see where the warning comes from. $ grep -rl 'Parentheses missing' ../t/lib/warnings/op./op.c./pod/perl561delta.pod./pod/perldiag.pod./pod/perl56delta.pod Perl_localize in op.c β€”which handles my , our , state , and local β€”contains the following snippet: /* some heuristics to detect a potential error */while (*s && (strchr(", \t\n", *s))) s++;while (1) { if (*s && strchr("@$%*", *s) && *++s && (isALNUM(*s) || UTF8_IS_CONTINUED(*s))) { s++; sigil = TRUE; while (*s && (isALNUM(*s) || UTF8_IS_CONTINUED(*s))) s++; while (*s && (strchr(", \t\n", *s))) s++; } else break;}if (sigil && (*s == ';' || *s == '=')) { Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS), "Parentheses missing around \"%s\" list", lex ? (PL_parser->in_my == KEY_our ? "our" : PL_parser->in_my == KEY_state ? "state" : "my") : "local");} Notice the comment on the first line. In My Life With Spam , Mark Dominus wrote, β€œOf course, this is a heuristic, which is a fancy way of saying that it doesn't work.” The heuristic in this case doesn't work either and produces a confusing warning. The conditional if (sigil && (*s == ';' || *s == '=')) { explains why perl -we 'open my $fh, $file' doesn't warn but does with a trailing semicolon. Watch what happens for similar but nonsensical code: $ perl -we 'open my $fh, $file ='Parentheses missing around "my" list at -e line 1.syntax error at -e line 1, at EOFExecution of -e aborted due to compilation errors. We get the warning! The 3-argument open case doesn't warn because "<" prevents sigil from becoming true, and the or die ... modifier passes muster, in obtuse terms, because the or token begins with a character other than ; or = . The intent of the warning appears to be providing a helpful hint for how to fix code that will otherwise produce surprising results, e.g. , $ perl -lwe 'my $foo, $bar = qw/ baz quux /; print $foo, $bar'Parentheses missing around "my" list at -e line 1.Useless use of a constant in void context at -e line 1.Use of uninitialized value $foo in print at -e line 1.quux Here, the warning does make sense, but the case you found is a leak in the heuristic. Less is more Perl has syntactic sugar that makes writing Unix-style filters easy, as explained in the perlop documentation. The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-" , which when opened gives you standard input. The @ARGV array is then processed as a list of filenames. The loop while (<>) { ... # code for each line} is equivalent to the following Perl-like pseudo code: unshift(@ARGV, '-') unless @ARGV;while ($ARGV = shift) { open(ARGV, $ARGV); while (<ARGV>) { ... # code for each line }} Using the null filehandle (also known as the diamond operator) makes your code behave like the Unix grep utility. filter each line of each file named on the command line, or filter each line of the standard input when given only a pattern The diamond operator also handles at least one corner case that your code doesn't. Note below that bar is present in the input but doesn't appear in the output. $ cat 0foobarbaz$ ./mygrep bar 0Parentheses missing around "my" list at ./mygrep line 10. Keep reading to see how the diamond operator improves readability, economy of expression, and correctness! Recommended improvements to your code #! /usr/bin/env perluse strict;use warnings;die "Usage: $0 pattern [file ..]\n" unless @ARGV >= 1;my $pattern = shift;my $compiled = eval { qr/$pattern/ };die "$0: bad pattern ($pattern):\n$@" unless $compiled;while (<>) { print if /$compiled/;} Rather than hardcoding the path to perl , use env to respect the user's PATH. Rather than blindly assuming the user provided at least a pattern on the command line, check that it's present or give a helpful usage guide otherwise. Because your pattern lives in a variable, it might change. This is hardly profound, but that means the pattern may need to be recompiled each time your code evaluates /$pattern/ , i.e. , for each line of input. Using qr// avoids this waste and also provides an opportunity to check that the pattern the user supplied on the command line is a valid regex. $ ./mygrep ?foo./mygrep: bad pattern (?foo):Quantifier follows nothing in regex; marked by <-- HERE inm/? <-- HERE foo/ at ./mygrep line 10. The main loop is both idiomatic and compact. The $_ special variable is the default argument for many of Perl's operators, and judicious use helps to emphasize the what rather than the how of the implementation's machinery. I hope these suggestions help!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5596874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264442/']}
jdg_73313
stackexchange
llm_judgeable_groundtruth_similarity
15226318
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that Session.save() persists the transient object. And I see that it also has saveOrUpdate() , and also persist() . I suppose then that save() is equivalent to SQL INCLUDE , is it? If I have an object that already exists on DB and I save() it, will another row be included, will its fields be updated, or will it just be ignored and nothing happen? Now provide the response and nothing else.
Difference between save and saveOrUpdate Main difference between save and saveOrUpdate method is that save generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record. So save will proceed without performing existence check, on the other hand saveOrUpdate will check for existence, if record exists it will be updated else a new record will be inserted. Basic differences between persist and save 1)First difference between save and persist is their return type. Similar to save method, persist also INSERT records into database but return type of persist is void while return type of save is Serializable object . 2) Another difference between persist and save is that both methods make a transient instance persistent. However, persist method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15226318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1956207/']}
jdg_73314
stackexchange
llm_judgeable_groundtruth_similarity
19221750
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to apply a certain (custom) function to all combinations of an array. I think its best to explain with an example: Matrix 1 : A B C1 2 3 Matrix 2 : A B C 4 5 6 I would like to do the following: obtain all the combinations of Matrix two and apply a function to each as follows: Matrix 3 : AB AC BC CB CA BA 4/2 4/3 5/3 6/2 6/1 5/1 Where the function applied to Matrix 3 is the corresponding element of Matrix 2 (represented by the first letter in each column of Matrix 3)/the corresponding element of Matrix 2 (represented by the second letter in each column in Matrix 3). Please let me know if anything is unclear, I feel that I may not have explained perfectly. Any help would be greatly appreciated! Thanks Mike Now provide the response and nothing else.
The result is not exactly in the format you asked for, but you can use outer to create a matrix of results from your two input vectors : x <- c(A=1,B=2,C=3)y <- c(A=4,B=5,C=6)outer(x,y, FUN="/") Will give : A B CA 0.25 0.2 0.1666667B 0.50 0.4 0.3333333C 0.75 0.6 0.5000000 If you really want a vector as result, you can use : m <- outer(x,y, FUN="/")v <- as.vector(m)names(v) <- as.vector(outer(names(x),names(y),FUN="paste0")) And then get : AA BA CA AB BB CB AC 0.2500000 0.5000000 0.7500000 0.2000000 0.4000000 0.6000000 0.1666667 BC CC 0.3333333 0.5000000
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19221750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2725103/']}
jdg_73315
stackexchange
llm_judgeable_groundtruth_similarity
9985013
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Take a very simple example, mfrow=c(1,3) ; each figure is a different histogram; how would I draw a horizontal line (akin to abline(h=10) ) that went across all 3 figures? (That is, even the margins between them.) Obviously, I could add an abline to each figure, but that's not what I want. I can think of a very complicated way to do this by really only having 1 figure, and drawing each 'figure' within it using polygon etc. That would be ridiculous. Isn't there an easy way to do this? Now provide the response and nothing else.
As @joran noted, the grid graphical system offers more flexible control over arrangement of multiple plots on a single device. Here, I first use grconvertY() to query the location of a height of 50 on the y-axis in units of "normalized device coordinates". (i.e. as a proportion of the total height of the plotting device, with 0=bottom, and 1=top). I then use grid functions to: (1) push a viewport that fills the device; and (2) plot a line at the height returned by grconvertY() . ## Create three example plotspar(mfrow=c(1,3))barplot(VADeaths, border = "dark blue") barplot(VADeaths, border = "yellow") barplot(VADeaths, border = "green") ## From third plot, get the "normalized device coordinates" of ## a point at a height of 50 on the y-axis.(Y <- grconvertY(50, "user", "ndc"))# [1] 0.314248## Add the horizontal line using gridlibrary(grid)pushViewport(viewport())grid.lines(x = c(0,1), y = Y, gp = gpar(col = "red"))popViewport() EDIT : @joran asked how to plot a line that extends from the y-axis of the 1st plot to the edge of the last bar in the 3rd plot. Here are a couple of alternatives: library(grid)library(gridBase)par(mfrow=c(1,3))# barplot #1barplot(VADeaths, border = "dark blue") X1 <- grconvertX(0, "user", "ndc")# barplot #2barplot(VADeaths, border = "yellow") # barplot #3m <- barplot(VADeaths, border = "green") X2 <- grconvertX(tail(m, 1) + 0.5, "user", "ndc") # default width of bars = 1Y <- grconvertY(50, "user", "ndc")## Horizontal linepushViewport(viewport())grid.lines(x = c(X1, X2), y = Y, gp = gpar(col = "red"))popViewport() Finally, here's an almost equivalent, and more generally useful approach. It employs the functions grid.move.to() and grid.line.to() demo'd by Paul Murrell in the article linked to in @mdsumner's answer: library(grid)library(gridBase)par(mfrow=c(1,3))barplot(VADeaths); vps1 <- do.call(vpStack, baseViewports())barplot(VADeaths) barplot(VADeaths); vps3 <- do.call(vpStack, baseViewports())pushViewport(vps1)Y <- convertY(unit(50,"native"), "npc")popViewport(3)grid.move.to(x = unit(0, "npc"), y = Y, vp = vps1)grid.line.to(x = unit(1, "npc"), y = Y, vp = vps3, gp = gpar(col = "red"))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9985013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1217536/']}
jdg_73316
stackexchange
llm_judgeable_groundtruth_similarity
12821222
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 made a program in c# which show 2 types of form 1 is getting values from the user and save it in Database and second is showing those values in a template of crystal report. My problem is when i move 1st form to 2nd form i hide the first form by using hide(); function and after getting the value on 2nd form from Database i move back to 1st form and hide the second form and show 1st but when i close the whole program it keep running and debugger showing its and running and also have a process in task manager. I want to know how can i close that background process with the form1 close. sorry for my bad English. rollno = txtrollno.Text; ReportCard objreport = new ReportCard(); objreport.Show(); this.Hide(); this is the code for hiding the 1st form . Form1 objshow = new Form1(); objshow.Show(); this.Hide(); and in this i hide 2nd and show 1st again. Now provide the response and nothing else.
Try using Close(); When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends. or Application.Exit(); This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread . or Environment.Exit(exitCode) Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12821222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1405015/']}
jdg_73317
stackexchange
llm_judgeable_groundtruth_similarity
11989261
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 long string that doesn't fit the width of the screen. For eg. String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed."; To make it easier to read, I thought of writing it this way - String longString = "This string is very long." + "It does not fit the width of the screen." + "So you have to scroll horizontally" + "to read the whole string." + "This is very inconvenient indeed."; However, I realized that the second way uses string concatenation and will create 5 new strings in memory and this might lead to a performance hit. Is this the case? Or would the compiler be smart enough to figure out that all I need is really a single string? How could I avoid doing this? Now provide the response and nothing else.
I realized that the second way uses string concatenation and will create 5 new strings in memory and this might lead to a performance hit. No it won't. Since these are string literals, they will be evaluated at compile time and only one string will be created. This is defined in the Java Language Specification #3.10.5 : A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator + [...] Moreover, a string literal always refers to the same instance of class String. Strings computed by constant expressions (Β§15.28) are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run-time are newly created and therefore distinct. Test: public static void main(String[] args) throws Exception { String longString = "This string is very long."; String other = "This string" + " is " + "very long."; System.out.println(longString == other); //prints true} However, the situation situation below is different, because it uses a variable - now there is a concatenation and several strings are created: public static void main(String[] args) throws Exception { String longString = "This string is very long."; String is = " is "; String other = "This string" + is + "very long."; System.out.println(longString == other); //prints false}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11989261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199882/']}
jdg_73318
stackexchange
llm_judgeable_groundtruth_similarity
2658479
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The inequality goes like this:$$\sqrt7^{\sqrt5}>\sqrt5^{\sqrt7}$$I have to prove this without using approximate numbers and I just cannot find out how. Now provide the response and nothing else.
$$7^5=16807>15625=5^6\\7^5>5^6\\\sqrt7^5=(\sqrt7^{\sqrt 5})^{\sqrt 5}>\sqrt5^6=\sqrt5^{\sqrt {36}}>\sqrt5^{\sqrt {35}}=(\sqrt5^{\sqrt {7}})^{\sqrt{5}}\\\sqrt7^{\sqrt 5}>\sqrt5^{\sqrt 7}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2658479', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/533323/']}
jdg_73319
stackexchange
llm_judgeable_groundtruth_similarity
680368
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Named function parameters can be emulated in PHP if I write functions like this function pythonic(array $kwargs){ extract($kwargs); // .. rest of the function body}// if params are optional or default values are requiredfunction pythonic(array $kwargs = array('name'=>'Jon skeet')){ extract($kwargs); // .. rest of the function body} Apart from losing intellisense in IDEs what are the other possible downsides of this approach? Edit: Security: Shouldn't security be a non-issue in this case, as the extracted variables are limited to function scope? Now provide the response and nothing else.
I would suggest using the associative array to pass named parameters, but keep them in the array without extracting them. function myFunc(array $args) { echo "Hi, " . $args['name']; // etc} There's a couple of reasons for this. Looking at that function, you can quite clearly see that I'm referring to one of the arguments passed into the function. If you extract them, and don't notice the extract() you (or the next guy) will be there scratching your head wondering where this " $name " variable came from. Even if you do know you're extracting the arguments to local variables, it's still a guessing game to a certain degree. Secondly, it ensures that other code doesn't overwrite the args. You may have written your function expecting only to have arguments named $foo and $bar , so in your other code, you define $baz = 8; , for example. Later on, you might want to expand your function to take a new parameter called "baz" but forget to change your other variables, so no matter what gets passed in the arguments, $baz will always be set to 8. There are some benefits to using the array too (these apply equally to the methods of extracting or leaving in the array): you can set up a variable at the top of each function called $defaults : function myFunc (array $args) { $default = array( "name" => "John Doe", "age" => "30" ); // overwrite all the defaults with the arguments $args = array_merge($defaults, $args); // you *could* extract($args) here if you want echo "Name: " . $args['name'] . ", Age: " . $args['age'];}myFunc(array("age" => 25)); // "Name: John Doe, Age: 25" You could even remove all items from $args which don't have a corresponding $default value. This way you know exactly which variables you have.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/680368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1897/']}
jdg_73320
stackexchange
llm_judgeable_groundtruth_similarity
510765
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 winforms application in which I am using 2 Forms to display all the necessary controls. The first Form is a splash screen in which it tells the user that it it loading etc. So I am using the following code: Application.Run( new SplashForm() ); Once the application has completed loading I want the SplashForm to hide or me sent to the back and the main from to be show. I am currently using the following: private void showMainForm(){ this.Hide(); this.SendToBack(); // Show the GUI mainForm.Show(); mainForm.BringToFront();} What I am seeing is that the MainForm is shown, but the SplashForm is still visible 'on top'. What I am currently doing is clicking on the MainForm to manually bring it to the front. Any ideas on why this is happening? Now provide the response and nothing else.
Probably you just want to close the splash form, and not send it to back. I run the splash form on a separate thread (this is class SplashForm): class SplashForm{ //Delegate for cross thread call to close private delegate void CloseDelegate(); //The type of form to be displayed as the splash screen. private static SplashForm splashForm; static public void ShowSplashScreen() { // Make sure it is only launched once. if (splashForm != null) return; Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm)); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Start(); } static private void ShowForm() { splashForm = new SplashForm(); Application.Run(splashForm); } static public void CloseForm() { splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal)); } static private void CloseFormInternal() { splashForm.Close(); splashForm = null; }...} and the main program function looks like this: [STAThread]static void Main(string[] args){ SplashForm.ShowSplashScreen(); MainForm mainForm = new MainForm(); //this takes ages SplashForm.CloseForm(); Application.Run(mainForm);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/510765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1816/']}
jdg_73321
stackexchange
llm_judgeable_groundtruth_similarity
1543111
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 came across this funny proof- $$4$$ $$=4+\frac 92-\frac 92$$ $$=\sqrt{(4-\frac 92)^2}+\frac 92$$ $$=\sqrt{16+\frac{81}{4}-36}+\frac 92$$ $$=\sqrt{25+\frac {81}{4}-45}+\frac 92$$ $$=\sqrt{(5-\frac 92)^2}+\frac 92$$ $$=5-\frac 92+\frac 92$$ $$=5$$ I suspect,that the error is in the second line where operation on negative is done before positive violating $BODMAS$ rule.But, $\sqrt{(4-\frac 92)^2}=4-\frac 92$ and the similar solving continues.So, where is the real error? Thanks for any help!! Now provide the response and nothing else.
The error is going from the second to third line. $$\sqrt{x^2}=|x|$$so $$\sqrt{\left(4-\frac{9}{2}\right)^2}=\left|4-\frac{9}{2}\right|\neq 4-\frac{9}{2}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1543111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/242402/']}
jdg_73322
stackexchange
llm_judgeable_groundtruth_similarity
3157189
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We can regard a sequence as a special kind of net . But the definition of "subnet" is more flexible than that of "subsequence", so it's easy to find subnets of a sequence that aren't subsequences. In fact, if $X$ is a compact topological space that is not sequentially compact , like $$ X = \prod_{x \in \mathbb{R}} [0,1] \; ,$$ we can have a sequence in $X$ that has no convergent subsequences, but it must have convergent subnets! I've always found this phenomenon mysterious. Can someone describe, as explicitly as possible, a sequence in some topological space that has no convergent subsequences, but has a convergent subnet? Does finding an example require the axiom of choice, or is there an 'explicit' one? Now provide the response and nothing else.
Much to my surprise, there is an explicit example, and it comes about at least in part because it seems that the theorem going back and forth between cluster points and convergent subnets does not require the axiom of choice, when done the right way. In the first part of my answer, I describe the example, being as explicit with the subnet as I possibly can to show there's no AC up my sleeve. In the second part I comment on why choice is necessary for Henno Brandsma's example. To get a sequence with a convergent subnet but no convergent subsequence in just ZF, we only really need to work out the details of Exercise E from Chapter 2 of Kelley's General Topology . Accordingly I will be following Kelley's definitions of subnet and so on throughout. Just for clarity, we will be taking $\newcommand{\N}{\mathbb{N}}\N$ to include $0$ in the following. We define a topology on $\N \times \N$ where $\{(n,m)\}$ is open if $(n,m) \neq (0,0)$ and $U \subseteq \N \times \N$ is an (open) neighbourhood of $(0,0)$ iff it contains $(0,0)$ and for all but finitely many $m \in \N$ , the set $\{ n \in \N \mid (m,n) \not\in U \}$ is finite. Or, if you prefer, the open sets are Sets not containing $(0,0)$ . Sets containing $(0,0)$ such that for all but finitely many $m \in \N$ , the set $\{ n \in \N \mid (m,n) \not\in U \}$ is finite. The first thing we need is: Lemma 1 : Any sequence $(m_i,n_i)_{i \in \N}$ of elements in $\N^2\setminus\{(0,0)\}$ does not converge to $(0,0)$ . Assume for a contradiction that there is such a sequence $(m_i,n_i)_{i \in \N}$ converging to $(0,0)$ . Given $k \in \N$ , define $V_k = \{ (m,n) \in \N^2 \mid m \neq k \} \cup \{ (0,0) \}$ . This is a neighbourhood of $0$ (using the "all but finitely many $m$ part"), so for each $k \in \N$ there is an $N_k$ such that for all $i \geq N_k$ , $(m_{i},n_{i}) \in V_k$ , i.e. $m_i \neq k$ . It follows that there are only finitely many $i \in \N$ such that $m_i = k$ . Now consider $U = \N^2 \setminus \{(m_i,n_i)\}_{i \in \N}$ . It contains $(0,0)$ , and for each $m \in \N$ , $$\{ n \in \N \mid (m,n) \not\in U \} = \{ n \in \N \mid (m,n) \in \{(m_i,n_i)\}_{i \in \N} \},$$ and this set is finite because $m_i = m$ only happens if $i < N_m$ . Therefore $U$ is a neighbourhood of $(0,0)$ (using the other part of the definition). But this contradicts $(m_i,n_i)_{i \in \N}$ converging to $(0,0)$ , so there is no such sequence. $\square$ Now, we define a sequence $(x_i)_{i \in \N}$ to be any enumeration of $\N^2 \setminus \{ (0,0) \}$ . There are many ways to do it, and it does not particularly matter how, so I won't give one explicitly as I don't want to get caught out in a silly mistake. By Lemma 1, no subsequence of it converges to $(0,0)$ . We define a subnet as follows. Take $\mathcal{N}$ to be the set of neighbourhoods of $(0,0)$ , ordered by $\supseteq$ . This is a directed poset. We define $$J = \{ (i,U) \in \N \times \mathcal{N} \mid x_i \in U \},$$ with the ordering being as a subposet of $\N \times \mathcal{N}$ . We take $f : J \rightarrow \N$ to be the projection mapping $\pi_1$ , and for each $(i,U) \in \N \times \mathcal{N}$ we define $y_{i,U} = x_i$ . Proposition $((y_{(i,U)})_{(i,U) \in J}, f)$ is a subnet of $(x_i)_{i \in \N}$ converging to $(0,0)$ . We first need to show that $J$ is directed as a poset. If $(i_1,U_1), (i_2,U_2) \in J$ , then $U_1 \cap U_2$ is a neighbourhood of $(0,0)$ , so is infinite, so there must exist $j \geq i_1,i_2$ such that $x_j \in U_1 \cap U_2$ . Then $(j,U_1 \cap U_2)$ is the upper bound we need. To show that $(y_{(j,U)})_{(j,U) \in J}$ is a subnet, we only need to show that for each $i \in \N$ there exists $(j,U) \in J$ such that for all $(j',U') \geq (j,U)$ $f(j',U') \geq i$ . To do this, we define $(j,U) = (i,\N^2)$ . For all $(j',U') \geq (i,\N^2)$ we have $f(j',U') = j' \geq i$ , as required. The last remaining part is to show that this subnet converges to $(0,0)$ . If $U \subseteq \N^2$ is a neighbourhood of $0$ , then it contains some $(m,n) \neq (0,0)$ , and by the definition of $(x_i)_{i \in \N}$ there exists some $i \in \N$ such that $x_i = (m,n) \in U$ . Now, for all $(j,V) \geq (i,U)$ , $y_{(j,V)} = x_j \in V \subseteq U$ , so $y_{(j,V)} \in U$ . $\square$ Henno Brandsma's example uses the Boolean ultrafilter lemma in the form of Tychonoff's theorem for Hausdorff spaces. There's a related example that shows that $\N$ , embedded in $\beta(\N)$ has no convergent subsequence (because convergent sequences in Stonean spaces are eventually constant ). Both of these examples actually require the existence of non-principal ultrafilters on $\N$ , which I will show as follows. Suppose $((y_i)_{i \in I}, f: I \rightarrow \N)$ is a convergent subnet of $(\pi_n)_{n \in \N}$ converging to $y \in 2^{2^{\N}}$ . Each $\pi_n$ is actually a Boolean homomorphism $2^\N \rightarrow 2$ , and since convergence in the product topology is pointwise, this implies that $y : 2^\N \rightarrow 2$ is a Boolean homomorphism. Therefore $y^{-1}(1)$ is an ultrafilter on $\N$ . In fact it is non-principal. This can be shown by the following argument. Define $\delta_n : \N \rightarrow 2$ to be the indicator function of $\{n\} \subseteq \N$ , and $N_{\delta_n,1}$ to be the subbasic clopen $$N_{\delta_n,1} = \{ f : 2^\N \rightarrow 2 \mid f(\delta_n) = 1 \}.$$ If $y(\delta_n) = 1$ , then $y \in N_{\delta_n,1}$ so by the definition of convergence, there exists $i_1 \in I$ such that for all $i' \geq i_1$ , $y_{i'} \in N_{\delta_n,1}$ . We also have, from the definition of subnet, that there exists $i_2 \in I$ such that for all $i' \geq i_2$ , $f(i') \geq n+1$ . By directedness of $I$ , there exists $i_3 \geq i_1,i_2$ . For all $i' \geq i_3$ , we have $y_{i'}(\delta_{n}) = 1$ , but also $y_{i'} = \pi_{f({i'})}$ with $f(i') \geq n+1$ and so $y_{i'}(\delta_{n}) = 0$ , a contradiction. Therefore $y(\delta_n) \neq 1$ for all $n \in \N$ and so $y^{-1}(1)$ is a non-principal ultrafilter. Now, there are various models of ZF in which dependent choice holds but there are no non-principal ultrafilters on $\N$ . Solovay's model in which all sets are Lebesgue measurable is a famous one, but there are many others such as the Solovay-Pincus model in which the Hahn-Banach theorem holds, but there are no non-principal ultrafilters on any set whatsoever. In these models, therefore, $(\pi_n)_{n \in \N}$ has no convergent subnets. Similarly, the set of principal ultrafilters in $\beta(\N)$ has no convergent subnets because it is closed, being all of $\beta(\N)$ . As a coda, I'll say that I have not addressed the question of whether "every compact space is sequentially compact" is consistent with ZF or ZF + DC. All we've seen is that the standard counterexamples don't work, but that we cannot go as far as "every sequence with a convergent subnet has a convergent subsequence". This seems to be a hard question, more suitable for MathOverflow. I couldn't find anything about it in standard references such as Howard and Rubin's Consequences of the Axiom of Choice . Added in edit: Apparently Andrew Stacey asked it on MathOverflow donkey's years ago, getting two bad answers, and an interesting answer by K.P. Hart explaining a mistake in one of the answers. However, no answer to the original question was forthcoming.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3157189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/327909/']}
jdg_73323
stackexchange
llm_judgeable_groundtruth_similarity
149715
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading through the study guides for the LPIC-1 . echo "This is a sentence. " !#:* !#:1->text3 I'm having trouble understanding how the above line of code repeats the echo command multiple times. I know that it is using a feature of bash 's history but I can't find any documentation on !#:* or !#:1 . Could someone explain this for me? Now provide the response and nothing else.
Yes, this is using history. !# is a history event designator that refers to the entire command line typed so far. :* is a word (range) designator that refers to all of the words, except the 0th.Β So,Β after you have typed echo "This is a sentence. " ,then !#:* expands to "This is a sentence.Β  " .Β And x - y (where x and y are integers)is a word (range) designator that refers to word number x through word number y .Β If y is omitted ( x - ),this is interpreted to mean word number x through the second to last word.Β So, after your β€œentire command line typed so far” stands as echo "This is a sentence. " "This is a sentence. " then !#:1- expands to "This is a sentence. " ,because each of the quoted "This is a sentence. " strings counts as one word,and so !#:1- is equivalent to !#:1 (just word numberΒ 1).Β So you end up with echo "This is a sentence. " "This is a sentence. " "This is a sentence. " >text3 The fact that the - and the > appear together in the command is just a confusion;they don’t interact.Β And the fact that β€œThis is a sentence.” is quoted obscures what is going on; if you said echo This is a sentence. !#:* !#:1- it would expand to echo This is a sentence. This is a sentence. !#:1- and thence to echo This is a sentence. This is a sentence. This is a sentence. This is a (because !#:1- expands to word number 1 through the second to last word.)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/149715', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/74033/']}
jdg_73324
stackexchange
llm_judgeable_groundtruth_similarity
4364345
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am proving that $f(z) = \mid z\mid^2$ is not an analytic function. So i didn't want to use the Cauchy-Riemann condition or anything but i know that this particular function is diffentiable at only $z=0$ and nowhere else. So I check the differentiability at $z=0$ without any difficulty , just by using the definition of diffentiable complex valued function as in pic : Now I let a another arbitrary point $z_0 \neq 0 $ and check the differentiability at $z_0$ just by using the existence of this limit $$\lim_{z \to z_o} \frac{f(z)-f(z_0)}{ z - z_0}$$ $\implies$ $\lim_{z \to z0o} \frac{\mid{z}\mid^2-\mid{z_0}\mid^2}{ z - z_0}$ $\implies$ $\lim_{z \to z_0} \frac{(X^2-X_0^2) + ( Y^2 -Y_0^2 )}{ (X-X_0) + (Y-Y_0)\iota}$ But now I am stuck that how can I provde the non-existence of Limit . If I will rationalise then also not getting any satisfactory results. Or choosing two different path is looking impossible because $z_0$ is an unknown point. Now provide the response and nothing else.
Let $x$ belongs to $\mathbb R\setminus \{0\}$ . You have $$\frac{\vert z_0 +x \vert^2 - \vert z_0\vert^2}{(z_0+x)-z_0}=\frac{x(z_0+\overline{z_0}) +x^2}{x}$$ while $$\frac{\vert z_0 +ix \vert^2 - \vert z_0\vert^2}{(z_0+ix)-z_0}=\frac{ix(-z_0+\overline{z_0}) +x^2}{ix}$$ You get the desired result as for $z_0 \neq 0$ , $$z_0+ \overline{z_0} \neq -z_0 +\overline{z_0}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4364345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/997851/']}
jdg_73325
stackexchange
llm_judgeable_groundtruth_similarity
61860220
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 having an error in my Controller. The repository can't be injected in the base constructor public class MyController : ControllerCRUDBase<Entity, TournamentDto>{ public MyController (IGenericRepository<Entity> repository, IMapper mapper) : base(repository, mapper) { }} Where my ControllerCRUDBase is: public abstract class ControllerCRUDBase<E, D> : ControllerBase where E : EntityBase where D : DtoBase { protected readonly IGenericRepository<EntityBase> _repository; protected readonly IMapper _mapper; public ControllerCRUDBase(IGenericRepository<EntityBase> repository, IMapper mapper) { _repository = repository; _mapper = mapper; } My IGenericRepository is: public interface IGenericRepository<TEntity> where TEntity : EntityBase { } And the Entity class is: public class Entity: EntityBase{} The error is this: cannot convert from 'IGenericRepository<Entity>' to 'IGenericRepository<EntityBase>' And I can't understand why. Now provide the response and nothing else.
The networking subsystem in WSL2 is different than the used in WSL1. You must consider the differences to access networking apps running on Windows and on Linux: In WSL1, Linux uses the same IP addresses than the Windows host, then, you can access the applications using localhost or 127.0.0.1 In WSL2, Linux runs on a lightweight virtual machine and has a different IP address. To access networking apps running on the Windows Host you must use the Windows IP address. Checking the IP address of the Windows host There are many ways to determine the IP addresses in the Windows host. You may run the following commands in your WSL Linux: cat /etc/resolv.conf shows the IP address of the eth0 interface in Windows ipconfig.exe shows the all the IP configuration in the Windows host route.exe print shows the network routing configuration in the Windows host Setting the DISPLAY variable for WSL2 Based on the Microsoft documentation, you may set the DISPLAY variable checking the nameserver in the /etc/resolv.conf file. ( @fqquiner and @VPraharsha already mentioned this) export DISPLAY=$(grep nameserver /etc/resolv.conf | awk '{print $2}'):0.0 However, I had problems using this solution, probably because I use my notebook with a WiFi connection and multiple virtual networks. Instead of the previous solution, I determine the Windows IP address using route.exe and checking the interface used in the default gateway. export DISPLAY=$(route.exe print | grep 0.0.0.0 | head -1 | awk '{print $4}'):0.0 Setting the DISPLAY variable in the .profile You may set the DISPLAY variable in your ~/.profile file. I used the following code: # set DISPLAY to use X terminal in WSL# in WSL2 the localhost and network interfaces are not the same than windowsif grep -q WSL2 /proc/version; then # execute route.exe in the windows to determine its IP address DISPLAY=$(route.exe print | grep 0.0.0.0 | head -1 | awk '{print $4}'):0.0else # In WSL1 the DISPLAY can be the localhost address if grep -q icrosoft /proc/version; then DISPLAY=127.0.0.1:0.0 fifi
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/61860220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13563716/']}
jdg_73326
stackexchange
llm_judgeable_groundtruth_similarity
4427
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 $\mathbb{Z}/2\mathbb{Z}$-graded algebra is said to supercommute if $xy = (-1)^{|x| |y|} yx$; in other words, odd elements anticommute. Why is this the "right" definition of supercommutativity? (Put another way, why is this the natural tensor product structure on super vector spaces?) Answers from both a categorical or physical point of view would be great. Now provide the response and nothing else.
The categorical answer is that (in characteristic zero) this is the only way that you can make a suitable symmetric tensor category, other than by using group representations. There is a Tannakian theorem of Deligne to this effect in the algebraic setting. One of the physical answers is equivalent to the categorical answer. "Parastatistics" is the topic of self-consistent linear actions of the symmetric group on identical quantum-mechanical particles. The parastatistics theorem in physics (or theorems or conjectures; the level of rigor of the real point is not entirely clear) is a lot like Deligne's theorem. It says that parastatistical particles come in two kinds, parafermions and parabosons, and that they can all be modeled as fermions and bosons together with internal state spaces which are group representations. Bosons and fermions may not look exactly the same as commutative or supercommutative algebras. But they are the same topic, because (if you apply second quantization in reverse) the values of their fields commute or anticommute. For particles in 2D, the correct group action is the braid group, not the symmetric group. So in this case, the parastatistics theorem does not hold and you can have "anyons". Then the allowed statistics is given by a unitary ribbon tensor category. However, since the category in question is no longer symmetric, there is no clear way to define commutativity; at least, nothing that's clearly important. Note also that isn't just that the principle of available symmetric tensor categories comes from category theory and is needed in physics. It's also needed in topology. The most traditional supercommutativity in mathematics is cohomology. To answer Qiaochu's question below, there's nothing wrong with using the standard switching map $v \otimes w \mapsto w \otimes v$ to define commutativity. It shows up all the time. The point is that the signed switching map $v \otimes w \mapsto (-1)^{|v||w|}w \otimes v$ is another valid and inequivalent symmetric monoidal structure. (The symmetric tensor structure is interpreted as what it means to permute factors of a product, of course.) There is nothing to prevent the signed switching map from arising among topological invariants or in physics, so it does arise. The structure theorems say that all "suitable" choices for the switching map are essentially these two, possibly disguised by a restriction to tensors that are invariant under a group action. For both good and bad reasons, I was deliberately vague about what it means for the symmetric tensor category to be suitable, in the sense that it will satisfy a structure theorem. You want some extra axioms and properties to hold, some of them related to existence of duals and traces. One version of the structure theorem, due to Deligne, is reviewed in the paper The classification of finite-dimensional triangular Hopf algebras over an algebraically closed field of characteristic 0 by Etingof and Gelaki ( published version ). (The theorem cited as [De2] is the relevant one.)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/4427', 'https://mathoverflow.net', 'https://mathoverflow.net/users/290/']}
jdg_73327
stackexchange
llm_judgeable_groundtruth_similarity
34225690
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a precedence one way or the other for separating a common subset of multiple tables into its own table with a key for type? Example:Hipmunk allows you to search for flights with "trip details" of { departure_location: Orlando, destination_location: Miami, departure_date: 2016-05-05, return_date: 2016-05-10} After making a search there is a recent search tracker and you can save a flight into "my saved flights". Further if you book a flight then there is presumably a record for that as well. So the following tables would all have "trip details" in common plus some other bits. So is there merit to duplicating the columns in all tables or having a common table for this common object.Should all 3 tables have from,to,departure,arrival or is there merit to abstracting that into a trip_details table that then has a from,to,arrival,departure,type. Type would be an enum for search,saved,booked. I've been asked to provide some sample tables so here they are Approach 1 recent -> id,from,to,departure,return,user_idsaved -> id,from,to,departure,return,user_id,flight_idbooked -> id,from,to,departure,return,user_id,flight_id,confirmation_number,payment_type... etc Approach 2 trip_details -> id,from,to,departure,return,user_id, type(recent,saved,booked)recent -> id, trip_details_id, user_idsaved -> id, trip_details_id, user_id, flight_idbooked -> id, trip_details_id, user_id, confirmation_number, payment_type... etc Note: Trip details row will never be shared across the 3 tables. Approach 2 will not reduce redundant data EDIT To help clarify, these are not my tables, I'm trying to figure this out in the abstract. Also maybe an example of the programming would help. Please don't get too hung up on the implementation details as I'm trying to figure out the question "if 3 tables all have 5 columns that are the same type and conceptually represent an object should that 'object' live in its own table? Even if moving it to its own table will not reduce data redundancy?" var recentSearch = { tripDetails: { departure_date: '2015-01-05', return_date: '2015-01-10', from: 'Orlando', to: 'Chicago' }}var savedSearch = { tripDetails: { departure_date: '2015-01-05', return_date: '2015-01-10', from: 'Orlando', to: 'Chicago' }}var booked = { flight_id: 1234, confirmation_number: 3456, book_date: '2015-12-12' tripDetails: { departure_date: '2015-01-05', return_date: '2015-01-10', from: 'Orlando', to: 'Chicago' }} Now provide the response and nothing else.
Even @MartinPieters's answer is correct I think that is not the best way to do it. Mock provide assert_has_calls to do this kind of duties. Your test could be: function.assert_has_calls([mock.call(1, 2), mock.call(2, 3)]) Where mock.call is a helper class do to these kind of jobs. Pay attention that is a has call and means the call list should be in the list of call and not equal. To solve it I usually define my own helper assert_is_calls() as follow def assert_is_calls(m, calls, any_order=False): assert len(m.mock_calls) == len(calls) m.assert_has_calls(calls, any_order=any_order) That a resume example >>> import mock>>> f = mock.Mock()>>> f(1)<Mock name='mock()' id='139836302999952'>>>> f(2)<Mock name='mock()' id='139836302999952'>>>> f.assert_has_calls([mock.call(1), mock.call(2)])>>> f.assert_has_calls([mock.call(2), mock.call(1)])Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/damico/.local/lib/python2.7/site-packages/mock/mock.py", line 969, in assert_has_calls ), cause) File "/home/damico/.local/lib/python2.7/site-packages/six.py", line 718, in raise_from raise valueAssertionError: Calls not found.Expected: [call(2), call(1)]Actual: [call(1), call(2)]>>> f.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)>>> f(3)<Mock name='mock()' id='139836302999952'>>>> f.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)>>> f.assert_has_calls([mock.call(1), mock.call(2)])>>> assert len(f.mock_calls)==2Traceback (most recent call last): File "<stdin>", line 1, in <module>AssertionError>>> assert len(f.mock_calls)==3>>> def assert_is_calls(m, calls, any_order=False):... assert len(m.mock_calls) == len(calls)... m.assert_has_calls(calls, any_order=any_order)... >>> assert_is_calls(f, [mock.call(1), mock.call(2), mock.call(3)])>>> assert_is_calls(f, [mock.call(1), mock.call(3), mock.call(2)])Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in assert_is_calls File "/home/damico/.local/lib/python2.7/site-packages/mock/mock.py", line 969, in assert_has_calls ), cause) File "/home/damico/.local/lib/python2.7/site-packages/six.py", line 718, in raise_from raise valueAssertionError: Calls not found.Expected: [call(1), call(3), call(2)]Actual: [call(1), call(2), call(3)]>>> assert_is_calls(f, [mock.call(1), mock.call(3), mock.call(2)], True)>>> assert_is_calls(f, [mock.call(1), mock.call(3)], True)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in assert_is_callsAssertionError>>>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34225690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736368/']}
jdg_73328
stackexchange
llm_judgeable_groundtruth_similarity
20827761
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 at a loss, I'm having issues creating a stored proc in my local Postgres server (postgres.app, Mac OS X 10.7), as so $ psqlpsql (9.3.0)Type "help" for help.dchaston=# CREATE OR REPLACE FUNCTION table_update()dchaston-# RETURNS TRIGGER AS $$dchaston$# BEGINdchaston$# NEW.last_edit = now();dchaston$# RETURN NEW;dchaston$# END;dchaston$# $$ language 'plpgsql';ERROR: could not access file "$libdir/plpgsql": No such file or directory I've checked the following: Languages installed: dchaston=# select * from pg_language;lanname | lanowner | lanispl | lanpltrusted | lanplcallfoid | laninline | lanvalidator | lanacl---------+----------+---------+--------------+---------------+-----------+--------------+--------internal | 10 | f | f | 0 | 0 | 2246 | c | 10 | f | f | 0 | 0 | 2247 | sql | 10 | f | t | 0 | 0 | 2248 | plpgsql | 10 | t | t | 12019 | 12020 | 12021 | (4 rows) lib directory (and pkglibdir just in case): $ pg_config --libdir/Applications/Postgres.app/Contents/MacOS/lib$ pg_config --pkglibdir/Applications/Postgres.app/Contents/MacOS/lib File present: $ cd /Applications/Postgres.app/Contents/MacOS/lib; ls plpg*plpgsql.so DLSUFFIX set correctly: lib/pgxs/src/Makefile.shlib:135: DLSUFFIX = .so Have tried uninstalling and reinstalling, but made no difference. Any ideas? Now provide the response and nothing else.
Did you install multiple instances (multiple versions or multiple instances of the same version) of Postgres on the same box? Standard Postgres is not fit for that. Debian or Ubuntu have additional infrastructure to allow multiple versions in parallel. I don't know about OS X, though. In standard Postgres the path for $libdir is compiled into the program. Multiple versions do not get along. When you execute pg_config --pkglibdir , make sure it's the one associated with your installation. Run: which pg_config Minor notes: 9.3.0 ? It's recommended to always upgrade to the latest point-release , which is 9.3.2 at the moment. Maybe a current source fixes your problem. Also check your settings whether you are using the $libdir you think you are using: SELECT * FROM pg_settings WHERE name ~~* '%lib%'; Don't quote the language name 'plpgsql' (though it's tolerated). It's an identifier: plpgsql . Use the plpgsql assignment operator := . = is undocumented but tolerated. Since Postgres 9.4 both := and = are documented. Otherwise your function definition is fine. That's not the root of the problem: CREATE OR REPLACE FUNCTION table_update() RETURNS trigger AS$func$BEGIN NEW.last_edit := now(); RETURN NEW;END$func$ LANGUAGE plpgsql;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20827761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1934117/']}
jdg_73329
stackexchange
llm_judgeable_groundtruth_similarity
31909094
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 class called Node that has an importance setter and getter, below: class Node: @property def importance(self): return self._importance @importance.setter def importance(self, new_importance): if new_importance is not None: new_importance = check_type_and_clean(new_importance, int) assert new_importance >= 1 and new_importance <= 10 self._importance = new_importance Later on, I have a class Theorem that inherits from Node . The only difference between a Theorem and a Node , as far as importance is concerned, is that a Theorem must have an importance of at least 3 . How can a Theorem inherit the importance setter, but add on the additional constraint that importance >= 3 ? I tried to do it this way: class Theorem(Node): @importance.setter def importance(self, new_importance): self.importance = new_importance # hoping this would use the super() setter assert self.importance >= 3 Now provide the response and nothing else.
You can refer to the existing property directly through the Node class, and use the property's setter method to create a new property from it: class Theorem(Node): @Node.importance.setter def importance(self, new_importance): # You can change the order of these two lines: assert new_importance >= 3 Node.importance.fset(self, new_importance) This will create a new property into Theorem class that uses the getter method from Node.importance but replaces the setter method with a different one.That's how properties in general work: calling a property's setter returns a new property with a custom setter, which usually just replaces the old property. You can learn more about how properties work by reading this answer (and the question too).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31909094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2203144/']}
jdg_73330
stackexchange
llm_judgeable_groundtruth_similarity
1373850
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two different styles for my window: Regular - window has title bar and can be moved/resized Fixed - window has no title bar and is fixed at the center of the screen The window is too wide for either of the monitors on my development machine, but it's a perfect fit for the target/install machine. So, when debugging, I need to be able to move the Window so I can see everything on it, but when I release the app, I need it to run in "full screen" mode (like a PowerPoint app in projector mode). Is there any way to set the Style property of the window based on whether I'm compiling in Debug vs. Release mode? I was thinking I might be able to use a binding, but I'm not quite sure how to implement it. Now provide the response and nothing else.
Create a Style picker class: namespace WpfApplication1{ public class DebugReleaseStylePicker { #if DEBUG internal static readonly bool debug = true; #else internal static readonly bool debug=false; #endif public Style ReleaseStyle { get; set; } public Style DebugStyle { get; set; } public Style CurrentStyle { get { return debug ? DebugStyle : ReleaseStyle; } } }} in your App.xamladd to your Application.Resources your debug and release style + a instance of the StylePicker and set the ReleaseStyle and DebugStyle to the previous set up styles: <Application.Resources> <Style x:Key="WindowDebugStyle"> <Setter Property="Window.Background" Value="Red"></Setter> </Style> <Style x:Key="WindowReleaseStyle"> <Setter Property="Window.Background" Value="Blue"></Setter> </Style> <WpfApplication1:DebugReleaseStylePicker x:Key="stylePicker" ReleaseStyle="{StaticResource WindowReleaseStyle}" DebugStyle="{StaticResource WindowDebugStyle}"/> </Application.Resources> In your Window markup set up the WindowStyle like this: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" Style="{Binding Source={StaticResource stylePicker}, Path=CurrentStyle}"> ..</Window> You can reuse the DebugReleaseStylePicker to set the style to any other control not just the Window.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1373850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129164/']}
jdg_73331
stackexchange
llm_judgeable_groundtruth_similarity
40619320
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 calculate the derivative of a function at x = 0, but I keep getting odd answers with all functions I have tried. For example with f(x)=x**2 I get the derivative to be 2 at all points. My finite difference coefficients are correct, it is second order accurate for the second derivative with respect to x. from numpy import *from matplotlib.pyplot import *def f1(x): return x**2n = 100 # grid pointsx = zeros(n+1,dtype=float) # array to store values of xstep = 0.02/float(n) # step sizef = zeros(n+1,dtype=float) # array to store values of fdf = zeros(n+1,dtype=float) # array to store values of calulated derivativefor i in range(0,n+1): # adds values to arrays for x and f(x) x[i] = -0.01 + float(i)*step f[i] = f1(x[i])# have to calculate end points seperately using one sided formdf[0] = (f[2]-2*f[1]+f[0])/step**2df[1] = (f[3]-2*f[2]+f[1])/step**2df[n-1] = (f[n-1]-2*f[n-2]+f[n-3])/step**2df[n] = (f[n]-2*f[n-1]+f[n-2])/step**2for i in range(2,n-1): # add values to array for derivative df[i] = (f[i+1]-2*f[i]+f[i-1])/step**2print df # returns an array full of 2... Now provide the response and nothing else.
I would call this a bug. I snapped together a simple test, just a class with some defaults: public class Test{ public int ID { get; set; } public int IntDef { get; set; } public bool BoolDef { get; set; } public DateTime? DateDef { get; set; }} (Note that the DateTime is nullable) The mapping: modelBuilder.Entity<Test>().HasKey(a => a.ID);modelBuilder.Entity<Test>().Property(s => s.DateDef).HasDefaultValueSql("GETDATE()");modelBuilder.Entity<Test>().Property(s => s.IntDef).HasDefaultValueSql("1");modelBuilder.Entity<Test>().Property(s => s.BoolDef).HasDefaultValue(true);// Equivalent:// modelBuilder.Entity<Test>().Property(s => s.BoolDef).HasDefaultValueSql("1"); SQL statement that creates the table: CREATE TABLE [Tests] ( [ID] int NOT NULL IDENTITY, [BoolDef] bit NOT NULL DEFAULT 1, [DateDef] datetime2 DEFAULT (GETDATE()), [IntDef] int NOT NULL DEFAULT (1), CONSTRAINT [PK_Tests] PRIMARY KEY ([ID])); When I insert a new Test without setting any value, the insert statement is: INSERT INTO [Tests]DEFAULT VALUES;SELECT [ID], [BoolDef], [DateDef], [IntDef]FROM [Tests]WHERE @@ROWCOUNT = 1 AND [ID] = scope_identity(); You see that the three default values (and the generated identity value) are read from the database after the insert. [By the way, this is new in EF-Core. In EF6, only identity values and column values that were marked as DatabaseGeneratedOption.Computed were read from the database after insert (and update)]. This is the created Test object: ID IntDef BoolDef DateDef1 1 True 21-11-16 19:52:56 Now I insert a new Test and assign all values, but, just for fun, I use the default values for the non-nullable types: var item = new Test{ IntDef = default(int), // 0 BoolDef = default(bool), // false DateDef = default(DateTime), // 01-01-01 0:00:00}; Here's the SQL statement: exec sp_executesql N'SET NOCOUNT ON;INSERT INTO [Tests] ([DateDef])VALUES (@p0);SELECT [ID], [BoolDef], [IntDef]FROM [Tests]WHERE @@ROWCOUNT = 1 AND [ID] = scope_identity();',N'@p0 datetime2(7)',@p0='0001-01-01 00:00:00' Of course, EF has no way to infer that the default values were assigned deliberately. So as you see, only for the nullable DateTime column the assigned value is inserted, not for the non-nullable columns. Now the value for DateDef isn't read from the database after the insert. The entity values are: ID IntDef BoolDef DateDef1 1 True 01-01-01 0:00:00 Not what one would expect after saving the entity --not at all! Which means: When you configure a property with a default value in EF-Core, and this default is different than the .Net default value, you can't insert an entity with default values for the .Net type (like false for a boolean). I think this is a serious bug, maybe it even disqualifies the new EF-Core behaviour concerning defaults. Addition As said in Ivan's comment, you can stop EF from setting default values for you by adding ValueGeneratedNever() , for example: modelBuilder.Entity<Test>().Property(s => s.IntDef) .HasDefaultValueSql("1").ValueGeneratedNever(); Now the value will be saved as it is and EF won't read it back after inserts and updates. All in all, I think defining defaults for non-nullable properties isn't useful. Tested with EF Core 1.1.0 preview.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40619320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73332
stackexchange
llm_judgeable_groundtruth_similarity
12597176
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 strange problem in my online test management system. Some users in the test form (test.php) need long time to answer the question and submit the form. After submitting the form the session is expired and user must login again this is not a code problem I set this value in top of all pages ini_set('session.gc_maxlifetime', 18000); Is there a way to refresh the session evrey 10 minutes without reloading the page in test form to prevent session expire? Please help me Thanks Now provide the response and nothing else.
You can use javascript XHR, or as others call it, AJAX. http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.get/ Using ajax you can call a php script that refreshes your session every 10 minutes. :) This is as far as i can go to "exact". javascript var refreshSn = function (){ var time = 600000; // 10 mins setTimeout( function () { $.ajax({ url: 'refresh_session.php', cache: false, complete: function () {refreshSn();} }); }, time);};// Call in pagerefreshSn() refresh_session.php <?phpsession_start();// store session dataif (isset($_SESSION['id']))$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.?> Anyway, another solution would be to extend the session time for the test page only usingthe solution presented here How do I expire a PHP session after 30 minutes?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12597176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1689953/']}
jdg_73333
stackexchange
llm_judgeable_groundtruth_similarity
7945075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To put the question another way, if one were to try and reimplement OpenGL or DirectX (or an analogue) using GPGPU (CUDA, OpenCL), where and why would it be slower that the stock implementations on NVIDIA and AMD cards? I can see how vertex/fragment/geometry/tesselation shaders could be made nice and fast using GPGPU, but what about things like generating the list of fragments to be rendered, clipping, texture sampling and so on? I'm asking purely for academic interest. Now provide the response and nothing else.
Modern GPUs have still lots of fixed-function hardware which is hidden from the compute APIS. This includes: The blending stages, the triangle rasterization and a lot of on-chip queues. The shaders of course all map well to CUDA/OpenCL -- after all, shaders and the compute languages all use the same part of the GPU -- the general purpose shader cores. Think of those units as a bunch of very-wide SIMD CPUs (for instance, a GTX 580 has 16 cores with a 32 wide SIMD unit.) You get access to the texture units via shaders though, so there's no need to implement that in "compute". If you would, your performance would suck most likely as you don't get access to the texture caches which are optimized for spatial layout. You shouldn't underestimate the amount of work required for rasterization. This is a major problem, and if you throw all of the GPU at it you get roughly 25% of the raster hardware performance (see: High-Performance Software Rasterization on GPUs .) That includes the blending costs, which are also done by fixed-function units usually. Tesselation has also a fixed-function part which is difficult to emulate efficiently, as it amplifies the input up to 1:4096, and you surely don't want to reserve so much memory up-front. Next, you get lots of performance penalties because you don't have access to framebuffer compression, as there is again dedicated hardware for this which is "hidden" from you when you're in compute only mode. Finally, as you don't have any on-chip queues, it will be difficult to reach the same utility ratio as the "graphics pipeline" gets (for instance, it can easily buffer output from vertex shaders depending on shader load, you can't switch shaders that flexibly.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7945075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74013/']}
jdg_73334
stackexchange
llm_judgeable_groundtruth_similarity
13600924
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 insert a varchar in my table. The type in the table is a datetime so I need to convert it. I didn't think this would be to big of a problem however it keeps inserting 1900-01-01 00:00:00.000 instead of the date I want. When I do a select with my converted date it does show me the correct date. I'll show you the code: INSERT INTO Item (CategoryId, [Date], Content, CreatedOn) SELECT CategoryId, Convert(datetime, '28/11/2012', 103), Content, GetDate() FROM Item i JOIN Category c ON i.CategoryId = c.Id JOIN Division d ON d.Id = c.DivisionId WHERE Date = Convert(datetime, '31/03/2005', 103) AND d.Id = '142aaddf-5b63-4d53-a331-8eba9b0556c4' The where clause works perfectly and gives me the filtered items I need, all data is correctly inserted except for the converted date. The gives like I said 1900-... If I just do the select so: SELECT CategoryId, Convert(datetime, '28/11/2012', 103), Content, GetDate()FROM Item iJOIN Category c ON i.CategoryId = c.IdJOIN Division d ON d.Id = c.DivisionIdWHERE Date = Convert(datetime, '31/03/2005', 103) AND d.Id = '142aaddf-5b63-4d53-a331-8eba9b0556c4' I get the correct date being: 2012-11-28 00:00:00.000 . I have tried to use a different conversion like: Convert(datetime, '20121128') But that just gives the same problem. Anyone that sees what I'm doing wrong? Thx Now provide the response and nothing else.
If you must use a string-based date format, you should pick one that is safe and works in every SQL Server instance, regardless of date format, language and regional settings. That format is known as ISO-8601 format and it's either YYYYMMDD (note: **NO** dashes!) or YYYY-MM-DDTHH:MM:SSS for a DATETIME column. So instead of Convert(datetime, '28/11/2012', 103) you should use CAST('20121128' AS DATETIME) and then you should be fine. If you're on SQL Server 2008 - you could also look into using DATE (instead of DATETIME ) for cases when you only need the date (no time portion). That would be even easier than using DATETIME and having the time portion always be 00:00:00
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13600924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1696470/']}
jdg_73335
stackexchange
llm_judgeable_groundtruth_similarity
108374
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a monthly time series with an intervention and I would like to quantify the effect of this intervention on the outcome. I realize the series is rather short and the effect is not yet concluded. The Data cds <- structure(c(2580L, 2263L, 3679L, 3461L, 3645L, 3716L, 3955L, 3362L, 2637L, 2524L, 2084L, 2031L, 2256L, 2401L, 3253L, 2881L, 2555L, 2585L, 3015L, 2608L, 3676L, 5763L, 4626L, 3848L, 4523L, 4186L, 4070L, 4000L, 3498L), .Dim=c(29L, 1L), .Dimnames=list(NULL, "CD"), .Tsp=c(2012, 2014.33333333333, 12), class="ts") The methodology 1) The pre-intervention series (up until October 2013) was used with the auto.arima function. The model suggested was ARIMA(1,0,0) with non-zero mean. The ACF plot looked good. pre <- window(cds, start=c(2012, 01), end=c(2013, 09))mod.pre <- auto.arima(log(pre))# Coefficients:# ar1 intercept# 0.5821 7.9652# s.e. 0.1763 0.0810# # sigma^2 estimated as 0.02709: log likelihood=7.89# AIC=-9.77 AICc=-8.36 BIC=-6.64 2) Given the plot of the full series, the pulse response was chosen below, with T = Oct 2013, which according to cryer and chan can be fit as follows with the arimax function: mod.arimax <- arimax(log(cds), order=c(1, 0, 0), seasonal=list(order=c(0, 0, 0), frequency=12), include.mean=TRUE, xtransf=data.frame(Oct13=1 * (seq(cds) == 22)), transfer=list(c(1, 1)))mod.arimax# Series: log(cds) # ARIMA(1,0,0) with non-zero mean # # Coefficients:# ar1 intercept Oct13-AR1 Oct13-MA0 Oct13-MA1# 0.7619 8.0345 -0.4429 0.4261 0.3567# s.e. 0.1206 0.1090 0.3993 0.1340 0.1557# # sigma^2 estimated as 0.02289: log likelihood=12.71# AIC=-15.42 AICc=-11.61 BIC=-7.22 The residuals from this appeared OK: The plot of fitted and actuals: plot(fitted(mod.arimax), col="red", type="b")lines(window(log(cds), start=c(2012, 02)), type="b") The Questions 1) Is this methodology correct for intervention analysis? 2) Can I look at estimate/SE for the components of the transfer function and say that the effect of the intervention was significant? 3) How can one visualize the transfer function effect (plot it?) 4) Is there a way to estimate how much the intervention increased the output after 'x' months? I guess for this (and maybe #3) I am asking how to work with an equation of the model - if this were simple linear regression with dummy variables (for example) I could run scenarios with and without the intervention and measure the impact - but I am just unsure how to work this this type of model. ADD Per request, here are the residuals from the two parametrizations. First from the fit: fit <- arimax(log(cds), order=c(1, 0, 0), xtransf= data.frame(Oct13a=1 * (seq_along(cds) == 22), Oct13b=1 * (seq_along(cds) == 22)), transfer=list(c(0, 0), c(1, 0)))plot(resid(fit), type="b") Then, from this fit mod.arimax <- arimax(log(cds), order=c(1, 0, 0), seasonal=list(order=c(0, 0, 0), frequency=12), include.mean=TRUE, xtransf=data.frame(Oct13=1 * (seq(cds) == 22)), transfer=list(c(1, 1))) mod.arimaxplot(resid(mod.arimax), type="b") Now provide the response and nothing else.
An AR(1) model with the intervention defined in the equation given in the question can be fitted as shown below. Notice how the argument transfer is defined; you also need one indicator variable in xtransf for each one of the interventions (the pulse and the transitory change): require(TSA)cds <- structure(c(2580L, 2263L, 3679L, 3461L, 3645L, 3716L, 3955L, 3362L, 2637L, 2524L, 2084L, 2031L, 2256L, 2401L, 3253L, 2881L, 2555L, 2585L, 3015L, 2608L, 3676L, 5763L, 4626L, 3848L, 4523L, 4186L, 4070L, 4000L, 3498L), .Dim = c(29L, 1L), .Dimnames = list(NULL, "CD"), .Tsp = c(2012, 2014.33333333333, 12), class = "ts")fit <- arimax(log(cds), order = c(1, 0, 0), xtransf = data.frame(Oct13a = 1 * (seq_along(cds) == 22), Oct13b = 1 * (seq_along(cds) == 22)), transfer = list(c(0, 0), c(1, 0)))fit# Coefficients:# ar1 intercept Oct13a-MA0 Oct13b-AR1 Oct13b-MA0# 0.5599 7.9643 0.1251 0.9231 0.4332# s.e. 0.1563 0.0684 0.1911 0.1146 0.2168# sigma^2 estimated as 0.02131: log likelihood = 14.47, aic = -18.94 You can test the significance of each intervention by looking at the t-statistic of the coefficients $\omega_0$ and $\omega_1$. For convenience, you can use the function coeftest . require(lmtest)coeftest(fit)# Estimate Std. Error z value Pr(>|z|) # ar1 0.559855 0.156334 3.5811 0.0003421 ***# intercept 7.964324 0.068369 116.4896 < 2.2e-16 ***# Oct13a-MA0 0.125059 0.191067 0.6545 0.5127720 # Oct13b-AR1 0.923112 0.114581 8.0564 7.858e-16 ***# Oct13b-MA0 0.433213 0.216835 1.9979 0.0457281 * # ---# Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1 In this case the pulse is not significant at the $5\%$ significance level. Its effect may be already captured by the transitory change. The intervention effect can be quantified as follows: intv.effect <- 1 * (seq_along(cds) == 22)intv.effect <- ts( intv.effect * 0.1251 + filter(intv.effect, filter = 0.9231, method = "rec", sides = 1) * 0.4332)intv.effect <- exp(intv.effect)tsp(intv.effect) <- tsp(cds) You can plot the effect of the intervention as follows: plot(100 * (intv.effect - 1), type = "h", main = "Total intervention effect") The effect is relatively persistent because $\omega_2$ is close to $1$ (if $\omega_2$ were equal to $1$ we would observe a permanent level shift). Numerically, these are the estimated increases quantified at each time point caused by the the intervention in October 2013: window(100 * (intv.effect - 1), start = c(2013, 10))# Jan Feb Mar Apr May Jun Jul Aug Sep Oct# 2013 74.76989# 2014 40.60004 36.96366 33.69046 30.73844 28.07132 # Nov Dec# 2013 49.16560 44.64838 The intervention increases the value of the observed variable in October 2013 by around a $75\%$. In subsequent periods the effect remains but with a decreasing weight. We could also create the interventions by hand and pass them to stats::arima as external regressors. The interventions are a pulse plus a transitory change with parameter $0.9231$ and can be built as follows. xreg <- cbind( I1 = 1 * (seq_along(cds) == 22), I2 = filter(1 * (seq_along(cds) == 22), filter = 0.9231, method = "rec", sides = 1))arima(log(cds), order = c(1, 0, 0), xreg = xreg)# Coefficients:# ar1 intercept I1 I2# 0.5598 7.9643 0.1251 0.4332# s.e. 0.1562 0.0671 0.1563 0.1620# sigma^2 estimated as 0.02131: log likelihood = 14.47, aic = -20.94 The same estimates of the coefficients as above are obtained. Here we fixed $\omega_2$ to $0.9231$. The matrix xreg is the kind of dummy variable that you may need to try different scenarios. You could also set different values for $\omega_2$ and compare its effect. These interventions are equivalent to an additive outlier (AO) and a transitory change (TC) defined in the package tsoutliers . You can use this package to detect these effects as shown in the answer by @forecaster or to build the regressors used before. For example, in this case: require(tsoutliers)mo <- outliers(c("AO", "TC"), c(22, 22))oe <- outliers.effects(mo, length(cds), delta = 0.9231)arima(log(cds), order = c(1, 0, 0), xreg = oe)# Coefficients:# ar1 intercept AO22 TC22# 0.5598 7.9643 0.1251 0.4332# s.e. 0.1562 0.0671 0.1563 0.1620# sigma^2 estimated as 0.02131: log likelihood=14.47# AIC=-20.94 AICc=-18.33 BIC=-14.1 Edit 1 I've seen that the equation that you gave can be rewritten as: $$\frac{(\omega_0 + \omega_1) - \omega_0 \omega_2 B}{1 - \omega_2 B} P_t$$ and it can be specified as you did using transfer=list(c(1, 1)) . As shown below, this parameterization leads, in this case, to parameter estimates that involve a different effect compared to the previous parameterization. It reminds me the effect of an innovational outlier rather than a pulse plus a transitory change. fit2 <- arimax(log(cds), order=c(1, 0, 0), include.mean = TRUE, xtransf=data.frame(Oct13 = 1 * (seq(cds) == 22)), transfer = list(c(1, 1)))fit2# ARIMA(1,0,0) with non-zero mean # Coefficients:# ar1 intercept Oct13-AR1 Oct13-MA0 Oct13-MA1# 0.7619 8.0345 -0.4429 0.4261 0.3567# s.e. 0.1206 0.1090 0.3993 0.1340 0.1557# sigma^2 estimated as 0.02289: log likelihood=12.71# AIC=-15.42 AICc=-11.61 BIC=-7.22 I'm not very familiar with the notation of package TSA but I think that the effect of the intervention can now be quantified as follows: intv.effect <- 1 * (seq_along(cds) == 22)intv.effect <- ts(intv.effect * 0.4261 + filter(intv.effect, filter = -0.4429, method = "rec", sides = 1) * 0.3567)tsp(intv.effect) <- tsp(cds)window(100 * (exp(intv.effect) - 1), start = c(2013, 10))# Jan Feb Mar Apr May Jun Jul Aug# 2014 -3.0514633 1.3820052 -0.6060551 0.2696013 -0.1191747 # Sep Oct Nov Dec# 2013 118.7588947 -14.6135216 7.2476455plot(100 * (exp(intv.effect) - 1), type = "h", main = "Intervention effect (parameterization 2)") The effect can be described now as a sharp increase in October 2013 followed by a decrease in the opposite direction; then the effect of the intervention vanishes quickly alternating positive and negative effects of decaying weight. This effect is somewhat peculiar but may be possible in real data. At this point I would look at the context of your data and the events that may have affected the data. For example, has there been a policy change, marketing campaign, discovery,... that may explain the intervention in October 2013. If so, is it more sensible that this event has an effect on the data as described before or as we found with the initial parameterization? According to the AIC, the initial model would be preferred because it is lower ($-18.94$ against $-15.42$). The plot of the original series does not suggest a clear match with the sharp changes involved in the measurement of the second intervention variable. Without knowing the context of the data, I would say that an AR(1) model with a transitory change with parameter $0.9$ would be appropriate to model the data and measure the intervention. Edit 2 The value of $\omega_2$ determines how fast the effect of the intervention decays to zero, so that's the key parameter in the model. We can inspect this by fitting the model for a range of values of $\omega_2$. Below, the AIC is stored for each of these models. omegas <- seq(0.5, 1, by = 0.01)aics <- rep(NA, length(omegas))for (i in seq(along = omegas)) { tc <- filter(1 * (seq_along(cds) == 22), filter = omegas[i], method = "rec", sides = 1) tc <- ts(tc, start = start(cds), frequency = frequency(cds)) fit <- arima(log(cds), order = c(1, 0, 0), xreg = tc) aics[i] <- AIC(fit)}omegas[which.min(aics)]# [1] 0.88plot(omegas, aics, main = "AIC for different values of the TC parameter") The lowest AIC is found for $\omega_2 = 0.88$ (in agreement with the value estimated before). This parameter involves a relatively persistent but transitory effect. We can conclude that the effect is temporary since with values higher than $0.9$ the AIC increases (remember that in the limit, $\omega_2=1$, the intervention becomes a permanent level shift). The intervention should be included in the forecasts. Obtaining forecasts for periods that have already been observed is a helpful exercise to assess the performance of the forecasts. The code below assumes that the series ends in October 2013. Forecasts are then obtained including the intervention with parameter $\omega_2=0.9$. First we fit the AR(1) model with the intervention as a regressor (with parameter $\omega_2=0.9$): tc <- filter(1 * (seq.int(length(cds) + 12) == 22), filter = 0.9, method = "rec", sides = 1)tc <- ts(tc, start = start(cds), frequency = frequency(cds))fit <- arima(window(log(cds), end = c(2013, 10)), order = c(1, 0, 0), xreg = window(tc, end = c(2013, 10))) The forecasts can be obtained and displayed as follows: p <- predict(fit, n.ahead = 19, newxreg = window(tc, start = c(2013, 11)))plot(cbind(window(cds, end = c(2013, 10)), exp(p$pred)), plot.type = "single", ylab = "", type = "n")lines(window(cds, end = c(2013, 10)), type = "b")lines(window(cds, start = c(2013, 10)), col = "gray", lty = 2, type = "b")lines(exp(p$pred), type = "b", col = "blue")legend("topleft", legend = c("observed before the intervention", "observed after the intervention", "forecasts"), lty = rep(1, 3), col = c("black", "gray", "blue"), bty = "n") The first forecasts match relatively well the observed values (gray dotted line). The remaining forecasts show how the series will continue the path to the original mean. The confidence intervals are nonetheless large, reflecting the uncertainty. We should therefore be cautions and revise the model as new data are recorded. $95\%$ confidence intervals can be added to the previous plot as follows: lines(exp(p$pred + 1.96 * p$se), lty = 2, col = "red")lines(exp(p$pred - 1.96 * p$se), lty = 2, col = "red")
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/108374', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2040/']}
jdg_73336
stackexchange
llm_judgeable_groundtruth_similarity
47588820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created an app on https://apps.dev.microsoft.com with the following Application Permissions: Calendars.Read (Admin Only) Calendars.ReadWrite (Admin Only) User.Read.All (Admin Only) The following is the only flow that has worked for me to be able to subscribe to notifications of another user, on another tenant, as described here Admin Consent Admin consent was then successfully granted via this URL https://login.microsoftonline.com/common/adminconsent?client_id=bbb35336-faee-4c10-84b4-34136634db41&state=1234&redirect_uri=https%3A%2F%2Fdashmeetings.com%2Fmicrosoft%2Foauth Get access token An access token was then obtained from POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token with headers Content-Type=application/x-www-form-urlencoded with {tenant} the value of tenant returned in the callback url, and body with key-value pairs grant_type=client_credentialsclient_id=bbb35336-faee-4c10-84b4-34136634db41client_secret=xxxscope=https://graph.microsoft.com/.default This returns an access token, but not a refresh token. I think this might be because offline_access isn't requested. How can I get a refresh token? Now provide the response and nothing else.
You're partially correct, you will only receive a refresh_token if you request the offline_access scope and you are using the authorization_code grant flow. Refresh tokens are not available when using the implicit grant and are unnecessary when using the client_credentials grant. When using client_credentials there isn't a user authenticated and therefore there isn't a need to "refresh" a token since you can simply request a new token when needed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47588820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3515394/']}
jdg_73337
stackexchange
llm_judgeable_groundtruth_similarity
2343573
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 problem that I'm not even sure what to search for in order to fix. When I press the spacebar my entire page moves up (scrolls down): I don't want this to happen. My body tag is styled to overflow:hidden , if that has anything to do with it, so the page won't have any scrollbars. I'm usually pretty good at executing the preliminary troubleshooting techniques but in this case I don't even know where to start. How can I stop this behaviour? Additional information: I am using jQuery 1.4.2 Now provide the response and nothing else.
This default scrolling behavior comes from the keydown event . In order to prevent it, you must handle the keydown event and prevent the default behavior, either by returning false from the event handler or calling event.preventDefault() . As a rule of thumb, think carefully before you prevent default behavior like spacebar scrolling . I use it all the time and I get extremely annoyed when it doesn't work in a page. But if you want to eat the key... window.onkeydown = function(e) { return e.keyCode !== 32;}; According to the MDN web docs for KeyboardEvent#keyCode , keyCode is a deprecated property. Although it still works in most browsers, you are encouraged to use KeyboardEvent#key going forward, which is a more standardized string representation of a key. The key value for spacebar is literally the input value: " " (single space string). So if you wanted to be very careful to support all browsers, you could write: window.onkeydown = function(e) { return ev.keyCode !== 32 && ev.key !== " ";}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2343573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281488/']}
jdg_73338
stackexchange
llm_judgeable_groundtruth_similarity
284344
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Several times I've seen people use title-case or even all lower-case naming for enum constants, for example: enum Color { red, yellow, green;} This makes working with their string form simple and easy, if you want to do throw new IllegalStateException("Light should not be " + color + ".") , for example. This seems more acceptable if the enum is private , but I still don't like it. I know I can make an enum constructor with a String field, and then override toString to return that name, like this: enum Color { RED("red"), YELLOW("yellow"), GREEN("green"); private final String name; private Color(String name) { this.name = name } @Override public String toString() { return name; }} But look how much longer that is. It's annoying to keep doing if you have a bunch small enums you want to keep simple. Is it okay to just use unconventional case formats here? Now provide the response and nothing else.
The short answer is, of course, whether you want to break with naming conventions for what are essentially constants... Quoting from the JLS : Constant Names The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. The long answer, with regards to use of toString() , is that's definitely the method to override if you want a more readable representation of the enum values. Quoting from Object.toString() (emphasis mine): Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object . The result should be a concise but informative representation that is easy for a person to read . It is recommended that all subclasses override this method. Now, I'm not sure why some of the answers drifted to talking about converting enums to-and-fro with String values, but I'll just give my take here as well. Such serialization of enum values can easily be taken care of by using either the name() or ordinal() methods. Both are final and thus you can be sure of the returned values so long as the names or positioning of the values do not change . To me, that's a clear-enough marker. What I gather from the above is: today, you might want to describe YELLOW as simply "yellow". Tomorrow, you might want to describe it as "Pantone Minion Yellow" . These descriptions should be returned from calling toString() , and I wouldn't expect either name() or ordinal() to change. If I do, that's something I need to resolve within my codebase or my team, and becomes a greater question than just an enum naming style . In conclusion, if all you intend to do is to log a more readable representation of your enum values, I'll still suggest sticking to conventions and then overriding toString() . If you also intend to serialize them into a data file, or to other non-Java destinations, you still have the name() and ordinal() methods to back you up, so there's no need to fret over overriding toString() .
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/284344', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/110560/']}
jdg_73339
stackexchange
llm_judgeable_groundtruth_similarity
71783382
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 change page title dynamically depending on web pages route, I have task to create and then import title component into the layout file but when I'm trying to do it nothing changes. const Title = ({ data }) => { function renderPageTitle(children) { let title = children.props.locale === 'ka' ? 'SHOPSHOP - αƒžαƒ˜αƒ αƒ•αƒ”αƒšαƒ˜ αƒαƒœαƒšαƒαƒ˜αƒœ αƒ¨αƒαƒžαƒ˜αƒœαƒ’ αƒ›αƒαƒšαƒ˜' : 'SHOPSHOP - The First Online Shopping Mall'; try { if (document?.URL?.includes('shop/')) { title = children?.props?.page?.blocks[0]?.shop?.title ? `${children?.props?.page?.blocks[0]?.shop?.title} | ${title}` : title; } else if (document?.URL?.includes('category')) { title = children?.props?.page?.blocks[1]?.content.title ? `${children?.props?.page?.blocks[1]?.content.title} | ${title}` : title; } else if (document?.URL?.includes('products')) { title = Object.values(children?.props?.page?.blocks[0]?.products)[0].name ? `${Object.values(children?.props?.page?.blocks[0]?.products)[0].name} | ${title}` : title; } else if (children?.props?.page?.title) { title = children?.props?.page?.title ? `${children?.props?.page?.title} | ${title}` : title; } else { return title; } } catch (error) { sendErrorLogs(error); } finally { return title; } } return <title>{renderPageTitle(data)}</title>;}; And then <Head> <Title data={children} /></Head> Now provide the response and nothing else.
This was introduced in the "zip" proposal P2321 originally described in "A Plan for C++23 Ranges" P2214 . P2321 swap for const tuple and const pair. Once tuples of references aremade const-assignable, the default std::swap can be called for consttuples of references. However, that triple-move swap does the wrongthing: int i = 1, j = 2;const auto t1 = std::tie(i), t2 = std::tie(j);// If std::swap(t1, t2); called the default triple-move std::swap then// this would doauto tmp = std::move(t1);t1 = std::move(t2);t2 = std::move(tmp);// i == 2, j == 2 This paper therefore proposes adding overloads of swap for consttuples and pairs to correctly perform element-wise swap. P2214 explains why const assignability is needed for the implementation of zip . It stems from assignment operators not being ref qualified.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/71783382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18090746/']}
jdg_73340