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
231759
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 was wondering what are some techniques to locate which code implemented a specific feature, on a desktop application. I am a junior developer, with only professional programming experience lying around web programming. In the Web it is easier to do that. For example, you "inspect" a button with the browser tools, and you can see what is being done when you click it. And then, presuming you have the full source code, you can drill down the hierarchy of the calls. But how do you do this in desktop applications? At least, without having to dive into the full codebase? Now provide the response and nothing else.
Back Tracing Back tracing is locating an endpoint to an event associated with the feature (see below). Once there, a breakpoint is placed in the debugger. The feature is triggered and when the debugger stops. The call stack is reviewed to back trace the calling path. While walking up the call stack you can take notes on variable states, or place new breakpoints to inspect the event again. The feature is trigger again and the debugger stops at the new breakpoints. You can then repeat back tracing or perform forward tracing until the goal is found. Pros & Cons It's always easier to walk up the call stack and see how you got somewhere. There could be millions of conditions that need to be true before reaching an endpoint. If you know the endpoint already you've saved yourself lots of work. If the feature is broken. You may never reach the endpoint, and time can be wasted trying to figure out why. Endpoint Discovery To debug a feature you have to know where in the source code the final goal is achieved. Only from this point can you backtrace to see how the code got there. An example; To understand how undo is performed. You know where in the code things are undone, but you don't know how things get there . This would be a candidate for backtracing to figure out how the feature works. Forward Tracing Forward tracing is locating a start point for an event associated with a feature (see below). Once there, logging messages are inserted into the source code or breakpoints are set. This process is repeated as you progress further away from the start point until you discover the goal for the feature. Pros & Cons It's the easiest starting point for finding a feature. Code complexity reduces the effectiveness of forward tracing. The more conditions there are in the code the greater the chance you'll go in the wrong direction. Forward tracing often results in setting breakpoints that will be triggered by unrelated events. Interrupting the debugging process and interfering with your search. Start Point Discovery You can use keywords, user interface identifiers (button IDs, window names) or easy to find event listeners associated with the feature. For example, you might start with the button used to trigger an undo feature. Process Of Elimination You can think of this as the middle point compared to start point and end point positions. You perform a process of elimination when you already know a piece of code is used in a feature, but it is neither the start or end of the feature. The direction you take from the middle point depends upon the number of entries and exits. If the code chunk is used in many places, then back tracing from this position could be very time consuming as they all have to be inspected. You then employ a process of elimination to reduce this list. Alternative, you can perform a forward trace from this point, but again if the code chunk branches out to many places this can also be a problem. You have to reduce position directions by not following paths that clearly wouldn't be executed for the feature. Moving past this code and only placing breakpoints where it's likely related to the feature. Middle point debugging often requires more advance IDE features. The ability to see code hierarchy and dependencies. Without those tools it's difficult to do. Pros & Cons Middle points are often the first peice of code that pops into your head when you think of the feature. You say to yourself "Ah, that has to use XXXX to work." Middle points can reveal start points the easiest. Middle points can be an easy way to pick up the trail to a feature when lost by synchronization or threading changes. Middle points can take you to code you are not familiar with. Costing you time to learn what is going on.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/231759', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/12443/']}
jdg_71141
stackexchange
llm_judgeable_groundtruth_similarity
15415446
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Has anyone used tablefunc to pivot on multiple variables as opposed to only using row name ? The documentation notes : The "extra" columns are expected to be the same for all rows with the same row_name value. I'm not sure how to do this without combining the columns that I want to pivot on (which I highly doubt will give me the speed I need). One possible way to do this would be to make the entity numeric and add it to the localt as milliseconds, but this seems like a shaky way to proceed. I've edited the data used in a response to this question: PostgreSQL Crosstab Query . CREATE TEMP TABLE t4 ( timeof timestamp ,entity character ,status integer ,ct integer); INSERT INTO t4 VALUES ('2012-01-01', 'a', 1, 1) ,('2012-01-01', 'a', 0, 2) ,('2012-01-02', 'b', 1, 3) ,('2012-01-02', 'c', 0, 4); SELECT * FROM crosstab( 'SELECT timeof, entity, status, ct FROM t4 ORDER BY 1,2,3' ,$$VALUES (1::text), (0::text)$$) AS ct ("Section" timestamp, "Attribute" character, "1" int, "0" int); Returns: Section | Attribute | 1 | 0---------------------------+-----------+---+--- 2012-01-01 00:00:00 | a | 1 | 2 2012-01-02 00:00:00 | b | 3 | 4 So as the documentation states, the extra column aka 'Attribute' is assumed to be the same for each row name aka 'Section'. Thus, it reports b for the second row even though 'entity' also has a 'c' value for that 'timeof' value. Desired Output: Section | Attribute | 1 | 0--------------------------+-----------+---+---2012-01-01 00:00:00 | a | 1 | 22012-01-02 00:00:00 | b | 3 | 2012-01-02 00:00:00 | c | | 4 Any thoughts or references? A little more background: I potentially need to do this for billions of rows and I'm testing out storing this data in long and wide formats and seeing if I can use tablefunc to go from long to wide format more efficiently than with regular aggregate functions. I'll have about 100 measurements made every minute for around 300 entities. Often, we will need to compare the different measurements made for a given second for a given entity, so we will need to go to wide format very often. Also, the measurements made on a particular entity are highly variable. EDIT: I found a resource on this: http://www.postgresonline.com/journal/categories/24-tablefunc . Now provide the response and nothing else.
The problem with your query is that b and c share the same timestamp 2012-01-02 00:00:00 , and you have the timestamp column timeof first in your query, so - even though you added bold emphasis - b and c are just extra columns that fall in the same group 2012-01-02 00:00:00 . Only the first ( b ) is returned since (quoting the manual) : The row_name column must be first. The category and value columns must be the last two columns, in that order. Any columns between row_name and category are treated as "extra". The "extra" columns are expected to be the same for all rows with the same row_name value. Bold emphasis mine. Just revert the order of the first two columns to make entity the row name and it works as desired: SELECT * FROM crosstab( 'SELECT entity, timeof, status, ct FROM t4 ORDER BY 1' ,'VALUES (1), (0)') AS ct ( "Attribute" character ,"Section" timestamp ,"status_1" int ,"status_0" int); entity must be unique, of course. Reiterate row_name first (optional) extra columns next category (as defined by the second parameter) and value last . Extra columns are filled from the first row from each row_name partition. Values from other rows are ignored, there is only one column per row_name to fill. Typically those would be the same for every row of one row_name , but that's up to you. For the different setup in your answer : SELECT localt, entity , msrmnt01, msrmnt02, msrmnt03, msrmnt04, msrmnt05 -- , more?FROM crosstab( 'SELECT dense_rank() OVER (ORDER BY localt, entity)::int AS row_name , localt, entity -- additional columns , msrmnt, val FROM test -- WHERE ??? -- instead of LIMIT at the end ORDER BY localt, entity, msrmnt -- LIMIT ???' -- instead of LIMIT at the end , $$SELECT generate_series(1,5)$$) -- more? AS ct (row_name int, localt timestamp, entity int , msrmnt01 float8, msrmnt02 float8, msrmnt03 float8, msrmnt04 float8, msrmnt05 float8 -- , more? )LIMIT 1000 -- ??!! No wonder the queries in your test perform terribly. Your test setup has 14M rows and you process all of them before throwing most of it away with LIMIT 1000 . For a reduced result set add WHERE conditions or a LIMIT to the source query! Plus, the array you work with is needlessly expensive on top of it. I generate a surrogate row name with dense_rank() instead. db<>fiddle here - with a simpler test setup and fewer rows.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15415446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1601562/']}
jdg_71142
stackexchange
llm_judgeable_groundtruth_similarity
2074032
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: For some function $f \in C(R)$ the following equality holds: $f(x) + f(y) = f(\sqrt{x^2 + y^2})$ for any $x, \ y \in R$. Prove that $f(x) = ax^2 \ \forall x\in \mathbb{R}$, where $a = f(1)$. Now provide the response and nothing else.
The crux of this proof is to show that $f$ agrees on $\mathbb{Q}$ with $ax^2$. Inductively applying the functional equation, we have ($n \in \mathbb{N}$)$$ \underbrace{f(1) + \dots + f(1)}_{n^2 \text{ times}} = n^2 f(1) = f(\sqrt{n^2}) = f(n)$$ Hence $f(n) = an^2$ at every positive integer $n$. Observe that $f$ is symmetric about the origin since$$ f(-x) + f(x) = f(\sqrt{x^2 + x^2}) = f(x) + f(x) \implies f(-x) = f(x)$$Hence $f(n) = an^2$ on $\mathbb{Z}$. If $p/q$ is a rational number (without loss of generality let $p,q > 0$), we have$$ p^2 f(1/q) = \sum_{r=0}^{p^2-1} f(1/q) = f(\sqrt{p^2/q^2}) = f(p/q)$$set $p = q$, then $q^2 f(1/q) = f(1)$. Hence $f(x) = ax^2$ on $\mathbb{Q}$. Since continuous functions agreeing on a dense subset of $\mathbb{R}$ must be the same, $f(x) = ax^2$ everywhere. A bit rough on the details but I think you can work it out yourself.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2074032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/376675/']}
jdg_71143
stackexchange
llm_judgeable_groundtruth_similarity
15501030
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i have this: <?php if ( ($cart->count_product) > 0) { print $cart->count_product; } else { print ''; } ?> and i need to put print $cart->count_product inside of <div class="my_class"></div> I tried different ways, but i'm missing something in syntax. I'll be glad if someone could help. Now provide the response and nothing else.
You can do the following: echo '<div class="my_class">';echo ($cart->count_product > 0) ? $cart->count_product : '';echo '</div>'; If you want to have it inside your statement, do this: if($cart->count_product > 0) { echo '<div class="my_class">'.$cart->count_product.'</div>';} You don't need the else statement, since you're only going to output the above when it's truthy anyway.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15501030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650803/']}
jdg_71144
stackexchange
llm_judgeable_groundtruth_similarity
32425836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After updating my app to beta7 I'm unable to run it from IIS Express using either view in browser or running it in the debugger it shows this exception in the browser but doesn't break on any exception in my code using the debugger: [Exception: Unexpected application failure. Status code '-2147024894'.] System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +361 [HttpException (0x80004005): Unexpected application failure. Status code '-2147024894'.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +579 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +120 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +712 I am able to run it using dnx web from the command line with no errors.I tried with a new web app using the vs template and that one runs fine in IIS Express so it must be something specific about my app but I have no idea what since it doesn't break on any error in my code when running in the debugger. Anyone have any idea what could be causing this or what kind of thing to check in my app or configuration to solve it? Note that dnvm list shows my default runtime as beta7 coreclr x64 which is also what I have set as the specific runtime in the web app properties and in global.json Now provide the response and nothing else.
To understand the "display class" you have to understand closures. The lambda you pass here is a closure , a special type of method that magically drags in state from the scope of the method it's in and "closes around" it. ...except of course that there's no such thing as magic. All that state has to actually live somewhere real, somewhere that's associated with the closure method and readily available from it. And what do you call the programming pattern where you associate state directly with one or more methods? That's right: classes. The compiler transforms the lambda into a closure class, then instantiates the class inside the hosting method so the hosting method can access the state in the class. The only way to not have this happen is to not use closures. If this is really impacting performance, use an old-school FOR loop instead of a LINQ expression.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32425836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1922568/']}
jdg_71145
stackexchange
llm_judgeable_groundtruth_similarity
24570360
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 Java is always pass-by-value, but I do not understand why this works: public static void swap(int[] arr, int i, int j){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;}public static void main(String[] args){ int[] arr = {3, 4, 5, 6}; swap(arr, 1, 3); // arr becomes {3, 6, 5, 4}} And this does not work: public static void swap(int[] arr, int[] arr2){ int[] tmp = arr; arr = arr2; arr2 = tmp;}public static void main(String[] args){ int[] arr = {3, 4, 5, 6}; int[] arr2 = {1, 2, 5, 6}; swap(arr, arr2);} Why? Now provide the response and nothing else.
In the second method, you are trying to swap references, which will not work because the references themselves are pass-by-value. The first method works correctly because it changes the object referenced by the array (which is mutable), it does not change the reference itself. Check out this blog post for more details on the differences between pass-by-value and pass-by-reference.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24570360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2861916/']}
jdg_71146
stackexchange
llm_judgeable_groundtruth_similarity
39345995
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 written the following code: class FigureOut: def setName(self, name): fullname = name.split() self.first_name = fullname[0] self.last_name = fullname[1] def getName(self): return self.first_name, self.last_namef = FigureOut()f.setName("Allen Solly")name = f.getName()print (name) I get the following Output: ('Allen', 'Solly') Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function? Is the whole process same as converting the multiple values to a list explicitly and then returning the list, for example in Java, as one can return only one object from a function in Java? Now provide the response and nothing else.
Since the return statement in getName specifies multiple elements : def getName(self): return self.first_name, self.last_name Python will return a container object that basically contains them. In this case, returning a comma separated set of elements creates a tuple . Multiple values can only be returned inside containers . Let's use a simpler function that returns multiple values: def foo(a, b): return a, b You can look at the byte code generated by using dis.dis , a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this: >>> import dis>>> def foo(a, b):... return a,b >>> dis.dis(foo) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BUILD_TUPLE 2 9 RETURN_VALUE As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present. You could alternatively specify another return type, for example a list, by using [] . For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent: >>> def foo_list(a, b):... return [a, b]>>> dis.dis(foo_list) 2 0 LOAD_FAST 0 (a) 3 LOAD_FAST 1 (b) 6 BUILD_LIST 2 9 RETURN_VALUE The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs. To summarize, one actual object is returned . If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly: >>> first_name, last_name = f.getName()>>> print (first_name, last_name) As an aside to all this, your Java ways are leaking into Python :-) Don't use getters when writing classes in Python, use properties . Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39345995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6354622/']}
jdg_71147
stackexchange
llm_judgeable_groundtruth_similarity
354796
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: Does this weighted sum of reciprocals of Fermat numbers, $$F=\sum_{k=0}^{\infty}\dfrac{2^{k}}{2^{2^{k}}+1}$$ have a nice closed form? Wolfram says it's $1$. Thanks. Now provide the response and nothing else.
Hint: Try to guess and prove a formula for partial sums$$S(n)=\sum_{k=0}^n\frac{2^k}{2^{2^k}+1}.$$Here$$S(0)=\frac13,\ S(1)=\frac{11}{15},\ S(2)=\frac{247}{255},\ldots$$See a pattern for $1-S(n)$?
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/354796', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1747/']}
jdg_71148
stackexchange
llm_judgeable_groundtruth_similarity
38436
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: How should we understand Gen 31:24 in view of the context (i.e., Laban speaks to Jacob) and an apparent Hebrew language nuance? The King James Version (“KJV”) provides a marginal note at Gen 31:24 that indicates that the text segment “either good or bad” is “from good to bad” in Hebrew. And God came to Laban the Syrian in a dream by night, and said unto him, Take heed that thou speak not to Jacob either good or bad. {either...: Heb. from good to bad} Now provide the response and nothing else.
The Hebrew phrase in question is מִטּוֹב עַד־רָע ( metov ad ra ), literally “from good to bad.” According to Gesenius on מן...עד ( min ... ad ), 1 There are used in opposition to each other—(α) מִן אֶל … from … unto (see אֶל let. a, 1); often for tam, quam, whether, or. Psa. 144:13, מִזַּן אֶל־וַן “from kind to kind,” i.e. things of every kind.—(β) מִן … עִד and מִן … וְעַד . Lev. 13:12, מֵרֹאשׁ וְעַד רַגְלָיו “from his head to his feet;” Isaiah 1:6; 1 Ki. 6:24. This phrase is often used when all things are without distinction to be included, as if from beginning to end, from extremity to extremity . Jon. 3:5, מִגְּדֹלָם וְעַד קְטַנָּם “from the highest to the lowest,” i.e. all; hence it often is tam, quam, both … and, Ex. 22:3; Deu. 29:10; 1 Sa. 30:19; and with a particle of negation , neither, nor . Gen. 14:23, אִם מִחוּט וְעַד שְׁרוֹךְ־נַעַל “neither a thread nor a shoe latchet;” Gen. 31:24 .—(γ) מִן … -ָ֫ה. Eze. 25:13, מִתֵּימָן … וּדְדָ֫נָה “from Teman … even to Dedan.” The particle of negation in the clause in question is פֶּן ( pen ) 2 which precedes the verb תְּדַבֵּר. Hence, the phrase וַיֹּאמֶר לוֹ הִשָּׁמֶר לְךָ פֶּן־תְּדַבֵּר עִם־יַעֲקֹב מִטּוֹב עַד־רָֽע would be translated as, And he said to him, “Be careful that you do not speak to Jacob either good or bad. or And he said to him, “Be careful that you speak to Jacob neither good nor bad. In summary, it is a Hebrew idiom, 3 since, as you stated in your comment, we [English-speakers] do not speak in this manner. While it can be translated verbatim into English, it would be nonsensical, hence it must be interpreted . Gesenius discusses the occurrences of this phrase and its meaning when translated into English. (Unfortunately, I do not think Gesenius really requires further clarification. Simply read what he is saying. Focus particularly on the bold-faced elements.) Footnotes 1 Gesenius, p. 483 , מִן and מִ·, number (3) 2 id. , p. 678 , פֵּן: II. פֵּן pr. subst. removing, taking away (from the root פָּנָה PI. No. 1), always in constr. פֶּן־ (followed by Makkeph) it becomes a conj. of removing, prohibiting, hindering, i.q. μή, ne, lest . 3 idiom (n.): a construction or expression of one language whose parts correspond to elements in another language but whose total structure or meaning is not matched in the same way in the second language. References Gesenius, Heinrich Friedrich Wilhelm. Gesenius’s Hebrew and Chaldee Lexicon to the Old Testament Scriptures. Trans. Tregelles, Samuel Prideaux. London: Bagster, 1860.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/38436', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/22026/']}
jdg_71149
stackexchange
llm_judgeable_groundtruth_similarity
484011
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need a help with determining if this statement is true or not. Does every infinite group has infinite cyclic subgroup? Now provide the response and nothing else.
No. Just take $\mathbb{Z}_2\oplus \mathbb{Z}_2\oplus \mathbb{Z}_2 \oplus \ldots$. Every element has finite order, so cannot generate an infinite group.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/484011', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/82756/']}
jdg_71150
stackexchange
llm_judgeable_groundtruth_similarity
332290
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 using optirun from bumblebee . It is designed to start my 2nd GPU, run the command given, and shut down the 2nd GPU at the end. A simplified example: optirun echo test | cat However there's a bug in optirun that requires that I now run a follow up command to force the GPU to shut down. Can I easily wrap some complex command such as echo test | cat in a shell script such that I can run optirun, and then follow that up at the end with command (my workaround to the bug)? The quoting and all seems to be an issue preventing me from doing this with a simple shell script. Now provide the response and nothing else.
I'm confident you're simply after $@ , the argument list to a script. Trivial example: $ cat >cc.sh <<EOF#!/bin/shhead "\$@"echo I AM DONEEOF$ chmod 755 cc.sh Works with arguments: $ ./cc.sh cc.sh #!/bin/shhead "$@"echo I AM DONEI AM DONE Works with STDIN/STDOUT $ cat cc.sh | ./cc.sh | tail -n 2echo I AM DONEI AM DONE Works with a mixture: $ cat cc.sh | ./cc.sh -n 2 | tail -n 2head "$@"I AM DONE Therefore: #!/bin/shoptirun "$@"rmmod <mod> [perhaps >/dev/null 2>&1 if you need to ignore errors from rmmod]
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/332290', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9035/']}
jdg_71151
stackexchange
llm_judgeable_groundtruth_similarity
20074015
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 HTML code looks like this: <article class="post"> <a class="thumbnail" href="#"> <img width="200" height="100" src="some.jpg" class="attachment-thumbnail"> </a> <header> <h2 class="posttitle"> <a href="#">Posttitle</a> </h2> </header></article> The image inside the first link only need to be displayed, when the link isn't visited yet. If the link is visited, I'll do a display: none; a:visited img { display: none !important; visibility: hidden !important; border: 1px solid red; * this is for testing*} http://jsfiddle.net/isherwood/rj394/2 But the image is still displayed. The testing-border is red. If I change :visited to :hover it does the display as it should (:hover and it's gone). Firebus tells me, that the image is 'display: none' but apparently it isn't... Does someone know this problem and knows a possible solution? Now provide the response and nothing else.
According with the documentation from Mozilla : For privacy reasons, browsers strictly limit the styles you can apply using an element selected by this pseudo-class: only color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, outline-color, column-rule-color, fill and stroke. Note also that the alpha component will be ignored: the alpha component of the not-visited rule is used instead (except when the opacity is 0, in that case the whole color is ignored, and the one of the not-visited rule is used. Though the color can be changed, the method getComputedStyle will lie and always give back the value of the non-visited color. So, you can't change the display value. You can see here as how is working with a different propery as border-color . You will have to use another approach as JavaScript + LocalStorage (mostly supported ). A roughly solution could be, using jQuery: $("a").on('click', function(){ var $this = $(this); localStorage.setItem($this.attr('href'), true); $this.addClass('visited');});$( document ).ready(function() { $("a").each(function(index, elem){ var item = $(elem); if (localStorage.getItem(item.attr('href'))){ item.addClass('visited'); } });}); A demo here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20074015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1860070/']}
jdg_71152
stackexchange
llm_judgeable_groundtruth_similarity
72302
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It's been a long time since I scratch built an FFT algorithm, and I feel like I should already know this, but I just can't recall and figured I might get a quick answer on here that may be useful to others. FWIW, I did see one question that was already answered that was very related, but I am hoping for clarification. Looking at Decimation in Time algorithms, bit reversal is typically shown applied to the input. For Decimation in Frequency, it is typically shown applied to the output. My questions are: What happens if no bit reversal is performed? If the natural order is important, does it matter if the bit reversal is performed at the beginning or the end? Are the DIT and DIF algorithms mathematically equivalent? I am implementing a FFT based convolution. It would seem that the bit reversal is not needed and I was hoping to figure out why. I found the figures/analysis here helpful for reference. Now provide the response and nothing else.
If you're using the FFT and iFFT to perform fast convolution , yes, you can do it in-place and you can do without bit-reversing in the sample processing, but you will have to bit-reverse the transfer function $H[k]$ . You would use the DIF for the forward FFT and the DIT for the inverse FFT. O&S have the clearest treatment, in my opinion. I am robbing some drawings from O&S. Note this DIF accepts the data input as normal order in and returns bit-reversed data in the output. Note that the butterfly has the twiddle factor multiplied in the output of the butterfly. Here is the DIT. Note that it accepts the data input in bit-reversed order and returns normal order data in the output. Also note that the butterfly exactly undoes the DIF butterfly. It multiplies first at the input to the butterfly. Now if you use the DIT as the iFFT, then you need to make sure you scale the input by $\frac1N$ (that can be done with the transfer function multiplication) and conjugate the twiddle factors $W_N^r$ . The multiplication in the frequency domain (between the FFT DIF and the iFFT DIT) must be done with the transfer function $H[k]$ pre-bitreversed. In the 1980s, I wrote a very simple DIF FFT and DIT iFFT in C code. Do you want it? I might be able to find it. Lemme know. Actually, I posted the C code here before .
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/72302', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/38168/']}
jdg_71153
stackexchange
llm_judgeable_groundtruth_similarity
2076838
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state. No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems: 1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers). 2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success). 3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1. 4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead). 5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again. 6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need. Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)). Answer and why I accepted it: So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). Now provide the response and nothing else.
This is a neat problem, and I've been thinking about it for a while (with solutions similar to Sjoerd's ), but in the end, here's what I think: Use your point 1) and stop worrying. Assuming real randomness, the probability that a random number has already been chosen before is the count of previously chosen numbers divided by the size of your pool, i.e. the maximal number. If you say you only need a billion numbers, i.e. nine digits: Treat yourself to 3 more digits, so you have 12-digit serial numbers (that's three groups of four digits – nice and readable). Even when you're close to having chosen a billion numbers previously, the probability that your new number is already taken is still only 0,1%. Do step 1 and draw again. You can still check for an "infinite" loop, say don't try more than 1000 times or so, and then fallback to adding 1 (or something else). You'll win the lottery before that fallback ever gets used.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2076838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252091/']}
jdg_71154
stackexchange
llm_judgeable_groundtruth_similarity
286944
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A recent question asks what makes degree 5 special when considering the roots of polynomials with integer coefficients etc. One answer is that the Galois Group of $S_5$ is not solvable. What I am looking for is the most straightforward example (with proof) of a polynomial with integer coefficients and Galois Group $A_5$. Such an object ought to be standard ... if I ever knew one, I have forgotten it. Now provide the response and nothing else.
I'll borrow from DonAntonio's answer the part about the discriminant of the polynomial$f=X^5+20X+16\in\mathbb Q[X]$: this is $2^{16}5^6$ and thus is a perfect square. Then $G_f$, the Galois group of $f$ over $\mathbb Q$, is contained in $A_5$. It remains to prove that $G_f=A_5$. First reduce the polynomial modulo $3$: $\overline f=X^5+2X+1\in\mathbb Z_3[X]$, and prove that $\overline f$ is irreducible. Since $G_{\overline f}$ is a subgroup of $G_f$, it follows that $G_f$ contains a $5$-cycle. Second, reduce the polynomial modulo $7$: $\hat f=X^5-X+2\in\mathbb Z_7[X]$, and note that $\hat f=(X+2)(X+3)(X^3+2X^2+5X+5)$. Furthermore, $X^3+2X^2+5X+5$ is irreducible over $\mathbb Z_7$ and for the same reason as above $G_f$ contains a $3$-cycle. In particular, the order of $G_f$ is divisible by $15$ and then $[A_5:G_f]\leq 4$. On the other side, $A_5$ can't contain a proper subgroup of index less than $5$ (this is true for every nonabelian simple group ). It follows that $G_f=A_5$. Edit. In this case the simplest way to compute the discriminant is to use the determinant formula which involves the power sums $s_i=x_1^i+\cdots+x_5^i$, where $x_i$ are the roots of $X^5+aX+b$. (This formula can be found in Jacobson, Basic Algebra I , page 258.) After some easy calculations one finds the discriminant: $2^8a^5+5^5b^4$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/286944', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2906/']}
jdg_71155
stackexchange
llm_judgeable_groundtruth_similarity
10765243
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 rewrite the following CURL command, so that it doesn't use the -F option, but still generates the exact same HTTP request? i.e. so that it passes the multipart/form-data in the body directly. curl -X POST -F example=test http://localhost:3000/test Now provide the response and nothing else.
Solved: curl \ -X POST \ -H "Content-Type: multipart/form-data; boundary=----------------------------4ebf00fbcf09" \ --data-binary @test.txt \ http://localhost:3000/test Where test.txt contains the following text, and most importantly has CRLF (\r\n) line endings : ------------------------------4ebf00fbcf09Content-Disposition: form-data; name="example"test------------------------------4ebf00fbcf09-- Notes: it is important to use --data-binary instead of plain old -d as the former preserves the line endings (which are very important). Also, note that the boundary in the body starts with an extra -- . I'm going to repeat it because it's so important, but that request-body file must have CRLF line endings. A multi-platform text editor with good line-ending support is jEdit ( how to set the line endings in jEdit ). If you're interested in how I worked this out (debugging with a Ruby on Rails app) and not just the final solution, I wrote up my debugging steps on my blog .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10765243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72176/']}
jdg_71156
stackexchange
llm_judgeable_groundtruth_similarity
4440902
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 tried this: $$ \sin{x} + \sin{3x} = \frac{8}{3\sqrt{3}} $$ $$ 2\sin{2x}\cos{x} = \frac{8}{3\sqrt{3}} $$ $$ 4\sin{x}\cos{x}\cos{x} = \frac{8}{3\sqrt{3}} $$ $$ \sin{x}(1-\sin^2{x}) = \frac{2}{3\sqrt{3}} $$ Here, I tried to set $\sin x = t$ $$ t(1-t^2) = \frac{2}{3\sqrt{3}}, $$ but I don't know to resolve this. Now provide the response and nothing else.
HINT To begin with, notice that $\sin(3x) = 3\sin(x) - 4\sin^{3}(x)$ . Hence it results that: \begin{align*}\sin(x) + \sin(3x) = \frac{8}{3\sqrt{3}} & \Longleftrightarrow 4\sin(x) - 4\sin^{3}(x) = \frac{8}{3\sqrt{3}}\\\\& \Longleftrightarrow \sin(x) - \sin^{3}(x) = \frac{2\sqrt{3}}{9}\end{align*} By inspection, one concludes that \begin{align*}\sin(x) = \frac{1}{\sqrt{3}}\end{align*} satisfies the resulting equation. From then on, you can factor the cubic equation to obtain a quadratic which is easy to deal with. Can you take it from here?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4440902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1053088/']}
jdg_71157
stackexchange
llm_judgeable_groundtruth_similarity
12900
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: My understanding is that $R^2$ cannot be negative as it is the square of R. However I ran a simple linear regression in SPSS with a single independent variable and a dependent variable. My SPSS output give me a negative value for $R^2$. If I was to calculate this by hand from R then $R^2$ would be positive. What has SPSS done to calculate this as negative? R=-.395R squared =-.156B (un-standardized)=-1261.611 Code I've used: DATASET ACTIVATE DataSet1. REGRESSION /MISSING LISTWISE /STATISTICS COEFF OUTS R ANOVA /CRITERIA=PIN(.05) POUT(.10) /NOORIGIN /DEPENDENT valueP /METHOD=ENTER ageP I get a negative value. Can anyone explain what this means? Now provide the response and nothing else.
$R^2$ compares the fit of the chosen model with that of a horizontal straight line (the null hypothesis). If the chosen model fits worse than a horizontal line, then $R^2$ is negative. Note that $R^2$ is not always the square of anything, so it can have a negative value without violating any rules of math. $R^2$ is negative only when the chosen model does not follow the trend of the data, so fits worse than a horizontal line. Example: fit data to a linear regression model constrained so that the $Y$ intercept must equal $1500$ . The model makes no sense at all given these data. It is clearly the wrong model, perhaps chosen by accident. The fit of the model (a straight line constrained to go through the point (0,1500)) is worse than the fit of a horizontal line. Thus the sum-of-squares from the model $(SS_\text{res})$ is larger than the sum-of-squares from the horizontal line $(SS_\text{tot})$ . If $R^2$ is computed as $1 - \frac{SS_\text{res}}{SS_\text{tot}}$ .(here, $SS_{res}$ = residual error.) When $SS_\text{res}$ is greater than $SS_\text{tot}$ , that equation could compute a negative value for $R^2$ , if the value of the coeficient is greater than 1. With linear regression with no constraints, $R^2$ must be positive (or zero) and equals the square of the correlation coefficient, $r$ . A negative $R^2$ is only possible with linear regression when either the intercept or the slope are constrained so that the "best-fit" line (given the constraint) fits worse than a horizontal line. With nonlinear regression, the $R^2$ can be negative whenever the best-fit model (given the chosen equation, and its constraints, if any) fits the data worse than a horizontal line. Bottom line: a negative $R^2$ is not a mathematical impossibility or the sign of a computer bug. It simply means that the chosen model (with its constraints) fits the data really poorly.
{}
{'log_upvote_score': 9, 'links': ['https://stats.stackexchange.com/questions/12900', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4498/']}
jdg_71158
stackexchange
llm_judgeable_groundtruth_similarity
69440494
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now that Python 3.10 has been released, is there any preference when indicating that a parameter or returned value might be optional, i.e., can be None . So what is preferred: Option 1: def f(parameter: Optional[int]) -> Optional[str]: Option 2: def f(parameter: int | None) -> str | None: Also, is there any preference between Type | None and None | Type ? Now provide the response and nothing else.
PEP 604 covers these topics in the specification section. The existing typing.Union and | syntax should be equivalent. int | str == typing.Union[int, str] The order of the items in the Union should not matter for equality. (int | str) == (str | int)(int | str | float) == typing.Union[str, float, int] Optional values should be equivalent to the new union syntax None | t == typing.Optional[t] As @jonrsharpe comments , Union and Optional are not deprecated, so the Union and | syntax are acceptable. Łukasz Langa , a Python core developer, replied on a YouTube live related to the Python 3.10 release that Type | None is preferred over Optional[Type] for Python 3.10+.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/69440494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3705840/']}
jdg_71159
stackexchange
llm_judgeable_groundtruth_similarity
189
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Over the course of my studies, I have switched largely from using Z-matrix representations of molecular geometries in calculations to Cartesian representations. The software that I use now makes it easy to add the sorts of constraints/restraints/transits that I would have previously used Z-matrices for, and I know that Z-matrix geometries can be problematic in large molecules * where minute changes in a bond angle or dihedral (due, for instance, to rounding errors/low-quality gradients) can result in large movements in peripheral atoms. What pros or cons exist for either geometry definition that I don't know about? What circumstances recommend one representation over another? *Or small molecules with silly Z-matrices. Now provide the response and nothing else.
Cartesian Space In Cartesian space, three variables (XYZ) are used to describe the position of a point in space, typically an atomic nucleus or a basis function. To describe the locations of two atomic nuclei, a total of 6 variables must be written down and kept track of. The general ruling is that for Cartesian space, 3N variables must be accounted for (where N is the number of points in space you wish to index). Internal Coordinates Z-matrices use a different approach. When dealing with Z-matrices, we keep track of the relative positions of points in space. Cartesian space is 'absolute' so to speak. A point located at (0,0,1) is an absolute location for a coordinate space that extends to infinity. However, consider a two atom system. The translation of the molecule through space (assuming a vacuum) will have no affect on the properties of the molecule. An H2 molecule centered around the origin (0,0,0) is no different from the same H2 molecule being centered around (1,1,1). However, say we increase the distance between the hydrogen atoms. We now have altered the molecule in such a way that the properties of that molecule has changed. What did we change? We simply changed the bond length, one variable. We increased the distance between the two atoms by some length R. With Z-matrices, we keep tabs on internal coordinates: bond length (R), bond angle (A), and torsional/dihedral angle (T/D). Using internal coordinates reduces our 3N requirement set by the Cartesian space down to a 3N-6 requirement (for non-linear molecules). For linear molecules we keep tabs on 3N-5 coordinates. When performing complex computations, the less you have to keep track of, the less expensive the computation. Symmetry Consider the following molecule, H2O. We know from experience that this molecule has C2V symmetry. The OH bond lengths should be equivalent. When using some sort of optimizing routine, you may want to specify symmetry in your system. With a Z-matrix, the process is very straightforward. You would construct your Z-matrix to define the OH(1) bond as being equivalent to the OH(2) bond. Whatever program you use should automatically recognize the constraint and will optimize your molecule accordingly giving you an answer based off a structure that is constrained to C2v symmetry. With Cartesian space this is not guaranteed. Rounding errors can cause your program to break symmetry, or your program may not be very good at guessing the point group of your molecule based on the Cartesian coordinates alone. Picking the Right One As a preface, programs like Gaussian convert your Cartesian coordinate space (or your pre-defined Z-matrix) into redundant internal coordinates before proceeding with an optimization routine unless you specify it to stick with Cartesians or your Z-matrix. I warn you that specifying your program to optimize using Cartesian coordinates makes your calculation much more expensive. I find that I will explicitly specify 'Z-matrix' when I know I'm dealing with high symmetry and when I know my Z-matrix is perfect. You will want to use Z-matrices on systems that are rather small. If dealing with systems with high symmetry, Z-matrices are almost essential. They can be rather tricky to implement and you will likely spend some time figuring out the proper form of your Z-matrix through trial-and-error. If you wish to scan a particular coordinate, Z-matrices are also very helpful as you can tell a program to scan across a bond length, angle or torsion with ease (as long as you've properly defined that coordinate in your Z-matrix). I use Cartesian coordinates for large systems, systems with very little or no symmetry, or when I'm in a hurry.
{}
{'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/189', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/84/']}
jdg_71160
stackexchange
llm_judgeable_groundtruth_similarity
2557375
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a MyWidget which contains a MySubWidget , e.g. a custom widget that contains a text field or something. I want other classes to be able to connect to signals and slots exposed by the contained MySubWidget instance. Is the conventional way to do this: Expose a pointer to the MySubWidget instance through a subWidget() method in MyWidget Duplicate the signals and slots of MySubWidget in the MyWidget class and write "forwarding" code Something else? Choice 1 seems like the least code, but it also sort of breaks encapsulation, since now other classes know what the contained widgets of MyWidget are and might become dependent on their functionality. Choice 2 seems like it keeps encapsulation, but it's a lot of seemingly redundant and potentially convoluted code that kind of messes up the elegance of the whole signals and slots system. What is normally done in this situation? Now provide the response and nothing else.
If you look at Qt's own code they prefer option 2. For example, look at QTabWidget and QTabBar . They share a number of signals and slots, yet QTabWidget hides the fact that it uses a QTabBar (well, sorta... QTabWidget::tabBar() obviously breaks this even though it's protected). Although this will result in more code, I think it's worth it for the encapsulation. Don't forget that you can connect signals to signals like so: connect(mySubWidget, SIGNAL(internalSignal(int)), this, SIGNAL(externalSignal(int))); Which will make MyWidget emit externalSignal(int) when MySubWidget emits internalSignal(int) . This helps with the signal side of things at least. I don't know of any easy way to do the same for slots, unfortunately.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2557375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39375/']}
jdg_71161
stackexchange
llm_judgeable_groundtruth_similarity
37199830
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For years we have used the following code to setup databases in a base class for our functional tests for our DAL, and this has worked extremely well for us. /// <summary>/// Initializes the test class by creating the integration database./// </summary>[TestInitialize]public virtual void TestInitialize(){ DataContext = new DataContext(ConnectionString); CleanupPreviousTestRunDatabases(); if (DataContext.Database.Exists()) { DataContext.Database.Delete(); } DataContext.Database.Create(); DataContext.Database.ExecuteSqlCommand(String.Format(Strings.CreateLoginCommand, DatabaseUserName, DatabasePassword)); DataContext.Database.ExecuteSqlCommand(String.Format("CREATE USER {0} FOR LOGIN {0}", DatabaseUserName)); DataContext.Database.ExecuteSqlCommand(String.Format("EXEC sp_addrolemember 'db_owner', '{0}'", DatabaseUserName));} However, using Entity Framework does not setup all components of a database and we would like to catch discrepancies between our EF DAL model and the actual database. We use the SSDT tools / Visual Studio Database Project for all of our database work, and I know you can write SQL unit tests, and in those SQL unit tests, I have seen the ability to setup and create a database based on the database project itself. This is what I would like to do, but from our other functional test libraries. I can reference the libraries and write some of the setup code, but what I'm looking for is: a) How do I provide which Database project to use to deploy? b) How can I specify connection string in code rather than an app.config, such as using localdb instead with a dynamically named database? namespace Product.Data.Tests{ using Microsoft.Data.Tools.Schema.Sql.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class FunctionalTest { [TestInitialize] public virtual void TestInitialize() { SqlDatabaseTestClass.TestService.DeployDatabaseProject(); SqlDatabaseTestClass.TestService.GenerateData(); } }} The app.config in a SQL Unit Test Project doesn't contain any reference back to the original Database project used to create it, and decompiling some of the test code and seeing how it works, I don't see any indication. Does it assume there is only one database project in the solution? Now provide the response and nothing else.
With some direction from the links @Ed Elliott posted, I was able to make this happen. You will need to add Microsoft.SqlServer.Dac as a assembly reference from C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\120\Microsoft.SqlServer.Dac.dll (Visual Studio 2015). It is part of the SSDT tooling, so I'm sure the path may be different for earlier versions. [TestClass]public class DatabaseTest{ protected string DatabaseConnectionString = $@"Data Source=(localdb)\v11.0; Integrated Security=True"; protected DatabaseContext DatabaseContext; protected string DatabaseName = $"UnitTestDB_{Guid.NewGuid().ToString("N").ToUpper()}"; public TestContext TestContext { get; set; } [TestInitialize] public virtual void TestInitialize() { var instance = new DacServices(DatabaseConnectionString); var path = Path.GetFullPath(Path.Combine(TestContext.TestDir, @"..\..\..\Build\Database\Database.dacpac")); using (var dacpac = DacPackage.Load(path)) { instance.Deploy(dacpac, DatabaseName); } DatabaseContext = new DatabaseContext(DatabaseConnectionString); } [TestCleanup] public virtual void TestCleanup() { DeleteDatabase(DatabaseName); }} Then how it would be used for a functional test in a unit test project. [TestClass]public class CustomerTypeTests : DatabaseTest{ private CustomerType customerType; [TestInitialize] public override void TestInitialize() { base.TestInitialize(); customerType = new CustomerType { Name = "Customer Type" }; } [TestMethod] public void AddOrUpdateCustomerType_ThrowExceptionIfNameIsNull() { ExceptionAssert.Throws<ArgumentNullException>(() => DatabaseContext.AddOrUpdateCustomerType(customerType)); }} Just a note to others, you should also setup your Build Dependencies so that your unit test project depends on the database project, ensuring it is built first and produces the correct dacpac file. What this solves for us, is this gives us a true database, not one just based on Entity Framework's model, which lacks quite a lot of SQL constructs (to be expected), especially default constraints, indexes, and other important elements of a database. At our DAL layer, this is essential for us.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37199830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52589/']}
jdg_71162
stackexchange
llm_judgeable_groundtruth_similarity
37815774
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 move the Seaborn pairplot legend outside the scatter plot matrix. The official docs don't give a keyword legend . I am trying to plot the legend outside the plot in 3 different locations simultaneously: bottom center, top center, right center I have tried this: import matplotlib.pyplot as pltimport seaborn as snsiris = sns.load_dataset("iris")g = sns.pairplot(iris,hue='species', palette='husl', markers='d', size=2.5, plot_kws= { "s":40, "alpha":1.0, 'lw':0.5, 'edgecolor':'k' })plt.legend(loc='upper center', bbox_to_anchor=(1.10, 1.0), ncol=1) #vertical legendplt.legend(loc='lower center', bbox_to_anchor=(0.0, -0.15), ncol=3) #horizontal legend bottomplt.legend(loc='upper left', bbox_to_anchor=(0.0, 1.15), ncol=3) #horizontal legend topg.savefig('Test.png', bbox_inches='tight') The output of the above code is this file: . All 3 legends are being printed incorrectly. I am not sure if it is doing the positioning that I requested. I am not sure what is happening on the right - it seems that 2 vertical legends are appearing and for some reason and they are fully overlapping each other. One of the two horizontal legends is not appearing at all. Is there a way to avoid overlapping the vertical legends and also place the legend outside the plot in 3 locations - top center, bottom center, right center? Now provide the response and nothing else.
pairplot already adds a legend outside the plot matrix and it is not clear where you want to move it. The other legends are probably being positioned as you requested even if that might be not what you actually want. plt.legend will attach a legend to the current axes and there can be only one legend per axes so in your code only the last legend is drawn. But you can attach several legends to a figure and IIUC you want to position the legends relative to the figure so figure legends seems like the best option. In order to plot figure legends you need to explicitly pass the handlers and labels. I had to use the private attribute PairPlot._legend_data for that, I did not find a way to do it using the public API. Unfortunately matplotlib won't automatically make room to acomodate these legends and they will overlap with the subplots unless you make some adjustments. I will just use subplot_adjust with some hardcoded values that work for me in this case because calculations are tricky. So this is the code that hopefully does what you want: g = sns.pairplot(iris, hue='species', palette='husl', markers='d', size=2.5, plot_kws= { "s":40, "alpha":1.0, 'lw':0.5, 'edgecolor':'k' })handles = g._legend_data.values()labels = g._legend_data.keys()g.fig.legend(handles=handles, labels=labels, loc='upper center', ncol=1)g.fig.legend(handles=handles, labels=labels, loc='lower center', ncol=3)g.fig.legend(handles=handles, labels=labels, loc='upper left', ncol=3)g.fig.subplots_adjust(top=0.92, bottom=0.08) The OP asked in a comment whether this can be found in the seaborn documentation. Of course part of this is just pure matplotlib, not specific to seaborn. But I also realized that I had to rely on a couple of undocumented features. The fact that PairGrid has a fig attribute referencing the Figure instance is not documented. Anyway that was an easy guess and I could have used fig = plt.gcf() instead. Getting the labels and handles of the legend is trickier. I learnt about the _legend_data attribute by looking at the docstring of PairGrid.add_legend , but the docstring itself is a bit hidden (it does not appear in the web) and the attribute is underscored as if it were private, so using it feels uncomfortable. I find it inconsistent that a private attribute is mentioned in the docstring of a public method, probably we should have legend_data as a public attribute, but I digress. Alternatively you could try to extract the labels and handles from the subplots. You could guess that the subplots have this information but there are no actual guaranties so this means relying on undocumented behaviour. It turns out that the non-diagonal subplots have it (but the diagonal ones don't, so if you just looked at the first subplot you would be misguided) and you can do handles, labels = fig.get_axes()[1].get_legend_handles_labels() . But as I said this is undocumented behaviour even if you are using only documented API. You could also create your own handles but it would be cumbersome, that's why I looked for shortcuts, even if undocumented.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37815774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4057186/']}
jdg_71163
stackexchange
llm_judgeable_groundtruth_similarity
427730
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 RDLC report and I am displaying it on the Report Viewer Control in my front end application. I am able to view the report perfectly. But the problem arises when I try to export the report to a PDF (using the built-in option). I print the report in 3 pages whereas my client wants it to be in a single page. I can't figure out the reason for it as in my report viewer I see only one page but in a PDF there are 3 pages. Can something be done about it so that I can control the size of the report? Now provide the response and nothing else.
The answer is pretty similar to what Dugan said, but it's not always just the margins.It is pretty simple though: When you are editing the rdlc file in design mode, firstly click on an empty part of the BODY area of your design. Hit F4 to see the properties tab. Here, you will see a "Size" property. This can be expanded for the width and height. The width you see here represents the width that the body of your report requires as printable area. Even if you have white space all over, the page knows that it needs to keep it as a printable area. It reserves the space, in some sense. As for the height, the system generally knows that it can grow or shrink as necessary, unless you have specified otherwise within your controls therein. So the width is what will, usually, play the most important role. Next, click on an empty area of the report (outside the header, body, and footer; basically the gray area around the design), then hit F4 to view the properties panel. Under the "Layout" category of the properties, you will see 3 different options:InteractiveSize,Margins,PageSize.Each of those Size attributes can be expanded to show the Width and Height. The Margins attribute can be expanded for the left/right/top/bottom. Basically, the pdf export works out of the PageSize (though I generally try to keep Interactive and Page size equal). When the pdf file is rendered via the ReportViewer's built-in export function, the width and height of each "page" within the pdf will be determined by the width and height in the report's PageSize attribute (you could override this if you used your own custom code for the pdf rendering).As for the margins, they specify how much space MUST be left blank and unprintable between the printable area reserved for your report and the edge of the page. In other words:Your report's Body's Width, Plus the Report's Left Margin, Plus the Report's Right Margin, MUST be smaller than or equal to the Report's PageSize's Width! So...if your margins are too wide, or if your report's body is too wide, or if the PageSize's width is too narrow, the rendered result is forced to be broken down to multiple pages in order to fit! For example: If my report's body has width 7.75", my Left margin is 0.5", my right margin is 0.5", and the width specified in the PageSize is 8.5", my report will always use 2 pages for each 1 page of data. The 7.75" width of the body, plus 0.5"+0.5" for the margins add up to 8.75", which is larger than the 8.5" available in my page. So the first 7.5" (or so) of each page of my report's body will be shown in the first page, and the rest will be split down to the next page. This will not be done inside the report viewer, as it allows for the report to grow beyond the page size by just adding a scrollbar, but it will be annoyingly noticeable in the pdf export.In order to make my example report fit in 1 page, I can either try and reduce the body of my report to 7.5" or less, or I can reduce the left and right margins by a total of 0.25" or more (for example, set them to 0.3" for a total reduction of 0.4"), or I can increase the PageSize to something larger than 8.75".Note: Acrobat Reader is pretty smart and knows about various paper sizes. Therefore, while arbitrary PageSizes will work, it is typically best to use real page sizes. As such, in my last example I would rather set the PageSize to have Width = 11" and Height = 8.5", which is a real letter-size in landscape! Adobe will typically understand this and print properly. Also Note: Some printers, especially older ones, have trouble printing with less than 0.3" margins. If you want to be nice to your users, you should best keep the margins large enough for those older printers ;) I hope this helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/427730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71164
stackexchange
llm_judgeable_groundtruth_similarity
5230043
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a small database pool in my web app. And this particular function: withPool pool = bracket (takeConn pool) (putConn pool) can be rewritten in applicative style: withPool = bracket <$> takeConn <*> putConn Arguably it is just as readable and much more elegant. So naturally, I want to write it like that. But database connection pool supposed to be fast, and I am afraid that this style introduces unnecessary overhead. So my question is, how much overhead (if any) does use of applicative functors incur in Haskell? Are there any benchmarks? Now provide the response and nothing else.
I really suspect they'll be compiled down to the same thing in most cases.I did a tiny test, import Control.Applicativetest1 :: (b -> b -> c) -> (a -> b) -> (a -> b) -> a -> ctest1 bracket takeConn putConn pool = bracket (takeConn pool) (putConn pool)test2 :: (b -> b -> c) -> (a -> b) -> (a -> b) -> a -> ctest2 bracket takeConn putConn = bracket <$> takeConn <*> putConn but I am constraining the type of test2 there to only functions (which isn't its most generalised type, right..?) Then I compiled with ghc -O -ddump-simpl to get some sort of intermediate output from GHC (I tried the C output, it was too ugly) and the two came out looking exactly the same, except for names. (I also tried without -O though, and they weren't the same, nor if I leave out the type annotations)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5230043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55150/']}
jdg_71165
stackexchange
llm_judgeable_groundtruth_similarity
41892470
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 module m : export = { a: 3} And then in my index.ts I want to re-export everything that m is exporting, so I use: export * from './m'; But it gives me an error: Error: TS2498:Module D:/Projects/typescript/m uses export = and cannot be used with export * . How to re-export from a module that uses export= syntax? I have no control over the module with export= syntax. Now provide the response and nothing else.
You can use import m = require("./m");export {m}; or import m = require("./m");export default m; Old style imports export = , require() aren't compatible with module exports. Refer to documentation UPDATE for JSON file importThe following works using the from syntax, once you turn on the required tsconfig option. Available since 2.9. import myObjectName from './path/to/file.json';export { myObjectName };
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41892470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2545680/']}
jdg_71166
stackexchange
llm_judgeable_groundtruth_similarity
28069389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Pressing F12 I can instantly change CSS of elements in Chrome. However, I can not input @media screen and (max-width) similar to here: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp When I press enter it simply disappears. What can I do to dynamically add and remove media queries? Now provide the response and nothing else.
When you edit the styles for a specific element in the inspector, it is as though you were editing the element's inline style attribute: you can only place property declarations such as color: red in your example. This is even reflected in the DOM visualization itself as you edit an element's styles. Media queries don't belong in inline styles, they belong in @media rules which appear only in a proper stylesheet. On Chrome, you will need to edit the inspector stylesheet directly in order to include your media queries. You can reach it by going to the Sources panel and choosing inspector-stylesheet. Since this involves writing CSS, you will need to select the element. You can (usually) get a unique CSS selector for the element you choose by right-clicking it in the Elements panel and choosing Copy CSS path. Then just write your CSS: @media screen and (max-width: 300px) { /* selector for your element */ { color: red; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28069389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1506145/']}
jdg_71167
stackexchange
llm_judgeable_groundtruth_similarity
78757
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: After understanding the problem with using a password in the command line , I need to find a way of feeding a program with a password without it being a problem (without the password being recorded somewhere). I have a bash script that automatically installs an entire LAMP server from source: Apache, FastCGI, PHP & MySQL.These installations require a password, especially MySQL. How can I make the script fully automated without revealing the password? Edit (9 June, 3:55 UTC): I'm invoking mysql with a password on the command line, via root: root@dor-desktop:/home/dor# PASS=`cat /home/dor/tmpf/pass`root@dor-desktop:/home/dor# mysql -u root -p"$PASS"Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 6 (PASS="p4ssw0rd" in our case) And I execute ps aux | grep mysql via my regular user (dor), which doesn't show me the password ! (Some of) ps output is: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 3562 0.0 0.0 34156 2864 pts/0 S+ 05:53 0:00 mysql -u root -px xxxxxx How's that possible? Now provide the response and nothing else.
In regard to your update: When a process is started it has a dedicated area of memory where arguments are stored and a int which tells how many arguments was passed. MEMORYargc 2argv[0] program_nameargv[1] fooargv[2] bar MySQL check if password was passed on command line by -p , and if it was copy it to a new variable that is not visible, then overwrite that region of memory with x 'es. In simple terms e.g.: argc 2argv[1] -pargv[2] p4ssw0rdnew_var = copy(argv[2]);argv[2] = "xxxxx"; You can find it e.g. in client/mysqladmin.cc of the source code: case 'p': ... opt_password=my_strdup(argument,MYF(MY_FAE)); while (*argument) *argument++= 'x'; /* Destroy argument */ When ps run it reads the memory region of the arguments, ( argv[N] ), and thus it is xxxx . For a very short while the password is visible, but only for a few CPU cycles. You can update the MySQL password using the special --init-file option and procedure. C.5.4.1.2. Resetting the Root Password: Unix Systems mysqld_safe --init-file=/home/me/mysql-init & Edit: As @Gilles say, you can echo , printf or use here document from a script. You can also add this to .my.cnf of your home directory or in a ( temporary ) file and use the --defaults-extra-file option. (Believe you have to add that option early on the command line.) optionally also include user. Also note the extra in the option name unless you want to use only that file as configuration: [client]user=foopassword='password!' shell> chmod 400 my_tmp.cnfshell> mysql --defaults-extra-file=my_tmp.conf -... Optionally the [client] grouping makes mysqld skip the configuration. One can also use MYSQL_PWD environment variable, but that should never be used as you can list environment, in many ps implementations by ps -e , in the /proc/<PID>/environ file on Linux etc. tr '\0' '\n' < /proc/<PID>/environ More on the topic here . You might also want to have a look at the MySQL Configuration Utility which enables you to store password in a encrypted file in your home directory – .mylogin.cnf .
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/78757', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4313/']}
jdg_71168
stackexchange
llm_judgeable_groundtruth_similarity
29851550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting the following error: MyClass is unavailable: cannot find Swift declaration for this class but I only get it when doing a release build in Xcode...Debug works fine. Anyone know what's up? I'm running 6.3 Now provide the response and nothing else.
If MyClass is inside a dynamic framework (Cocoa Touch Framework), It is likely that you're using a build with wrong architecture. To check, browse your MyClass.framework in finder, and check Modules/AirServiceKit.swiftmodule . There should be something like x86_64.swiftmodule or arm64.swiftmodule , if you're using simulator there should be x86, or arm if you're building for device.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29851550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174955/']}
jdg_71169
stackexchange
llm_judgeable_groundtruth_similarity
25732570
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 number of functions that return a future that is the result of a for comprehension, but i need to need to recover from some possible failures on the way out. The standard syntax seems to capture the for comprehension as an intermediate results like so: def fooBar(): Future[String] = { val x = for { x <- foo() y <- bar(x) } yield y x.recover { case SomeException() => "bah" }} The best alternative to I've found is to wrap the whole for comprehension in parentheses: def fooBar(): Future[String] = (for { x <- foo() y <- bar(x)} yield y).recover { case SomeException() => "bah"} This mostly seems like a shortcut than an improvement in syntax, so I'm wondering if there is a better way to weave recovery into for comprehensions? Now provide the response and nothing else.
Some brace adjustment helps, though some people prefer braces instead of parens for a multiline expression: scala> def f = ( | for { | x <- foo; | y <- bar(x) | } yield y | ) recover { | case _: NullPointerException => -1 | }f: scala.concurrent.Future[Int] if you don't like scala> foo flatMap bar recover { case _: NullPointerException => -1 }res9: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@3efe7086 You can go all syntaxy: object Test extends App { import concurrent._ import duration.Duration._ import ExecutionContext.Implicits._ type ~>[A, B] = PartialFunction[A, B] type NPE = NullPointerException class `recovering future`[A, R >: A](val f: Future[A], val pf: Throwable ~> R) { def map[B >: A <: R](m: A => B) = new `recovering future`[B, R](f map m, pf) def flatMap[B >: A <: R](m: A => Future[B]) = new `recovering future`[B, R](f flatMap m, pf) def recovered: Future[R] = f recover pf } object `recovering future` { implicit def `back to the future`[A, R >: A](x: `recovering future`[A, R]): Future[R] = x.recovered } implicit class `inline recoverer`[A](val f: Future[A]) { def recovering[B >: A](pf: Throwable ~> B) = new `recovering future`(f, pf) } def f = Future(8) def g(i: Int) = Future(42 + i) def e(i: Int): Future[Int] = Future((null: String).length) Unadorned: for { x <- f y <- g(x) } Console println y // 50 And with the recover inlined: def compute: Future[Int] = for { x <- f recovering { case _: NPE => -1 } y <- g(x) } yield y Console println (Await result (compute, Inf)) // 50 Or showing the failing case: def fail: Future[Int] = for { x <- f recovering { case _: NPE => -1 } y <- e(x) } yield y Console println (Await result (fail, Inf)) // -1} if you swing that way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25732570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32577/']}
jdg_71170
stackexchange
llm_judgeable_groundtruth_similarity
9502779
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an enterprise of around 3,500 PCs I have to manage with Microsoft's System Center Configuration Manager (SCCM). The SCCM client heavily depends on WMI and sometimes WMI breaks for whatever reason. I'm developing a Powershell script that remotely repairs WMI on these broken clients. Most clients that I attempt to query WMI remotely have no problem while others simply hang my script for minutes and even infinitely. I've gotten past some of these my using the WMISearcher object type and using the ReturnImmediately and Timeout Options properties but there's still a few hanging indefinitely. I'm looking for something to add to this script so that no client can hang up my script due to a WMI issue. Here's the small script I have thus far. The script hangs at the "$oResult = $oWmi.Get()" line. $oWmi = [WMISearcher]'';$oWmi.Options.ReturnImmediately = $true;$oWmi.Options.Timeout = '0:0:2';$oWmi.Scope.Path = "\\$PCNAME\root\cimv2";$oWmi.Query = 'SELECT * FROM Win32_OperatingSystem';$oResult = $oWmi.Get();$oResult | Out-Null Now provide the response and nothing else.
The cryptohash package is probably the simplest to use. Just read your input into a lazy 1 ByteString and use the hashlazy function to get a ByteString with the resulting hash. Here's a small sample program which you can use to compare the output with that of sha1sum . import Crypto.Hash.SHA1 (hashlazy)import qualified Data.ByteString as Strictimport qualified Data.ByteString.Lazy as Lazyimport System.Process (system)import Text.Printf (printf)hashFile :: FilePath -> IO Strict.ByteStringhashFile = fmap hashlazy . Lazy.readFile toHex :: Strict.ByteString -> StringtoHex bytes = Strict.unpack bytes >>= printf "%02x"test :: FilePath -> IO ()test path = do hashFile path >>= putStrLn . toHex system $ "sha1sum " ++ path return () Since this reads plain bytes, not characters, there should be no encoding issues and it should always give the same result as sha1sum : > test "/usr/share/dict/words"d6e483cb67d6de3b8cfe8f4952eb55453bb99116d6e483cb67d6de3b8cfe8f4952eb55453bb99116 /usr/share/dict/words This also works for any of the hashes supported by the cryptohash package. Just change the import to e.g. Crypto.Hash.SHA256 to use a different hash. 1 Using lazy ByteStrings avoids loading the entire file into memory at once, which is important when working with large files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9502779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999246/']}
jdg_71171
stackexchange
llm_judgeable_groundtruth_similarity
144423
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: A while ago I started to create a winform application and at that time it was small and I did not give any thought of how to structure the project. Since then I added additional features as I needed and the project folder is getting bigger and bigger and now I think it is time to structure the project in some way, but I am not sure what is the proper way, so I have few questions. How to properly restructure the project folder? At the moment I am thinking of something like this: Create Folder for Forms Create Folder for Utility classes Create Folder for Classes that contain only data What is the naming convention when adding classes? Should I also rename classes so that their functionality can be identified by just looking at their name? For example renaming all forms classes, so that their name ends with Form .Or is this not necessary if special folders for them are created? What to do, so that not all the code for main form ends up in Form1.cs Another problem I encountered is that as the main form is getting more massive with each feature I add, the code file (Form1.cs) is getting really big. I have for example a TabControl and each tab has bunch of controls and all the code ended up in Form1.cs. How to avoid this? Also, Do you know any articles or books that deal with these problems? Now provide the response and nothing else.
It looks like you've fallen into some of the common pitfalls, but don't worry, they can be fixed :) First you need to look at your application a little differently and start breaking it down into chunks. We can split the chunks in two directions. First we can separate controlling logic (The business rules, data access code, user rights code,all that sort of stuff) from the UI code. Second we can break the UI code down into chunks. So we'll do the latter part first, breaking the UI down into chunks. The easiest way to do this is to have a single host form on which you compose your UI with usercontrols. Each user control will be in charge of a region of the form. So imagine your application had a list of users, and when you click on a user a text box below it is filled with their details. You could have one user control managing the display of the user list and a second one managing the display of the user's details. The real trick here is how you manage the communication between the controls. You don't want 30 user controls on the form all randomly holding references to each other and calling methods on them. So you create an interface for each control. The interface contains the operations the control will accept and any events it raises. When you think about this app, you don't care if the list box list selection changes, you are interested in the fact a new user has changed. So using our example app, the first interface for the control hosting the listbox of users would include an event called UserChanged which passes a user object out. This is great because now if you get bored of the listbox and want a 3d zoomy magic eye control, you just code it to the same interface and plug it in :) Ok, so part two, separating the UI logic from the domain logic. Well, this is a well worn path and I'd recommend you look at MVP pattern here. It's really simple. Each control is now called a View (V in MVP) and we've already covered most of what is needed above. In this case, the control and an interface for it. All we're adding is the model and the presenter. The model contains the logic that manages your application state. You know the stuff, it would go to the database to get the users, write to the database when you add a user, and so on. The idea is you can test all of this in complete isolation from everything else. The Presenter is a bit more tricky to explain. It is a class which sits between the model and the View. It is created by the view and the view passes itself into the presenter using the interface we discussed earlier. The presenter doesn't have to have its own interface, but I like to create one anyway. Makes what you want the presenter to do explicit. So the presenter would expose methods like ListOfAllUsers which the View would use to get its list of users, alternatively, you could put an AddUser method the View and call that from the presenter. I prefer the latter. That way the presenter can add a user to the listbox when ever it wants. The Presenter would also have properties like CanEditUser, which will return true if the user selected can be edited. The View will then query that every time it needs to know. You might want editable ones in black and read only ones in Gray. Technically that's a decision for the View as it is UI focused, whether the user is editable in the first place is for the Presenter. The presenter knows because it talks to the Model. So in summary, use MVP. Microsoft provide something called SCSF (Smart Client Software Factory) which uses MVP in the way I've described. It does a lot of other things too. It's quite complex and I don't like the way they do everything, but it may help.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/144423', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/51733/']}
jdg_71172
stackexchange
llm_judgeable_groundtruth_similarity
797966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In WPF, when I right-click on a treeview item I would like it to be Selected/Activated before showing the context menu. This sounds pretty simple, but the inclusion of a hierachicalDataTemplate complicates things a little. I have the following treeview: <TreeView x:Name="trv" ContextMenu="{StaticResource contextMenu}" ItemTemplate="{StaticResource treeHierarchicalDataTemplate}" ItemsSource="{Binding Source={StaticResource meetingItems}}" > <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="trv_PreviewMouseRightButtonDown"/> <Setter Property="IsExpanded" Value="True"></Setter> </Style> </TreeView.ItemContainerStyle> </TreeView> And here is my event handler... private void trv_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e){ TreeViewItem item = sender as TreeViewItem; if (item != null) { item.Focus(); e.Handled = true; }} Note how I add an EventSetter above. This ALMOST works. But it only selects the root-level treeview node (i.e. the root parent of the node on which I right click). This may be because of my hierarchical data template? This template can contain children OF THE SAME TYPE. Here is my hierarchical data template... <HierarchicalDataTemplate x:Key="treeHierarchicalDataTemplate" ItemsSource="{Binding Path=ChildMeetingItems}"> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding="{Binding Path=Red}" Value="True"> <Setter TargetName="img" Property="Image.Source" Value="pack://siteoforigin:,,,/images/bookRed.png"></Setter> </DataTrigger> </HierarchicalDataTemplate.Triggers> <StackPanel x:Name="treeViewItemPanel" Background="Transparent" Orientation="Horizontal"> <Image Width="16" Height="16" x:Name="img" Margin="0,0,4,0" Source="pack://siteoforigin:,,,/images/bookGreen.png"></Image> <TextBlock Foreground="DarkGray" Text="{Binding DisplayIndex}" Margin="0,0,5,0"></TextBlock> <TextBlock Text="{Binding Summary}"></TextBlock> </StackPanel></HierarchicalDataTemplate> Any idea on why only the root node instead of child nodes are selected when I right-click? Now provide the response and nothing else.
That's because the ItemContainerStyle is not inherited by the child nodes.You need to add the same EventSetter on the ItemContainerStyle o your HierarchicalDataTemplate. <HierarchicalDataTemplate x:Key="treeHierarchicalDataTemplate" ItemsSource="{Binding Path=ChildMeetingItems}"> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding="{Binding Path=Red}" Value="True"> <Setter TargetName="img" Property="Image.Source" Value="pack://siteoforigin:,,,/images/bookRed.png"></Setter> </DataTrigger> </HierarchicalDataTemplate.Triggers> <StackPanel x:Name="treeViewItemPanel" Background="Transparent" Orientation="Horizontal"> <Image Width="16" Height="16" x:Name="img" Margin="0,0,4,0" Source="pack://siteoforigin:,,,/images/bookGreen.png"></Image> <TextBlock Foreground="DarkGray" Text="{Binding DisplayIndex}" Margin="0,0,5,0"></TextBlock> <TextBlock Text="{Binding Summary}"></TextBlock> </StackPanel><HierarchicalDataTemplate.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="trv_PreviewMouseRightButtonDown"/> </Style> </HierarchicalDataTemplate.ItemContainerStyle></HierarchicalDataTemplate>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/797966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22702/']}
jdg_71173
stackexchange
llm_judgeable_groundtruth_similarity
18656824
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 dynamically created N panels, the distance between them in height 15px panel.Location = new Point (x, y); y = panel.Bottom + 15; I can make the width of the smaller, and so I need distance in height between the panels was always 15pxI have a method with different checks for resize, and I try changes distance, but it always works differently... public void checkResize(string msg_out, object panel_sender, object text_msg_sender, int panHei, int numbs){ Panel pan_item = (Panel)panel_sender; Label lab_item = (Label)text_msg_sender; char[] msg_arr = msg_out.ToCharArray(); int panWidRaz = 308 - pan_item.Width; int panWidw = pan_item.Width; if (int.Parse(pan_item.Name) != numbs - 1) { if (panWidw < buff) { /* if (panWidRaz % 15 == 0) { for (int i = int.Parse(pan_item.Name); i >= 0; i--) { panel1.Controls[i.ToString()].Location = new Point(panel1.Controls[i.ToString()].Location.X, panel1.Controls[i.ToString()].Location.Y + 1); } }*/ //width control becomes smaller panels are becoming more in height, it is necessary that the distance between the panels remained 15px } if (panWidw > buff) { /*if (panWidRaz % 15 == 0) { for (int i = int.Parse(pan_item.Name); i >= 0; i--) { panel1.Controls[i.ToString()].Location = new Point(panel1.Controls[i.ToString()].Location.X, panel1.Controls[i.ToString()].Location.Y - 1); } }*/ //width control becomes bigger panels are becoming less in height, it is necessary that the distance between the panels remained 15px } buffCountPan++; if (buffCountPan == panel1.Controls.Count - 1) { buff = panWidw; buffCountPan = 0; } if (msg_arr.Length > 26) { int panWid = (308 - pan_item.Width) / 5; int panWidLab = 308 - pan_item.Width; pan_item.Height = panHei + panWid; lab_item.MaximumSize = new System.Drawing.Size(300 - panWidLab, 100); lab_item.MinimumSize = new System.Drawing.Size(300 - panWidLab, 14); } } } I can't post image here... reputation... i make scrin of work my panel http://pixs.ru/showimage/Bezimeni1p_9639414_8969341.png Now provide the response and nothing else.
This error occurs when trying to access UI elements from any thread that is not the UI thread. To access/modify elements from a non-UI-thread, use runOnUIThread . However as you need to change a UI element from within a fragment , runOnUIThread should be invoked onto the fragments owning activity. You can do this through getActivity().runOnUIThread() . EG: timer.schedule(new TimerTask() { @Override public void run() { // Your logic here... // When you need to modify a UI element, do so on the UI thread. // 'getActivity()' is required as this is being ran from a Fragment. getActivity().runOnUiThread(new Runnable() { @Override public void run() { // This code will always run on the UI thread, therefore is safe to modify UI elements. myTextBox.setText("my text"); } }); }}, 0, 3000); // End of your timer code. For further information see the following documentation: Android Fragments (specifically, getActivity() ). TimerTask . Invoking a Runnable on the UI thread.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18656824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2753330/']}
jdg_71174
stackexchange
llm_judgeable_groundtruth_similarity
26821
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: I have the following ~/.emacs: ;; Added by Package.el. This must come before configurations of;; installed packages. Don't delete this line. If you don't want it,;; just comment it out by adding a semicolon to the start of the line.;; You may delete these explanatory comments.(package-initialize)(require 'highlight-symbol)(global-set-key [(control f3)] 'highlight-symbol)(global-set-key [f3] 'highlight-symbol-next)(global-set-key [(shift f3)] 'highlight-symbol-prev)(global-set-key [(meta f3)] 'highlight-symbol-query-replace) Then I added the file highlight-symbol.el to my ~/.emacs.d folder. However when I start emacs I get: Warning (initialization): An error occurred while loading ‘~/.emacs’:File error: Cannot open load file, No such file or directory, highlight-symbol I am new to emacs, what am I doing wrong? Now provide the response and nothing else.
Looking at the help from require ( C-h f require ) (require FEATURE &optional FILENAME NOERROR) If feature FEATURE is not loaded, load it from FILENAME. If FEATURE is not a member of the list 'features', then the feature is not loaded; so load the file FILENAME. If FILENAME is omitted, the printname of FEATURE is used as the file name, and 'load' will try to load this name appended with the suffix '.elc' or '.el', in that order. So let's look at load help (either C-h f load or simply use TAB to navigate to the blue link then use RET ): This function searches the directories in `load-path'. Again we can have a look at load-path help (either C-h v load-path , since it's a variable, or navigating to the link) and, probably, find that .emacs.d is not in the list. This can be fixed by adding this to the init file: (add-to-list 'load-path "~/.emacs.d") For it to take effect immediately you can use C-x C-e ( eval-last-sexp ) with point at end of line.
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/26821', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/13105/']}
jdg_71175
stackexchange
llm_judgeable_groundtruth_similarity
10745542
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to convert an object (is declared here as 'obj': object is array, primitive) to a string array. object can be anything uint[], int16[], etc. I have been trying to use string[] str = Array.ConvertAll<object, string>((object[])obj, Convert.ToString); The problem occurs when I try to cast the unknown type object into object[].I have been getting casting error. One attempt I made, which failed, was using object[] arr = (object[])obj; or IEnumerable<object> list = obj as IEnumerable<object>object[] arr = (object[])list; I saw postings regarding value type and reference type issue on casting. Would there be a simple code that can handle casting to object[] regardless of type of object, as long as it is an array ?I am trying to avoid manual handling of every possible type casting. thanks in advance Now provide the response and nothing else.
You can use the fact that every array implements IEnumerable : string[] arr = ((IEnumerable)obj).Cast<object>() .Select(x => x.ToString()) .ToArray(); This will box primitives appropriately, before converting them to strings. The reason the cast fails is that although arrays of reference types are covariant, arrays of value types are not: object[] x = new string[10]; // Fineobject[] y = new int[10]; // Fails Casting to just IEnumerable will work though. Heck, you could cast to Array if you wanted.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10745542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971943/']}
jdg_71176
stackexchange
llm_judgeable_groundtruth_similarity
15979428
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 currently trying to figure out what the appropriate number of workers is for each Amazon Instance Type. I used to run one Gunicorn worker, however that proved to be quite slow. Many developers are currently using this formula to gauge how many workers would be suitable: NUM_WORKERS=3 #recommended formula here is 1 + 2 * NUM_CORES The problem I'm having is that Amazon isn't quite clear as to the number of cores each instance is running. For example, an M1 Small Instance has 1 EC2 Compute Unit (1 virtual core with 1 EC2 Compute Unit) What does that essentially mean? That it has one core? or that it has two cores? Now provide the response and nothing else.
I know this is a old question. But I think I have a better answer to this question. Gunicorn docs suggests that 2n+1 [ gunicorn -w <2n+1> myapp:wsgi ] is a good guess for number of workers (Yes, n = number of cores). I came up with a tiny shell script to apply this formula. All you need to do is this: gunicorn -w $(( 2 * `cat /proc/cpuinfo | grep 'core id' | wc -l` + 1 )) myapp:wsgi Where the command cat /proc/cpuinfo | grep 'core id' | wc -l will return the total number of actual CPU cores (n). So $(( 2 * `cat /proc/cpuinfo | grep 'core id' | wc -l` + 1 )) equates to 2n+1 formula. This will apply 2n+1 formula to all the linux-based machines. You dont need to know the number of workers for each type of instance or anything like that. Reference: http://dhilipsiva.com/2015/10/22/appropriate-number-of-gunicorn-workers.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15979428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761761/']}
jdg_71177
stackexchange
llm_judgeable_groundtruth_similarity
257046
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 two files large files: f1.txt: 5020118359 |13ZJ24001218 |20141224|R5020120475 |13ZJ38000813 |20141204|R5020127431 |13ZJ38001569 |20141201|R5020127689 |12ZJ44000606 |20141203|R5020127728 |13ZJ38001356 |20141203|R5020127956 |13ZJ62002544 |20141205|R5020127972 |13ZJ49000082 |20141205|R5020128325 |13ZJ57000785 |20141210|R5020128706 |13ZJ38002805 |20141211|R5020129084 |10XJ70107764 |20141217|R5020129102 |12ZJ54000041 |20141217|R f2.txt: 09Y90301055212ZJ5400004111XJ6211838508Y90901894609Y90201195411XJ5712034610XJ7010776411XJ4016532909XJ4200833608Y91202143511XJ5104027207Y910027235 Output: 5020129084 |10XJ70107764 |20141217|R5020129102 |12ZJ54000041 |20141217|R it will compare 2nd column of the first file and 1st column of the second file and then print the matched records of the 1st file. Now provide the response and nothing else.
You can filter it in find by using -mindepth option. Like this: function enterDIR { find . -mindepth 1-maxdepth 1 -type d | while read DIR ; do #recurse into every directory below top-level directory cd "$DIR/" enterDIR done createDirectory convertFLAC} But the whole script doesn't look like a good solution. If I understand your idea correct, you want to walk through the whole directory tree, create there new directory, convert flac to mp3 if any and copy all non-flac files to a new dir. I would do that this way: find . -mindepth 1 -type -d -exec mkdir -p {}/originalFLAC/Music \+find . -type f -iname "*.flac" -exec ffmpeg -i {} -ab 320k -map_metadata 0 {}.mp3 \;find . -type f ! -iname "*.flac" | while read file ; do cp -v "$file" "$(dirname "$file")"/originalFLAC/Music/ ; done
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/257046', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/152841/']}
jdg_71178
stackexchange
llm_judgeable_groundtruth_similarity
18658295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to get full process name from struct task_struct . The comm field stores only 16 characters, while process name can be longer. Is there any way to get full process name? This can be done through by getting struct vm_area_struct from task_struct , and further obtain file to which vm_area is mapped, but this is unreliable. Now provide the response and nothing else.
Did you mean exe file name? You can get the exe of current process as follows : char *pathname,*p;mm = current->mm;if (mm) { down_read(&mm->mmap_sem); if (mm->exe_file) { pathname = kmalloc(PATH_MAX, GFP_ATOMIC); if (pathname) { p = d_path(&mm->exe_file->f_path, pathname, PATH_MAX); /*Now you have the path name of exe in p*/ } } up_read(&mm->mmap_sem);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18658295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1056303/']}
jdg_71179
stackexchange
llm_judgeable_groundtruth_similarity
51063205
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 know a good practise for this problem. I am calling to three services concat with switchMaps, but I need a variable of first service for the last service. How was the best practice to do this? Example: this.session.account.get().switchMap(account => this.employerApi.get(account.accountId)).switchMap(employer => this.addressApi.get(employer.addressId)).filter(address => address.numer % 2).subscribe(address => console.log(¿¿¿¿¿account.name?????, address.name)); Thanks for your help Now provide the response and nothing else.
The simplest way would be to aggregate the values as you go: this.session.account.get() .switchMap(account => this.employerApi.get(account.accountId).map(employer => ({employer, account})) .switchMap(data => this.addressApi.get(employer.addressId).map(address => ({...data, address})) .filter(data => data.address.number % 2) .subscribe(...)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51063205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3607840/']}
jdg_71180
stackexchange
llm_judgeable_groundtruth_similarity
3171578
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: An object $I$ in a category $\mathcal{A}$ is initial if for each $\mathcal{A}$ -object $X$ , there is a unique morphism $I\rightarrow X$ . An object $J$ in a category $\mathcal{A}$ is final if for each $\mathcal{A}$ -object $X$ , there is a unique morphism $X\rightarrow J$ . These are definitions from Cohn's Basic Algebra. Let $\mathcal{R}$ be the category of rings. In this category $0$ ring is final object, and $\mathbb{Z}$ is initial object. Q. In defining rings, the author mentioned that it should contain $1$ , multiplicative identity; it is not necessarily distinguished from $0$ . The author call $0$ to be trivial ring (see p. 79, Section 4.1). In defining ring homomorphism, author says that the multiplicative identity should go to multiplicative identity. I am not getting then why the zero ring can not be initial object? The map $0\mapsto 0\in R$ is unique ring homomorphism from ring $\{0\}$ to any ring $R$ , am I right? Now provide the response and nothing else.
The function $f:\{0\}\to R$ with $f(0) = 0$ doesn't map the multiplicative identity of $\{0\}$ to the multiplicative identity of $R$ (unless $R$ is also a zero ring). $\Bbb Z$ is the initial object of rings with multiplicative identity, as $f:\Bbb Z\to R$ with $f(n) = n\cdot 1_R$ is the unique unit-preserving ring homomorphism from $\Bbb Z$ to $R$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3171578', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15847/']}
jdg_71181
stackexchange
llm_judgeable_groundtruth_similarity
20313611
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 custom UiTablleviewCell with some images and labels, and I would like to have rotated label in tableview cell...so I would like to edit initWithStyle method, but it seems like it's never called. - (id)initWithStyle:(UITableViewCellStyle)stylereuseIdentifier:(NSString*)reuseIdentifier{NSLog(@"creating cell");self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];if (self){}return self;} but in my log, I cant see this message. In tableview I have standard cellForRow method - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *simpleTableIdentifier = @"messagesCell"; TBCellMessagesCell *cell = (TBCellMessagesCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; cell.selectionStyle = UITableViewCellSelectionStyleNone; // smt stuff return cell;} so I'm wondering how does tableview initialize tableviewcells, I can think about some workarounds but I would like to have it clean.Thank you. Now provide the response and nothing else.
If the cells come from a storyboard or nib file, then initWithStyle:reuseIdentifier is not called, initWithCoder: is called instead. Here's a typical implementation of an overwritten initWithCoder: : -(id)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; if (self) { // Do your custom initialization here } return self;} Will not work if you need to access IBOutlet during custom initialization.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20313611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1762099/']}
jdg_71182
stackexchange
llm_judgeable_groundtruth_similarity
1786
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 previously posted this question on Mathgroup but received no response I am using Workbench to profile my code. Suppose I have 2 modules, let's call them A, B (they are too long to replicate here). While running my code, Module B is called repeatedly from A, say in a Do loop. Module A is called once. I would like to profile total usage of B (not just one instance), which rules out embedding each call to B in a Profile[] statement (as this generates a Profile output for each call). I could, of course, profile A, but the information produced on B would be buried in between timing data pertaining to other parts of A (which for my long module A makes it virtually impossible to understand what's happening in B). Is there a way to accomplish this? Now provide the response and nothing else.
If you can settle for anything other than Workbench's Profile , here is a simplistic profiler function with a fairly low latency: ClearAll[profile];SetAttributes[profile, HoldAll];profile[code_] := Block[{$totalTime = 0, t, res, time,exclude}, SetAttributes[{time, exclude}, HoldAll]; exclude[cd_] := (t = AbsoluteTime[];res = cd; $totalTime -= AbsoluteTime[] - t; res); time[cd_] := (t = AbsoluteTime[];res = cd; $totalTime += AbsoluteTime[] - t; res); {code, $totalTime}]; To illustrate how you can use it: b[] := Do[Range[10], {100}];aa[] := Module[{}, Pause[2]; Do[time@b[], {1000}]; Pause[3]; ]; Note that I inserted time wrapper in the place in the code which I want to profile. All invocations of time will add up: profile[aa[]](* ==> {Null, 0.0791}*) Note that profile has some overhead, but it seems to at least give the right order of magnitude for the result: a[] := Module[{}, Pause[2]; time@Do[b[], {1000}]; Pause[3]; ]; profile[a[]](* ==> {Null,0.0781250}*) The granularity may be not as good as in Profile , but in case it is not enough (meaning you are timing something very fast), you should try to wrap time around pieces of code where your very fast operation is repeated (like loops). You can wrap pieces inside those which you want to exclude, in the exclude wrapper. Obviously, the code or functions it uses should not use the symbols time and exclude for other purposes, but this is easy to fix by placing profile into a separate context / package.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/1786', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/518/']}
jdg_71183
stackexchange
llm_judgeable_groundtruth_similarity
3091611
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: Is there a way to exactly solve the following differential equation: $$\left(\frac{dx}{dt}\right)^2 = -\tan x \frac{d^2x}{dt^2} $$ Now provide the response and nothing else.
Imagine that you're driving on a road and you're sitting in the car. By Newton's laws of motion whenever there's an acceleration, you will feel something pulls you toward the seat, or more generally in the opposite direction of acceleration. Since velocity is a vector and acceleration is caused by a change in velocity, two things can cause acceleration: a change in the direction of the velocity vector or a change in its magnitude. While we're driving on a straight road, the direction is always the same. The only kind of acceleration that we feel is caused by a change in the magnitude of velocity (speed). On the other hand, we all have felt that when we're making a U-turn or driving on a non-straight (curved) road, even with constant speed, some mysterious force pulls us toward the center of the circle that fits our path the best at that point. This kind of acceleration is caused by a change in the direction of velocity and it is caused by the curvature of the road. In geometry, we're interested in this second type of change. We don't want the change in the magnitude of velocity counts because we want a straight line to have zero curvature. Therefore, we must first do something to ensure that the velocity of our curve is always constant, preferably equal to $1$ . This can be achieved by reparametrizing our curve using the arc length as you said. See here for more information about reparametrizing by the arc length. Also, the idea of measuring curvature using acceleration is important and it is the basis of defining many important concepts in future such as geodesics, covariant differentiation, parallel transport, etc.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3091611', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153388/']}
jdg_71184
stackexchange
llm_judgeable_groundtruth_similarity
9132766
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a large amount of apps. They all have a build.xml file located in the projects base directory. I am trying to create an ant script that will go through and call a specific target on each of the build.xml files in all the projects. Here are the issues: Some of the projects are in deeper directories than others. Only some of the projects need to be built at a time. I was trying to use subant + antfile and defining a CSV of file paths in a properties file, but this did not work. Below is what i have and the error i am getting. If there is a better way to do this or you know what my problem is, please let me know! Thanks! This is the property defined in a property file. I am wanting the person running the script to add the file paths in here that are relative to the current location of the script they are running. projects.to.build= This is the subant task i am trying to use in the main build script. <filelist id="projectNames" dir="${basedir}" files="${projects.to.build}" /> <target name="debugAll" description="Builds all the projects listed in the projectNames.properties file."> <subant target="debug" antfile="${projects.to.build}"> </subant> </target> Here is the error i get when i try to run the build script when there are projects defined in the properties file. I am using the relative path. For example: ..\Apps\AnApp1\build.xml,..\Apps\AnApp2\build.xml,..\OtherApps\foo\AnotherApp1\build.xml "No Build Path Specified" (at my subant task) Now provide the response and nothing else.
You specified the antfile attribute, so ANT was expecting to a single build.xml file. The subant documentation describes how you can use a fileset as child parameter. Here's an example: <project name="Subant demo" default="run-debug-target"> <target name="run-debug-target"> <subant target="debug"> <fileset dir="." includes="**/build.xml" excludes="build.xml"/> </subant> </target></project> Update Alternatively a filelist could be used: <project name="Dry run" default="run"> <target name="run"> <subant target="test"> <filelist dir="projects" files="one/build.xml,two/build.xml,three/build.xml,four/build.xml"/> </subant> </target></project> Processing the following build files: projects/one/build.xml projects/two/build.xml projects/three/build.xml projects/four/build.xml
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9132766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427763/']}
jdg_71185
stackexchange
llm_judgeable_groundtruth_similarity
116596
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I convert $$ W m^{-2} sr^{-1} nmm^{-1} $$ to $$ W m^{-2} nm^{-1} $$ I have the following matlab code to illustrate the spectral energy distribution of solar radiation: h = 6.626e-34; % Planck's Constant = 4.135 x 10^-15 eV sc = 3e8; % speed of light (MKS)T= 6000; % kelvink = 1.38066e-23; % Boltzmann constant in J/Klamda = 0:20e-9:3200e-9;p = 2*3.14*h*c*c./(lamda.^5);b6000 = p./(exp(h*c./(lamda*k*T)-1));lamda = lamda.*1000000;plot(lamda,b6000,'.');title('Planck Radiation Law');xlabel('Wavelength [\mu{m}]')ylabel('Irradiance [W m^{-2} sr^{-1} nmm^{-1}]');xlim([0 3.2]); This is my result: How would I change my yaxis to be the same as the example shown? but I need the yaxis to be in units of $$ W m^{-2} nm^{-1} $$ so that the curve looks like From the plot, it seems that dividing the irradiance by 10.^14 would do the trick, is this correct? Could someone explain the unit conversion, for a non-physicist? This function is taken from here http://web.mit.edu/8.13/matlab/Examples/planck.m Updated version: From all of the advice given here, this is the updated and hopefully correct methods: h = 6.626e-34; % Planck's Constantc = 3e8; % speed of lightT = 6000; % absolute temperaturek = 1.38066e-23; % Boltzmann constant in J/Klambda = 0:20e-9:3200e-9; % wavelength% spectral radiancep = 2*h*c*c./(lambda.^5);b6000 = p./(exp(h*c./(lambda*k*T))-1);b6000 = (1e-9).*b6000;% multiply by the square of the ratio of the solar radius of earth's% orbital radiusb6000 = b6000.*(2.177e-5);% apply Lambert's cosine lawb6000 = b6000.*pi;% convert units for lambdalambda = lambda.*1e6;% print resultfh = figure(1);plot(lambda,b6000)xlabel('Wavelength [\mu{m}]');ylabel('Irradiance [W m^{-2} nm^{-1}]'); Now provide the response and nothing else.
The dimensional prefactor that ends up in your code is$$\frac{hc^2}{\lambda^5}=\frac{6.626\times10^{-34}\text{ J s}\times (3\times10^8\text{ m s}^{-1})^2}{(\tilde\lambda \text{ m})^5},$$where $\tilde\lambda$ is dimensionless and goes from 0 to 3200×10 -9 . This will come out in terms of a number $p$, which is what your code calculates, with some units:$$\frac{hc^2}{\lambda^5}=p\frac{\text{J s}\times \text m^2\text{ s}^{-2}}{\text{m}^5}=p\frac{\text{W}}{\text{m}^3}=p\frac{\text{W}}{\text{m}^2}\frac{1}{\text m}\frac{10^{-9}\,\text m}{1\,\text{nm}}=10^{-9} p\:\text W\,\text m^{-2}\,\text{nm}^{-1}.$$ Note also that you need to distinguish carefully between radiance (which is the Planck's law quantity you're calculating), which is the power flow per unit of solid angle, and irradiance, which is integrated over solid angle, as detailed in Carl Witthoft's answer. If you put this together, then, the spectral radiance is$$B_\lambda(T)=10^{-9}\frac{2\times6.626\times10^{-34}\times (3\times10^8)^2}{\tilde\lambda^5}\frac{\text W\,\text m^{-2}\,\text{sr}^{-1}\,\text{nm}^{-1}}{\exp\left(\frac{6.626\times10^{-34}\times3\times10^8}{\tilde\lambda \times 6000\times 1.38066\times 10^{-23}}\right)-1}.$$This peaks at ∼$12\:\text{kW}\,\text m^{-2}\,\text{sr}^{-1}\,\text{nm}^{-1}$, which is consistent with the graph in Wikipedia ; it represents the energy flow from the Sun, per unit of solid angle, across a unit area which is right next to the Sun's surface. Note that this is not comparable to the graph you give, which plots the solar spectrum as measured on Earth . To get to the latter, you need to multiply by the square of the ratio of the solar radius to the Earth's orbital radius,$$\left(\frac{R_☉}{a_⊕}\right)^2=\left(\frac{\phantom{000\,}696\,342\text{ km}}{152\,098\,232\text{ km}}\right)^2\approx 2.177\times10^{-5}.$$You then need to account for the fact that the Sun emits in all directions. As garyp points out, this is done by means of Lambert's cosine law , which essentially says that after integrating over solid angle you need to put an extra factor of $\pi$. Once you do that, you recover the graph you give: Finally, note that $\text{nmm}$ is not an SI unit. The matlab function you are basing yourself on has a typo at a crucial place which, in my view, renders it essentially useless, or at least useless without a careful examination of what it's actually calculating. Be very careful whenever you see that sort of thing!
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/116596', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/20059/']}
jdg_71186
stackexchange
llm_judgeable_groundtruth_similarity
27030
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 using constrOptim to minimize a log likelihood function for maximum likelihood estimation of parameters. I wish to set the bounds on my parameters, but to not understand the constrOptim definition of the feasibility region. The feasible region is defined by ui %*% theta - ci >= 0 I have a set of parameters with bounds [lower, upper] a[0,5] ie 0<a<5b[0,Inf]c[0,Inf]e[0,1]theta (starting values) = c(1, 1, 0.01,0.1) What are the ui (constraint matrix (k x p)) and ci (constraint vector of length k) for these parameter bounds? Is there a straightforward way to get from a list of upper and lower bounds to a ui and ci value? Now provide the response and nothing else.
Here's an example that we can use to illustrate ui and ci , with some extraneous output removed for brevity. It's maximizing the log likelihood of a normal distribution. In the first part, we use the optim function with box constraints, and in the second part, we use the constrOptim function with its version of the same box constraints. # function to be optimized> foo.unconstr <- function(par, x) -sum(dnorm(x, par[1], par[2], log=TRUE))> x <- rnorm(100,1,1)> optim(c(1,1), foo.unconstr, lower=c(0,0), upper=c(5,5), method="L-BFGS-B", x=x)$par[1] 1.147652 1.077654$value[1] 149.3724> > # constrOptim example> > ui <- cbind(c(1,-1,0,0),c(0,0,1,-1))> ui [,1] [,2][1,] 1 0[2,] -1 0[3,] 0 1[4,] 0 -1> ci <- c(0, -5, 0, -5)> > constrOptim(c(1,1), foo.unconstr, grad=NULL, ui=u1, ci=c1, x=x)$par[1] 1.147690 1.077712$value[1] 149.3724... blah blah blah ...outer.iterations[1] 2$barrier.value[1] -0.001079475> If you look at the ui matrix and imagine multiplying by the parameter vector to be optimized, call it $\theta$, you'll see that the result has four rows, the first of which is $\theta_1$, the second $-\theta_1$, the third $\theta_2$, and the fourth $-\theta_2$. Subtracting off the ci vector and enforcing the $\ge 0$ constraint on each row results in $\theta_1 \ge 0$, $-\theta_1 + 5 \ge 0$, $\theta_2 \ge 0$ and $-\theta_2 + 5 \ge 0$. Obviously, multiplying the second and fourth constraints by -1 and moving the constant to the right hand side gets you to $\theta_1 \le 5$ and $\theta_2 \le 5$, the upper bound constraints. Just substitute your own values into the ci vector and add appropriate columns (if any) to the ui vector to get the box constraint set you want.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/27030', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4843/']}
jdg_71187
stackexchange
llm_judgeable_groundtruth_similarity
771642
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 you integrate this function? $$\int\frac{x^3}{(x+5)^2}dx$$I have tried it myself by substitution but I can't seem to get rid of the $x$s. Now provide the response and nothing else.
Hint: Rewrite it as $$\int \frac{(u-5)^3}{u^2}\text{d}u$$ by making the substitution $u = x+5$ and rearranging that until you can get $x$ (i.e., if $u = x+5$, then $x = ?$)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/771642', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/124203/']}
jdg_71188
stackexchange
llm_judgeable_groundtruth_similarity
11579865
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 a dataset called 'input' with the following observations ID Salary 10 1000 20 2000 30 3000 40 4000 I need an output dataset with following observations ID Salary Next_row_Salary 10 1000 2000 20 2000 3000 30 3000 4000 40 4000 null Note: The scenario is next obersavtion's salary should be the current observation's value for the column Next_Row_salary.If there is no next observation then the current observation's value for the column Next_Row_salary should be 'null'. Kindly help me out in creating a sas code for this scenario. Now provide the response and nothing else.
There are a few ways to achieve this, here's how I would do it. data have; input ID Salary; cards;10 100020 200030 300040 4000;run;data want; recno=_n_+1; set have end=last; if not last then set have (keep=salary rename=(salary=next_row_salary)) point=recno; else call missing(next_row_salary);run;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11579865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/933047/']}
jdg_71189
stackexchange
llm_judgeable_groundtruth_similarity
3128424
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 split 2 in the cyclotomic ring $S = \mathbb{Z}[\sqrt{-1}]?$ Clearly the field $\mathbb{Q}(i)$ is a degree 2 normal extension. However, $(2)$ in $S$ is equal to $(2) = (1 - i)^2.$ Thus, the ideal cannot split anymore so we can deduce that $(1 - i)$ is in fact a prime ideal. But $S$ is a Dedekind domain and $(1 - i)$ is not a maximal ideal...I say this because $S/(1 - i) \cong \mathbb{Z}.$ Did I mistakenly assume that $\mathbb{Z}[i]/(1 - i) \cong \mathbb{Z}?$ Now provide the response and nothing else.
$\langle 1 - i \rangle$ is in fact a maximal ideal. Do notice that $\langle 1 - i \rangle \subseteq \langle 1 + i \rangle$ since $$\frac{1 - i}{1 + i} = -i.$$ Wait, did I get dyslexic? $$\frac{1 + i}{1 - i} = i.$$ So in fact $\langle 1 - i \rangle = \langle 1 + i \rangle$ . Furthermore, this ideal contains every Gaussian integer of even norm, but no Gaussian integer of odd norm. Add 1 to any Gaussian integer of even norm and you get a Gaussian integer of odd norm. Add 1 again and you have another Gaussian integer of even norm. Therefore, $\langle 1 - i \rangle$ is as large as it can possibly be without being the whole ring. Textbook maximal ideal.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3128424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/351828/']}
jdg_71190
stackexchange
llm_judgeable_groundtruth_similarity
37095
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a front end module that generates an (ECG) signal that varies from +/-2.5 V. I want to shift this signal to 0 - 5V. What is the best way to do this? Would a summing amplifier like the below circuit good enough? With R1 = R2 and V1 = 2.5V, V2 = my signal, V3 = V4 = GND Now provide the response and nothing else.
First thing to try is a simple resistor adder, without opamp. But it's clear that this won't work here: a resistor adder always attenuates the signal, and we need a \$\times\$1 amplification. This is a non-inverting summing amplifier. You would think that we simply have to add 2.5 V, but do you have that? I'm assuming you have 5 V, so let's use that and see where it gets us. If we have -2.5 V on the Vin input the non-inverting input should be zero if you want 0 V out, regardless of the values of R3 and R4. So R1 and R2 form a voltage divider, and R2 should be twice R1 to get the 0 V. Next we have to find the amplification, which is determined by R3 and R4: \$ A_V = \dfrac{R3 + R4}{R3} \$ If we have 2.5 V on the Vin input and with R2 = 2 \$\times\$R1 we get 3.33 V on the non-inverting input of the opamp. To make that 5 V out we have to amplify by 1.5, so R3 must be twice R4. We could use the following values: R1 = 10 kΩ R2 = 20 kΩ R3 = 20 kΩ R4 = 10 kΩ You'll need an RRIO (Rail-to-Rail I/O) opamp if you want to power if from a single 5 V supply.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/37095', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11234/']}
jdg_71191
stackexchange
llm_judgeable_groundtruth_similarity
12566228
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is wrong with the following piece of code? #include <iostream>template<typename K>struct A { struct X { K p; }; struct Y { K q; };};template<typename K>void foo(const typename A<K>::X& x, const typename A<K>::Y& y) { std::cout << "A" << std::endl;}int main() { A<float>::X x; A<float>::Y y; foo(x, y); } clang gives the following error message: 17:2: error: no matching function for call to 'foo' foo(x, y); ^~~10:6: note: candidate template ignored: couldn't infer template argument 'K'void foo(const typename A<K>::X& x, const typename A<K>::Y& y) { ^1 error generated. Now provide the response and nothing else.
The argument K in const typename A<K>::X is not deducible . Basically, everything left of a :: is not deducible (if :: separates a nested-name). It's trivial to see why it makes no sense to ask for deduction by running through this thought experiment: struct A { typedef int type; }struct B { typedef int type; }template <typename T> void foo(typename T::type);foo(5); // is T == A or T == B ?? There's no one-to-one mapping from types to nested types: Given any type (such as int ), there could be many ambient types of which it is a nested type, or there needn't be any.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12566228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316448/']}
jdg_71192
stackexchange
llm_judgeable_groundtruth_similarity
702347
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: How to write a sed (or awk , or both) which will rewrite the following: echo 'v100 v201 v102 v300 v301 v500 v999 v301' | sed/awk ... to this output: v1 v2 v3 v4 v5 v6 v7 v5 i.e. each subsequent vx was rewritten to start with v1...vn and where the same v was used in the sequence (i.e. v301 ) the same v should be applied (as in v5 ). Sidenote: the example input sequence shows all possible eventualities (i.e. duplicates, out of order originals, jumps in original numbers). Are you the sed or awk expert who can answer this? Now provide the response and nothing else.
Using awk : awk '{ for (i=1; i<=NF; ++i) $i = (seen[$i] ? seen[$i] : seen[$i] = "v" ++n) }; 1' This goes through all the fields of each input line and reassigns it. The value that it is reassigned is v followed by the next value of the counter n , unless the field's value has been seen before, in which case its new value will be the same as that field's value was given previously. The 1 at the end triggers the outputting of the modified line. Testing: $ echo 'v100 v201 v102 v300 v301 v500 v999 v301' | awk '{ for (i=1; i<=NF; ++i) $i = (seen[$i] ? seen[$i] : seen[$i] = "v" ++n) }; 1'v1 v2 v3 v4 v5 v6 v7 v5 Alternative awk command that only modifies the field if it matches the regular expression ^v[0-9]+$ : awk '{ for (i=1; i<=NF; ++i) if ($i ~ "^v[0-9]+$") $i = (seen[$i] ? seen[$i] : seen[$i] = "v" ++n) }; 1' Or, formatted across multiple lines for readability: awk '{ for (i=1; i<=NF; ++i) if ($i ~ "^v[0-9]+$") $i = (seen[$i] ? seen[$i] : seen[$i] = "v" ++n)}; 1'
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/702347', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/241016/']}
jdg_71193
stackexchange
llm_judgeable_groundtruth_similarity
18061781
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to C++ reference , you can new an object by: MyClass * p1 = new MyClass; or by MyClass * p2 = new (std::nothrow) MyClass; The second one will return a null pointer instead of throwing an exception. However, I hardly see this version in my experience. For example Google does not recommend using exception in their code, but they are not using the nothrow version either in Chromium as I can see. Is there any reason that we prefer the default one against the nothrow one? Even in a project that is not using exception? -- EDIT -- Follow up question: should I check return value of malloc() ? It looks like, on the contrary, many people advice to check return value of malloc, some said because: many allocation failures have nothing to do with being out of memory. Fragmentation can cause an allocation to fail because there's not enough contiguous space available even though there's plenty of memory free. Is this true? Why we treat malloc() and new() differently in this case? Now provide the response and nothing else.
However, I hardly see this version in my experience. You would use it (or, equivalently, catch the exception from the default version) if you can handle the failure locally; perhaps by requesting to free some other memory and then retrying, or by trying to allocate something smaller, or using an alternative algorithm that doesn't need extra memory. Is there any reason that we prefer the default one against the nothrow one? The general principle of exceptions: if you can't handle it locally, then there's no point in checking locally. Unlike return values, exceptions can't be ignored, so there's no possibility of ploughing on regardless and using a null pointer. Even in a project that is not using exception? Often, an out-of-memory condition can't be handled at all. In that case, terminating the program is probably the best response; and that is the default response to an unhandled exception. So, even if you're not using exceptions, the default new is probably the best option in most situations. should I check return value of malloc() ? Yes: that's the only way to check whether it succeeded. If you don't, then you could end up using a null pointer, giving undefined behaviour: often a crash, but perhaps data corruption or other bizarre behaviour and long debugging sessions to (hopefully) figure out what went wrong. Why we treat malloc() and new differently in this case? Because malloc forces us to check the return value, while new gives us the option of less intrusive error handling.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18061781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/558892/']}
jdg_71194
stackexchange
llm_judgeable_groundtruth_similarity
10395
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: To define some package-wide functions/variables, what approach is recommended? I tried to use contexts with the Begin function, but this failed: Clear[fun];fun[] := Module[{}, Begin["myContext`"]; x = 1; End[]; ];fun[]myContext`x I would expect myContext'x to be 1, but it seems to be undefined. Why does this fragment fail, what should I do instead? Now provide the response and nothing else.
I'm just going to go ahead an rephrase the answer. The problem as Leonid points out is akin to shadowing. Here is a very simple example of the behavoir: Remove[test`x, x](Begin["test`"];x = 42;End[];{x, test`x} ) {42,test`x} Remove[test`x, x]Begin["test`"];x = 42;End[];{x, test`x} {x,42} If you use Trace You will see that in the second example everything is evaluated line-by-line, which means that when we get to x=42 the active context is test` , however in the first case, we initially evaluate the CompoundExpression which means we put Global`x into scope, which means we already have an x defined when we evaluate x=42 thus it's interpreted as Global`x=42 . A way to get around this is to use the fact that MakeBoxes will automatically remove any context currently in $ContextPath while ToExpression Automatically puts any symbol not found in any context into $Context . Here I exclude the System` context in order to avoid scoping for example Sin to test`Sin : SetAttributes[ContextScope, HoldAll]ContextScope[context_, expression_, exclude_: {"System`"}] :=Block[{held}, Block[{$ContextPath = Complement[$ContextPath, {"System`"}]}, held = MakeBoxes[expression]]; Block[{$Context = context, $ContextPath = {context}}, ToExpression[held]]]ContextScope["test`", x = Sin[0]]{x, test`x} {x,0} This will however still put Global`x in scope, it simply does not assing a value to it. So any new call to x=somethign will assign a value to Global`x and not to test`x as would normally be expected if you had done a line by line evaluation of the context switching.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/10395', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1488/']}
jdg_71195
stackexchange
llm_judgeable_groundtruth_similarity
4174080
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 does the following bit of code work in C: int res = pow(2, 3);printf("%d\n", res); while this other doesn't? int a = 2;int b = 3;int res = pow(a, b);printf("%d\n", res); Even if I try double a = 2;double b = 3;double res = pow(a, b);printf("%f\n", res); I get an undefined reference to `pow' What am I doing wrong? Now provide the response and nothing else.
When it works, it's because the calculation was done by the compiler itself (and included in the binary as if you wrote it out) printf("8\n"); When it doesn't work, is because the pow function is included in the math library and the math library isn't linked with your binary by default. To get the math library to be linked, if your compiler is gcc, use gcc ... -lm ... With other compilers, should be the same :) but read the documentation
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4174080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130758/']}
jdg_71196
stackexchange
llm_judgeable_groundtruth_similarity
2828826
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is probably a dumb question, but I can't find the answer in the docs. Did the "Done" button on the pop-up keyboard always cause the keyboard to disappear? I see a lot of code around the web like this: - (BOOL)textFieldShouldReturn:(UITextField *)theTextField { [theTextField resignFirstResponder]; return YES;} When I press the "Done" button, the keyboard pops down and the UITextField resigns first responder. I'm presuming that pressing the "Done" button didn't used to cause a UITextField to resignFirstResponder , but that behavior changed at some time. I'm debugging on OS 3.0 - 3.1.3 Now provide the response and nothing else.
I made a small test project with just a UITextField and this code #import <UIKit/UIKit.h>@interface TextFieldTestViewController : UIViewController<UITextFieldDelegate>{ UITextField *textField;}@property (nonatomic, retain) IBOutlet UITextField *textField;@end#import "TextFieldTestViewController.h"@implementation TextFieldTestViewController@synthesize textField;- (void)viewDidLoad{ [self.textField setDelegate:self]; [self.textField setReturnKeyType:UIReturnKeyDone]; [self.textField addTarget:self action:@selector(textFieldFinished:) forControlEvents:UIControlEventEditingDidEndOnExit]; [super viewDidLoad];}- (IBAction)textFieldFinished:(id)sender{ // [sender resignFirstResponder];}- (void)dealloc { [super dealloc];}@end The text field is an unmodified UITextField dragged onto the NIB, with the outlet connected. After loading the app, clicking in the text field brings up the keyboard. Pressing the "Done" button makes the text field lose focus and animates out the keyboard. Note that the advice around the web is to always use [sender resignFirstResponder] but this works without it.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2828826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74118/']}
jdg_71197
stackexchange
llm_judgeable_groundtruth_similarity
5396719
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 UIButton in my iPhone app that, when clicked, plays a movie. The code to play the movie looks like this: NSURL *url = [[NSBundle mainBundle] URLForResource:@"Robot" withExtension:@"m4v"];moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];moviePlayer.controlStyle = MPMovieControlModeDefault;[moviePlayer.view setFrame: self.view.bounds];[self.view addSubview: moviePlayer.view];[moviePlayer play]; I'd like the movie to open in full screen mode, the way that all movies did prior to the iOS 3.2 update, where the blue "Done" button was in the top left corner, and the video played in landscape mode by default. Does anyone know how to do this? Thanks. Now provide the response and nothing else.
Assuming that self.view is using the entire screen: NSURL *url = [[NSBundle mainBundle] URLForResource:@"Robot" withExtension:@"m4v"];moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];moviePlayer.controlStyle = MPMovieControlStyleFullscreen;moviePlayer.view.transform = CGAffineTransformConcat(moviePlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));[moviePlayer.view setFrame: self.view.bounds];[self.view addSubview: moviePlayer.view];[moviePlayer play]; Now assuming that you basically dont want to use the current self.view but simply have it working in fullscreen (I call this; fake-fullscreen as it does not invoke the fullscreen-property); NSURL *url = [[NSBundle mainBundle] URLForResource:@"Robot" withExtension:@"m4v"];moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];moviePlayer.controlStyle = MPMovieControlStyleFullscreen;moviePlayer.view.transform = CGAffineTransformConcat(moviePlayer.view.transform, CGAffineTransformMakeRotation(M_PI_2));UIWindow *backgroundWindow = [[UIApplication sharedApplication] keyWindow];[moviePlayer.view setFrame:backgroundWindow.frame];[backgroundWindow addSubview:moviePlayer.view];[moviePlayer play];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5396719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/468461/']}
jdg_71198
stackexchange
llm_judgeable_groundtruth_similarity
18319
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Traditional 802.3ad link aggregation only works when all of the links in the group are going to/from the same devices/switches. So you couldn't have a system with one half of a bonded link going into switch A and the other half going into switch B and expect LACP to work. I suppose STP (if enabled) should block one of them to prevent a loop. Is that correct? I realise that bonding/trunking can only provide double bandwidth in specific circumstances, e.g. when there are separate communication flows. It wouldn't give double the bandwidth if both source and destination are the same. What I'm looking for is a way of connecting 2 switches together with multiple links to provide N times the bandwidth between them. I guess with LACP on the uplink ports between the 2 switches the bandwidth would still be limited to each discrete traffic flow: so traffic flows from switch-port A-3 to B-9 and B-4 to A-8 would each be able to hit close to 1Gbps (supposing there are 2 links in LACP) but A-6 to B-3 would not be able to exceed 1Gbps Is my understanding above all correct? Are there any vendor-specific implementations/extensions that can allow a single physical server to run LACP across 2 switches? I suppose this is where stackable switches come in? Multiple physical switches configured as a single logical switch? Are there any vendor-specific implementations/extensions that can increase the bandwidth of a single traffic flow by simultaneously using multiple links? EDIT: On further thought this would be useless, as the rate of data going into switch would still only be the bandwidth of a single port. Unless your server was connected to a 1Gbps port but the switches were connected together using a pair of 100Mbps ports. Now provide the response and nothing else.
Yes, if I am reading things correctly it appears your understanding is correct. Yes, there are implementations that will allow you to do link aggregation between a host and two switches. Switch stacking will allow a stack of individual switches to be managed as one device. Typically one of switches in the stack becomes the master for the stack allowing it to manage link aggregation across multiple switches. A second option is virtual switching which also allows this functionality across multiple switches even if they are not stacked. This typically requires higher end hardware, specific software versions and additional requirements in order to implement. Examples are virtual switching system (VSS)/ multichassis EtherChannel (MEC)/ virtual port channel (VPC) from Cisco or virtual chassis from Juniper. No. One of the hard invariants (i.e. absolute requirements) for L2 networking is the sequential delivery of frames. In link aggregation this is enforced by requiring a flow to traverse only one link in the group. If there is any sort of delay on that link, this invariant can still be maintained. If a flow were traversing two links and one of the links were to experience a delay (even a very short one), this could result in frames being delivered out of order violating this invariant. Ultimately, if you are running into a need to exceed the speed of a link for a single flow, you would need to upgrade your interfaces to the next available speed technology (i.e. 1G to 10G, 10G to 40G, etc). Cisco is also spearheading a push for *multigigabit" providing speeds of 2.5G or 5G across Cat5e/6 cabling at distances up to 100 meters.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/18319', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/15284/']}
jdg_71199
stackexchange
llm_judgeable_groundtruth_similarity
124655
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: My electric utility released an iPhone app called "DTE Insight" which (among other things) measures the amount of power flowing through an appliance's power cord by asking you to hold the cord against a specific part of the iPhone at a specific angle. I tested this app against the measurements from my Kill-a-Watt, and the app seems remarkably accurate to the point where I don't really understand how it works. I understand that current flowing through a conductor creates a magnetic field around the conductor, and I imagine that this app is using the phone's magnetic field sensor to try to measure the magnetic field caused by the current flowing through the cable, then multiplying the calculated current by an assumed voltage of 115 or 120 or whatever in order to estimate power. What confuses me is that household appliance cables contain two current-carrying conductors. Wouldn't the opposing magnetic fields from the two conductors interfere with and almost completely cancel out their respective fields out in the area around the cable? The app does ask whether the cord being tested is a two- or three-pronged cord, and whether the cord is round or flat. Can anybody explain to me how this might work? Data I did some tests using the app and my Kill-a-Watt to measure power draw of the same loads. I did five trials of each of the four loads using the app. The loads were: Assorted computing equipment sharing a power strip An electric fan on low An electric fan on medium An electric fan on high The results are as follows: Compute Load: Kill-a-Watt: 632 W, 757 VA App: 678 W, 667 W, 623 W, 662 W, 644 W Fan on Low: Kill-a-Watt: 56 W, 57 VA App: 75 W, 75 W, 75 W, 75 W, 77 W Fan on Medium: Kill-a-Watt: 75 W, 75 VA App: 103 W, 101 W, 98 W, 100 W, 97 W Fan on High: Kill-a-Watt: 97 W, 102 VA App: 132 W, 129 W, 131 W, 128 W, 131 W Reproducibility If you want to try this yourself, you have to select "Tools" and then "Take a Power Scan" from the main menu of the app. Now provide the response and nothing else.
Not having used said app I believe it is a master of assumptions and averages. The far field of a transmission line with two opposite current conductors is essentially zero. However the near field on anything other than a solid screen co-ax will always have a unbalanced component around it. The maximum unbalance will be when the two current conductors are 'eclipsed' and the near field will be mostly due to the nearer conductor. What I suggest for better trials is that you take a mains cable and carefully remove the outer covering for 12 inches or so to separate the internal wires (do this with a spare kettle cord if you like). Then run your tests with the phone placed next to just one of the live wires and see if it has repeatable results. It is also important to remember that the magnetic field sensor in the phone should be a 3 axis device so it can determine the magnetic field 'direction' and infer the conductor placement to a degree and correct a bit. Accuracy of 30% compared to a somewhat more predictable device I think is pretty phenomenal like you have found. Getting better will obviously be much harder given the loose test conditions required. It does remind me of a totally passive DC ammeter that my friend had that was over 50 years old. It was merely placed against a (single) conductor (such as the alternator charging lead in a car) and would deflect its needle to indicate the local induced magnetic field proportional to the current. Orientation was important and it would not have read accurately if a return conductor was nearby, however the principal is pretty much the same.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/124655', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/51042/']}
jdg_71200
stackexchange
llm_judgeable_groundtruth_similarity
3022845
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 have list of required elements in any order defined in dtd, but have no idea how I could do this. For example, I have following definition: <!ELEMENT parent (child1, child2, child3)> This dtd declaration will successfully validate following piece of xml: <parent> <child1></child1> <child2></child2> <child3></child3></parent> But in following case xml will not pass validation: <parent> <child2></child2> <child1></child1> <child3></child3></parent> One of the possible solution is to declare <!ELEMENT parent (child1 | child2 | child3)> But in this case one of the childs might be missing though validation will be successful. I need correct dtd element declaration for the case when list of required elements can be present in any order. Now provide the response and nothing else.
ChrisF is wrong to say you can't do this (but kudos for checking the spec!); DevNull [now known as Daniel Haley] is right to say you can. There is, however, one complication: the content model given by DevNull for parent violates the determinism rules of XML. Informally, these rules say the parser must know, without lookahead, which token in the content model each element in the document matches. If in a parent element the parser sees a child1 , it can't know without lookahead whether it has just matched the first or second occurrence of child1 in DevNull's content model. This is an error (but as it happens it's an error that processors are not obligated to report -- it's an error that means "all bets are off, the processor may do anything here, including fail to notice anything is wrong"). A content model for parent that obeys the determinism rules can be formed by factoring out common prefixes, thus: <!ELEMENT parent ( (child1, ( (child2,child3) | (child3,child2))) | (child2, ( (child1,child3) | (child3,child1))) | (child3, ( (child1,child2) | (child2,child1))) ) > This is less convenient than declarations for this model can be in other schema languages, and for more than three elements it's error prone and extremely tedious to do by hand. But it's not impossible to declare the content model you want with DTDs. Or perhaps I should say it's impossible only for DTD authors who are incapable of putting up with any inconvenience. Note also that unless the sequence of children carries some information, some design authorities argue strongly that it's better to fix a sequence.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3022845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50962/']}
jdg_71201
stackexchange
llm_judgeable_groundtruth_similarity
1475550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to have one div at center of another div horizontally. <div id="container"> <div id="centered"> hello world; </div> </div I tried with below style with "margin: 0px auto" trick, but it only works in FF, not in IE. div { border-width: 2px; border-style: solid; } #centered { margin: 0 auto; width: 30px; } #container { width: 100px; } Is there any way to achieve this cross browser? Now provide the response and nothing else.
You probably are not including a DOCTYPE in your document, thus throwing IE into quirks mode. Add this at the top of your file, for example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> See the difference here: with doctype , without doctype . It is a very good practice to always include a DOCTYPE into your document to make your website be as consistent as possible across browsers. With a DOCTYPE and a reset stylesheet cross browser layouts are much more reliable. The above DOCTYPE is just one of many choices. For more, check out this stackoverflow question You may also notice that Stackoverflow's sister site aimed at designers is named after this very important aspect of web design: Doctype .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1475550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26349/']}
jdg_71202
stackexchange
llm_judgeable_groundtruth_similarity
1399101
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider the measurable space $(\mathbb{R}, \Sigma)$, where $$\Sigma := \{ A \subset \mathbb{R} \,:\, A \text{ is countable or } A^c \text{ is countable}\}.$$ Proving this is indeed a $\sigma$-algebra is easy: The countable union of countable sets is again countable; if the countable union contains at least one cocountable set, the coset of this union will be a subset of a countable set and thus countable. Now consider the following map: $$\mu: \Sigma \to [0,\infty], \quad A \mapsto \begin{cases}0 \quad \text{if $A$ is countable} \\ 1 \quad \text{else}\end{cases}$$ How would I prove that this map is a measure? Again, if I only consider disjoint unions of countable sets $\sigma$-additivity is obvious. But what about disjoint unions that contain uncountable sets with countable complement? I suspect that every disjoint union of sets in $\Sigma$ contains at most one uncountable set with countable coset, but I can't find a rigorous proof for this. The only uncountable sets $A \in \Sigma$ with countable coset I can picture at this moment are of the form $$A = \mathbb{R} \setminus Q,$$ where $Q \subset \mathbb{Q}$. Now provide the response and nothing else.
Assume that there are two disjoint uncountable sets $A, B$ with countable complements. Then $\mathbb{R} = (A\cap B)^c = A^c \cup B^c$ would be the union of two countable sets, in contradiction to the uncountability of the real numbers.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1399101', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104897/']}
jdg_71203
stackexchange
llm_judgeable_groundtruth_similarity
59517991
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 angular 8 I am using HttpParams in Sending Data to the Server via Post method I am getting 502 status code error , sending data via HttpPrams ERROR HttpErrorResponse {headers: HttpHeaders, status: 502, statusText: "Bad Gateway", url: " http://central-portal-app-alb-1565375077.ap-south-1.elb.amazonaws.com/api/v1/user/login ", ok: false, …} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} status: 502 statusText: "Bad Gateway" here is my service file code service.ts @Injectable()export class RestService { baseUrl = environment.baseUrl; login = this.baseUrl + 'user/login'; constructor(private http: HttpClient) { }userlogin(userid, smpassword) {const params = new HttpParams().set('user_id', userid).set('sm_password', smpassword);console.log(params);return this.http.post(this.baseUrl + 'user/login', params.toString(),{ headers: new HttpHeaders({ 'Content-Type' : 'application/json' })}); login.component.ts @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css']})export class LoginComponent implements OnInit { Userlogin: FormGroup; constructor(private route: Router , private fb: FormBuilder , private rest: RestService) { this.Userlogin = this.fb.group({ email : ['', [Validators.required , Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$') ]], password : ['', [Validators.required , Validators.minLength(5) ] ] }); } // , Validators.required ngOnInit() { } login() { const email = this.Userlogin.get('email').value; const password = this.Userlogin.get('password').value; this.rest.userlogin(email, password).subscribe( result => { console.log(result); } ); // this.route.navigateByUrl('/pendingapproval'); } Now provide the response and nothing else.
I have received below errors when running Spring Boot Project for AWS SNS i.InstanceMetadataServiceResourceFetcher : Fail to retrieve tokencom.amazonaws.util.EC2MetadataUtils : Unable to retrieve the requested metadata (/latest/dynamic/instance-identity/document). Failed to connect to service endpoint:Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instanceError creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance Resolution applied:Add below code snippet to SpringBootApplication & Click on Run Button in the IDE @SpringBootApplication( exclude = { org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration.class, org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration.class, org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration.class })
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59517991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10489872/']}
jdg_71204
stackexchange
llm_judgeable_groundtruth_similarity
2442085
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 no problems getting the Json to work and parse the json return. I was just wondering how I could build a dynamic "whatever data is" and stick it into [data] to pass my parameters from there and not manually append them to the url. From jquery website example: $.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name);}); I thought I could build a string ( which doesn't make sense anyway ) and drop it inside the { }, but I obviously don't understand that part. name: isn't a string and you can't put a variable in that part, so how would I dynamically put items into whatever [data] is. UPDATE: Thanks for the answers. Would I be able to remove a parameter name from the object if I didn't find a valid value later on or would I need to destroy it and recreate it? I am using some select boxes to choose things and I may not have something selected so I wouldn't want to pass that parameter name/value. Now provide the response and nothing else.
You can build your object like this: var someVar = someRandomString();$.getJSON('test.js', (function() { var theData = {}; theData[someVar] = someRandomValue(); return theData;})(), function(jsonStuffFromServer) { alert("JSON Data: " + jsonStuffFromServer.users[3].name);}); Of course you don't have to build up the "data" object right there in an anonymous function; you can do it separately beforehand: var theData = {};theData[someVariableWithANameInIt] = someRandomValue();$.getJSON(url, theData, function(jsonStuff) { ... }); Here's how you could build up such an object from a set of <select> elements on your page: var theData = {};$('#myForm select').filter(function() { return $(this).val() != ''; }) .each(function() { theData[this.name] = $(this).val(); });$.getJSON(url, theData, function(jsonStuff) { ... });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2442085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133544/']}
jdg_71205
stackexchange
llm_judgeable_groundtruth_similarity
380272
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $L = \{a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, ... ,a_{n}\}$ be a logtrace containing a finite set of antenna samples submitted within a time window. What what would be a good way to express the number of distinct cellIDs $a^{cid}$ in $L$? where $a_{t}^{cid}$ is the cellID of the current registered antenna at time $t$. Assuming $A=\{1,4,3,5,4,3\}$, the result of the calculatin i'm searching for should be 4. Btw: What would be $ \#(A \cap A)$ ? 4 or 6? (if the result is 4, i would still like to avoid this weird notation.) Here's how i chose to write it, with the help of Brian M. Scott's answer. Let $a$ be an antenna sample, where $a^{cid}$ indicates the cellID and $a^{lac}$ the location area code (lac) of the antenna sample. Let $T = \{a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, ... ,a_{n}\}$ be a logtrace containing a finite sequence of antenna samples $a$ submitted within a time window, and $T^{cid}$ the finite sequence of cellIDs $a^{cid} \in T$. Then, Number of distinct cellIDs $=|C|$. Where $C$ is a set of cellIDs $c \in T^{cid}$. Now provide the response and nothing else.
Your $L$ isn’t actually a set: since it’s intrinsically ordered, it’s a finite sequence, or an $n$ -tuple. If you throw away the temporal order, what you have left is a multiset . And if you throw away the information about how many times each cellID appears, you have a set. If $A$ is considered as a multiset, its cardinality is $6$ . If, however, it’s considered as a set, which is how you wrote it, then it’s simply equal to $\{1,3,4,5\}$ and has cardinality $4$ . I’m not sure how to answer your notational question, because the answer depends on whether you’re willing to replace $L$ by an intermediate entity first. Technically, $L$ can be viewed as a function from $\{1,\dots,n\}$ to the set of cellIDs. From that point of view the number that you want is $|\operatorname{ran}L|$ , the cardinality of the range of $L$ . But I suspect that you’d find that a bit clumsy, and it might be best simply to define your own notation, e.g., $n_C(L)$ , for the number of distinct cellIDs. Added in response to edit: @ndrizza: Technically what you’ve written isn’t right, because the terms of a sequence aren’t actually elements of a sequence, and therefore it’s not actually correct to write $c\in T^{cid}$ or $a_t^{cid}\in T$ . On the other hand, your meaning is pretty clear, and I’m a bit fussier than most about notation, so it’s entirely possible that it would be acceptable for your intended audience. I might say something like this: Let $a$ be an antenna sample, where $a^{cid}$ indicates the cellID and $a^{lac}$ the location area code (lac) of the antenna sample. Let $T = \{a_{1}, a_{2}, a_{3}, a_{4}, a_{5}, ... ,a_{n}\}$ be a logtrace containing a finite sequence of antenna samples $a$ submitted within a time window, and $T^{cid}$ be the corresponding finite sequence of cellIDs $a^{cid}$ . Let $C_T$ be the set of distinct cellIDs in $T^{cid}$ ; then $|C_T|$ is the number of distinct cellIDs occurring in $T$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/380272', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75736/']}
jdg_71206
stackexchange
llm_judgeable_groundtruth_similarity
705566
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's take some theorem of ZFC, e.g.:$$(1)\: \exists x \forall y ( y \notin x) $$We can then choose a constant, denote it by '$\varnothing$' to get the following:$$(2)\:\forall x (x\notin \varnothing) $$My question is: what's the precise proof of (2) given (1)? Also, let the axioms of FOL be the ones from Geoffrey Hunter's Metalogic (axiom schemata QS1-7), plus the axioms of ZFC (though I think they're irrelevant). The only allowed rule of inference is modus ponens. P.S. I know that the question is ridiculous, and obviously the "jump" between (1) and (2) makes sense. The only thing that bugs me is that I can't justify this "jump" formally :) Now provide the response and nothing else.
It is a standard theorem about FOL that given a theory which entails a wff $\exists_1x\varphi(x)$, then we can conservatively add a new constant $c$ to the language of the theory, together with the new axiom $\varphi(c)$. This is conservative in this sense that we will still be able to prove nothing in the language of the original theory which we couldn't prove before (even when we use the new constant to instantiate old universal axioms -- see Henning Makholm's important comment below). So there is a good sense in which the new constant just sprinkles onto the original theory some "syntactic sugar" (some nice notation that enables the medicine to go down more easily, by helping us to put things more snappily or more memorably) without at all changing the basic power of the theory. That is all that is going on in the present case. Adding notation for the empty set is typically just adding syntactic sugar, which we are allowed to do because, once we know there is a set with no members, it is immediate that this is unique, so we have $\exists_1x\forall y(y \notin x)$, and we can apply that mentioned standard theorem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/705566', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/132181/']}
jdg_71207
stackexchange
llm_judgeable_groundtruth_similarity
3230727
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok saddle up cowboys, because this is going to be a long one. I have been spending the morning going through some of my old code and I'm left wondering about best practices and optimzation. In order to avoid a ride down subjective lane I'll just post some examples with some hopefully easy to answer questions. I will try to keep the examples very simple for ease of an answer and to decrease the likelihood of mistakes. Here we go: 1) Assignment vs jQuery Calls I understand that when accessing selectors it's generally considered better to assign a selector to a variable rather than make the same call more than once - ex. $('div#apples').hide();$('div#apples').show(); vs. var oranges = $('div#oranges');oranges.show();oranges.hide(); Does this same rule apply when referencing jQuery's $(this) ? Ex. A simple bit of script to make some data in a table clickable and customize the link. $('tr td').each( function() { var colNum = $(this).index(); var rowNum = $(this).parent().index(); $(this).wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); }) vs. $('tr td').each( function() { var self = $(this); var colNum = self.index() var rowNum = self.parent().index() self.wrap('<a href="example.com/hello.html?column=' + colNum + '&row=' + rowNum +'">'); }); 2) this vs $(this) Ok so this next one is something that I have wondered about for a long time but I can't seem to find any information on it. Please excuse my ignorance. When does it make sense to call the vanilla js this as opposed to the jQuery wrapped $(this) ? It's my understanding that - $('button').click(function() { alert('Button clicked: ' + $(this).attr('id'));}); Is much less efficient than accessing the DOM attribute of the vanilla this object like the following - $('button').click(function() { alert('Button clicked: ' + this.id);}); I understand what is going on there, Im just wondering if there is a rule of thumb to follow when deciding which to use. 3) Is more specificity always better? This one is pretty simple, is it ALWAYS beneficial to be more specific with our selectors? It's easy to see that $('.rowStripeClass') would be much slower than $('#tableDiv.rowStripeClass') , but where do we draw the line? Is $('body div#tableDiv table tbody tr.rowStripeClass') faster still? Any input would be appreciated! If you've made it this far, thanks for taking a look! If you haven't, :p Now provide the response and nothing else.
I'll try to answer these as concisely as possible: Cache it when it's used often, especially in a loop situation, running the same code to get the same result is never a good thing for performance, cache it. Use this when you only need a DOM element and $(this) when you need the jQuery methods (that wouldn't be available otherwise), your example of this.id vs $(this).attr("id") is perfect, some more common examples: Use this.checked instead of $(this).is(':checked') Use $.data(this, 'thing') instead of $(this).data('thing') Any other case where creating a jQuery object isn't useful basically. Decending from an ID selector is preferred for performance...how specific do you need to be? That completely depends, in short: be as specific as you need to be .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3230727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241642/']}
jdg_71208
stackexchange
llm_judgeable_groundtruth_similarity
52211682
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 learn vue.js and I created a basic form in HTML and CSS: <!DOCTYPE HTML><head><meta charset="utf-8"><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/locale/pl.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script><link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/><link rel="stylesheet" href="https://dl.dropboxusercontent.com/s/ggg4zmxzjgz4i9b/style.css"/><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" /></head><body><div id="app"><div class="col-xs-5" id="mail_div"> <label for="mail">Mail:</label> <input v-model="mail" placeholder="E-mail adress:" type="text" class="form-control" id="mail"></div><div class="col-xs-5" id="date_div"> <label for="date">Date:</label> <div class='input-group date' id='datetimepicker1'> <input v-model="date" placeholder="Pick a date:" type='text' class="form-control" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div></div><div class="col-xs-5" id="adress_div"> <label for="adress">Adress:</label> <input v-model="adress" placeholder="Adress of the point:"type='text' class="form-control" id="adress"></div> <div class="col-xs-5" id="company_div"> <label for="company">Company:</label> <input v-model="company" placeholder="Company name:"type='text' class="form-control" id="company"></div> <div class="col-xs-5" id="fliers_div"> <label for="fliers">Number:</label> <input v-model="fliers" placeholder="Write the number:" type='number' class="form-control" id="fliers"> </div> <div id="table"><table class="table"> <thead> <th scope="col">Mail</th> <th scope="col">Date</th> <th scope="col">Adress</th> <th scope="col">Company</th> <th scope="col">Number</th> </thead> <tbody> <tr> <th scope="row">{{ mail }}</th> <td>{{ date }}</td> <td>{{ adress }}</td> <td>{{ company }}</td> <td>{{ fliers }}</td> </tr> </tbody></table></div><div id="button"> <div id="button_container_1"> <button type="button" class="btn btn-primary">Add a row</button> </div> <div id="button_container_2"> <button type="button" class="btn btn-success">Download</button> </div></div></div><script src="https://dl.dropboxusercontent.com/s/3cml0fff7nbfpot/script.js"></script><script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker({locale:'pl'}); });</script></body> And here's my .js file, which is not doing a lot so far: var app = new Vue({ el: '#app', data: { mail:'', date:'', adress:'', company:'', fliers:''}}) This code updates the row of the table dynamically when I submit data. The effect I want to achieve should let me enter the data for more rows after pressing the blue button. How to do this using vue.js? I've found some tutorials for dynamic tables in vue.js, but I haven't been able to found easy to grasp solutions for my case. Now provide the response and nothing else.
You should make the following changes: Declare an array in the data property (lets call it rowData ) Declare a method in methods: (lets call it addItem ) Inside the method, populate a javascript object from the attributes(mail, date, address) Push the object in the rowData array and clear the model attributes var app = new Vue({ el: '#app', data: { mail:'', date:'', adress:'', company:'', fliers:'', rowData:[] //the declared array }, methods:{ addItem(){ var my_object = { mail:this.mail, date:this.date, adress:this.adress, company: this.company, fliers: this.fliers }; this.rowData.push(my_object) this.mail = ''; this.date = ''; this.adress = ''; this.company = ''; this.fliers = ''; } }}) Then update your html like this: <tr v-for="item in rowData" > <th scope="row">{{ item.mail }}</th> <td>{{ item.date }}</td> <td>{{ item.adress }}</td> <td>{{ item.company }}</td> <td>{{ item.fliers }}</td></tr> Every time you push a new object to the rowData array, VueJs will automatically detect and render a new row in the table.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52211682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7259299/']}
jdg_71209
stackexchange
llm_judgeable_groundtruth_similarity
903103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This concept seems to trouble me. Why does an NSError object need its pointer passed to a method that is modifying the object? For instance, wouldn't just passing a reference to the error do the same thing? NSError *anError;[myObjc doStuff:withAnotherObj error:error]; and then in doStuff: - (void)doStuff:(id)withAnotherObjc error:(NSError *)error { // something went bad! [error doSomethingToTheObject]; } Why doesn't the above work like most other object messaging patterns work? Why must instead we use error:(NSError **)error? Now provide the response and nothing else.
The NSError** pattern is used when a method normally returns some value but instead may need to return an error object (of type NSError* ) if it fails. In Objective-C a method can only return one type of object, but this is a case where you want to return two. In C-like languages when you need to return an extra value you ask for a pointer to a value of that type, so to return an NSError* you need an NSError** parameter. A more realistic example would be this: // The method should return something, because otherwise it could just return// NSError* directly and the error argument wouldn't be necessary- (NSArray *)doStuffWithObject:(id)obj error:(NSError **)error{ NSArray *result = ...; // Do some work that might fail if (result != nil) { return result; } else { // Something went bad! // The caller might pass NULL for `error` if they don't care about // the result, so check for NULL before dereferencing it if (error != NULL) { *error = [NSError errorWithDomain:...]; } return nil; // The caller knows to check error if I return nil }} If you only had an NSError* parameter instead of an NSError** then doStuff would never be able to pass the error object back to its caller.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/903103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40882/']}
jdg_71210
stackexchange
llm_judgeable_groundtruth_similarity
8685002
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried it with findwindow and process but it didn't work, how can I find a specific button ? For example I have the button class AfxWnd90u and the instance 21 . I want to check if this button is visible. I tried it with this code, but I couldn't find the button. I think I made a mistake with the instance. Between I didn't use findwindow here because I experimented a little bit. //////IMPORTANT/////////////System.Diagnostics.Process[] move = System.Diagnostics.Process.GetProcessesByName("PartyGaming");ArrayList save = new ArrayList();RECT rct = new RECT();listBox1.Items.Add(move.Length);List<System.Diagnostics.Process> process = new List<System.Diagnostics.Process>();// use only the process with the button AfxWnd90u21for (int i = 0; i < move.Length;++i ) { IntPtr hCheck = FindWindowEx(move[i].MainWindowHandle, IntPtr.Zero, "AfxWnd90u21", null); //if button is visible if (hCheck != IntPtr.Zero) process.Add(move[i]); //////IMPORTANT/////////////} Now provide the response and nothing else.
I believe a combination of FindWindow and SendMessage Windows API functions will give you want you want. The tricky part will be discovering the window class names, but something like WinSpy++ could help you there. Here's a sample of how to use the API. Open Notepad.exe a few times, type in some text and then run this sample. using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.InteropServices;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { List<WinText> windows = new List<WinText>(); //find the "first" window IntPtr hWnd = FindWindow("notepad", null); while (hWnd != IntPtr.Zero) { //find the control window that has the text IntPtr hEdit = FindWindowEx(hWnd, IntPtr.Zero, "edit", null); //initialize the buffer. using a StringBuilder here System.Text.StringBuilder sb = new System.Text.StringBuilder(255); // or length from call with GETTEXTLENGTH //get the text from the child control int RetVal = SendMessage(hEdit, WM_GETTEXT, sb.Capacity, sb); windows.Add(new WinText() { hWnd = hWnd, Text = sb.ToString() }); //find the next window hWnd = FindWindowEx(IntPtr.Zero, hWnd, "notepad", null); } //do something clever windows.OrderBy(x => x.Text).ToList().ForEach(y => Console.Write("{0} = {1}\n", y.hWnd, y.Text)); Console.Write("\n\nFound {0} window(s).", windows.Count); Console.ReadKey(); } private struct WinText { public IntPtr hWnd; public string Text; } const int WM_GETTEXT = 0x0D; const int WM_GETTEXTLENGTH = 0x0E; [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] public static extern int SendMessage(IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8685002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/944430/']}
jdg_71211
stackexchange
llm_judgeable_groundtruth_similarity
30440
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 want to be sure to understand well the situation where SSL certificate is compromised. If I ask for a rekey, I suppose the old certificate will remain valid.The future communications with the new certificate will be valid but I will have potentially pishing problems. The best IMHO is to revoke the certificate and use a new instead. Thanks for advices Now provide the response and nothing else.
"Rekey" is a term which is usually employed when obtaining a new certificate: it means that you want the new certificate to use a newly generated key pair, instead of reusing the same public key as was in a previous certificate. "Revocation" is the act of declaring, on the CA side, that a given certificate should no longer be considered as valid (it is a bit like having the certificate expire earlier than its nominal expiry date). When a certificate is revoked, its serial number appears in the CRL published by the CA (that's how the rest of the World is made aware of the revocation). The two actions are mostly orthogonal to each other, but there are situations where you want both. In particular, if your private key was stolen: You need to have the certificate revoked. Key compromise is the main reason why we need a revocation system. This should prevent usage of the stolen key to power a fake server (that is, assuming that the client browsers obtain and honour revocation information, which is a rather bold assumption). Since the certificate was revoked, you can no longer use it for your own server (it blocks you and the thief alike), so you probably need a new certificate. And since the old key was stolen, you will want a new one, so that's a "rekey" situation as well. Some CA will automatically trigger revocation when you ask for a new certificate with a new key pair; some other will not. Some will talk about the old certificate being "deactivated" which may be the same as "revocation", or could be something else (e.g. something like an account close on their side), depending on how much they abuse terminology. Any decent CA ought to have a specific procedure for key compromise which will do things correctly.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/30440', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1284/']}
jdg_71212
stackexchange
llm_judgeable_groundtruth_similarity
409791
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 need to encrypt and be able to decrypt files with openssl , currently I do this simply with: openssl enc -aes-256-cbc -salt -in "$input_filename" -out "$output_filename" and the decryption with: openssl enc -aes-256-cbc -d -salt -in "$input_filename" -out "$output_filename" But with large files, I would like to see progress. I tried different variations of the following (decryption): pv "$input_filename" | openssl enc -aes-256-cbc -d -salt | pv > "$output_filename" But this fails to ask me for a password. I am unsure as to how to go about it? EDIT1: I found this tar over openssl : https://stackoverflow.com/a/24704457/1997354 While it could be extremely helpful, I don't get it much. EDIT2: Regarding the named pipe: It almost works. Except for the blinking progress, which I can't show you obviously and the final result looking like this: enter aes-256-cbc decryption password:1.25GiB 0:00:16 [75.9MiB/s] [==============================================================================================================================================================================================>] 100% 1.25GiB 0:00:10 [ 126MiB/s] [ <=> ] Now provide the response and nothing else.
You should try openssl enc -aes-256-cbc -d -salt -in "$input_filename" | pv -W >> "$output_filename" From the Manual : -W, --wait : Wait until the first byte has been transferred before showing any progress information or calculating any ETAs. Useful if the program you are piping to or from requires extra information before it starts, eg piping data into gpg(1) or mcrypt(1) which require a passphrase before data can be processed. which is exactly your case. If you need to see the progress bar, for the reason clearly explained by Weijun Zhou in a comment below, you can reverse the order of the commands in the pipe: pv -W "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/409791', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/126755/']}
jdg_71213
stackexchange
llm_judgeable_groundtruth_similarity
27110568
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 make a form where you write a number send it with Jquery and is shown by PHP without refreshing the page ,by far i have this code but if preventDefault() is placed it will post but the content is not shown,also if i remove it, the content is shown but the page will pe refreshed. Javascript: $('#testut').unbind('submit').bind('submit',function(ev) { ev.preventDefault(); $.ajax({ type: 'post', url: 'incerc.php', data: $('form').serialize(), success: function () { $('.success').fadeIn(500); } });});} HTML: Test<br /><?phpif(isset($_POST['test'])) { $test = $_POST['test']; $numar = $_POST['numar']; echo 'Order name:'.$test.'<br />Number:'.$numar.'<br />';} else { echo 'No <br />';}?><div id='testut'> <form id='test' method='post'> <input type='text' name='numar'><br /> <input type='submit' name='test' onclick ='check()' value='Place'><br /> <span class='success' style='display:none'>Order was successfully placed.</span> </form></div> Now provide the response and nothing else.
I would recommend iterating over the entire list. Thankfully, you can use an enhanced for loop: for(String listItem : myArrayList){ if(myString.contains(listItem)){ // do something. }} EDIT To the best of my knowledge, you have to iterate the list somehow. Think about it, how will you know which elements are contained in the list without going through it? EDIT 2 The only way I can see the iteration running quickly is to do the above. The way this is designed, it will break early once you've found a match, without searching any further. You can put your return false statement at the end of looping, because if you have checked the entire list without finding a match, clearly there is none. Here is some more detailed code: public boolean containsAKeyword(String myString, List<String> keywords){ for(String keyword : keywords){ if(myString.contains(keyword)){ return true; } } return false; // Never found match.} EDIT 3 If you're using Kotlin, you can do this with the any method: val containsKeyword = myArrayList.any { it.contains("keyword") }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27110568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3469090/']}
jdg_71214
stackexchange
llm_judgeable_groundtruth_similarity
12346
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 would like to know if there is some formula / graph which would provide / show the efficiency of a certain type of propeller in space. Specifically, I'm interested in the acceleration attainable at certain speeds. I'm writing a science fiction book and I'm trying to make it as correct as possible, fact wise. The propeller I'm talking about is the ion drive Now, my book takes place in a world where fusion power is finally ours. So, please, let us assume that we have unlimited energy so you could power a dozen huge ion drives non stop. OK, there's the question of argon/xenon fuel, let's assume we have 1 year of that. So... the question is... what speed could you reach? If a continuous acceleration of $10\frac{\mathrm{m}}{\mathrm{s}}$ is applied (I put that number because it would also constitute an advantage for my crew - living in Earth's gravity), that would mean that a ship would reach the speed of light in just 347 DAYS But I know that's impossible because the EFFICIENCY of the ion drive would DECREASE as the ship's speed would approach the exhaust speed of the drive's "nozzle" (well, it doesn't have a nozzle per-se, as you can see in Wiki, but anyway...) Please do not fear to elaborate on top of my question. Let's suppose for example that maybe the ion drives of the future have a much higher thrust/efficiency/nozzle exhaust speed. This isn't only about currently POSSIBLE facts but also about THEORETICAL limitations which might be overcome in the future (such as fusion energy). Now provide the response and nothing else.
The principle of relativity says that we can analyze a physical situation from any reference frame, as long as it moves with some constant speed relative to a known inertial frame. Thus, the ion drive does not find it more difficult to accelerate the ship when the ship is "going fast" because the ion drive cannot physically distinguish going fast from going slow. However, if the ion drive is going fast in the reference frame of Earth, then when the ion drive burns, say 1 kg of fuel, it picks up less speed in the Earth frame than it does in the rocket frame due to the relativistic velocity addition law . That velocity addition law is just the angle-addition law for the hyperbolic tangent. So, suppose the ship accelerates by shooting individual ions out the back. Each time it does this, it accelerates the same amount from its own comoving frame. Then from an Earth frame, the $\textrm{arctanh}$ of the rocket's speed increases by the same amount each time. If, as a function of the proper time $\tau$ experienced on the rocket, the acceleration of the rocket is $a(\tau)$ in a comoving frame, there is a quantity called the rapidity of the rocket which increases the way velocity does in Newtonian mechanics. The rapidity $\theta$ will be $\theta(\tau) = \int_0^\tau a(\tau) d\tau$, and the velocity is then $v(\tau) = \tanh\theta$. Specifically, if $a = g$, the velocity is $$v(\tau) = \tanh(g\tau)$$ When one year of time has passed on the rocket, its velocity relative to Earth will be $\tanh(1.05) = 0.78$, or 78% the speed of light. The limit of the $\tanh$ function is one as $\tau \to \infty$, so the rocket never gets to light speed. A more important limiting factor is the fuel. If the rocket carries all its fuel, then once it burns through it all, it can't go any more. Fusion isn't a way around this because by $E=mc^2$ there is a limited energy you can get from a given mass of fuel. If a fraction $f$ of the rocket is fuel, when the fuel is all burned, the momentum of the rocket will be $\gamma m (1-f) \beta$, with $m$ the original mass. The energy of the rocket is $\gamma m (1-f)$. Similar relations hold for the fuel. The conservation of momentum and energy give $$m = \gamma m (1-f) + E_{fuel}$$ $$0 = \gamma m \beta (1-f) + p_{fuel}$$ $E_{fuel}$ and $p_{fuel}$ are the energy and momentum of the fuel after burning. Solving for $\beta$ gives $$\beta = \frac{-p_{fuel}}{m - E_{fuel}}$$ The minus sign shows that the fuel and rocket go opposite directions. To maximize $\beta$, we want to make $p_{fuel}$ as large as possible subject to a fixed $E_{fuel}$. This means that we want the speed of the fuel as high as possible, so assume the fuel is massless with $\beta_{fuel} = 1$ and $p_{fuel} = -E_{fuel}$. Plugging this into the previous equations and doing some algebra, I got $$\beta = \frac{1 - (1-f)^2}{1 + (1-f)^2}$$ Even if half the rocket's original mass were fuel, it would only get to 3/5 the speed of light.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/12346', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2414/']}
jdg_71215
stackexchange
llm_judgeable_groundtruth_similarity
29051809
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 instantiate an object from a class, an object is saved in the java heap. When I save the object by serializing it and I later deserialize the object, do I understand correctly that the object will now have a new heap address but will still be the EXACT SAME instance of the class. Now provide the response and nothing else.
The answer to your question cannot be just a yes or no. To analyze the concept is required. I will suggest you to take a pencil and paper and do it yourself keeping the below points in mind. All java objects are created in java heap (except for some which arekept in pool but for you question we will skip them for now). When an instance of a class is created using new keyword,deserialization, clone method or reflection api's newInstance method,a new space in heap is reserved and we assign it to a object reference(the reference can be of the object's class or one of the superclasses of the object's class - again we can ignore this detail fornow). When you save your object, the object's state is saved with all it'snested objects. When you deserialize your object, the object will create a new entryin heap which will not have any references to any of the objects. Look at the below diagram for picturizing the above concept in you context: All the object A references are pointing to one heap entry and if you try objectB.getObjectA() == objectC.getObjectA() or any other such operation, you will get true. Case 1 When you save the objects separately and deserialize them here is what happens in the heap: As you can figure out now that objectBcopy.getObjectA() == objectCcopy.getObjectA() will not return true as the references of object A for the copied objects are no more same. Case 2 On the contrary, when you save the objects in a single file and deserialize them later, here is what happens in the heap: As you can figure out now that objectBcopy.getObjectA() == objectCcopy.getObjectA() will now be true as the references of object A copy are same, but that's still a new copy of object A. A quick program to support my deductions (Case 1 and Case 2): public class Test{ public static void main (String args[]) throws IOException, ClassNotFoundException{ A a = new A(); B b = new B(); b.a = a; C c = new C(); c.a = a; System.out.println("b.a == c.a is " + (b.a == c.a)); // Case 1 - when two diferent files are used to write the objects FileOutputStream fout = new FileOutputStream("c:\\b.ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(b); oos.close(); fout.close(); fout = new FileOutputStream("c:\\c.ser"); oos = new ObjectOutputStream(fout); oos.writeObject(c); oos.close(); fout.close(); FileInputStream fileIn = new FileInputStream("c:\\b.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); B bCopy = (B) in.readObject(); in.close(); fileIn.close(); fileIn = new FileInputStream("c:\\c.ser"); in = new ObjectInputStream(fileIn); C cCopy = (C) in.readObject(); in.close(); fileIn.close(); System.out.println("Case 1 - bCopy.a == cCopy.a is " + (bCopy.a == cCopy.a)); // Case 2 - when both the objects are saved in the same file fout = new FileOutputStream("c:\\both.ser"); oos = new ObjectOutputStream(fout); oos.writeObject(b); oos.writeObject(c); oos.close(); fout.close(); fileIn = new FileInputStream("c:\\both.ser"); in = new ObjectInputStream(fileIn); bCopy = (B) in.readObject(); cCopy = (C) in.readObject(); in.close(); fileIn.close(); System.out.println("Case 2 - bCopy.a == cCopy.a is " + (bCopy.a == cCopy.a)); }}class A implements Serializable{}class B implements Serializable{ A a;}class C implements Serializable{ A a;} With the following output: b.a == c.a is true Case 1 - bCopy.a == cCopy.a is false Case 2 - bCopy.a == cCopy.a is true
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29051809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4670721/']}
jdg_71216
stackexchange
llm_judgeable_groundtruth_similarity
45040
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: According to Ohm's law , if there is a potential difference, $V$, across a resistor then there is a current, $I$, flowing through it. Since we assume that points along the connecting wire are at the same potential, how can current, $I$ flow between points at the same potential, $V$? Now provide the response and nothing else.
When there is no resistance, as is the case with an ideal wire, any value of current satisfies Ohm's Law: $V = I R$ since both $V=0$ and $R=0$. UPDATE: But isn't V is like what causes the current? Perhaps a mechanical analogy of the resistor will help. Consider the dashpot where the velocity of the arm is analogous to current while the force acting on the arm is analogous to voltage. The relationship between the force and velocity for a dashpot with impedance $\mu$ is: $F = \mu v $ This has the form of Ohm's law and is in fact its mechanical analog. If the dashpot impedance is zero, the arm can have any velocity even though the force is zero. Physically, this seems reasonable since, when there is no external or damping force acting on the arm, we expect that the motion will be unchanging. Similarly, if there is a steady current through a zero resistance (an ideal wire), we shouldn't expect that a voltage is required to maintain that current, we should expect that the current will be unchanging.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/45040', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4521/']}
jdg_71217
stackexchange
llm_judgeable_groundtruth_similarity
93713
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the growth rate in n of the denominator of the rational $r_n$, $n=1,2,3,\ldots$ in $1>r_n>1-e^{-n}$ with the smallest denominator? If $I_n$ is a (sufficiently random) sequence of disjoint intervals in R>0, whose lenght (ie elementary measure) is given by a f(n) decreasing to 0, with $\sum_n f(n) = \infty$, what is the expected growth rate of the lowest denominator of all rationals in $I_n$ ? Now provide the response and nothing else.
It is best to index the rows and columns from $0$ to $2^m-1$, so $X_{ij}=i\,XOR\,j$. We have a recursive construction for these matrices. Let $J$ denote the matrix of all ones.Let $X_m$ denote the matrix of size $2^m\times2^m$. Then we have in the block form$$X_{m+1}=\pmatrix{X_m&X_m+2^mJ\cr X_m+2^mJ&X_m\cr}$$for all natural numbers $m$. On any row of $X_m$ all the integers in the range $[0,2^m-1]$ appear exactly once, so all the row sums are $\sum_{j=0}^{2^m-1}j=\frac12\,2^m(2^m-1)=2^{m-1}(2^m-1)$, and thus the vector $(1,\ldots,1)^T$ is an eigenvector belonging to this eigenvalue. Assume that $v_m\in\mathbf{R}^{2^m}$ is an eigenvector of $X_m$ belonging to an eigenvalue $\lambda$. Furthermore, assume that either the entries of $v_m$ are all equal to one or that their sum is equal to zero. This latter requirement implies that $v_m$ is an eigenvector of the matrix $J$ belonging to the eigenvalue $\mu=2^m$ or to the eigenvalue $\mu=0$ depending which case applies. Given this we can then construct two eigenvectors of $X_{m+1}$: $v_{m+1}^+=(v_m|v_m)$ and$v_{m+1}^-=(v_m|-v_m)$ by replicating the components of $v_m$ either without or with a sign change. We then see that $v_{m+1}^+$ is an eigenvector of $X_{m+1}$ belonging to the eigenvalue $\lambda+(\lambda+2^m\mu)=2\lambda+2^m\mu$, and $v_{m+1}^-$ is an eigenvector belonging to the eigenvalue $\lambda-(\lambda+2^m\mu)=-2^m\mu$. Using this construction we can then recursively construct $2^{m+1}$ linearly independent eigenvectors of $X_{m+1}$ given $2^m$ linearly independent eigenvectors of $X_m$. This is because the component sum of $v_{m+1}^-$ is always equal to zero, and the component sum of $v_{m+1}^+$ is either zero (if that was the case with $v_m$) or it consists of all ones (ditto), so the assumption that these will be eigenvectors of $J$ will always hold. The starting point $m=0$ is covered by the all one vector, so basically this explains all the observations. Most of the time $\mu=0$, so we get the doubles of the eigenvalues of $X_{m+1}$ (with $v_{m+1}^+$) as well as zero (with $v_{m+1}^-$). The case where $\mu=2^m$ yields the positive eigenvalue (with $v_{m+1}^+$) as well as the negative eigenvalue with largest absolute value (with $v_{m+1}^-$).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/93713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21685/']}
jdg_71218
stackexchange
llm_judgeable_groundtruth_similarity
368695
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: // Car states : START, RUN, STOP// START ==> RUN ==> STOP ==> Write// CarFromStartToStop() :// Car is initailly at STOP phase. // We start the and car comes in RUN phase.// Then at the end car comes in STOP phase.// WriteCarResults() : // Writes car's current status. eg : oil status, odometer etc.class Info1 {public: void Run(){ CarFromStartToStop(); WriteCarResults(); }private: void CarFromStartTopStop(){ // Its own impelementation of how car will run. } void WriteCarResults(){ // Write car's current status for running from start to finish. } Car c;}; // RUN ==> STOP ==> Write// CarFromRuningToStop() :// The car is in RUN phase.// Then at the end car comes in STOP phase.// WriteCarResults() : // Writes car's current status. eg : oil status, odometer etc.class Info2 {public: void Run(){ CarFromRuningToStop(); WriteCarResults(); }private: void CarFromRuningToStop(){ // Its own impelementation of how car will run. } void WriteCarResults(){ // Write car's current status for running from start to finish. } Car c;}; I have these two class. At first glance I would say we could use inheritance. They more of less do the same thing. They run the car and write data. But when I look close, I am not sure if inheritance is good choise. Why? Because the only method that are common (use same exact code) between two class is WriteCarResults. Other then that there is no code that are common. My question: How can I make sure that I dont have to write the code that are common between the class(WriteCarResults). Options: Use inheritance (for some reason I feel this approach is reallycontrived). Pull the writeCarResults() function out of the class. (I like thisapproach but not sure if this is a good one. Another problem I feelwith this approach is WriteCarResults() should be part of the Info*class). Please let me know if there is any design that would let me not write writeCarResults() function twice. Now provide the response and nothing else.
Believe it or not, what is truly hampering your design here is the names. Info1 and Info2 are terribly meaningless, Run() steals its name from one of the car's phases yet covers all phases and more, and worst of all CarFromStartToStop() and CarFromRunningToStop() both leak implementation details making polymorphism imposible, whether you use inheritance or not. A name should convey intent. It should ensure that what is found inside is not a surprise. But it should not tell you how . If it says how then implementation cannot change. Polymorphism means the implementation can change. Here's what happens when you follow these naming principles: class StartToStopSimulator {public: void Simulate(){ OperateCar(); WriteCarResults(); }private: void OperateCar(){ c.Start(); c.Run(); c.Stop(); } void WriteCarResults(){ c.Status(outputPort); } Car c;}; class RunningToStopSimulator {public: void Simulate(){ OperateCar(); WriteCarResults(); }private: void OperateCar(){ c.Run(); c.Stop(); } void WriteCarResults(){ c.Status(outputPort); } Car c;}; With these new names we're ready to refactor to use polymorphism. class Simulator {public: void Simulate(){ OperateCar(); WriteCarResults(); }private: void OperateCar(){ operator.Operate(c); } void WriteCarResults(){ c.Status(outputPort); } Car c; Operator operator; Output outputPort;}; And you'd construct it like this: Simulator sim = new Simulator( new CarCamaro(), new OperatorSRS(), new OutputConsole() ); Now the Operator used decides what steps should be taken to operate the car. The two Operator classes will be different then the previous classes in that they will focus ONLY on the phases. This is polymorphism through composition and delegation but you could have used inheritance here if you'd really wanted to. Composition usually proves to be more flexible. It just requires a little more keyboard typing.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/368695', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/301729/']}
jdg_71219
stackexchange
llm_judgeable_groundtruth_similarity
932241
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This sounds like a daft question at first, but bear with me. It is common knowledge that binaries for one CPU architecture do not run on others. So for example it is impossible to run (without a compatibility layer of some kind), an x86 binary on a sparc64 chip. The instruction sets are different, so clearly that will not work. But when the binary is for the same CPU, but for a different operating system, which part of the code prevents execution from being possible. For example, running an x86 Solaris binary on an x86 Linux box. I am assuming that there is some kind of platform specific stub which relates to the run-time linker or process scheduler? I would be interested to know. Thanks. Now provide the response and nothing else.
There are a number of reasons. The main ones, ordered in "distance from the metal" are: The operating systems may have different binary formats for executable files. In this case you will not be able to load the binary in the first place. The program may use another method to indicate they wish to place a system call (e.g. INT21 vs INT80). The program may rely on system calls that are not present in the other OS (e.g. dlopen()) The program may rely on the standard library not present on the other OS. The program may rely on other libraries that are not available on the other OS. Of course there are many more ways a program running in an unexpected environment can fail spectacularly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/932241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109414/']}
jdg_71220
stackexchange
llm_judgeable_groundtruth_similarity
45574100
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 doing an MVC 5 Application, and I am calling a API controller method that is in another Solution. I am using HttpClient() . and I am calling PostAsJsonAsync with some parameters, an instance of a class. It looks like this. string apiUrl = "localhost:8080/api/";ContactWF contactWF = new contactWF();contactWF.contact_id=0;contactWF.UserOrigin_id=20006contactWF.ProcessState_id=2;using (HttpClient client = new HttpClient()){ client.BaseAddress = new Uri(apiUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl + "Contact/Method", contactWF); if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<int>().Result; }} My API controller method is like this. [ActionName("Method")][HttpGet]public int Method([FromBody] ContactWF userwf){ return 10;} It Works fine... My problem is when I try Serialized the parameter class instance I replace line HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl + "Contact/Method", contactWF); with this one string jsonData = JsonConvert.SerializeObject(contactWF);HttpResponseMessage response = client.PostAsJsonAsync("api/Contact/Method", jsonData).Result; I've got an Error:405 ... It looks like the Json string it is not recognize as a Parameter. My Json string looks like this. "{\"Contact_id\":0,\"Description\":null,\"ProcessState_id\":2,\"Type_id\":0,\"Object_id\":0,\"Parent_id\":null}" that is ContactWD class converter to json. What´s wrong? Now provide the response and nothing else.
The idea would be to create an axes ax and a twin axes ax2 = ax.twinx() and to then plot each dataframe to one of them, df.plot(ax=ax) and df2.plot(ax=ax2) . import numpy as npimport pandas as pdimport matplotlib.pyplot as plta = np.linspace(-5,5, 11)data1 = np.sort(np.random.rand(len(a),5))data1[:,0] =a data2 = np.sort(np.random.rand(len(a),5))*10data2[:,0] =a df = pd.DataFrame(data1, columns=["A", "B1", "C1", "D1", "E1"])df2 = pd.DataFrame(data2, columns=["A", "B2", "C2", "D2", "E2"])fig, ax = plt.subplots()ax2 = ax.twinx()df.plot(x="A", y=["B1", "C1", "D1", "E1"], ax=ax)df2.plot(x="A", y=["B2", "C2", "D2", "E2"], ax=ax2, ls="--")plt.show() If instead you want to have two separate plots (the question is not clear on this point), you can do it by fig, (ax, ax2) = plt.subplots(ncols=2) and removing the twinx call.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45574100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3047200/']}
jdg_71221
stackexchange
llm_judgeable_groundtruth_similarity
49735270
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 get the sum of a specific class of input fields and dump the sum into a separate input field and its not working as expected. When I try it with a single input field to add, it works, but when there are multiple inputs with the same class to sum together, it results in NaN. Here is a demo of what I am trying to do and it NOT working. https://www.w3schools.com/code/tryit.asp?filename=FQ7RM8CBI064 Can someone tell me what I am doing wrong? Now provide the response and nothing else.
Your loop is not bad, but you can simplify it: public static <T> int indexOf(List<T> list, Predicate<? super T> predicate) { for(ListIterator<T> iter = list.listIterator(); iter.hasNext(); ) if(predicate.test(iter.next())) return iter.previousIndex(); return -1;} You can use a stream like public static <T> int indexOf(List<T> list, Predicate<? super T> predicate) { return IntStream.range(0, list.size()) .filter(ix -> predicate.test(list.get(ix))) .findFirst().orElse(-1);} but this will become quite inefficient if the list is large and not random access. I’d stay with the loop. Starting with Java 9, there’s the alternative public static <T> int indexOf(List<T> list, Predicate<? super T> predicate) { long noMatchPrefix = list.stream().takeWhile(predicate.negate()).count(); return noMatchPrefix == list.size()? -1: (int) noMatchPrefix;} which is really expressive regarding the task “count the elements up to the first match”, but is not exactly the same as “get the index of the first matching element”, which shows when there is no match, so we need to replace the result with -1 then.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49735270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9619993/']}
jdg_71222
stackexchange
llm_judgeable_groundtruth_similarity
1119131
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking at the wikipedia page for Dependent Types and I am getting stuck trying to understand the definition. It says, ... given a type $A:U$ in a universe of types $U$, one may have a family of types $B:A\rightarrow U$ which [sic] assigns to each term $a:A$ a type $B(a):U$. So far, so good. I read from this that a "family of types" $B$ is an ordinary function from a type $A$ to a universe of types $U$, and I deduce that the members $a$ of a type $A$ are called "terms." I get horked on the next sentence: A function whose codomain varies depending on its argument is a dependent function , ... As I read it, $B$ cannot be such a function because its codomain $U$ does not vary depending on its argument. The value of $B(a)$, of course, varies depending on its argument $a$, but not the codomain of $B$, which is always the same universe $U$. Perhaps the writer means that the value $B(a)$ at input $a$ is, in turn, the "function whose codomain varies depending on its argument." If so, then $B(a)=u$ is a function whose codomain varies depending on its argument, and that would mean that each type $u$ in $U$ is a function whose codomain varies depending on its argument, but now I'm lost, because I don't know enough about types, in general, to complete the thought. Now provide the response and nothing else.
The article is trying to explain the notion of a dependent product, but the passage you quote is not very precise. To use set-theoretic terms, if $A$ is a set and $B$ is a set-valued function on $A$, the dependent product:$$\prod_{x:A} B(x)$$denotes the set of all functions $f: A \rightarrow U$, where $U$ is the union of the sets $B(x)$, such that for each $x \in A$, $f(x) \in B(x)$. A member of the dependent product, which the wikipedia article calls a dependent function, is a function equipped with a fine-grained description of its codomain giving a "bound" $B(x)$ on the value of $f(x)$ for each $x$ in its domain.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1119131', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14168/']}
jdg_71223
stackexchange
llm_judgeable_groundtruth_similarity
1085627
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a Django app that has activities and objects that have foreign keys to the User object that is defined in django.contrib.auth.models. In doing this, I get the username property of the user, which is the login id. Since the User object stores the full name, how do I make a ChoiceField on an form display the full names of the user, not the username, but still link it back to the correct User object after the form is Posted? Now provide the response and nothing else.
Not absolutely sure the following works if you have a regular ChoiceField but if you have a modelChoiceField you can do the following: class UserModelChoiceField(forms.ModelChoiceField): """ Extend ModelChoiceField for users so that the choices are listed as 'first_name last_name (username)' instead of just 'username'. """ def label_from_instance(self, obj): return "%s (%s)" % (obj.get_full_name(), obj.username)class XYZForm(forms.Form): ... xyz = UserModelChoiceField(User.objects.all())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1085627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40529/']}
jdg_71224
stackexchange
llm_judgeable_groundtruth_similarity
436117
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: Why can't CAN baud rate increase beyond 1Mbps Now provide the response and nothing else.
From Controller Area Network Physical Layer Requirements CAN is an open collector technology – the protocol could not work otherwise. This means that the recessive state of a CAN transceiver is not actively driven. The termination resistors together with transceiver input capacitance and cable capacitance create an RC time-constant discharge when an actively-driven dominant bit on the bus transitions to an un-driven recessive bit. For signaling rates greater than CAN's 1Mbps, a technology that actively drives the bus in both states such as RS-485 is required to facilitate the bus transitions required for high-speed signaling rates. Ultimately, the answer to the question is how the CAN protocol is implemented at a physical level. Change that protocol and a higher data rate can be used. From Understanding Microchip’s CAN Module Bit Timing : ... the CAN protocol implements a non-destructive bitwise arbitration scheme that allows multiple nodes to arbitrate for control of the bus. Therefore, it is necessary for all the nodes to detect/ sample the bits within the same bit time. The relationship between propagation delay and oscillator tolerance effect both the CAN data rate and the bus length. Two masters on either end of the CAN bus must be able to communicate and arbitrate which one has the bus, while each are on the bus at the same time. If the bus length is 30 m, the time it takes to propagate the signal over the bus is: $$t_{BUS} = 30\ m @ 5.5\ ns/m = 165\ ns$$ Assuming the input comparator delay is \$t_{CMP}\$ = 40 ns and the output driver delay is \$t_{DRV}\$ = 60 ns for all devices. The round trip time for a bit on the physical bus will be: $$t_{PROP} = 2(t_{BUS} + t_{CMP} + t_{DRV}) = 2 (165\ ns + 40\ ns + 60\ ns) = 530\ ns$$ $$TQ = 530\ ns/6 = 88.33\ ns $$ $$t_{BIT} = 10\times TQ = 883.3\ ns $$ $$ f = 1/t_{BIT} = 1 / 883.3\ ns = 1.13\ MHz $$ The maximum rate is governed by bus length, line capacitance, connected nodes and the drivers selected by the protocol. In principle at 30 m, CAN (ISO 11898) could do 1.13 Mbps if everything was perfect. The longer the bus, the slower the data rate. But a shorter bus would mean a higher rate. CAN bit rate vs. bus length: Both referenced documents go into this at greater length. CAN (ISO 11898) can transfer up to 8 bytes at 1 Mbps with a protocol based in the 80's. With today's vehicles, there is a need to transfer more data (64 byte packets), but at 1 Mbps, 64 bytes would take up to large of a time slot, possibly delaying vital data. CAN FD (Flexible Data-Rate) is an extension to the original CAN bus protocol (ISO 11898-1). It is meant to run on existing CAN buses and eventually replace CAN. The protocol starts out at the CAN 1 Mbps (500 kbps, etc.), with the possible arbitration process between multiple CAN and CAN FD masters, but when the CAN FD master obtains the bus, the data transfer rate accelerates to 5 Mbps to CAN FD slaves. At this rate, 64 bytes can be transferred in less time than an 8 byte CAN 1 Mbps packet. This means there is no timing conflict with existing CAN transfers. Once the CAN FD master gives up the bus, any CAN or CAN FD master can obtain bus. From CAN FD EXPLAINED - A SIMPLE INTRO (2019) : The true answer depends upon the 1 Mbps arbitration process for a 40m CAN bus, but once the bus is obtained the bandwidth can be accelerated dependent on bus length, line capacitance, number of connected nodes and the drivers. The CAN FD bandwidth is 3-8 times the classic CAN bandwidth.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/436117', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/220765/']}
jdg_71225
stackexchange
llm_judgeable_groundtruth_similarity
45756011
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 get the value of say "ip" from my following curl output: { "type":"example", "data":{ "name":"abc", "labels":{ "key":"value" } }, "subsets":[ { "addresses":[ { "ip":"192.168.103.178" } ], "ports":[ { "port":80 } ] } ]} I have found many examples in the internet to parse json output of curl requests and I have written the following code, but that doesn't seem to return me the value of say "ip" package mainimport ("encoding/json""fmt""io/ioutil""log""net/http""time")type svc struct { Ip string `json:"ip"`}func main() {url := "http://myurl.com"testClient := http.Client{ Timeout: time.Second * 2, // Maximum of 2 secs}req, err := http.NewRequest(http.MethodGet, url, nil)if err != nil { log.Fatal(err)}res, getErr := testClient.Do(req)if getErr != nil { log.Fatal(getErr)}body, readErr := ioutil.ReadAll(res.Body)if readErr != nil { log.Fatal(readErr)}svc1 := svc{}jsonErr := json.Unmarshal(body, &svc1)if jsonErr != nil { log.Fatal(jsonErr)}fmt.Println(svc1.Ip)} I would appreciate if anyone could provide me hints on what I need to add to my code to get the value of say "ip". Now provide the response and nothing else.
You can create structs which reflect your json structure and then decode your json. package mainimport ( "bytes" "encoding/json" "fmt" "log")type Example struct { Type string `json:"type,omitempty"` Subsets []Subset `json:"subsets,omitempty"`}type Subset struct { Addresses []Address `json:"addresses,omitempty"`}type Address struct { IP string `json:"IP,omitempty"`} func main() { m := []byte(`{"type":"example","data": {"name": "abc","labels": {"key": "value"}},"subsets": [{"addresses": [{"ip": "192.168.103.178"}],"ports": [{"port": 80}]}]}`) r := bytes.NewReader(m) decoder := json.NewDecoder(r) val := &Example{} err := decoder.Decode(val) if err != nil { log.Fatal(err) } // If you want to read a response body // decoder := json.NewDecoder(res.Body) // err := decoder.Decode(val) // Subsets is a slice so you must loop over it for _, s := range val.Subsets { // within Subsets, address is also a slice // then you can access each IP from type Address for _, a := range s.Addresses { fmt.Println(a.IP) } }} The output would be: 192.168.103.178 By decoding this to a struct, you can loop over any slice and not limit yourself to one IP Example here: https://play.golang.org/p/sWA9qBWljA
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45756011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4949839/']}
jdg_71226
stackexchange
llm_judgeable_groundtruth_similarity
1633790
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: Does $x^{y^z}$ equal $x^{(y^z)}$? If so, why? Why not simply apply the order of the operation from left to right? Meaning $x^{y^z}$ equals $(x^y)^z$? I always get confused with this and I don't understand the underlying rule. Any help would be appreciated! Now provide the response and nothing else.
In the usual computer science jargon, exponentiation in mathematics is right-associative , which means that $x^{y^z}$ should be read as $x^{(y^z)}$, not $(x^y)^z$. In expositions of the BODMAS rules that are careful enough to address this question, the rule is to evaluate the top exponent first. One way to help remember this convention is to note that $(x^y)^z = x^{yz}$ (i.e., $x^{(yz)}$), so it would be silly if out of the two possibilities, $x^{y^z}$ meant the one that can be expressed without using two tiers of superscripts.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1633790', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245761/']}
jdg_71227
stackexchange
llm_judgeable_groundtruth_similarity
8914070
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to mimic the facebook ios side menu and have it working however the issue I am having is that I cannot send the sidemenu to the back as discussed in another question on SO iphone facebook side menu using objective c . I'm not using the library suggested but instead using the code that was suggested. I have - (void)viewDidLoad{ NSLog(@"View Did Load is running"); activitySpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; activitySpinner.frame = CGRectMake(0.0, 0.0, 40.0, 40.0); activitySpinner.center = self.view.center; [self.view addSubview:activitySpinner]; SideMenuView *myDelegate = [[SideMenuView alloc] init]; [self setSideMenuDelegate:myDelegate]; //set the delegate's currentViewController property so that we can add a subview to this View. [sideMenuDelegate setCurrentViewController:self]; //sideMenu = [[SideMenuView alloc] initWithNibName:@"SideMenuView" bundle:nil]; [self.view addSubview:myDelegate.view]; [self.view sendSubviewToBack:myDelegate.view]; [super viewDidLoad]; self.searchDisplayController.searchBar.scopeButtonTitles = nil; [self fetchCustomers]; // Do any additional setup after loading the view, typically from a nib.} In my controller where I want the side menu but the view seems to get loaded into the current view instead of just going to the back so it can be seen when I slide the menu over. Can someone help me get the myDelegate view to the back? Now provide the response and nothing else.
I am not entirely sure what you are trying to accomplish, so I have to guess. It sounds like you want to hide myDelegate.view behind self.view . It won't work this way. sendSubviewToBack: sends the subview to the back of the view hierarchy of the sender , in your case, self.view . It will never send a subview below its superview. You can instead add myDelegate.view as a subview to self.view s superview, and put it behind self.view : [[self.view superview] insertSubview:myDelegate.view belowSubview:self.view];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8914070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/442695/']}
jdg_71228
stackexchange
llm_judgeable_groundtruth_similarity
37213
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 stack of tiff files. When imported to Mathematica , they form a $P \times M \times N$ matrix, where $P$ is the number of single images in the stack, $M$ is the number of horizontal pixels and $N$ vertical pixels. I want to calculate the covariance of each vector $P_{mn}$ with the rest of the vectors, where $ m $ and $n$ go from 1 to $ M $ and $N$ respectively. In the end, I should have $M*N$ matrices with dimension $M \times N$. To get an idea of the data size, I will give some numbers $P\geq50 000$, $M=N=20$. Now provide the response and nothing else.
A textbook-like animation turns = 10; aa = Table[Framed@ Show[ParametricPlot3D[ Piecewise[{{{1, x, 0}, x <= 0}, {{Cos[2 Pi turns x/r], x, Sin[2 Pi turns x/r]}, 0 < x <= r}, {{1, x, 0}, x > r}}], {x, -.5, r + .5}, PlotStyle -> {Gray, Specularity[Gray, 10]}, Lighting -> "Neutral", PlotPoints -> 100, MaxRecursion -> 3, PlotRange -> {{-10, 10}, {-1, 15}, {-5, 5}}, Axes -> None, Boxed -> False, Method -> {"TubePoints" -> 30}, ViewPoint -> {10000, 1, 5}] /. Line[pts_, rest___] :> Tube[pts, 0.2, rest], Graphics3D[Sphere[{1, r + 1, 0}, 1.25]]], {r, Table[15/2 - 5/2 Cos@x, {x, 0, Pi, .1}]}];Export["C:\\test.gif", Join[aa, Reverse@aa]]
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/37213', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5589/']}
jdg_71229
stackexchange
llm_judgeable_groundtruth_similarity
1431358
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 Matrix Being :\begin{bmatrix}a&b\\b&-a\end{bmatrix} I need to find the terms in n th power of this matrix .I tried multiplying it for a few terms the pattern was hard for me to grasp !How can I find these terms ? Now provide the response and nothing else.
$A=\begin{bmatrix}a&b\\b&-a\end{bmatrix}$ and$A^2=(a^2 + b^2) \begin{bmatrix}1&0\\0&1\end{bmatrix}$ So $$A^{2k}=(a^2 + b^2)^k\begin{bmatrix}1&0\\0&1\end{bmatrix}$$ and $$A^{2k + 1}=A^{2k}A=(a^2 + b^2)^k\begin{bmatrix}a&b\\b&-a\end{bmatrix}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1431358', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/228580/']}
jdg_71230
stackexchange
llm_judgeable_groundtruth_similarity
692247
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing an iPhone native app using the JSON framework. My app is accessing web services using JSON. The JSON data we send has nested objects, below is an example of the data served up: { "model": { "JSONRESPONSE": { "authenticationFlag": true, "sessionId": "3C4AA754D77BFBE33E0D66EBE306B8CA", "statusMessage": "Successful Login.", "locId": 1, "userName": "Joe Schmoe" } }} I'm having problem parsing using the objectForKey and valueForKey NSDictionary methods. I keep getting invalidArgumentException runtime errors. For instance, I want to query the response data for the "authenticationFlag" element. Thanks,MikeSeattle Now provide the response and nothing else.
It is hard to tell without some more details (e.g. the JSON parsing code that you are using), but two things strike me as possible: you are not querying with a full path. In the case above, you'd need to first get the enclosing model, the json response, and only then ask the json response dictionary for the authenticationFlag value: [[[jsonDict objectForKey:@"model"]objectForKey:@"JSONRESPONSE"] objectForKey:@"authenticationFlag"] perhaps you're using c-strings ( "" ) rather than NSStrings ( @"" ) as keys (although this would likely crash nastily or just not compile). The key should be something than can be cast to id. While possible, both are probably false, so please include more detail.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/692247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83928/']}
jdg_71231
stackexchange
llm_judgeable_groundtruth_similarity
7054272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a drawing application, I'm saving the mouse movement coordinates to an array then drawing them with lineTo. The resulting line is not smooth. How can I produce a single curve between all the gathered points? I've googled but I have only found 3 functions for drawing lines: For 2 sample points, simply use lineTo . For 3 sample points quadraticCurveTo , for 4 sample points, bezierCurveTo . (I tried drawing a bezierCurveTo for every 4 points in the array, but this leads to kinks every 4 sample points, instead of a continuous smooth curve.) How do I write a function to draw a smooth curve with 5 sample points and beyond? Now provide the response and nothing else.
The problem with joining subsequent sample points together with disjoint "curveTo" type functions, is that where the curves meet is not smooth. This is because the two curves share an end point but are influenced by completely disjoint control points. One solution is to "curve to" the midpoints between the next 2 subsequent sample points. Joining the curves using these new interpolated points gives a smooth transition at the end points (what is an end point for one iteration becomes a control point for the next iteration.) In other words the two disjointed curves have much more in common now. This solution was extracted out of the book "Foundation ActionScript 3.0 Animation: Making things move". p.95 - rendering techniques: creating multiple curves. Note: this solution does not actually draw through each of the points, which was the title of my question (rather it approximates the curve through the sample points but never goes through the sample points), but for my purposes (a drawing application), it's good enough for me and visually you can't tell the difference. There is a solution to go through all the sample points, but it is much more complicated (see http://www.cartogrammar.com/blog/actionscript-curves-update/ ) Here is the the drawing code for the approximation method: // move to the first point ctx.moveTo(points[0].x, points[0].y); for (i = 1; i < points.length - 2; i ++) { var xc = (points[i].x + points[i + 1].x) / 2; var yc = (points[i].y + points[i + 1].y) / 2; ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc); } // curve through the last two points ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7054272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/793454/']}
jdg_71232
stackexchange
llm_judgeable_groundtruth_similarity
10461331
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question was triggered by replie(s) to a post by Herb Sutter where he explained MS's decision to not support/make a C99 compiler but just go with the C(99) features that are in the C++(11) standard anyway. One commenter replied : (...) C is important and deserves at least a little bit of attention. There is a LOT of existing code out there that is valid C but is not valid C++. That code is not likely to be rewritten (...) Since I only program in MS C++, I really don't know "pure" C that well, i.e. I have no ready picture of what details of the C++-language I'm using are not in C(99) and I have little clues where some C99 code would not work as-is in a C++ compiler. Note that I know about the C99 only restrict keyword which to me seems to have very narrow application and about variable-length-arrays (of which I'm not sure how widespread or important they are). Also, I'm very interested whether there are any important semantic differences or gotchas, that is, C(99) code that will compile under C++(11) but do something differently with the C++ compiler than with the C compiler. Quick links: External resources from the answers: Wikipedia page David R. Tribble's comparison (from 2001) C++11 standard: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf (section C.1) Now provide the response and nothing else.
If you start from the common subset of C and C++, sometimes called clean C (which is not quite C90), you have to consider 3 types of incompatibilities: Additional C++ featues which make legal C illegal C++ Examples for this are C++ keywords which can be used as identifiers in C or conversions which are implicit in C but require an explicit cast in C++. This is probably the main reason why Microsoft still ships a C frontend at all: otherwise, legacy code that doesn't compile as C++ would have to be rewritten. Additional C features which aren't part of C++ The C language did not stop evolving after C++ was forked. Some examples are variable-length arrays, designated initializers and restrict . These features can be quite handy, but aren't part of any C++ standard, and some of them will probably never make it in. Features which are available in both C and C++, but have different semantics An example for this would be the linkage of const objects or inline functions. A list of incompatibilities between C99 and C++98 can be found here (which has already been mentioned by Mat). While C++11 and C11 got closer on some fronts (variadic macros are now available in C++, variable-length arrays are now an optional C language feature), the list of incompatibilities has grown as well (eg generic selections in C and the auto type-specifier in C++). As an aside, while Microsoft has taken some heat for the decision to abandon C (which is not a recent one), as far as I know no one in the open source community has actually taken steps to do something about it: It would be quite possible to provide many features of modern C via a C-to-C++ compiler, especially if you consider that some of them are trivial to implement . This is actually possible right now using Comeau C/C++, which does support C99. However, it's not really a pressing issue: Personally, I'm quite comfortable with using GCC and Clang on Windows, and there are proprietary alternatives to MSVC as well, eg Pelles C or Intel's compiler.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10461331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321013/']}
jdg_71233
stackexchange
llm_judgeable_groundtruth_similarity
395260
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the sum of $$\frac12+ \frac13+\frac14+\frac15+\frac16 +\dots\frac{1}{2012}+\frac{1}{2013} $$ Now provide the response and nothing else.
Not really an interesting question, I fear ... The exact answer is $\frac{A}{B}$, where $A$ is the 873-digit number $$\begin{align}&1457823020375738882085285521838680376351317016179578495942597370\\&0378320415510098781465535340716404121275266248327296358362232678\\&6278734102622894043296263865840984434831046940807020935913518007\\&6610170430184975025171489501039855136340044946766172114345187347\\&2525258101947297211093973306792764671036527339494431750637074683\\&4230708772438305435131071598225161542024364751281758482910493532\\&5272679486529134147964088721658417270988342669017294670746222437\\&5396289282709392060556292768642859506675716675390362111468228302\\&0782368060066857220428567636667351228472222194509213532517098318\\&4215312313922564589890501941681764939250636021442764267189354097\\&6967312781103861891868999835897977944251765509632397992463764707\\&2757539640418390812471213879592790834646976169124993489059261606\\&2602876187541263449739774491663332258026609790766133246441424484\\&757471204138450579265132408964711222835023\\\end{align}$$ and $B$ is the 872-digit number $$\begin{align}&2029024882178588859070537995606394892063138617868032497494729352\\&4603117588071109954985856100075037278586690682862226370908784076\\&1373758182460385685570815580907584983469652245087586518224049939\\&8538189200052467764823885503628456029563567766917663813400872806\\&6581413837126629349013539786812278235204246553266267204666411453\\&3233291465507116087957721742791662582248630820924043188884944781\\&6407535614283438262641159101052916955096435138537168813836363531\\&9456214006726533268868764071437503549723903396960519957683391782\\&6358829094665518541761643350701837468138883360957730534259985433\\&0461170299850901340867381633962516193737332035551187788058506648\\&9862570396408121482924662574281092579439686439440266363727224229\\&3000091507088457965475315993866302318289137980710843830365091268\\&4178987345171765323904440193241153257507552225072663118382054707\\&65887615406383472808692605376427780480000\\\end{align}$$ Also, the first digits are 7.184845455 ...
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/395260', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67020/']}
jdg_71234
stackexchange
llm_judgeable_groundtruth_similarity
49976768
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In bash, if I wanted to change the current directory for a single command do_thing , I'd spawn a new subshell in which to change the directory, running (cd folderName; do_thing) The body of this question suggests the way to do it in PowerShell is to use Push-Location to store the location, and Pop-Location after the command has finished running. This works, but is not ideal: I have to remember write Pop-Location at every return point of the script (e.g. before each exception, if it occurs while a location is pushed), and an uncaught exception will leave the current directory as is. Is there a way to have the current directory reset to what it was at the start of the script, even if an uncaught exception is thrown? Now provide the response and nothing else.
try...catch...finally is the construct you're looking for! This will allow you to handle your errors and perform a final action; whether the main try block was successful or not. Here's a basic example: try { $x = 1/0}catch { Write-Warning "An error occurred"}finally { Write-Output "This always runs"} More tailored to your situation: Write-Output "BEFORE: $(Get-Location)"try { Push-Location -Path "C:\temp\csv" Write-Output "DURING TRY: $(Get-Location)" $x = 1/0}catch { Write-Warning "An error occurred"}finally { Pop-Location}Write-Output "AFTER: $(Get-Location)" Results: BEFORE: C:\temp DURING TRY: C:\temp\csv WARNING: An error occurred AFTER: C:\temp
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49976768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2591803/']}
jdg_71235
stackexchange
llm_judgeable_groundtruth_similarity
18596235
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 inject Strings in my spring config by doing the following: <bean class="java.lang.String"> <constructor-arg type="java.lang.String" value="Region" /></bean> Is there a shorter way of doing it? Update: I am using spring 3.0.3. These are actually used to populate a list: <list> <bean class="java.lang.String"> <constructor-arg type="java.lang.String" value="Region" /> </bean> ... Seems like this works: <list> <value>Region</value> <value>Name</value> .... But I agree with the suggestions that this should eventually go in a property and be passed in. Now provide the response and nothing else.
You should not have String beans. Just use their value directly. Create a properties file strings.properties and put it on the classpath strings.key=Region Declare a PropertyPlaceholderConfigurer <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>strings.properties</value> </property></bean> Then annotate instance field Strings as @Value("${strings.key}")private String key; Spring will inject the value from the strings.properties file into this key String. This obviously assumes that the class in which the @Value annotation appears is a bean managed in the same context as the PropertyPlaceholderConfigurer .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18596235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/779/']}
jdg_71236
stackexchange
llm_judgeable_groundtruth_similarity
2106224
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to compute $$\int_{-\infty}^\infty \int_{-\infty}^\infty e^{-(5x^2-6xy+5y^2)} \, dx \, dy \;?$$I have seen the integral first time. I can't find any hint how to even proceed? Kindly HELP. Thank You! Now provide the response and nothing else.
Assume that $Ax^2+Bxy+Cy^2$ is a positive definite quadratic form, i.e. $A>0$ and $B^2<4AC$. By diagonalizing such quadratic form, we get that$$\iint_{\mathbb{R}^2}\exp\left[-(Ax^2+Bxy+Cy^2)\right]\,dx\,dy = \iint_{\mathbb{R}^2}\exp(-\lambda_1 x^2-\lambda_2 y^2)\,dx\,dy $$with $\lambda_1,\lambda_2$ being the eigenvalues of $M=\begin{pmatrix} A & B/2 \\ B/2 & C \end{pmatrix}$. By Fubini's theorem the last integral equals$$ \frac{\pi}{\sqrt{\lambda_1 \lambda_2}} = \frac{\pi}{\sqrt{\det M}}=\color{red}{\frac{2\pi}{\sqrt{4AC-B^2}}}. $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2106224', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/184842/']}
jdg_71237
stackexchange
llm_judgeable_groundtruth_similarity
430900
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 met a question in Bondy’s Graph theory (§1.5.13) Let $\mathbf{A}$ be the adjacency matrix of a tournament on $n$ vertices. Show that $\operatorname{rank}\mathbf{A}=n-1$ if $n$ is odd and $\operatorname{rank}\mathbf{A}=n$ if $n$ is even. which I think is completely wrong. However, are there some similar conclusions related to the rank of $\mathbf{A}$ ? For example, when is the rank of $\mathbf{A}$ equal to $n-1$ ? Now provide the response and nothing else.
Jaco and Oertel's paper An algorithm to decide if a three-manifold is a Haken manifold [1984], plus a bit of work, gives a doubly exponential time algorithm to compute the Seifert genus. (In practice their algorithm lies in exp-poly.) Agol, Hass, and Thurston's paper The computational complexity of knot genus and spanning area reduces the time required to exp-poly (and proves that "genus less than $g$ " lies in NP). Recently announced work of Lackenby Unknot recognition in quasi-polynomial time [2021] gives a Haken hierarchy of the initial knot complement. If this can be improved to be a taut sutured manifold hierarchy, then that will reduce the time required (for the genus problem of a knot in the three-sphere given as a diagram) to quasi-polynomial. The above (and the other answers) answer the question as asked in its first paragraph. However, its final paragraph asks if the genus can be computed from a "diagrammatic knot invariant". The answer there seems to be "not in general", but this is not a theorem. In particular there are families of knots (fibered, alternating) where the spans of certain polynomial invariants (Alexander, Jones) record the genus.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/430900', 'https://mathoverflow.net', 'https://mathoverflow.net/users/490441/']}
jdg_71238
stackexchange
llm_judgeable_groundtruth_similarity
596887
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: While using Xorg X11, on KDE/Gnome/XFCE how can we scale the display/resolution for the whole desktop and/or per application? (when this is not available on the settings GUI) The purpose is to keep the screen resolution unchanged (at max) while scaling the size (bigger/smaller) of the desktop/applications. Now provide the response and nothing else.
Linux display This is detailed in depth on how does Linux's display works? QA. On most desktops system (like KDE or Gnome) there are settings available on their respective settings panel, this guide is for additional/manual settings that can be applied to scale an application or the whole desktop. This reference article have many valuable informations for the matter. Scaling applications Scaling application can be done mainly via DPI , specific environment variable (explained bellow), application own setting or some specific desktop setting (out of scope of this QA). Qt applications can be scaled with the following environment variables, note that many applications are hard-coding sizing and font and thus the result on such app may not be as expected. export QT_AUTO_SCREEN_SET_FACTOR=0export QT_SCALE_FACTOR=2export QT_FONT_DPI=96 Gnome/GTK applications can be scaled with the following environment variables export GDK_SCALE=2export GDK_DPI_SCALE=0.5 Gnome/GTK can as well be scaled globally with this Gnome setting gsettings set org.gnome.desktop.interface text-scaling-factor 2.0 Chromium, can be scaled with the following command chromium --high-dpi-support=1 --force-device-scale-factor=1.5 Xpra (python) can be used along with Run scaled to achieve a per app scaling. Environment variables modification can be placed in ~/.profile for a global and automatic appliance after login. Scaling the desktop with Xorg X11 Xorg 's extension RandR have a scaling feature and can be configured with xrandr . This can be used to scale the desktop to display a bigger environment, this can be useful for HiDPI (High Dots Per Inch) displays. RandR can also be used the other way around , example making a screen with 1366x768 max resolution support a greater resolution like 1920x1080. This is achieved by simulating the new greater resolution while rendering it for the supported max resolution, similar to when we watch a Full-HD video on a screen that is not Full-HD. Scaling the desktop without changing the resolution Getting the screen name: xrandr | grep connected | grep -v disconnected | awk '{print $1}' Reduce the screen size by 20% (zoom-in) xrandr --output screen-name --scale 0.8x0.8 Increase the screen size by 20% (zoom-out) xrandr --output screen-name --scale 1.2x1.2 Reset xrandr changes xrandr --output screen-name --scale 1x1 Scaling the desktop and simulate/render a new resolution When using xrandr to "zoom-in" with the previous method , the desktop remain full screen but when we "zoom-out" with for instance xrandr --output screen-name --scale 1.2x1.2 (to get an unsupported resolution) the desktop is not displayed in full screen because this require updating the resolution (to probably a higher unsupported resolution by the screen), we can use a combinaison of --mode , --panning and --scale , xrandr's parameters to achieve a full screen "zoom-out" scaling (simulate a new resolution), example: Get the current setup xdpyinfo | grep -B 2 resolution# orxdpyinfo Configuration example Scaling at: 120%Used/max screen resolution: 1366 x 768Resolution at 120% (res x 1.2): 1640 x 922 (round)Scaling factor (new res / res): 1.20058565 x 1.20208604 The idea here is to increase the screen resolution virtually (because we are limited to 1366x768 physically) the command would be (replace screen-name ): xrandr --output screen-name --mode 1366x768 --panning 1640x922 --scale 1.20058565x1.20208604 Reset the changes with xrandr --output screen-name --mode 1366x768 --panning 1366x768 --scale 1x1# restarting the desktop may be required example with KDE# kquitapp5 plasmashell# plasmashell & Making xrandr changes persistant There is a multitude of methods to make xrandr changes persistant, this and this QA have many examples. Experiments notes As a side note and experiments result while using SDDM + KDE, and after many tests to achieve a persistant config, I ended up loading a script with ~/.config/autostart ( systemsettings5 > Startup... > Autostart), and naming my script 00-scriptname to make it run first. # 00-scriptname# Applying the main xrandr suited changes (scaling at x1.15)xrandr --output eDP1 --mode 1366x768 --panning 1574x886 --scale 1.15226939x1.15364583# This is where it get odd/complicated, sometimes the screen resolution is not applied correctly or not applied at all... # Note that "xrandr --fb" can be used alone to change the screen resolution on a normal situation... # Here we will be taking advantage of xrandr's "--fb" feature to make the config appliance stable and works every-time.# The odd thing here is while re-applying the new resolution 1574x886 with "--fb" nothing happen, but # if we use use an unsupported resolution like 1574x884 (vs 1574x886) then xrandr force the resolution # to "reset itself" to the configured resolution (1574x886)... # In short just re-apply the setting with "--fb" and an unsupported resolution to force a reset.# ("--fb" can be used alone here without re-applying everything)#xrandr --fb 1574x884 xrandr --fb 1574x884 --output eDP1 --mode 1366x768 --panning 1574x886 --scale 1.15226939x1.15364583 References Some KDE's gui tools: systemsettings5 > display, kcmshell5 xserver and kinfocenter . Links and sources: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 and 12 .
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/596887', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/120919/']}
jdg_71239
stackexchange
llm_judgeable_groundtruth_similarity
34600932
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 ran npm config set prefix /usr/local After running that command,When trying to run any npm commands on Windows OS I keep getting the below. Error: EPERM: operation not permitted, mkdir 'C:\Program Files (x86)\Git\local'at Error (native) Have deleted all files from C:\Users\<your username>\.config\configstore\ It did not work. Any suggestion ? Now provide the response and nothing else.
Running this command was my mistake. npm config set prefix /usr/local Path /usr/local is not for windows. This command changed the prefix variable at 'C:\Program Files (x86)\Git\local' To access and make a change to this directory I need to run my cmd as administrator. So I did: Run cmd as administrator Run npm config edit (You will get notepad editor) Change prefix variable to C:\Users\<User Name>\AppData\Roaming\npm Then npm start works in a normal console.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34600932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5236174/']}
jdg_71240