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 | 16990014 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to highlight a large comment block and automatically insert breaks after a certain length? Simple Example # This is a super long message that has too much information in it. Although inline comments are cool, this sentence should not be this long. After # This is a super long message that has too much information in it.# Although inline comments are cool, this sentence should not be this# long.
Now provide the response and nothing else.
| Yes! And it's simpler than the length of this answer might suggest! Background There's a command called wrap_lines which has the capability to to exactly what you want. wrap_lines is defined in Packages/Default/paragraph.py , line 112, and is sparsely documented at the Unofficial Docs' list of commands : wrap_lines Wraps lines. By default, it wraps lines at the first ruler’s column. width [Int]: Specifies the column at which lines should be wrapped. wrap_lines is already accessible via the items located in the Edit -> Wrap menu. There are options to wrap the paragraph in which the cursor lies at column 70, 78, 80, 100, and 120, as well as the first ruler. By default, Wrap Paragraph at Ruler is mapped to Alt+Q on Windows and Super+Alt+Q on OSX. Working with Rulers What do I mean by the first ruler? You might summon a ruler via View -> Ruler , but if you want more than one on-screen (or would rather have your rulers in writing), you can add a JSON array of integers—each of which defines a ruler—to any .sublime-settings file. The array I've added to my user preferences file, for example, looks like this: "rulers":[ 79, 80, 72], Thanks to that first ruler rule, Alt+Q will wrap a line that's longer than 79 characters at the 79-column mark, even though there's a ruler "before" it at column 72. "First ruler" doesn't mean the leftmost ruler , but the first defined ruler . If I moved 80, to index 0 like I have below, then the lines would wrap at 80 columns instead. Likewise for 72 . "rulers":[ 80, 79, 72], Using a Key Binding Rulers are for the weak, you say? You can also write a new key binding to wrap a line at a column of your choice! Just add something like this to your Preferences -> Key Bindings – User file: { "keys": ["alt+q"], "command": "wrap_lines", "args": {"width": 80} }, Removing the args object would instead wrap at the first ruler, like the Wrap Paragraph at Ruler command does. Wrap Paragraph at Ruler is actually defined just like that in the default Windows keymap file: { "keys": ["alt+q"], "command": "wrap_lines" }, Caveats One of the best (and, in some cases, worst) things about the wrap_lines command is that it will detect any sequence of non-alphanumeric characters that begins the line and duplicate it when wrapping. It's great for writing comments, since the behavior that your example suggested does indeed happen: # This is a super long message that has too much information in it. Although inline comments are cool, this sentence should not be this long, because having to scroll to the right to finish reading a comment is really annoying! Becomes: # This is a super long message that has too much information in it.# Although inline comments are cool, this sentence should not be this# long, because having to scroll to the right to finish reading a# comment is really annoying! But if the line happens to start with any other symbols, like the beginning of a quote, Sublime Text doesn't know any better than to wrap those, too. So this: # "This is a super long message that has too much information in it. Although inline comments are cool, this sentence should not be this long, because having to scroll to the right to finish reading a comment is really annoying!" Becomes this, which we probably don't want: # "This is a super long message that has too much information in it.# "Although inline comments are cool, this sentence should not be this# "long, because having to scroll to the right to finish reading a# "comment is really annoying!" It's a good idea to be careful with what starts your original line. Also, the wrap_lines command targets the entire paragraph that your cursor is touching , not just the current line nor, surprisingly, only the working selection. This means that you can use the command again on a newly-wrapped series of lines to re-wrap them at a different column, but you might also end up wrapping some lines that you didn't want to—like if you're aligning a paragraph under a header in Markdown: # Hey, this header isn't really there!Be careful with what starts the original line. Also, the `wrap_lines` command **targets the entire paragraph**, not just the current line. If the command is activated anywhere within that block of text, you'll get this: # Hey, this header isn't really there! Be careful with what starts theoriginal line. Also, the `wrap_lines` command **targets the entireparagraph**, not just the current line. You can avoid this sort of issue with clever use of whitespace; another empty line between the header and the paragraph itself will fix the wrapping, so: # Hey, this header isn't really there!Be careful with what starts the original line. Also, the `wrap_lines` command **targets the entire paragraph**, not just the current line. Becomes: # Hey, this header isn't really there!Be careful with what starts the original line. Also, the`wrap_lines` command **targets the entire paragraph**, not justthe current line. Since the operation is so fast, you shouldn't have much trouble with tracking down the causes of any errors you encounter, starting over, and creatively avoiding them. Sublime Text usually doesn't have any trouble with mixing together comments and non-comments in code, so if you're lucky, you won't ever have to worry about it! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16990014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/811459/']} | jdg_74841 |
stackexchange | llm_judgeable_groundtruth_similarity | 96935 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a directory where lots of cached files are getting generated very quickly. Since these are very small files, it is consuming all my inodes very quickly. Currently I am running the following command to find all the files older than 12 hours and delete them. $ find ./cache -mtime +0.5 -exec rm {} \; But the rate at which this command is deleting is slower than the rate at which files are being generated. Can someone tell me some alternative way to remove large number of files quickly.
Now provide the response and nothing else.
| Try using xargs : find ./cache -mtime +0.5 -print0 | xargs -0 rm -f Update explaination for @pradeepchhetri If you use find with -exec , every file that find found will call rm one time. So if you found a huge of files, i.e 10000 files, you called rm 10000 times. xargs will treat ouput of find as command argument to rm , so that, xargs will provide as many arguments as rm can handle at once, i.e rm -f file1 file2 ... So it makes less fork call, make program run faster. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/96935', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3979/']} | jdg_74842 |
stackexchange | llm_judgeable_groundtruth_similarity | 3498492 |
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 want some link to not do anything but only respond to javascript actions what's the best way to avoid the link scrolling to the top edge of the page ? I know several ways of doing it, they all seem to work fine : <a href="javascript:void(0)">Hello</a> or <a id="hello" href="#">Hello</a><script type="text/javascript> $(document).ready(function() { $("#toto").click(function(){ //... return false; }); });</script> and even : <a id="hello" href="#">Hello</a><script type="text/javascript> $(document).ready(function() { $("#toto").click(function(event){ event.preventDefault(); //... }); });</script> Do you have any preference ? why ? in which conditions ? PS: of course the above examples assume you're using jquery but there's equivalents for mootools or prototype.
Now provide the response and nothing else.
| Binding: javascript: URLs are a horror to be avoided at all times; inline event handler attributes aren't brilliant either, but OK for a bit of rapid development/testing; binding from script, leaving the markup clean, is typically considered a best practice. jQuery encourages this, but there is no reason you can't do it in any library or plain JS. Responses: In jQuery return false means both preventDefault and stopPropagation , so the meaning is different if you care about parent elements receiving the event notification; jQuery is hiding it here but preventDefault / stopPropagation have to be spelled differently in IE usually ( returnValue / cancelBubble ). However: You have a link that isn't a link. It doesn't link anywhere; it's an action. <a> isn't really the ideal markup for this. It'll go wrong if someone tries to middle-click it, or add it to bookmarks, or any of the other affordances a link has. For cases where it really does point to something, like when it opens/closes another element on the page, set the link to point to #thatelementsid and use unobtrusive scripting to grab the element ID from the link name. You can also sniff the location.hash on document load to open that element, so the link becomes useful in other contexts. Otherwise, for something that is purely an action, it would be best to mark it up like one: <input type="button"> or <button type="button"> . You can style it with CSS to look like a link instead of a button if want. However there are some aspects of the button styling you can't quite get rid of in IE and Firefox. It's usually not significant, but if you really need absolute visual control a compromise is to use a <span> instead. You can add a tabindex property to make it keyboard-accessible in most browsers although this isn't really properly standardised. You can also detect keypresses like Space or Enter on it to activate. This is kind of unsatisfactory, but still quite popular (SO, for one, does it like this). Another possibility is <input type="image"> . This has the accessibility advantages of the button with full visual control, but only for pure image buttons. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3498492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143148/']} | jdg_74843 |
stackexchange | llm_judgeable_groundtruth_similarity | 387627 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm increasingly seeing mobile networking technologies being used to get internet access in areas where it is otherwise not available. While mobile networking is usually not yet viable as the primary internet connection, mobile technology looks like a good option for an emergency fallback. Bandwith is not the problem: With HDSPA, speeds of several MBit are possible, which provides a decent uplink. However, I know from personal experience that mobile networks internet links (via GPRS, UMTS etc.) have much higher latencies than regular DSL (200-400 ms for UMTS, even more for GPRS). This of course makes them unsuitable for many applications, such as VoIP and teleconferencing. Where does this latency come from? Are there any technologies available that can mitigate this problem, to make UMTS viable for low-latency applications? I assume there must be some inherent technical reason, but what is it? Does it have to do with how data is transmitted over the air? And if it is because of the wireless transmission, why does WLAN have much lower latencies?
Now provide the response and nothing else.
| The book "High Performance Browser Networking" from Ilya Grigorik answers exactly this. There is a whole chapter (7th) dedicated to mobile networks. The book states that the problem with high performance is almost always tied to latency, we usually have plenty of bandwidth but the protocols gets in the way. Be it TCP slow start , the Radio Resource Controller (RRC) or suboptimal configurations. If you are experiencing poor latency only in mobile networks it's the way they are designed. There is a table in the book about typical latencies: Table 7-2. Data rates and latency for an active mobile connection Generation | Data rate | Latency2G | 100–400 Kbit/s | 300–1000 ms3G | 0.5–5 Mbit/s | 100–500 ms4G | 1–50 Mbit/s | < 100 ms Although very relevant to latency the TCP characteristic three-way handshake or the slow-start don't really answer the question, as they affect wired connections equally. What does really affect the latency in mobile networks is the layer under IP. If the layer under IP has a latency of half a second, a TCP connection to a server will take ~1.5 sec (0.5s*3), as you see the numbers add up pretty quick. As said before that's supposing that the mobile is not idle. If the handset is idle it first has to "connect" to the network, that requires to negotiate a reserve of resources with the tower (simplified), and that takes between 50-100ms in LTE, up to several seconds in 3G, and more in earlier networks. Figure 7-12. LTE request flow latencies Control plane latency: Fixed, one-time latency cost incurred for RRC negotiation and state transitions: <100 ms for idle to active, and <50 ms for dormant to active. User plane latency: Fixed cost for every application packet transferred between the device and the radio tower: <5 ms. Core network latency: Carrier dependent cost for transporting the packet from the radio tower to the packet gateway: in practice, 30–100 ms. Internet routing latency: Variable latency cost between the carrier’s packet gateway and the destination address on the public Internet. In practice, the end-to-end latency of many deployed 4G networks tends to be in the 30–100 ms range once the device is in a connected state. So, you have for one request (Figure 8-2. Components of a "simple" HTTP request): RRC negotiation 50-2500 ms DNS lookup 1 RTT TCP handshake 1 RTT (preexisting connection) or 3 RTT (new connection) TLS handshake 1-2 RTTs HTTP request 1-n RTTs And with real data: Table 8-1. Latency overhead of a single HTTP request | 3G | 4GControl plane | 200–2,500 ms | 50–100 msDNS lookup | 200 ms | 100 msTCP handshake | 200 ms | 100 msTLS handshake | 200–400 ms | 100–200 msHTTP request | 200 ms | 100 msTotal latency overhead | 200–3500 ms | 100–600 ms In addition if you have a interactive application that you want to perform moderately ok in a mobile network you can experiment disabling the Nagle algorithm (the kernel waits for data to coalescence into bigger packets instead of sending multiple smaller packets) look for ways to test it in https://stackoverflow.com/a/17843292/869019 . There is the option to read the entire book for free by everyone at https://hpbn.co/ sponsored by Velocity Conference. This is a very highly recommended book, not only to people developing websites, it is useful to everyone who does serve bytes over some network to a client. | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/387627', 'https://serverfault.com', 'https://serverfault.com/users/2439/']} | jdg_74844 |
stackexchange | llm_judgeable_groundtruth_similarity | 44977 |
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 searched the Internet and can't seem to find a source on how to find the eigenvalues on a TI-83 Plus calculator. Can anyone give me a hand?
Now provide the response and nothing else.
| The thing with the TI-83 Plus is that although there aren't any built-in functions for finding the eigenvalues of a matrix, you do have a usable programming language at your disposal for writing a program to do it for you. To that end, I had translated (a very long time ago!) some of the algorithms from the venerable FORTRAN package EISPACK into TI-BASIC. In particular, for the case of finding the eigenvalues of some general real matrix, I translated the FORTRAN routines elmhes() (similarity transformation of a matrix to upper Hessenberg form via Gauss transforms) and hqr() (the Francis QR algorithm for upper Hessenberg matrices) into the TI-BASIC routines prgmHESGAU and prgmEIGVAL , respectively. You can download these two programs (zipped up) from here ; if you want to see the code before committing them to your calculator, you can use SourceCoder . Briefly, the way to use these is to input the matrix whose eigenvalues you want into the matrix [H] , run prgmHESGAU first (optionally deleting matrix [I] if you're pressed for space) and then run prgmEIGVAL . The eigenvalues of your matrix will be in the list ∟EIG (so input something like [[1,4,2][2,-3,1][0,2,-5]]→[H]:prgmHESGAU:prgmEIGVAL:∟EIG ). I won't be discussing the algorithms behind them here; suffice it to say that these two are the practical applications of the fact that similarity transformations of a matrix preserve eigenvalues. Note that this set computes eigenvalues only; if eigenvectors are needed as well, then the programs are slightly more complicated, and I'll edit this answer to include those routines if there's interest. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/44977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_74845 |
stackexchange | llm_judgeable_groundtruth_similarity | 2785718 |
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 example: $12$ reversed is $21$ and $12$ + $9$ = $21$. $17$ with the two values swapped is $71$, and $17$ + $9$ + $9$ + $9$ + $9$ + $9$ + $9$ = $71$. Take the number $123$ and add $9$ a total of $22$ times you get $321$, which is the reverse. It seems to work for every number. Why is this the case? Is it just a addition thing?
Now provide the response and nothing else.
| Any number is congruent modulo $9$ to the sum of its digits:$$a_na_{n-1}\ldots a_1a_0\equiv a_n+a_{n-1}+\ldots +a_1+a_0\pmod 9$$If you reverse the digits, the sum is unchanged. Therefore $$a_0a_1\ldots a_{n-1}a_n\equiv a_na_{n-1}\ldots a_1a_0\pmod 9$$which is equivalent to your statement. Note a stronger statement implied by the same reasoning: By adding or subtracting a suitable amount of $9$'s, you can reach any permutation of the digits. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2785718', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/545694/']} | jdg_74846 |
stackexchange | llm_judgeable_groundtruth_similarity | 9276378 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following code gives an unreachable statement compiler error public static void main(String[] args) { return; System.out.println("unreachable");} Sometimes for testing purposes a want to prevent a method from being called, so a quick way to do it (instead of commenting it out everywhere it's used) is to return immediately from the method so that the method does nothing. What I then always do to get arround the compiler error is this public static void main(String[] args) { if (true) { return; } System.out.println("unreachable");} I'm just curious, why is it a compiler error?? Will it break the Java bytecode somehow, is it to protect the programmer or is it something else? Also (and this to me is more interesting), if compiling java to bytecode does any kind of optimization (or even if it doesn't) then why won't it detect the blatant unreachable code in the second example? What would the compiler pseudo code be for checking if a statement is unreachable?
Now provide the response and nothing else.
| Unreachable code is meaningless, so the compile-time error is helpful. The reason why it won’t be detected at the second example is, like you expect, for testing / debugging purposes. It’s explained in The Specification: if (false) { x=3; } does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here. The rationale for this differing treatment is to allow programmers to define "flag variables" such as: static final boolean DEBUG = false; and then write code such as: if (DEBUG) { x=3; } The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text. Reference: http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.21 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9276378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196618/']} | jdg_74847 |
stackexchange | llm_judgeable_groundtruth_similarity | 122254 |
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 have seen some similar questions to this one on here recently, so I hope this isn't redundant. Basically, suppose I have two cofiber sequences of spectra (or perhaps just work in some general homotopy category or something) $X\overset{f}\to Y\to Cf$ and $X'\overset{g}\to Y'\to Cg$. I'd like to look at an induced filtration on $Cf\wedge Cg$ along the lines of the bottom level being $X\wedge X'$, the middle level being something like $(X\wedge Y')\cup (Y\wedge X')$ and the top level being $Y\wedge Y'$, or something along those lines. Or I guess I should say I'd like to have filtration quotients that look like that. Honestly, I'd like to do this all in a cellular context. Intuitively this all seems pretty obvious, but does anyone have a good reference where such a filtration is discussed really rigorously, or a good way to think about it? Thanks, as always.
Now provide the response and nothing else.
| This is an excellent question that I have thought a lot about. I'd rather answer it in a more general context that was motivated by what I knew to be true in the stable homotopy category. The reference is "The additivity of traces in triangulated categories", #99 on my web site. The essential point there is to formulate axioms relating triangulations to symmetric monoidal structures, and Axiom (TC3), with $Z=Cf$ and $Z'=Cg$, formulates exactly what happens when you smash two triangles (cofiber sequences) together. The motivation in terms of your question is given on page 49; I think the diagrams on pages 49 and 50 display the `filtration' you ask for, in appropriate generality, and they are what you see when you follow through on your concrete question. The equivalent form (TC3') of (TC3) may perhaps be easier to compare with your question, since it has $Z \wedge Z'$ conveniently displayed as the end target. The description of the proof of (TC3) on pages 60-61 follows the lines of your question.Edit: the page numbers above are those of the published paper; the page numbers of the file on my web site are 12-13 (for 49-50) and 21-22 (for 60-61). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/122254', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11546/']} | jdg_74848 |
stackexchange | llm_judgeable_groundtruth_similarity | 546220 |
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 example, in this text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu tellus vel nunc pretium lacinia. Proin sed lorem. Cras sed ipsum. Nunc a libero quis risus sollicitudin imperdiet. I want to match the word after 'ipsum'.
Now provide the response and nothing else.
| This sounds like a job for lookbehinds, though you should be aware that not all regex flavors support them. In your example: (?<=\bipsum\s)(\w+) This will match any sequence of letter characters which follows "ipsum" as a whole word followed by a space. It does not match "ipsum" itself, you don't need to worry about reinserting it in the case of, e.g. replacements. As I said, though, some flavors (JavaScript, for example) don't support lookbehind at all. Many others (most, in fact) only support "fixed width" lookbehinds — so you could use this example but not any of the repetition operators. (In other words, (?<=\b\w+\s+)(\w+) wouldn't work.) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/546220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154560/']} | jdg_74849 |
stackexchange | llm_judgeable_groundtruth_similarity | 2148543 |
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 wrote a confusion matrix calculation code in Python: def conf_mat(prob_arr, input_arr): # confusion matrix conf_arr = [[0, 0], [0, 0]] for i in range(len(prob_arr)): if int(input_arr[i]) == 1: if float(prob_arr[i]) < 0.5: conf_arr[0][1] = conf_arr[0][1] + 1 else: conf_arr[0][0] = conf_arr[0][0] + 1 elif int(input_arr[i]) == 2: if float(prob_arr[i]) >= 0.5: conf_arr[1][0] = conf_arr[1][0] +1 else: conf_arr[1][1] = conf_arr[1][1] +1 accuracy = float(conf_arr[0][0] + conf_arr[1][1])/(len(input_arr)) prob_arr is an array that my classification code returned and a sample array is like this: [1.0, 1.0, 1.0, 0.41592955657342651, 1.0, 0.0053405015805891975, 4.5321494433440449e-299, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.70943426182688163, 1.0, 1.0, 1.0, 1.0] input_arr is the original class labels for a dataset and it is like this: [2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1] What my code is trying to do is: I get prob_arr and input_arr and for each class (1 and 2) I check if they are misclassified or not. But my code only works for two classes. If I run this code for a multiple classed data, it doesn't work. How can I make this for multiple classes? For example, for a data set with three classes, it should return: [[21, 7, 3], [3, 38, 6],[5, 4, 19]] .
Now provide the response and nothing else.
| Scikit-Learn provides a confusion_matrix function from sklearn.metrics import confusion_matrixy_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]confusion_matrix(y_actu, y_pred) which output a Numpy array array([[3, 0, 0], [0, 1, 2], [2, 1, 3]]) But you can also create a confusion matrix using Pandas: import pandas as pdy_actu = pd.Series([2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2], name='Actual')y_pred = pd.Series([0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2], name='Predicted')df_confusion = pd.crosstab(y_actu, y_pred) You will get a (nicely labeled) Pandas DataFrame: Predicted 0 1 2Actual0 3 0 01 0 1 22 2 1 3 If you add margins=True like df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True) you will get also sum for each row and column: Predicted 0 1 2 AllActual0 3 0 0 31 0 1 2 32 2 1 3 6All 5 2 5 12 You can also get a normalized confusion matrix using: df_confusion = pd.crosstab(y_actu, y_pred)df_conf_norm = df_confusion.div(df_confusion.sum(axis=1), axis="index")Predicted 0 1 2Actual0 1.000000 0.000000 0.0000001 0.000000 0.333333 0.6666672 0.333333 0.166667 0.500000 You can plot this confusion_matrix using import matplotlib.pyplot as pltdef plot_confusion_matrix(df_confusion, title='Confusion matrix', cmap=plt.cm.gray_r): plt.matshow(df_confusion, cmap=cmap) # imshow #plt.title(title) plt.colorbar() tick_marks = np.arange(len(df_confusion.columns)) plt.xticks(tick_marks, df_confusion.columns, rotation=45) plt.yticks(tick_marks, df_confusion.index) #plt.tight_layout() plt.ylabel(df_confusion.index.name) plt.xlabel(df_confusion.columns.name)df_confusion = pd.crosstab(y_actu, y_pred)plot_confusion_matrix(df_confusion) Or plot normalized confusion matrix using: plot_confusion_matrix(df_conf_norm) You might also be interested by this project https://github.com/pandas-ml/pandas-ml and its Pip package https://pypi.python.org/pypi/pandas_ml With this package confusion matrix can be pretty-printed, plot.You can binarize a confusion matrix, get class statistics such as TP, TN, FP, FN, ACC, TPR, FPR, FNR, TNR (SPC), LR+, LR-, DOR, PPV, FDR, FOR, NPV and some overall statistics In [1]: from pandas_ml import ConfusionMatrixIn [2]: y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]In [3]: y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]In [4]: cm = ConfusionMatrix(y_actu, y_pred)In [5]: cm.print_stats() Confusion Matrix:Predicted 0 1 2 __all__Actual0 3 0 0 31 0 1 2 32 2 1 3 6__all__ 5 2 5 12Overall Statistics:Accuracy: 0.58333333333395% CI: (0.27666968568210581, 0.84834777019156982)No Information Rate: ToDoP-Value [Acc > NIR]: 0.189264302376Kappa: 0.354838709677Mcnemar's Test P-Value: ToDoClass Statistics:Classes 0 1 2Population 12 12 12P: Condition positive 3 3 6N: Condition negative 9 9 6Test outcome positive 5 2 5Test outcome negative 7 10 7TP: True Positive 3 1 3TN: True Negative 7 8 4FP: False Positive 2 1 2FN: False Negative 0 2 3TPR: (Sensitivity, hit rate, recall) 1 0.3333333 0.5TNR=SPC: (Specificity) 0.7777778 0.8888889 0.6666667PPV: Pos Pred Value (Precision) 0.6 0.5 0.6NPV: Neg Pred Value 1 0.8 0.5714286FPR: False-out 0.2222222 0.1111111 0.3333333FDR: False Discovery Rate 0.4 0.5 0.4FNR: Miss Rate 0 0.6666667 0.5ACC: Accuracy 0.8333333 0.75 0.5833333F1 score 0.75 0.4 0.5454545MCC: Matthews correlation coefficient 0.6831301 0.2581989 0.1690309Informedness 0.7777778 0.2222222 0.1666667Markedness 0.6 0.3 0.1714286Prevalence 0.25 0.25 0.5LR+: Positive likelihood ratio 4.5 3 1.5LR-: Negative likelihood ratio 0 0.75 0.75DOR: Diagnostic odds ratio inf 4 2FOR: False omission rate 0 0.2 0.4285714 I noticed that a new Python library about Confusion Matrix named PyCM is out: maybe you can have a look. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2148543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260253/']} | jdg_74850 |
stackexchange | llm_judgeable_groundtruth_similarity | 392977 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My question might sound dumb, but I don't really see why the graphics of $\arccos(x)$ and $\sec(x)$ are different. As far as I know $\arccos(x)$ is the inverse cosine function $(\cos(x)^{-1})$ and $\sec(x)$ = $\frac{1}{\cos(x)}$ (source Wolfram|Alpha). So why aren't they equal? Thanks in advance.
Now provide the response and nothing else.
| That's a problem of notation and probably a lack of definitions. We define $\sec x$ as the multiplicative inverse of $\cos x$, in other words, fixed $a \in \mathbb{R}$, $\sec a$ is the number such that $\sec a \cos a = 1$. Now $\arccos x$ is a little different thing: it's the inverse function of $\cos x$. I don't know if you've learned this but the formal definition of a function is that of a collection of ordered pairs. In other words, since a function from a set $A$ to a set $B$ should be a rule assigning for each $a \in A$ some $b \in B$ we can simply define a function as the set of all ordered pairs of elements in $a$ together with related elements in $b$. However, we require the additional property that if $(a,b) \in f$ and if $(a,c)\in f$ then $b = c$ and this is just the formal way to state the "vertical line rule". Since the second element in each pair is unique we give it a name: if $(a,b) \in f$ then $b = f(a)$. Also to state starting and ending sets we write functions from $A$ to $B$ as $f: A \to B$. Now, if you have a function you have a collection of ordered pairs right? So, you can create a new set of ordered pairs by reversing the pairs. So if $f : A \to B$ is a function from $A$ to $B$ we define the inverse $f^{-1}$ by the property that $(a,b) \in f^{-1}$ when $(b,a)\in f$. Now it's not at all clear when $f^{-1}$ is a function. Just to show you that consider the following function that maps naturals to naturals: $$f = \{(1,2), (3,2), (4,1)\}\subset \mathbb{N}\times \mathbb{N}$$ This is a function by our definition. Now the inverse is $f^{-1} = \{(2,1), (2,3), (1,4)\}$, now this isn't a function because $(2,1)\in f^{-1}$ and $(2,3)\in f^{-1}$. So $f^{-1}$ will be a function if the original function also satisfies $f(x) = f(y)$ implying $x = y$. This kind of function is called one-one, and so if $f$ is one-one, $f^{-1}$ will be a function called then inverse function . Also, if $f: \mathbb{R} \to \mathbb{R}$ has an inverse function $f^{-1}:\mathbb{R} \to \mathbb{R}$ then $f(f^{-1}(x)) = x$ and $f^{-1}(f(x)) = x$. So $\arccos$ is defined precisely this way: fixing one interval where $\cos$ is one-one, you define $\arccos$ in that interval by the property that $\arccos x$ is the number $y$ such that $\cos y = x,$ in other words, it returns you the value of angle whose cosine is $x$. Just a reference to finish: you can find treatments like this in books like Spivak's Calculus or Apostol's Calculus Vol. 1. I hope the way I exposed this helps you a little. Good luck! EDIT: The problem of notation I've mentioned and forgot talking about is that both the multiplicative inverse and the inverse function are in some contexts denoted by $\cos^{-1}$ and this usually happens to all trigonometric functions. So to avoid confusion, I recommend writing $\arccos$, $\arcsin$ and so on for the inverse functions. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/392977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78005/']} | jdg_74851 |
stackexchange | llm_judgeable_groundtruth_similarity | 153277 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
There seems to be a lot of recent activity concerning topological modular forms (TMF), which I gather is an extraordinary cohomology theory constructed from the classical theory of modular forms on the moduli space of elliptic curves. I gather that the homotopy theorists regard it as a major achievement. My question is as follows : what sorts of more classical topological problems is it useful for solving? It is clear why non-algebraic-topologists should care about the more classical extraordinary cohomology theories (e.g. K-theory and cobordism theory); they allow elegant solutions to problems that are obviously of classical interest. Does TMF also allow solutions to such problems, or is it only of technical interest within algebraic topology? My background : my research interests are in geometry and topology, but I am not an algebraic topologist (though I have used quite a bit of algebraic topology in my research).
Now provide the response and nothing else.
| One of the closer connections to geometric topology is likely from invariants of manifolds. The motivating reason for the development of topological modular forms was the Witten genus . The original version of the Witten genus associates power series invariants in $\mathbb{C}[[q]]$ to oriented manifolds, and it was argued that what it calculates on M is an $S^1$-equivariant index of a Dirac operator on the free loop space $Map(S^1,M)$. It is also an elliptic genus, which Ochanine describes much better than I could here . This is supposed to have especially interesting behavior on certain manifolds. An orientation of a manifold is a lift of the structure of its tangent bundle from the orthogonal group $O(n)$ to the special orthogonal group $SO(n)$, which can be regarded as choosing data that exhibits triviality of the first Stiefel-Whitney class $w_1(M)$. A Spin manifold has its structure group further lifted to $Spin(n)$, trivializing $w_2(M)$. For Spin manifolds, the first Pontrjagin class $p_1(M)$ is canonically twice another class, which we sometimes call "$p_1(M)/2$"; a String manifold has a lift to the String group trivializing this class. Just as the $\hat A$-genus is supposed to take integer values on manifolds with a spin structure, it was argued by Witten that the Witten genus of a String manifold should take values in a certain subring: namely, power series in $\Bbb{Z}[[q]]$ which are modular forms. This is a very particular subring $MF_*$ isomorphic to $\Bbb{Z}[c_4,c_6,\Delta]/(c_4^3 - c_6^2 - 1728\Delta)$. The development of the universal elliptic cohomology theory ${\cal Ell}$, its refinement at the primes $2$ and $3$ to topoogical modular forms $tmf$, and the so-called sigma orientation were initiated by the desire to prove these results. They produced a factorization of the Witten genus $MString_* \to \Bbb{C}[[q]]$ as follows:$$MString_* \to \pi_* tmf \to MF_* \subset \Bbb{C}[[q]]$$Moreover, the map $\pi_* tmf \to MF_*$ can be viewed as an edge morphism in a spectral sequence. There are also multiplicative structures in this story: the genus $MString_* \to \pi_* tmf$ preserves something a little stronger than the multiplicative structure, such as certain secondary products of String manifolds and geometric "power" constructions. What does this refinement give us, purely from the point of view of manifold invariants? The map $\pi_* tmf \to MF_*$ is a rational isomorphism, but not a surjection. As a result, there are certain values that the Witten genus does not take, just as the $\hat A$--genus of a Spin manifold of dimension congruent to 4 mod 8 must be an even integer (which implies Rokhlin's theorem). Some examples: $c_6$ is not in the image but $2c_6$ is, which forces the Witten genus of 12-dimensional String manifolds to have even integers in their power series expansion; similarly $\Delta$ is not in the image, but $24\Delta$ and $\Delta^{24}$ both are. (The full image takes more work to describe.) The map $\pi_* tmf \to MF_*$ is also not an injection; there are many torsion classes and classes in odd degrees which are annihilated. These actually provide bordism invariants of String manifolds that aren't actually detected by the Witten genus, but are morally connected in some sense because they can be described cohomologically via universal congruences of elliptic genera. For example, the framed manifolds $S^1$ and $S^3$ are detected, and Mike Hopkins' ICM address that Drew linked to describes how a really surprising range of framed manifolds is detected perfectly by $\pi_* tmf$. These results could be regarded as "the next version" of the same story for the relationship between the $\hat A$-genus and the Atiyah-Bott-Shapiro orientation for Spin manifolds. They suggest further stages. And the existence, the tools for construction, and the perspective they bring into the subject have been highly influential within homotopy theory, for entirely different reasons. Hope this provides at least a little motivation. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/153277', 'https://mathoverflow.net', 'https://mathoverflow.net/users/44912/']} | jdg_74852 |
stackexchange | llm_judgeable_groundtruth_similarity | 51496 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My problem is the following: Suppose I have a matrix A which looks the following: A = {{1, 2, 0, 0, 0}, {2, 3, 0, 1, 0}, {3, 4, 1, 0, 0}, {5, 6, 0, 0, 1}, {6, 7, 0, 0, 0}} What I want Mathematica to do is to drop or delete an entire row if the sum of columns 3,4&5 of that specific row is equal to zero. E.g. A[[1]] should be dropped because the sum of the last three elements of this row is zero. Same for the last row of matrix A . I tried the following but it's not working, and I don't know whether it's my fault or whether Mathematica encountered a problem with that specific case: A2 = Do[If[ Transpose[A][[3]][[i]] + Transpose[A][[4]][[i]] + Transpose[A][[5]][[i]] = 0, Drop[A[[n]]]], {i, Length[Transpose[A][[1]]]}]A Set::write: Tag Plus in 0+0+0 is Protected. Set::write: Tag Plus in 0+0+1 is Protected. Set::write: Tag Plus in 0+0+1 is Protected. General::stop: Further output of Set::write will be suppressed during this calculation. {{1, 2, 0, 0, 0}, {2, 3, 0, 1, 0}, {3, 4, 1, 0, 0}, {5, 6, 0, 0, 1}, {6, 7, 0, 0, 0}}
Now provide the response and nothing else.
| A = {{1, 2, 0, 0, 0}, {2, 3, 0, 1, 0}, {3, 4, 1, 0, 0}, {5, 6, 0,0, 1}, {6, 7, 0, 0, 0}};Select[A, Total@#[[3 ;; 5]] != 0 &]Cases[A, _?(Total@#[[3 ;; 5]] != 0 &)] {{2, 3, 0, 1, 0}, {3, 4, 1, 0, 0}, {5, 6, 0, 0, 1}} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/51496', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/15851/']} | jdg_74853 |
stackexchange | llm_judgeable_groundtruth_similarity | 950698 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I configure a DNS zone such that both a.b.c and b.c can serve as host names? In other words, can b.c be both a subdomain and a hostname at the same time? Is this perhaps just a matter of serving both A and NS (for delegation) records for b in c 's zone?
Now provide the response and nothing else.
| Yes you can! You also do somethhing similar when making example.com and www.example.com point to an A record. You will have to create the A record on the delegated zone though. You can combine A and NS records but you can’t combine them with a CNAME record. Note that the terms “hostname” and “subdomain” are kinda synonymous as you can create A records for www.test(.example.com.) and both wwe and test are considered a subdomain. You’re talking about a delegation of a zone here. And you can both delegate a zone and assign an A record to it (from the delegated zone, as its apex). | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/950698', 'https://serverfault.com', 'https://serverfault.com/users/450811/']} | jdg_74854 |
stackexchange | llm_judgeable_groundtruth_similarity | 76049 |
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:
Everywhere I see someone needing to get a sorted, unique list, they always pipe to sort | uniq . I've never seen any examples where someone uses sort -u instead. Why not? What's the difference, and why is it better to use uniq than the unique flag to sort?
Now provide the response and nothing else.
| sort | uniq existed before sort -u , and is compatible with a wider range of systems, although almost all modern systems do support -u -- it's POSIX. It's mostly a throwback to the days when sort -u didn't exist (and people don't tend to change their methods if the way that they know continues to work, just look at ifconfig vs. ip adoption). The two were likely merged because removing duplicates within a file requires sorting (at least, in the standard case), and is an extremely common use case of sort. It is also faster internally as a result of being able to do both operations at the same time (and due to the fact that it doesn't require IPC ( Inter-process communication ) between uniq and sort ). Especially if the file is big, sort -u will likely use fewer intermediate files to sort the data. On my system I consistently get results like this: $ dd if=/dev/urandom of=/dev/shm/file bs=1M count=100100+0 records in100+0 records out104857600 bytes (105 MB) copied, 8.95208 s, 11.7 MB/s$ time sort -u /dev/shm/file >/dev/nullreal 0m0.500suser 0m0.767ssys 0m0.167s$ time sort /dev/shm/file | uniq >/dev/nullreal 0m0.772suser 0m1.137ssys 0m0.273s It also doesn't mask the return code of sort , which may be important (in modern shells there are ways to get this, for example, bash 's $PIPESTATUS array, but this wasn't always true). | {} | {'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/76049', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5032/']} | jdg_74855 |
stackexchange | llm_judgeable_groundtruth_similarity | 39486521 |
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 service in which I need to ask an outside server via rest for some information: public class SomeService { public List<ObjectA> getListofObjectsA() { List<ObjectA> objectAList = new ArrayList<ObjectA>(); ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {}; ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef); return responseEntity.getBody(); }} How can I write a JUnit test for getListofObjectsA() ? I have tried with the below: @RunWith(MockitoJUnitRunner.class)public class SomeServiceTest { private MockRestServiceServer mockServer; @Mock private RestTemplate restTemplate; @Inject private SomeService underTest;@Beforepublic void setup() { mockServer = MockRestServiceServer.createServer(restTemplate); underTest = new SomeService(restTemplate); mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));} @Test public void testGetObjectAList() { List<ObjectA> res = underTest.getListofObjectsA(); Assert.assertEquals(myobjectA, res.get(0));} However the above code does not work, it shows that responseEntitty is null . How can I correct my test to properly mock restTemplate.exchange ?
Now provide the response and nothing else.
| You don't need MockRestServiceServer object. The annotation is @InjectMocks not @Inject . Below is an example code that should work @RunWith(MockitoJUnitRunner.class)public class SomeServiceTest { @Mock private RestTemplate restTemplate; @InjectMocks private SomeService underTest; @Test public void testGetObjectAList() { ObjectA myobjectA = new ObjectA(); //define the entity you want the exchange to return ResponseEntity<List<ObjectA>> myEntity = new ResponseEntity<List<ObjectA>>(HttpStatus.ACCEPTED); Mockito.when(restTemplate.exchange( Matchers.eq("/objects/get-objectA"), Matchers.eq(HttpMethod.POST), Matchers.<HttpEntity<List<ObjectA>>>any(), Matchers.<ParameterizedTypeReference<List<ObjectA>>>any()) ).thenReturn(myEntity); List<ObjectA> res = underTest.getListofObjectsA(); Assert.assertEquals(myobjectA, res.get(0)); } | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39486521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2386710/']} | jdg_74856 |
stackexchange | llm_judgeable_groundtruth_similarity | 323750 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to access a list 's (or tuple 's, or other iterable's) next or previous element while looping through it with a for loop? l = [1, 2, 3]for item in l: if item == 2: get_previous(l, item)
Now provide the response and nothing else.
| Expressed as a generator function: def neighborhood(iterable): iterator = iter(iterable) prev_item = None current_item = next(iterator) # throws StopIteration if empty. for next_item in iterator: yield (prev_item, current_item, next_item) prev_item = current_item current_item = next_item yield (prev_item, current_item, None) Usage: for prev,item,next in neighborhood(l): print prev, item, next | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/323750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/985/']} | jdg_74857 |
stackexchange | llm_judgeable_groundtruth_similarity | 18929782 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a generic rmarkdown template that will do analysis on a data frame. I'd like to be able to pass in a data frame to a rmarkdown file instead of hard-coding it each time. Below is a snippet I've been experimenting with. You can see that at the top I have to load the data frame (mtcars). I also manually identity the independent variables (ivs) and dependent variables (dvs). I'd like to pass these in as parameters. I'm trying to do a quick and dirty version of the SPSS Explore functionality. "Explore.Rmd": ```{r}library(ggplot2)data(mtcars)mtcars$am <- factor(mtcars$am, levels=c(0,1), labels=c("Manual", "Automatic"))df <- mtcarsivs <- c("cyl", "disp", "hp", "drat", "wt", "am", "qsec")dvs <- c("mpg", "qsec")```Histograms-------------------------------------```{r}for (v in union(ivs, dvs)){ hist <- ggplot(df, aes_string(x=v)) + geom_histogram() print(hist)}``` I'd like to have code that looks something like this to generate the HTML using knitr or something similar. myDF <- read.delim("mydata.tab")ivs <- c("iv1", "iv2", "iv3")dvs <- c("dv1", "dv2", "dv3")magic("Explore.Rmd", myDF, ivs, dvs) # <- how do I do this part? So, is it possible to have a static rmarkdown file and pass parameters to it? Or would there be another way to accomplish what I'm trying to do?
Now provide the response and nothing else.
| Another option is to list your variables using params in the rmarkdown::render function, see: http://rmarkdown.rstudio.com/developer_parameterized_reports.html . First, declare and provide default values for parameters in the YAML of the rmarkdown document: ---title: My Documentoutput: html_documentparams: df: !r data(mtcars); mtcars ivs: ["cyl", "disp", "hp", "drat", "wt", "am", "qsec"] dvs: ["mpg", "qsec"]--- These are then accessible in the report body through the list params : Histograms-------------------------------------```{r}for (v in union(params$ivs, params$dvs)){ hist <- ggplot(params$df, aes_string(x=v)) + geom_histogram() print(hist)}``` Finally, override the default values by passing a list of named arguments to rmarkdown::render : myDF <- read.delim("mydata.tab")ivs <- c("iv1", "iv2", "iv3")dvs <- c("dv1", "dv2", "dv3")rmarkdown::render("MyDocument.Rmd", params = list(df = myDF, ivs = ivs, dvs = dvs)) Since the YAML defines default values, one need provide only what one wishes to override, e.g., rmarkdown::render("MyDocument.Rmd", params = list(ivs = c("cyl", "wt"))) will still use the mtcars dataset, but only plots histograms for cyl , wt , mpg , and qsec . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18929782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/681/']} | jdg_74858 |
stackexchange | llm_judgeable_groundtruth_similarity | 46226143 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to design an HTML email template which is sent through email to my clients. I know that for designing an 'html email template ': No css files should be linked , all styling should be inline to html. All images should be referenced through online server url and should not be stored locally. My question is: Can I use bootstrap in html for designing an HTML email without downloading it and linking as a css file locally?
Now provide the response and nothing else.
| No. Bootstrap is a pre-defined framework containing properties for elements and classes which is used using external css entirely (with the properties for elements and classes being defined in an external file). Since external css can't be used to style e-mails, Bootstrap can't be used either. One might say that they can copy the code from the Bootstrap.css file and paste it withing <style></style> tags but even that is internal css and e-mails don't allow that. E-mails only allow inline css. So, Bootstrap can't be used in e-mails, and hence not in e-mail templates. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46226143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8610877/']} | jdg_74859 |
stackexchange | llm_judgeable_groundtruth_similarity | 1665726 |
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 optimize my PostgreSQL 8.3 DB tables to the best of my ability, and I'm unsure if I need to use varchar_pattern_ops for certain columns where I'm performing a LIKE against the first N characters of a string. According to this documentation , the use of xxx_pattern_ops is only necessary "...when the server does not use the standard 'C' locale". Can someone explain what this means? How do I check what locale my database is using?
Now provide the response and nothing else.
| Currently some locale [ docs ] support can only be set at initdb time, but I think the one relevant to _pattern_ops can be modified via SET at runtime, LC_COLLATE. To see the set values you can use the SHOW command. For example: SHOW LC_COLLATE _pattern_ops indexes are useful in columns that use pattern matching constructs, like LIKE or regexps. You still have to make a regular index (without _pattern_ops ) to do equality search on an index. So you have to take all this into consideration to see if you need such indexes on your tables. About what locale is, it's a set of rules about character ordering, formatting and similar things that vary from language/country to another language/country. For instance, the locale fr_CA (French in Canada) might have some different sorting rules (or way of displaying numbers and so on) than en_CA (English in Canada.). The standard "C" locale is the POSIX standards-compliant default locale. Only strict ASCII characters are valid, and the rules of ordering and formatting are mostly those of en_US (US English) In computing, locale is a set of parameters that defines the user's language, country and any special variant preferences that the user wants to see in their user interface. Usually a locale identifier consists of at least a language identifier and a region identifier. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1665726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107277/']} | jdg_74860 |
stackexchange | llm_judgeable_groundtruth_similarity | 60341627 |
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 the value is not same so I double qouted it, what I want to know is how go's map hash works so that cusKey and a is different in type result in the key is different. package mainimport ( "fmt")type key intconst cusKey key = 1const a int = 1func main() { dic := make(map[interface{}]interface{}) dic[cusKey] = 5 dic[a] = 6 fmt.Println(dic[cusKey]) fmt.Println(dic[a])} the output is 56 How go achieve this? The two keys value are all 1 . I know in go if the type is different, two value is different. So the two 1 is not identical. But how actually go's map did it? I tried to find out at map.go in source, but I can't found where go implement the hash funcion. Is it calculates hash of the keys with type annotations?
Now provide the response and nothing else.
| a and cusKey cannot be equal because they have different types. a is of type int , and cusKey is of type key (which has int as its underlying type, but it is a different type). Go maps require keys to be comparable. Spec: Map types: The comparison operators == and != must be fully defined for operands of the key type The key type of your dic map is interface{} , it's an interface type, and interface values are comparable if Spec: Comparison operators: Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil . An interface value stores the dynamic type and value, schematically, it's a "(value, type)" pair. When interface values are compared, the type is compared too, and if they don't match, the interface value comparison will yield false . For details about interface representation, see Go Data Structures: Interfaces (by Russ Cox) . For internals about Go's map, check out Dave Cheney: How the Go runtime implements maps efficiently (without generics) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60341627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5484988/']} | jdg_74861 |
stackexchange | llm_judgeable_groundtruth_similarity | 538313 |
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:
Vectors in vector spaces depend only on their size and direction. Force vectors, for example, depend also on their location. Opposite force at different locations, for example, do not annihilate each other but form torque. Why this anomaly?
Now provide the response and nothing else.
| The answer is that force is a vector, you just have to be careful about what the vector space is. As a starting point, I think it would be useful to review what exactly a force is. Imagine we've chosen some inertial reference frame $O$ and are using it to describe a universe which consists of nothing but a single particle, which has coordinates $\mathbf{x}(t)$ . As I'm sure you're aware, Newton's second law for this system just asserts that if we have some force law for the particle $\mathbf{F}(\mathbf{x}, \mathbf{\dot{x}},t)$ , the particle's motion satisfies $$\frac{d^2\mathbf{x}}{dt^2} = \mathbf{F}(\mathbf{x}, \mathbf{\dot{x}},t)/m$$ where m is the mass of the particle. The important thing to notice about this is that force isn't tied to random points in space -- it's tied to the movement of particles within space. I can't apply a force on an empty piece of vaccuum-- I can only do so to a particle. In this vein, we should then not be thinking of the force as acting on the vector space describing space, but rather the vector space describing the location of our particles. Now, for one particle, this is somewhat of a moot point because both of these vector spaces are just $\mathbb{R}^3$ . But what about if we have two particles? There's no "nice" (ie continuous, linear) way to describe the location of two particles in space using one vector in $\mathbb{R}^3$ , which we need if we're gonna be using vector algebra and calculus to solve stuff. But there is a nice way if we expand our vector space to $\mathbb{R}^6$ -- just let the first three components describe the location of particle 1, and the second three components describe the location of particle 2! In this formalism, it's clear how a force acting on particle 1 is different from a force acting on particle 2-- they're completely different vectors in $\mathbb{R}^6$ . Hopefully the generalization to arbitrary numbers of particles is obvious-- we can describe the location of $N$ particles using a vector in $\mathbb{R}^{3N}$ , and it's in this vector space-- known as configuration space -- that force lives. Using this concept of configuration space is very useful in physics and guides us to the incredibly important concept of lagrangian mechanics. Note-- when I say force "lives" in configuration space, I'm using that as shorthand for saying that it's the co-domain of the force. To recap-- force isn't tied to arbitrary locations in physical space, it's tied to the location of particles inhabiting that physical space. And these locations are described by the $3N$ dimensional configuration space, which is the vector space that force formally lives in. An alternate viewpoint If my description of force as a vector in $\mathbb{R}^{3N}$ seems contrived, be aware that another, perhaps more intuitive way of looking at the situation is by saying that each particle has its own force vector associated with it that depends on time and the locations/velocities of itself and all the other particles. In this viewpoint (which is the one taken in JiK's answer), the reason that applying a force to two different particles results in different dynamics of your system is because although both forces are members of $\mathbb{R}^3$ , they're two completely independent vectors since they're describing the dynamics of different particles. It's this independence that lets us combine the vector spaces of all the different forces in a natural way using the direct sum. Aside from just doing it because we can, this combination of vector spaces is useful for three main reasons: As mentioned before, it helps lead us to Lagrangian mechanics. On the aesthetic front, it combines $N$ different vector differential equations into one. It helps clarify the conditions we need to impose on $\mathbf{F}$ to guarantee existence and uniqueness of trajectories through configuration space via the Picard-Lindelöf theorem. Strictly speaking to do so we must first turn the force equation from a $3N$ dimensional 2nd order ODE to a $6N$ dimensional 1st order ODE, but this is trivial. Further discussion In the comments, Aloizio Macedo brought up a good point, which is that if you read my answer in a certain way it can seem like it's saying that force should only be described in terms of what particles are actually doing. Yet, I also seem to implicitly define force as a function on all of configuration space which is a contradiction because the system doesn't occupy every point of configuration space along its trajectory. So what gives? Well, in my mind, this comes down to a chicken and the egg type situation-- is the path of the particle through configuration space what's given and a force law deduced from that? Or is it the other way around and the force law is what's fundamental and what determines the path through configuration space? When I was writing my answer, I had the second one in mind, with force being given as some function $\mathbf{F}: \mathbb{R}^{3N} \times \mathbb{R}^{3N} \times \mathbb{R} \rightarrow \mathbb{R}^{3N}$ satisfying some continuity requirements. However, as Aloizio said, it's possible to read my second paragraph as saying that forces should only be defined when acting on particles, which necessitates the first viewpoint and a different formalism that makes the path through configuration space $\gamma$ the fundamental thing describing our universe and derives force through that. This wasn't my intention with the second paragraph. I just wanted to emphasize for the OP that force is something that fundamentally has to do with how particles move in space, rather than with space itself-- a statement that's true regardless of which of the above viewpoints you subscribe to. Hopefully that clears things up and addresses the concerns people may have had with my description of force. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/538313', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/9459/']} | jdg_74862 |
stackexchange | llm_judgeable_groundtruth_similarity | 30363647 |
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 query is like this: { "query": { "filtered": { "filter": { "bool": { "must": [ { "term": { "online": 1 } }, { "terms": { "mediaType": "flash" } } ] } } } }} it raise a QueryParsingException [[comos_v2] [terms] filter does not support [mediaType]] ,of which the field "mediaType" exactly does not exist in mapping.my question is why term filter does not raise the Exception?
Now provide the response and nothing else.
| The above is not a valid Query DSL. In the above Terms filter the values to "mediaType" field should be an array It should be the following : { "query": { "filtered": { "filter": { "bool": { "must": [ { "term": { "online": 1 } }, { "terms": { "mediaType": ["flash"] } } ] } } } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30363647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4915811/']} | jdg_74863 |
stackexchange | llm_judgeable_groundtruth_similarity | 25868430 |
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 came up with this program in some other site and thought of trying it, here's the program: #include <stdio.h>int main(){ int a=10; switch(a) { case '1': printf("one"); break; case '2': printf("two"); break; defau4t: printf("none"); } return 0;} Suprisingly enough, this compiles without errors or warnings. How is this possible? Isn't there an error on keyword "default"? Could anyone explain this behaviour?
Now provide the response and nothing else.
| The token is not considered to be a keyword at all. This is a goto jump mark named "defau4t" pointing at otherwise dead code (after the break; of case '2': )... Try this for laughs (and an endless loop): switch(a){ case '1': printf("one"); break; case '2': printf("two"); break; defau4t: printf("none"); default: goto defau4t;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25868430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387328/']} | jdg_74864 |
stackexchange | llm_judgeable_groundtruth_similarity | 22644780 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to import and merge a set of csv files using the following code, but it doesn't seem to be passing the by=c("X","Y") argument to the merge function. Any recommendations on how to fix this? Thank you csvfiles <- list.files(path = ".", pattern='bbg_.*\\.csv$')csvfiles <- paste("fx/",csvfiles,sep="")csvfilesmy.df <- do.call("merge",list(lapply(csvfiles, read.csv, header = TRUE), by=c("date","fx_code")))
Now provide the response and nothing else.
| merge doesn't accept more than 2 data.frames, so you can't pass it a larger list using do.call : do.call(merge, list(iris, iris, iris))#Error in fix.by(by.x, x) : # 'by' must specify one or more columns as numbers, names or logical Use Reduce instead: Reduce(function(x, y) merge(x, y, by="Species"), list(iris, iris, iris))#works | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22644780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3461430/']} | jdg_74865 |
stackexchange | llm_judgeable_groundtruth_similarity | 40433463 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Learning React from the docs and came across this example: class Square extends React.Component { constructor() { super(); this.state = { value: null, }; } ...} According to Mozilla , super allows you to use this in the constructor. Is there any other reason to use a standalone super (I know super allows you to access parent class's methods as well) but with React is there any other use case of just calling super() by itself?
Now provide the response and nothing else.
| super() is called inside a react component only if it has a constructor. For example, the below code doesn't require super: class App extends React.component { render(){ return <div>Hello { this.props.world }</div>; }} However if we have a constructor then super() is mandatory: class App extends React.component { constructor(){ console.log(this) //Error: 'this' is not allowed before super() }} The reason why this cannot be allowed before super() is because this is uninitialized if super() is not called. However even if we are not using this we need a super() inside a constructor because ES6 class constructors MUST call super if they are subclasses . Thus, you have to call super() as long as you have a constructor. (But a subclass does not have to have a constructor.) We call super(props) inside the constructor if we have to use this.props , for example: class App extends React.component{ constructor(props){ super(props); console.log(this.props); // prints out whatever is inside props }} I hope I could make it clear. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40433463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6730305/']} | jdg_74866 |
stackexchange | llm_judgeable_groundtruth_similarity | 17328921 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand the affect of inheritance order in C++.. I looked online, but I couldn't find a clear and sufficient answer... So, for the sake of the question, assume there are 2 classes: class B and class C. Now, define: class A1 : public B, public C{ ... };class A2 : public C, public B{ ... }; What is the difference between A1 and A2? Thanks a lot!
Now provide the response and nothing else.
| The C++11 Standard says (§10.1) [class.mi] : The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1). The three referenced paragraphs reveal that Constructors are called in the order you write them down (first base class in the list is constructed first) (§12.6.2.10). Different rules apply to virtual base classes which are always constructed from the most-derived class before any direct base classes. Destructors are called in the inverse order of construction (first base class in the list is destructed last) Storage layout is unspecified. You must not make any assumptions about the class layout in memory. The only exception are so called standard-layout classes (§9), which is basically a C-style struct. But since those are not allowed to have more than one class with non-static members in the class hierarchy, the question does not really apply here. Note that the memory layout can be important. For example, if an external library makes naive C-style casts that assume that the part of the object it's interested in is at the beginning, it can lead to run time errors that are hard to debug. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17328921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324827/']} | jdg_74867 |
stackexchange | llm_judgeable_groundtruth_similarity | 2098636 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that $$f\left ( x \right )= \begin{cases}1 & x \in \mathbb{Q}, \\ 0 & x\in \mathbb{R}\setminus \mathbb{Q}.\end{cases}$$ is not integrable. I came across this. I think that the function itself is not continuous? But I do not think that is a legitimate answer to this question.
Now provide the response and nothing else.
| Let $S(f,P)$ and $s(f,P)$ be the upper and low sums of $f$ with respect to partition $P$ of interval $[0,1]$ . Let $M_i=\sup\{f(x)| x \in I_i\}$ and $m_i=\inf\{f(x)| x \in I_i\}$ , where $I_i$ is the $i$ th interval of the partition $P$ . Note that $M_i=1$ for all $i$ , because every interval $I_i$ of the partition $P$ contains rational numbers. On the other hand, $m_i=0$ for all $i$ because every interval $I_i$ of the partition $P$ contains irrational numbers. By definition, $$S(f,P)=\sum_{i=1}^nM_i\mu(I_i)=\sum_{i=1}^n1\mu(I_i)=\sum_{i=1}^n\mu(I_i)=1-0=1$$ $$s(f,P)=\sum_{i=1}^nm_i\mu(I_i)=\sum_{i=1}^n0\mu(I_i)=0$$ Thus, $f$ is not Riemann integrable because the upper and lower integrals are not equal. (The upper integral is the limit of the upper sums and the lower integral is the limit of the lower sums). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2098636', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/406563/']} | jdg_74868 |
stackexchange | llm_judgeable_groundtruth_similarity | 20009031 |
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 asked a question about ASP.NET MVC Generic Controller and this answer shows a controller like this: public abstract class GenericController<T> where T : class{ public virtual ActionResult Details(int id) { var model = _repository.Set<T>().Find(id); return View(model); }} Which can be implemented like this. public class FooController : GenericController<Foo>{} Now when someone requests /Foo/Details/42, the entitiy is pulled from the _repository's Set<Foo>() , without having to write anything for that in the FooController . The way he explain that is good but think i want to develop a generic controller for product and customer where i will not use EF to load product & customer model rather use MS data access application block. public abstract class GenericController<T> where T : class { public virtual ActionResult Details(int id) { //var model = _repository.Set<T>().Find(id); var model =customer.load(id); or var model =product.load(id); return View(model); } } So when request comes like /Customer/Details/42 or /product/Details/11 then generic controller's details method will call but how we can detect that request comes from which controller and accordingly instantiate right class to load right model. If request comes for Customer then I need to load customer details from detail action method or if request comes for Product then I need to load Product details from detail action method of generic controller. How do I use generics to get the dataset of type T with the Entity Framework Data block?
Now provide the response and nothing else.
| You may create a set of repositories for working with your entities, like CustomerRepository , ProductRepository from base interface like public interface IBaseRepository{ T Get<T>(int id); void Save<T>(T entity);} and then extend your base controller class with repository type and its instance with any of DI frameworks public abstract class GenericController<T, TRepo> where T : class where TRepo : IBaseRepository, new() { private IBaseRepository repository; public GenericController() { repository = new TRepo(); } public virtual ActionResult Details(int id) { var model =repository.Get<T>(id); return View(model); } } Example for CustomerController public class CustomerController : GenericController<Customer, CustomerRepository>{} where CustomerRepository: public class CustomerRepository : IBaseRepository{ public T Get <T>(int id) { // load data from DB return new Customer(); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20009031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/728750/']} | jdg_74869 |
stackexchange | llm_judgeable_groundtruth_similarity | 40955656 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
def loadTest(filename): f=open(filename,'r') k=0 line=f.readline() labels=[] vectors=[] while line and k<4: k=k+1 l=line[:-1].split(r'","') s=float(l[0][1:]) tweet=l[5][:-1] print(l) line=f.readline() f.close() return What do split(r'","') actually does inside python split method?
Now provide the response and nothing else.
| Raw string vs Python string r'","' The r is to indicate it's a raw string . How is a raw string different to a regular python string? The special characters lose their special meaning inside a raw string . For example \n is a newline character inside a python string which will lose its meaning in a raw string and will simply mean backslash followed by n. string.split() string.split() will break and split the string on the argument that is passed and return all the parts in a list. The list will not include the splitting character(s). string.split('","') will break and split the string on every "," and return all the broken parts in a list excluding "," Eg: print 'Hello world","there you are'.split(r'","') Output: ['Hello world', 'there you are'] split() can do even more... You can specify how many parts you want your string to break into by passing in an extra parameter. Lets consider this string: 'hello,world,there,you,are' Split on all commas and break into n+1 parts where n is the number of commas: >>>print 'hello,world,there,you,are'.split(',')['hello', 'world', 'there', 'you', 'are'] Split on first comma and break only into 2 parts. >>>'hello,world,there,you,are'.split(',',1) ['hello', 'world,there,you,are'] Split on first and second comma and break into 3 parts. And so on... >>>'hello,world,there,you,are'.split(',',2)['hello', 'world', 'there,you,are'] And even more... From the docs: If splitting character(s) i.e separator is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example, >>>' 1 2 3 '.split()['1', '2', '3']>>>' 1 2 3 '.split(None, 1)['1', '2 3 ']>>>''.split()[]>>>' '.split()[]>>>' '.split(None)[] And even... . . . What? Isn't it enough that you are looking for more? Don't be so greedy :P.Just question yourself ? , it will make you non-greedy :D (You will get the joke if you know regular expressions) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40955656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3621111/']} | jdg_74870 |
stackexchange | llm_judgeable_groundtruth_similarity | 2992399 |
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:
People at my class acted like it was obvious, but I am not that sure: Why is this set not countable? $$\{-1,1\}^{\mathbb{Z}^2}$$ So, this set contains all the functions from $$\mathbb{Z}^2\to\{-1,1\}$$ where $\mathbb{Z}$ is the set of integers. Thank you for all the nice answers!
Now provide the response and nothing else.
| There is a bijection from $\Bbb Z^2$ to $\Bbb N$ , inducing a bijection from $\{-1,1\}^{\Bbb Z^2}$ to $\{-1,1\}^{\Bbb N}$ . And $\{-1,1\}^{\Bbb N}$ is famously uncountable by Cantor's diagonal argument: Assume for contradiction that it is countable. Then it's possible to list all functions in $\{-1,1\}^{\Bbb N}$ as $f_1,f_2,f_3,\ldots$ . Now consider the function $g\in \{ -1,1 \} ^{\Bbb N}$ given by $$g(n)=-f_n(n)$$ This function cannot be equal to any of the functions $f_1,f_2,\ldots$ , so it's not in the list, contradicting that our list contained all functions of $\{-1,1\}^{\Bbb N}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2992399', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/430930/']} | jdg_74871 |
stackexchange | llm_judgeable_groundtruth_similarity | 25960 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Would you be able to see the curvature of Mars from the top of Olympus Mons? And how much curvature would you see if it was visible, would it be only barely detectable, or would you see a lot of curvature? Olympus Mons is 25km high and the tallest known mountain in the Solar System. Mars is just over half the size of Earth. Here on Earth, the curvature of the planet is hardly visible from the height of commerical aeroplane (roughly 10km). I was wondering, considering the height of Olympus Mons and the size difference of Mars, if the curvature from up there would be very pronounced.
Now provide the response and nothing else.
| The impression I get from the Wikipedia page on Olympus Mons is that from the top of the volcano, you can't even see parts of Mars that aren't Olympus Mons. Quoted from above: Because of the size of Olympus Mons and its shallow slopes, an observer standing on the Martian surface would be unable to view the entire profile of the volcano, even from a great distance. The curvature of the planet and the volcano itself would obscure such a synoptic view. Similarly, an observer near the summit would be unaware of standing on a very high mountain, as the slope of the volcano would extend far beyond the horizon, a mere 3 kilometers away. Emphasis mine. Wikipedia sources the bold line to this source in the Way Back Machine , which works out the math. Near the bottom of the page, there is a section starting with the phrase: Years ago someone asked me if a person could see the horizon of Mars from the top of Olympus Mons. That is not as simple as one may think. If Mars was a prefect sphere and the slopes of Olympus Mons were smooth then the distance to the horizon could be calculated fairly easy. However, the surface of Mars has hills and valleys, and Tharsis bulges out from the mean spherical surface of Mars several miles, so one must consider that as well. That's pretty much your question. The conclusion is: Second, if this same [6 foot tall] person stood at the top of Olympus Mons (88704 ft) we would find that he or she could see a lot further to the horizon, some 265 miles away, if nothing was in the way: $\cos A = (11,121,762.53 / (11,121,762.53 + 88704 + 6)$ $A = 7.2^\circ = 0.126\ \textrm{radians} \leftarrow (0.126 \times 11,121,762.53 ft) / 5280 = 265 \textrm{miles}$ At those angles a person 6 feet high would be looking down at an angle of 7.2 degrees in order to see the horizon of Mars, so they would surely look down into the hump positioned at 50 miles away or at the 2.5-degree grade of the slope instead of over it to the horizon. So it would seem that the horizon, as viewed from the top of Olympus Mons, would still be part of Olympus Mons. Indeed, you wouldn't even be able to see most of Olympus Mons from the top. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/25960', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/2844/']} | jdg_74872 |
stackexchange | llm_judgeable_groundtruth_similarity | 10367751 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Going through Learn Python the Hard Way, lesson 25. I try to execute the script, and the result is like so: myComp:lphw becca$ python l25 myComp:lphw becca$ Nothing prints or displays in terminal. Here's the code. def breaks_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words)def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print worddef print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print worddef sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words)def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words)def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) Please help!
Now provide the response and nothing else.
| All your code is function definitions, but you never call any of the functions, so the code doesn't do anything. Defining a function with the def keyword just, well, defines a function . It doesn't run it. For example, say you just have this function in your program: def f(x): print x You're telling the program that whenever you call f , you want it to print the argument. But you're not actually telling it that you want to call f , just what to do when you do call it. If you want to call the function on some argument, you need to do so, like this: # defining the function f - won't print anything, since it's just a function definitiondef f(x): print x# and now calling the function on the argument "Hello!" - this should print "Hello!"f("Hello!") So if you want your program to print something, you need to put in some calls to the functions you defined. What calls and with what arguments depends on what you want the code to do! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10367751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1186742/']} | jdg_74873 |
stackexchange | llm_judgeable_groundtruth_similarity | 6337595 |
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 open several different workbooks (excel xlsx format) in COM, and mess with them. As the program progresses I wish to close one specific workbook but keep the rest open. How do I close ONE workbook? (instead of the entire excel application) xl = Dispatch("Excel.Application")xl.Visible = Falsetry: output = xl.Workbooks.Open(workbookName) output2 = xl.Workbooks.Open(workbook2Name)except com_error: print "you screwed up blahblahblah" exit()#work on some stuff#close output but keep output2 open
Now provide the response and nothing else.
| The the Workbook COM object has a Close() method . Basically, it should be something like: xl = Dispatch('Excel.Application')wb = xl.Workbooks.Open('New Workbook.xlsx')# do some stuffwb.Close(True) # save the workbook The above was just a skeleton here's some code that works on my machine against Office 2010: from win32com.client import Dispatchxl = Dispatch('Excel.Application')wb = xl.Workbooks.Add()ws = wb.Worksheets.Add()cell = ws.Cells(1)cell.Value = 'Some text'wb.Close(True, r'C:\Path\to\folder\Test.xlsx') Of course, that creates a new xlsx file. But then I'm able to successfully open and modify the file in the same session as follows: wb = xl.Workbooks.Open(r'C:\Path\to\folder\Test.xlsx')ws = wb.Worksheets(1)cell = ws.Cells(2)cell.Value = 'Some more text'wb.Close(True) Don't know if any of that helps... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6337595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/322900/']} | jdg_74874 |
stackexchange | llm_judgeable_groundtruth_similarity | 34532878 |
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 use activation functions other than the pre-implemented "logistic" and "tanh" in the R package neuralnet. Specifically, I would like to use rectified linear units (ReLU) f(x) = max{x,0}. Please see my code below. I believe I can use custom functions if defined by (for example) custom <- function(a) {x*2} but if I set max(x,0) instead of x*2 then R tells me that 'max is not in the derivatives table', and same for '>' operator. So I am looking for a sensible workaround as I am thinking numerical integration of max in this case wouldn't be an issue. nn <- neuralnet( as.formula(paste("X",paste(names(Z[,2:10]), collapse="+"),sep="~")), data=Z[,1:10], hidden=5, err.fct="sse", act.fct="logistic", rep=1, linear.output=TRUE) Any ideas? I am a bit confused as I didn't think the neuralnet package would do analytical differentiation.
Now provide the response and nothing else.
| The internals of the neuralnet package will try to differentiate any function provided to act.fct . You can see the source code here . At line 211 you will find the following code block: if (is.function(act.fct)) { act.deriv.fct <- differentiate(act.fct) attr(act.fct, "type") <- "function"} The differentiate function is a more complex use of the deriv function which you can also see in the source code above. Therefore, it is currently not possible to provide max(0,x) to the act.fct . It would require an exception placed in the code to recognize the ReLU and know the derivative. It would be a great exercise to get the source code, add this in and submit to the maintainers to expand (but that may be a bit much). However, regarding a sensible workaround, you could use softplus function which is a smooth approximation of the ReLU. Your custom function would look like this: custom <- function(x) {log(1+exp(x))} You can view this approximation in R as well: softplus <- function(x) log(1+exp(x))relu <- function(x) sapply(x, function(z) max(0,z))x <- seq(from=-5, to=5, by=0.1)library(ggplot2)library(reshape2)fits <- data.frame(x=x, softplus = softplus(x), relu = relu(x))long <- melt(fits, id.vars="x")ggplot(data=long, aes(x=x, y=value, group=variable, colour=variable))+ geom_line(size=1) + ggtitle("ReLU & Softplus") + theme(plot.title = element_text(size = 26)) + theme(legend.title = element_blank()) + theme(legend.text = element_text(size = 18)) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34532878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5731191/']} | jdg_74875 |
stackexchange | llm_judgeable_groundtruth_similarity | 163764 |
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 copied the title and concept for this question from here . I have data = {{"ID", "Value"}, {1, 48}, {1, 45}, {1, 52}, {1, 43}, {1, 41}, {2, 50}, {2, 42}, {2, 51}, {2, 52}, {bb, 52}, {bb, 54}, {dd, 20}, {dd, 25}, {dd, 27}, {cc, 30}}; I want to create a new column called "Count" so that: result = {{"ID", "Value", "Count"}, {1, 48, 1}, {1, 45, 2}, {1, 52, 3}, {1, 43, 4}, {1, 41, 5}, {2, 50, 1}, {2, 42, 2}, {2, 51, 3}, {2, 52, 4}, {bb, 52, 1}, {bb, 54, 2}, {dd, 20, 1}, {dd, 25, 2}, {dd, 27, 3}, {cc, 30, 1}}; I have a huge data with almost 2 billion observations. Therefore, efficient coding would save a lot of time and energy. As always, help is much appreciated. Thanks
Now provide the response and nothing else.
| r1 = Join[{Append[First[data], "Count"]}, Join @@ Values @ GroupBy[Rest @data, First, MapIndexed[Join, #]&]] {{ID,Value,Count},{1,48,1},{1,45,2},{1,52,3},{1,43,4},{1,41,5},{2,50,1},{2,42,2},{2,51,3},{2,52,4},{bb,52,1},{bb,54,2},{dd,20,1},{dd,25,2},{dd,27,3},{cc,30,1}} Update 1: Prepend[Join @@ (MapIndexed[Join, #]&/@ SplitBy[Rest @ data, First]), Append[First[data], "Count"]] {{ID,Value,Count},{1,48,1},{1,45,2},{1,52,3},{1,43,4},{1,41,5},{2,50,1},{2,42,2},{2,51,3},{2,52,4},{bb,52,1},{bb,54,2},{dd,20,1},{dd,25,2},{dd,27,3},{cc,30,1}} Update 2: addCounter = Module[{cnt}, cnt[_String] := "Count"; cnt[_] := 1; {##, cnt[#]++} & @@@ #]&;addCounter @ data {{"ID", "Value", "Count"}, {1, 48, 1}, {1, 45, 2}, {1, 52, 3}, {1, 43, 4}, {1, 41, 5}, {2, 50, 1}, {2, 42, 2}, {2, 51, 3}, {2, 52, 4}, {bb, 52, 1}, {bb, 54, 2}, {dd, 20, 1}, {dd, 25, 2}, {dd, 27, 3}, {cc, 30, 1}} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/163764', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/18636/']} | jdg_74876 |
stackexchange | llm_judgeable_groundtruth_similarity | 625726 |
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:
If we take a lamp containing hydrogen gas and heat it up ( gas-discharge lamp) , it produces hydrogen's emission spectrum. Why doesn't it produce a blackbody spectrum? After all, the gas has some temperature, and that allows for a blackbody spectrum. Similarly, why does an incandescent light bulb (which has a tungsten filament within) yield a blackbody spectrum when heated, as opposed to tungsten's emission spectrum?
Now provide the response and nothing else.
| To be a blackbody a source must be in thermal equilibrium and be capable of absorbing all radiation that is incident upon it. The hydrogen discharge lamp can do the former - the hydrogen energy levels are populated according to the Boltzmann factors $^1$ and there may even be a little ionisation. However, it cannot do the latter - it could absorb radiation at the discrete frequencies governed by the hydrogen energy levels, but is otherwise quite transparent (by design). To get it to emit as a blackbody (why would you want to do that - you use discharge lamps to see the line spectrum?) you need a source of absorption over a continuum of wavelengths and you need to make sure there are enough absorbers (by making the gas dense, or having a large amount of gas) that it is opaque to radiation. That could be done (and is done in the Sun for example) by raising the temperature and having significant amounts of hydrogen photoionisation, which then allows a photorecombination continuum (in practice this actually involves H $-$ ions in the Sun). If you then ramp up the density of the gas, the recombination continuum would get stronger, gradually filling in the gaps between the emission lines until you approached a blackbody spectrum. I doubt there is enough hydrogen gas in a discharge tube to do this, since by design they are meant to display clean line spectra. A filament lamp is different. The solid filament already has a continuum of conduction band energy states available to populate and depopulate. It is thus opaque to radiation at a wide range of frequencies corresponding to the continuum of transition energies between these states. If in thermal equilibrium, then the radiation it produces will be continuous and approximate to a blackbody spectrum. $^1$ This is only really true for thermal excitation. In most discharge tubes you are supplying energy by accelerating electrons and ions with electric fields. In such circumstances it is unlikely that the atoms, ions and electrons have energy distributions characterised by Maxwell-Boltzmann distributions and therefore could not emit blackbody radiation (or even thermal radiation) at a well-defined temperature. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/625726', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/177855/']} | jdg_74877 |
stackexchange | llm_judgeable_groundtruth_similarity | 298 |
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:
Am I looking for a better behaved distribution for the independent variable in question, or to reduce the effect of outliers, or something else?
Now provide the response and nothing else.
| I always hesitate to jump into a thread with as many excellent responses as this, but it strikes me that few of the answers provide any reason to prefer the logarithm to some other transformation that "squashes" the data, such as a root or reciprocal. Before getting to that, let's recapitulate the wisdom in the existing answers in a more general way. Some non-linear re-expression of the dependent variable is indicated when any of the following apply: The residuals have a skewed distribution. The purpose of a transformation is to obtain residuals that are approximately symmetrically distributed (about zero, of course). The spread of the residuals changes systematically with the values of the dependent variable ("heteroscedasticity"). The purpose of the transformation is to remove that systematic change in spread, achieving approximate "homoscedasticity." To linearize a relationship. When scientific theory indicates. For example, chemistry often suggests expressing concentrations as logarithms (giving activities or even the well-known pH). When a more nebulous statistical theory suggests the residuals reflect "random errors" that do not accumulate additively. To simplify a model. For example, sometimes a logarithm can simplify the number and complexity of "interaction" terms. (These indications can conflict with one another; in such cases, judgment is needed.) So, when is a logarithm specifically indicated instead of some other transformation? The residuals have a "strongly" positively skewed distribution. In his book on EDA, John Tukey provides quantitative ways to estimate the transformation (within the family of Box-Cox, or power, transformations) based on rank statistics of the residuals. It really comes down to the fact that if taking the log symmetrizes the residuals, it was probably the right form of re-expression; otherwise, some other re-expression is needed. When the SD of the residuals is directly proportional to the fitted values (and not to some power of the fitted values). When the relationship is close to exponential. When residuals are believed to reflect multiplicatively accumulating errors. You really want a model in which marginal changes in the explanatory variables are interpreted in terms of multiplicative (percentage) changes in the dependent variable. Finally, some non - reasons to use a re-expression : Making outliers not look like outliers. An outlier is a datum that does not fit some parsimonious, relatively simple description of the data. Changing one's description in order to make outliers look better is usually an incorrect reversal of priorities: first obtain a scientifically valid, statistically good description of the data and then explore any outliers. Don't let the occasional outlier determine how to describe the rest of the data! Because the software automatically did it. (Enough said!) Because all the data are positive. (Positivity often implies positive skewness, but it does not have to. Furthermore, other transformations can work better. For example, a root often works best with counted data.) To make "bad" data (perhaps of low quality) appear well behaved. To be able to plot the data. (If a transformation is needed to be able to plot the data, it's probably needed for one or more good reasons already mentioned. If the only reason for the transformation truly is for plotting, go ahead and do it--but only to plot the data. Leave the data untransformed for analysis.) | {} | {'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/298', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/125/']} | jdg_74878 |
stackexchange | llm_judgeable_groundtruth_similarity | 32431 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In critical applications tires are inflated using pure nitrogen ( link ). But carbon dioxide (CO2) is a larger molecule (will leak slower from the tire), as well as inert (will not oxidize rim and will not combust in case of an accident). ( link ) Also, from the ideal gas law , pressure is proportional to the density, individual gas constant and temperature. Assuming constant volume (i.e. P ∝ R*T), any change in temperature is "amplified" by the individual gas constant. And the gas constant is in favor of CO2: R(CO2) < R(O2) < R(N2) . ( ref ) So CO2 seems to give better pressure stability over temperature fluctuations. Also, CO2 storage is cheaper than nitrogen storage. So why tires are inflated with nitrogen and not CO2?
Now provide the response and nothing else.
| Nitrogen is inert and doesn't affect rubber or the steel rim. Carbon dioxide is highly reactive and affects both the rubber by causing swelling in the rubber. It also would cause corrosion in iron based rims (particularly Carbon- Steel). Edit: When CO2 is mixed with moisture becomes Carbolic acid which is corrosive. It all depends on concentration. It is like comparing Acetic Acid commonly referred to as Vinegar. At 3% you can put on french fries. At industrial strength 97% not only will it dissolve the french fry but also human flesh right down to the bone very fast. As for CO2 affect on rubber I cited a industry source-(Air Liquide) a company that specialized in compressed gases. In the case of automotive tires using CO2 would probably cause catastrophic failure. My experience with Nitrogen is that I have noticed it to be much more quieter while driving and less pressure variations when the temperature varies from season to season. http://encyclopedia.airliquide.com/encyclopedia.asp?LanguageID=11&GasID=26 Check under Material Compatibility under the heading of Elastomers- Quite illuminating..... | {} | {'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/32431', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/9511/']} | jdg_74879 |
stackexchange | llm_judgeable_groundtruth_similarity | 33576979 |
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 think of a reason why Tomcat would have a shutdown port but I can't think of any. As I understand it this port only works if messaged locally as it's attached to the loopback device, hence what's the point of having this? Couldn't this be done via internal command in a way that couldn't be spoofed by someone from outside your network? Thank you!
Now provide the response and nothing else.
| The shutdown port provides an OS neutral, scriptable way to shutdown a Tomcat instance. Once you remove the shutdown port you are almost certainly into the realms of OS specific code (or at least different code for Windows vs Unix plus derivatives). By default, Tomcat aims for common configuration and behaviour across all platforms. The security profile of Tomcat installations vary wildly from single developer machines to thousands of instances in the cloud. It is impossible for the default configuration to be perfect for all likely installation environments. Tomcat aims for reasonably secure defaults that admins are expected to adjust to suit their environment. In this case, the security risks come if untrusted users a) have access to the shutdown port and b) know the shutdown command. This should be a fairly rare scenario, hence why the shutdown port remains enabled for localhost by default. I certainly wouldn't want to run a service where I cared about its security on a machine where I had untrusted users. That said it does happen and, for those use cases, the shutdown port can be disabled. Once the shutdown port is disabled, the Unix + derivatives solution is to set TOMCAT_PID at which point the scripts will continue to work as expected. On Windows, you are proably going to need to run as a service. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33576979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5460637/']} | jdg_74880 |
stackexchange | llm_judgeable_groundtruth_similarity | 30700169 |
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 Haskell, it is said that any ADT can be expressed as sum of products. I'm trying to find a flat type that is isomorphic to Tree , on Data.Tree . Tree a = Node a [Tree a] -- has a nested type (List!) I want to write a functionally identical definition for Tree without nested types: Tree = ??? -- no nested types allowed For that, I tried writing the recursive relation for the type algebras: L a = 1 + a * L aT a = a * L (T a) Inlining L, I had: T a = a * (1 + T a * L (T a))T a = a * (1 * T a * (1 + T a * L (T a)))T a = a * (1 + T a * (1 + T a * (1 + T a * L (T a)))) That wasn't going anywhere, so I stopped and did the multiplications, leaving me with: T a = a + a * T a + a * T a * T a ... Which is the same as: T a = a * (T a) ^ 0 + a * (T a) ^ 1 + a * (T a) ^ 2 ... That is a sum of products, but it is infinite. I can't write that in Haskell. By abusing the algebra: (T a) - (T a) ^ 2 = a * T a- (T a) ^ 2 - a * T a + (T a) = 0 Solving for T a , I found that: T a = 1 - a Which obviously doesn't make any sense. So, back to the original question: how do I flatten Tree from Data.Tree so I can write a type that is isomorphic to it without nested types? This question isn't a duplicate of my previous question . The last one is about representing nested types with the Scott Encoding, for which the correct answer is "ignore the nesting". This one proceeds to ask how to flatten a nested type anyway (since it is needed for a particular use of the Scott Encoding, but not obligatory in general).
Now provide the response and nothing else.
| Once you got to T a = a * (1 + T a * L (T a)) you could continue = a + a * T a * L (T a) -- distribute = a + T a * (a * L (T a)) -- commute and reassociate = a + T a * T a -- using your original definition of T backwards so you arrive at data Tree a = Leaf a | InsertLeftmostSubtree (Tree a) (Tree a) I'm not sure to what extent this is an instance of a general procedure, however. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30700169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1031791/']} | jdg_74881 |
stackexchange | llm_judgeable_groundtruth_similarity | 10084 |
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 can I run commands in batch mode over ssh? That is, what is the ssh command's equivalent of sftp -b <filename> <hostname> ? I have a set of commands which I wish to run across a set of hosts connecting over ssh . Over sftp , i store the commands in a file filename and connect to the host and run the commands using the previously mentioned command. Is something like that possible over ssh ?
Now provide the response and nothing else.
| Correct me if I'm wrong, but you seem to be wanting to run regular shell commands on the remote server where the script is local. #!/bin/shtrap "rm -f /tmp/sendonssh.$$.*" 0 1 2 3 15# commands to run on the remote servercat <<'EOF' >> /tmp/sendonssh.$$.shmkdir -p /tmp/foobar.$$mv $HOME/xyzzy /tmp/foobar.$$chmod 640 $HOME/xyzzyEOF# call for each argumentfor userhost in "$@"; do errorout=`ssh -aTxo BatchMode=yes $userhost /bin/sh -s < /tmp/sendonssh.$$.sh 2>&1` rc=$? if [ $rc -ne 0 ]; then echo "Error: $userhost: $errorout" exit $rc fidone I do this with some 'remote execution' apps in my test environment using Python instead of the shell: ssh $userhost python < $pythonscriptfilename . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/10084', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4950/']} | jdg_74882 |
stackexchange | llm_judgeable_groundtruth_similarity | 184025 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This topic has been inspired by some time spending on trying to refining my knowledge about PDE's in general. Then everybody knows how to solve $$y''(t)=\pm y(t).$$ Then I tried to slightly modify the question and I focused on $$(\therefore)\;y''(t)=f(y(t)),\; f\in C^1(\mathbb R,\mathbb R).$$ What I was trying to do was to derive some general properties about the solutions to this equation. In particular I ask to you, since I was not able to answer myself: Must a solution of $(\therefore)$, not identically zero, have necessarily a finite number of zeroes on $[0,1]$? My idea was to derive an estimate like $$|y(\eta)-y(\xi)|\leq C|\eta-\xi|^p,\; p>1;$$ Moreover, if a solution $y$ were to have an infinite number of zeroes in $[0,1]$, the the set of zeroes should have an accumulation point, and in this point all the derivatives should be equal to $0$ by continuity, then maybe the function should remain to much squeezed to be different from zero. Hope you can help me because this interests me a lot. Many thanks for your attention. (I tried to post this on mathlinks as well but nobody answered me yet)
Now provide the response and nothing else.
| This is a familiar type of ODE. In the following I shall deal with the "purely formal" aspect of it. Questions of sign under the square root or behavior near special points have to be treated "at runtime". Let $F$ be a primitive of the given function $y\mapsto f(y)$. Multiplying the given differential equation by $y'(t)$ we get$$y''(t)y'(t)=f\bigl(y(t)\bigr)\,y'(t)$$or$${d\over dt}\left({1\over2} y'^2(t)-F\bigl(y(t)\bigr)\right)=0\ .$$Therefore there is a constant $C$ such that$$y'(t)=\sqrt{2F\bigl(y(t)\bigr)+C}\ .$$Now the variables can be separated:$${dy\over\sqrt{2F(y)+C}}= dt\ .$$This shows that ODEs of the considered type can be solved by quadratures. (The trick of multiplying by $y'$ is absolutely standard in mechanics, where it leads to the principle of "conservation of energy".) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/184025', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15453/']} | jdg_74883 |
stackexchange | llm_judgeable_groundtruth_similarity | 34701596 |
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 know if there is any ruby function or method to find out the type of object ( Integer , String , Symbol , etc.).
Now provide the response and nothing else.
| The assumption you've made is that if the value returned by a mathematical operation is an integer, the value's class will be Fixnum. That's not correct. Take a look: a = 5puts a.class# => Fixnumb = 5.0puts b.class# => Float Mathematically speaking, 5 and 5.0 are the same number and that number is an integer. But 5 and 5.0 in Ruby (like many other programming languages) are not the same. One is a fixed-point value (ergo Fixnum) and the other is a floating-point value (Float). A Fixnum can represent integers only, but a Float can represent both integers and fractions (but, it behooves me to mention, not all fractions ). In Ruby, when you do a mathematical operation with two Fixnums, a Fixnum is returned: a = 4puts a.class # => Fixnumx = a ** 2puts x # => 16puts x.class # => Fixnum However, if either number is a Float, a Float is returned: a = 4x = a ** 2.0puts x # => 16.0puts x.class # => Floatb = 4.0puts b.class # => Floaty = b ** 2puts y # => 16.0puts y.class # => Floaty = b ** 2.0puts y # => 16.0puts y.class # => Float You asked how to "find the type of an object," and the answer to that question is to use the Object#class method, as above. But as you can see, "Is the object a Fixnum?" and "Is the object an integer?" are two different questions. If you want to know if a number in Ruby is an integer even if it's a Float, refer to the excellent answers to this question: Checking if a Float is equivalent to an integer value in Ruby | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34701596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5688533/']} | jdg_74884 |
stackexchange | llm_judgeable_groundtruth_similarity | 19501584 |
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 pass in the url for the template via a scope variable. The scope will not change so the template doesn't need to update based on it, but currently the scope variable is always undefined. <div cell-item template="{{col.CellTemplate}}"></div> Ideally the directive would be: .directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) { return { scope: { template: '@template' }, templateUrl: template // or {{template}} - either way }; }]) This doesn't work however. I've tried a lot of different permutations in accomplishing the same concept, and this seems the closest, however it still doesn't work. .directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) { return { scope: { template: '@template' }, link: function (scope, element, attrs) { var templateUrl = $parse(attrs.template)(scope); $http.get(templateUrl, { cache: $templateCache }).success(function (tplContent) { element.replaceWith($compile(tplContent)(scope)); }); } }; }]) I've also tried using ng-include, but that also doesn't evaluate scope variables before compiling. The CellTemplate value is coming from a database call so is completely unknown before evaluation. Any suggestions for getting this working would be greatly appreciated! Edit:I'm using angular 1.0.8 and am not able to upgrade to a newer version.
Now provide the response and nothing else.
| You are not far off at all. You don't need to use an isolated scope for the directive. You can pass the templateUrl like this: <div cell-item template="col.CellTemplate"></div> Then add a watch to detect when the template value changes: .directive("cellItem", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) { return { restrict: 'A', link: function(scope , element, attrs) { scope.$watch(attrs.template, function (value) { if (value) { loadTemplate(value); } }); function loadTemplate(template) { $http.get(template, { cache: $templateCache }) .success(function(templateContent) { element.replaceWith($compile(templateContent)(scope)); }); } } } }]); Here is a working Plunker: http://plnkr.co/edit/n20Sxq?p=preview | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19501584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404894/']} | jdg_74885 |
stackexchange | llm_judgeable_groundtruth_similarity | 2776 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
If ℝ # exists then why is cof(θ L(ℝ) ) = ω? Also I have the same question for the L(V λ+1 ) generalization (if it's actually a different proof; I presume it isn't), i.e. if θ is defined as the sup of the surjections in L(V λ+1 ) of V λ+1 onto an ordinal, then if V λ+1 # exists why is cof(θ L(V λ+1 ) ) = ω?
Now provide the response and nothing else.
| This is because the pieces of the sharp singularize Theta. Let s_n be the sequence of the first n cardinals above continuum and let a_n be the nth cardinal above continuum. Then the theory of reals with a parameter s_n in L_{a_n+1}(R) is a set of reals A_n. They are Wadge cofinal in Theta, another words the sequence is not in L(R) but each A_n is and that is why you get a singularization. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/2776', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1178/']} | jdg_74886 |
stackexchange | llm_judgeable_groundtruth_similarity | 97252 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find all normal subgroups of $S_3 \times S_3$. What are normal subgroup and $S_3 \times S_3$? Could I have some examples?
Now provide the response and nothing else.
| Just like in any group there are two "obvious" normal subgroups (the trivial subgroup and the whole group), but there may be others, in a direct product there are some "obvious" normal subgroups, but there may be others. If $G$ and $H$ are groups, and $N\triangleleft G$ is any normal subgroup of $G$ and $M\triangleleft H$ is any normal subgroup of $H$, then $N\times M$ is a subgroup of $G\times H$, and in fact $(N\times M)\triangleleft (G\times H)$. I don't know which of the many equivalent definitions of normal subgroup you are using, nor what theorems you may have already proven about normal subgroups, so I'll leave the verification to you. So, for example, since the normal subgroups of $S_3$ are $\{1\}$, $A_3$, and $S_3$, then you automatically get nine normal subgroups of $S_3\times S_3$ by taking all subgroups: $\{1\}\times\{1\}$ (the trivial subgroup), $\{1\}\times A_3$, $\{1\}\times S_3$, $A_3\times\{1\}$, $A_3\times A_3$, $A_3\times S_3$, $S_3\times\{1\}$, $S_3\times A_3$, and $S_3\times S_3$ (the whole group). But there may be others (just like there are subgroups of $G\times H$ that are not of the form $A\times B$ with $A\leq G$ and $B\leq H$). To give you a different example, take $C_2\times C_2$, there $C_2$ is the cyclic group of order $2$. The only subgroups of $C_2$ are $\{1\}$ and $C_2$, so you only get four normal subgroups of $C_2\times C_2$ this way: $\{1\}\times\{1\}$, $\{1\}\times C_2$, $C_2\times\{1\}$, and $C_2\times C_2$. But there is another (normal) subgroup of $C_2\times C_2$: $\{ (1,1), (x,x)\}$; this does not come as a product of two normal subgroups. So you still need to check to see if, in addition to the nine normal subgroups of $S_3\times S_3$ that we found above, there may be another. To get you started, assume that $N\triangleleft S_3\times S_3$ is not the trivial subgroup, and $(a,b)\in N$. If $a\neq 1$, consider conjugation by elements of the form $(x,1)$ to try to figure out what is the collection of all elements of the form $(y,1)$ that are in $N$. Then work symmetrically to find elements of the form $(1,z)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/97252', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7667/']} | jdg_74887 |
stackexchange | llm_judgeable_groundtruth_similarity | 2257322 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider an application handling uploading of potentially very large PNG files. All uploaded files must be stored to disk for later retrieval. However, the PNG files can be up to 30 MB in size, but disk storage limitations gives a maximum per file size of 1 MB. The problem is to take an input PNG of file size up to 30 MB and produce an output PNG of file size below 1 MB. This operation will obviously be lossy - and reduction in image quality, colors, etc is not a problem. However, one thing that must not be changed is the image dimension. Hence, an input file of dimension 800x600 must produce an output file of dimension 800x600. The above requirements outlined above are strict and cannot be changed. Using ImageMagick (or some other open source tool) how would you go about reducing the file size of input PNG-files of size ~30 MB to a maximum of 1 MB per file, without changing image dimensions?
Now provide the response and nothing else.
| PNG is not a lossy image format, so you would likely need to convert the image into another format-- most likely JPEG. JPEG has a settable "quality" factor-- you could simply keep reducing the quality factor until you got an image that was small enough. All of this can be done without changing the image resolution. Obviously, depending on the image, the loss of visual quality may be substantial. JPEG does best for "true life" images, such as pictures from cameras. It does not do as well for logos, screen shots, or other images with "sharp" transitions from light to dark. (PNG, on the other hand, has the opposite behavior-- it's best for logos, etc.) However, at 800x600, it likely will be very easy to get a JPEG down under 1MB. (I would be very surprised to see a 30MB file at those smallish dimensions.) In fact, even uncompressed , the image would only be around 1.4MB: 800 pixels * 600 pixels * 3 Bytes / color = 1,440,000 Bytes = 1.4MB Therefore, you only need a 1.4:1 compression ratio to get the image down to 1MB. Depending on the type of image, the PNG compression may very well provide that level of compression. If not, JPEG almost certainly could-- JPEG compression ratios on the order of 10:1 are not uncommon. Again, the quality / size of the output will depend on the type of image. Finally, while I have not used ImageMagick in a little while, I'm almost certain there are options to re-compress an image using a specific quality factor. Read through the docs, and start experimenting! EDIT: Looks like it should, indeed, be pretty easy with ImageMagick. From the docs : $magick> convert input.png -quality 75 output.jpg Just keep playing with the quality value until you get a suitable output. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2257322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58394/']} | jdg_74888 |
stackexchange | llm_judgeable_groundtruth_similarity | 9128732 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to programatically add an IIS 7.x site and I got stuck when this should be created with a HTTPS/SSL binding by default, usig SiteCollection.Add(string, string, string, byte[]) overload . Giving https:*:80:test.localhost https:*:443:test.localhost as bindingInformation throws an ArgumentException with this message: The specified HTTPS binding is invalid. What's wrong in this binding information? Thank you. EDIT : I'm using Microsoft.Web.Administration assembly.
Now provide the response and nothing else.
| Here is what I did to create https site and it worked. I skip some parts of code here, of course. using Microsoft.Web.Administration...using(var manager = new ServerManager()){ // variables are set in advance... var site = manager.Sites.Add(siteName, siteFolder, siteConfig.Port); var store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); // certHash is my certificate's hash, byte[] var binding = site.Bindings.Add("*:443:", certHash, store.Name); binding.Protocol = "https"; store.Close(); site.ApplicationDefaults.EnabledProtocols = "http,https"; manager.CommitChanges();} UPD: the certificate is created from a pfx file the following way: // get certificate from the filestring pfx = Directory.GetFiles(folder, "*.pfx", SearchOption.AllDirectories).FirstOrDefault();var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);var certificate = new X509Certificate2(pfx, certPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);store.Add(certificate);store.Close();certHash = certificate.GetCertHash(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9128732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411632/']} | jdg_74889 |
stackexchange | llm_judgeable_groundtruth_similarity | 18979176 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Who can explain what's going on? public class MagicFinal { public static void main(String[] args) { System.out.println(A.s); }}class A { static { System.out.println("class has been loaded"); } public static final String s = "final"; public static final Integer i = 3; } Console : final What's it? I don't understand why the class has not been loaded, I know classes always load at the first call. Field s is in pool of string, I see that final modifier is magic. If I delete final modifier ( public static String s = "final" ) I will get Console : class has been loaded final Note: I have changed field i : public static final int i = 3; and show it in console.I got the same as in String situation. Why?
Now provide the response and nothing else.
| "final" is a string literal and as such is a compile-time constant expression . The value of a static final variable initialized with a compile-time constant expression is directly hardcoded into the class which references it, and no reference is made to the originating class. Therefore the initialization of the originating class does not occur. As a side point, please note the distinction between class loading and class initialization : only the latter's occurrence is precisely specified by the JLS. Class loading can happen at any time. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18979176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2625691/']} | jdg_74890 |
stackexchange | llm_judgeable_groundtruth_similarity | 232975 |
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:
As many know, one can implement a simple node to node rs485 communication by using only two wires, A and B. Well, the standard specify to connect the ground of the two node together. from Wikipedia: In addition to the A and B connections, the EIA standard also specifies a third interconnection point called C, which is the common signal reference ground. I stumbled upon tens of articles that speak about this third connection but still couldn't understand the concept. Why can't the receiver just act as a simple voltmeter? measuring the voltage between A and B? If both nodes are battery operated(different battery for each node) does the ground connection make any difference? Why is it better for (outdoor) nodes to be earthed when cables are long? How is this ground connection good for protection from transient?
Now provide the response and nothing else.
| It is a myth that you can make RS485 interfaces work without the Common (C) ground wire connected up between the various devices on the bus. The receiver is only capable of measuring the relative potential between the A and B signals when the common mode voltage of the A and B inputs is kept within -7V to +12V of the GND reference of the receiver. The idea that both sides of the interface being operated on batteries would somehow make a difference is also a myth. It all comes down to what the common mode voltage is between the transmitter GND and the receiver GND. The third wire connection keeps the common mode voltage under control. Without it any undue influence to either unit or to the bus between the two can lead to the common mode voltage going outside the -7V to +12V range. This influence could be due to coupling into other systems through EMI. It can also be common to see this show up as AC variation that follows the mains line frequency. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/232975', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/69076/']} | jdg_74891 |
stackexchange | llm_judgeable_groundtruth_similarity | 19563737 |
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 write a command line utility in node.js. As one of the features it should change the current working directory of the shell it was called from. Something like node.js version of cd . Is it possible to achieve this? If so, how? To clarify, I'd like to be able to change the current directory in the terminal window by running the script. /some/path> .../some/path> nodecd /other/path/other/path> ... The problem is that process.chdir() works for the SCRIPT directory, not for the SHELL directory. I need to be able to somehow pass the current shell through the bash invocation to node script, and alter the path of that shell within the script - creating a subshell won't solve the problem.
Now provide the response and nothing else.
| In short: you can't. The working directory is limited to the context of a process (and perhaps child processes, but certainly not parent processes). So the cwd of your Node process cannot propagate back to your shell process. A common trick is to have your Node app print the working directory to stdout, and have your shell run your Node app like this: cd "$(node app)" A simple test case: // app.jsconsole.log('/tmp'); And if you create a shell alias/function for it, it should be relatively painless. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19563737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/876409/']} | jdg_74892 |
stackexchange | llm_judgeable_groundtruth_similarity | 9234406 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
export logback.configurationFile=123 on mac os x got this:"-bash: export: `logback.configurationFile=123': not a valid identifier" Tried export logback_configurationFile=123 that worked. but logback does not seem to recognize that env variable. Any suggestions?
Now provide the response and nothing else.
| -Dlogback.configurationFile is not the same as setting it as an Environment variable. The -D flag is a Java parameter to your program (accessible by System.getProperty() ) while the environment variable defined by export will be accessible by System.getenv() .Looking at the Logback code it looks like it uses System.getProperty() to read the logback.configurationFile value. So in reality you have to pass the parameter to the JVM on startup, this means that you can set the environment variable to whatever you like and then just use it in when you start the JVM. export LOGBACK_CONFIG_FILE_LOCATION=/tmp/logback.confjava -Dlogback.configurationFile=${LOGBACK_CONFIG_FILE_LOCATION} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9234406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464253/']} | jdg_74893 |
stackexchange | llm_judgeable_groundtruth_similarity | 24689 |
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:
If I have something like a windmill generator that generates AC current, but at variable frequency, what device(s) would I need to convert that variable frequency into a constant 60hz frequency, so that the power can be used for net-metering?
Now provide the response and nothing else.
| As noted by several people AC->DC-> AC is the easiest way and would be the most normal. But - Cycloconverter - Olde tech system - something to think about for the more technically informed. However, if your wind-turbine AC frequency is always high relative to AC you can get a moderately good result by using what is known as a cyclo-converter. This is an option that I have not heard of being used in the domestic WT market and which is usually associated with high powers or Olde technology BUT a Cycloconverter could be extremely easily implemented at good cost in the 100 Watt - 30 KW size range with modern electronics. It is stated in a number of places on web that Honda use cycloconverters in some of their portable motor generator units. This is not certain but may well be true as this would allow them to use high frequencies with consequent reduced size magnetics and would also allow a degree of frequency stabilisation. I had noticed the very small size of their units wrt power levels and wondered what magic they had worked. A cycloconverter takes the available waveforms and compares them to a reference desired output waveform. It then draws power from the waveform that is closest to what is required. Waveform distortion obviously occurs but if the relative frequencies are high and multiple phases are available, quite modest output filtering may produce an acceptable result in many cases. An advantage is the efficiency can be very high, as the "best" alternator phase is simply being switched to the output at any time and losses are mainly switch (typically MOSFET) dissipation losses plus switching losses. Switching losses are modest as even at 10:1 input to output frequency switching rate is only around a few kHz. (Multiple switchings per output cycle mean switching rate is > N x fout) The diagram below shows basic operation with 3 phase in and 1 phase out. A major advantage is that because input and output float relative to each other, and given input phase can be instantly inverted in polarity relative to the output if requried. This significantly increases the number of waveform segments to choose from and thus the available spectral purity for a given input:output arrangement. Multiple input phases are required to choose from - the more the better. As WT's often have 3 phase output and may have more this method may be a good match to the requirement. (The available number is effectively increased by polarity inversion - see below). From here Technical comment - not relevant for questioner: This is very B.O.T.E. but seems OK - Variable input frequency is easily handled with some effect on spectral purity. As long as rate of change of frequency is small compared to frequency this would not be a major problem. Typical loaded rotor inertias would usually make this not an issue. eg in the diagram above fin_3 phase is about 3 x Fout_1 phase. The shortest time period between switchings is about 10% of fin. The longest is about 25% Fin. If fout = 50 Hz then time period of longest segment ~~= 1/(50 x 3 x 10 ) = < 1 mS. WT prop at say 3000 RPM = 50 RPS = 20 mS per rev = 20 times longest segment . Blade inertia needs to be such that blade speed does not change vastly over say 1 revolution. If WT rotation rate doubled in 1 second (wow) then speed would change by ~= 2%/revolution = OK. Note that the above deals with frequency but not Voltage changes. In many cases an AC-DC-AC system will be preferred due to tye freedom i gives to alter bith frequency and voltage. Wikipedia - cycloconverters [Book, 1972, MIT press The theory and design of cycloconverters About 20 page paper UoTK, Knoxville. About 2000 Cycloconverter tutorial Images linked to pages. Many many many ... | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/24689', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7088/']} | jdg_74894 |
stackexchange | llm_judgeable_groundtruth_similarity | 9695329 |
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 double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised. So when I do double x = 54.999999999999943157;int y = (int) x; y = 54 instead of 55! This puzzled me for a long time. How do I get it to correctly round?
Now provide the response and nothing else.
| add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate. float x = 55; // stored as 54.999999...x = x + 0.5 - (x<0); // x is now 55.499999...int y = (int)x; // truncated to 55 C++11 also introduces std::round , which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust. A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9695329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1255592/']} | jdg_74895 |
stackexchange | llm_judgeable_groundtruth_similarity | 14413404 |
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 algorithm is about to store strings from Array A to Array B by storing "A", "B" to Index 8 and Index 9I really initiate to make the array size of B to be 10 because later I will put some other things there. My partial code: string[] A = new string[]{"A","B"}string[] B = new string[10]; int count;for(count = 0; count < A.length; count++){ B[count] = A[count]}
Now provide the response and nothing else.
| So you want to increment every index with 2: string[] A = new string[] { "A", "B", "C", "D" };string[] B = new string[A.Length + 2];for (int i = 0; i < A.Length; i++){ B[i + 2] = A[i];} Demo Index: 0 Value: Index: 1 Value: Index: 2 Value: AIndex: 3 Value: BIndex: 4 Value: CIndex: 5 Value: D Edit : So you want to start with index 0 in B and always leave a gap? string[] A = new string[] { "A", "B", "C", "D" };string[] B = new string[A.Length * 2 + 2]; // you wanted to add something other as wellfor (int i = 0; i/2 < A.Length; i+=2){ B[i] = A[i / 2];} Demo Index: 0 Value: AIndex: 1 Value: Index: 2 Value: BIndex: 3 Value: Index: 4 Value: CIndex: 5 Value: Index: 6 Value: DIndex: 7 Value: Index: 8 Value: Index: 9 Value: Update " Is there any alternative coding aside from this?" You can use Linq, although it would be less readable and efficient than a simple loop: String[] Bs = Enumerable.Range(0, A.Length * 2 + 2) // since you want two empty places at the end .Select((s, i) => i % 2 == 0 && i / 2 < A.Length ? A[i / 2] : null) .ToArray(); Final Update according to your last comment( start with index 1 in B ): for (int i = 1; (i-1) / 2 < A.Length; i += 2){ B[i] = A[(i-1) / 2];} Demo Index: 0 Value: Index: 1 Value: AIndex: 2 Value: Index: 3 Value: BIndex: 4 Value: Index: 5 Value: CIndex: 6 Value: Index: 7 Value: DIndex: 8 Value: Index: 9 Value | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14413404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1944787/']} | jdg_74896 |
stackexchange | llm_judgeable_groundtruth_similarity | 32612803 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have you written a utility to print all parameters of an intent? Like... Intent i = ... Log.d(tag, "INTENT = " + Util.printIntent(i) ); including target, extras, data, etc ? Thanks for the help. UPDATE:What I have so far ... if (G.DEBUG) Log.d(U.getTag(), "INTENT = " + intentToString(intent) );public static String intentToString(Intent intent) { if (intent == null) {return null;} String out = intent.toString(); Bundle extras = intent.getExtras(); if (extras != null) { extras.size(); out += "\n" + printBundle(extras); } if (intent.getAction() != null) out+="\nAction = " + intent.getAction(); if (intent.getType() != null) out+="\nType = " + intent.getType(); if (intent.getData() != null) out+="\nData = " + intent.getData(); if (intent.getPackage() != null) out+="\nPackage = " + intent.getPackage(); if (intent.getDataString() != null) out+="\nDataString = " + intent.getDataString();return out; }
Now provide the response and nothing else.
| The Intent#toString() method works pretty good, it will print most stuff but it doesn't print the extras unfortunately. The extras are in a Bundle that can also be printed with Bundle#toString() but if the Intent just arrived from another process then the contents of the extras Bundle won't be printed until you trigger it to be unparcelled, also it doesn't properly print lists or arrays. This code below should help print out just about everything: public static String intentToString(Intent intent) { if (intent == null) { return null; } return intent.toString() + " " + bundleToString(intent.getExtras());}public static String bundleToString(Bundle bundle) { StringBuilder out = new StringBuilder("Bundle["); if (bundle == null) { out.append("null"); } else { boolean first = true; for (String key : bundle.keySet()) { if (!first) { out.append(", "); } out.append(key).append('='); Object value = bundle.get(key); if (value instanceof int[]) { out.append(Arrays.toString((int[]) value)); } else if (value instanceof byte[]) { out.append(Arrays.toString((byte[]) value)); } else if (value instanceof boolean[]) { out.append(Arrays.toString((boolean[]) value)); } else if (value instanceof short[]) { out.append(Arrays.toString((short[]) value)); } else if (value instanceof long[]) { out.append(Arrays.toString((long[]) value)); } else if (value instanceof float[]) { out.append(Arrays.toString((float[]) value)); } else if (value instanceof double[]) { out.append(Arrays.toString((double[]) value)); } else if (value instanceof String[]) { out.append(Arrays.toString((String[]) value)); } else if (value instanceof CharSequence[]) { out.append(Arrays.toString((CharSequence[]) value)); } else if (value instanceof Parcelable[]) { out.append(Arrays.toString((Parcelable[]) value)); } else if (value instanceof Bundle) { out.append(bundleToString((Bundle) value)); } else { out.append(value); } first = false; } } out.append("]"); return out.toString();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32612803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3014987/']} | jdg_74897 |
stackexchange | llm_judgeable_groundtruth_similarity | 9663552 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Looking at some algorithm exercices on the net, I found an interesting one : How would you implement a FIFO using a LIFO ? I tried myself but I ended up with only one solution : each time we want the front element of the FIFO, copy the lifo into another lifo ( excluding last element, which is the front), get the front element and remove it, then copy back the second LIFO into the first LIFO. But this is of course horribly slow, it makes a simple loop like this : for(!myfifo.empty()) { myfifo.pop();} going O(n²) instead of O(n) on a standard implementation of the FIFO. Of course, LIFO are not made to do FIFO and we won't certainly have the same complexity by using a "native" FIFO and a fake-FIFO based on a LIFO, but I think there is certainly a way of doing better than O(n²). Has anyone an idea about that ? Thanks in advance.
Now provide the response and nothing else.
| You can get amortized time complexity of O(1) per OP FIFO [queue] using 2 LIFOs [stacks]. Assume you have stack1 , stack2 : insert(e): stack1.push(e)take(): if (stack2.empty()): while (stack1.empty() == false): stack2.push(stack1.pop()) return stack2.pop() //assume stack2.pop() handles empty stack already example: push(1)|1| | ||-| |-|push(2)|2| | ||1| | ||-| |-|pop()push 2 to stack2 and pop it from stack1:|1| |2||-| |-|push 1 to stack2 and pop it from stack2:| | |1|| | |2||-| |-|pop1 from stack2 and return it:| | |2||-| |-| To get real O(1) [not amortized], it is much more complicated and requires more stacks, have a look at some of the answers in this post EDIT: Complexity analysis: each insert() is trivaially O(1) [just pushing it to stack1 ] Note that each element is push() ed and pop() ed at most twice, once from stack1 and once from stack2 . Since there is no more ops then these, for n elements, we have at most 2n push() s and 2n pop() s, which gives us at most 4n * O(1) complexity [since both pop() and push() are O(1) ], which is O(n) - and we get amortized time of: O(1) * 4n / n = O(1) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9663552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/706528/']} | jdg_74898 |
stackexchange | llm_judgeable_groundtruth_similarity | 6449565 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created an object in R that contains several attributes. How can I easily access them? I can do: attr(x, attributeName) or: attributes(x)$attributeName but none of them is really convenient. Is there a quicker way (like the dot in C++ or Java)?
Now provide the response and nothing else.
| attributes() returns a named list. I'd call it once and store them, then access via names. There is no point repeatedly calling either attr() or attributes() if you don't have to. x <- 1:10attr(x, "foo") <- "a"attr(x, "bar") <- "b"(features <- attributes(x)) which gives: R> (features <- attributes(x))$foo[1] "a"$bar[1] "b" then access in the usual way R> features["foo"]$foo[1] "a"R> features$foo[1] "a" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6449565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482711/']} | jdg_74899 |
stackexchange | llm_judgeable_groundtruth_similarity | 6022302 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A project on GitHub that I have a fork of has a new pull requests that I want to pull into my fork that the author has not pulled in yet. Is there a simple way to apply pull request from other forks into my fork? Is there something else here that I am missing?
Now provide the response and nothing else.
| You can do it manually quite easily: add the other fork as a remote of your repo: git remote add otherfork git://github.com/request-author/project.git fetch his repo's commits git fetch otherfork You have then two options to apply the pull request (if you don't want to choose pick 1.) If you don't care about applying also the eventual commits that have been added between the origin and the pull request, you can just rebase the branch on which the pull request was formed git rebase master otherfork/pullrequest-branch If you only want the commits in the pull request, identify their SHA1 and do git cherry-pick <first-SHA1> <second-SHA1> <etc.> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6022302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3765/']} | jdg_74900 |
stackexchange | llm_judgeable_groundtruth_similarity | 25569 |
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:
Most English translations say something like: And the LORD God commanded the man, saying, “Of every tree of the garden you are free to eat; The Hebrew says: ויצו יהוה אלהים על־האדם לאמר מכל עץ־הגן אכל תאכל It seems that וַיְצַו֙ should be translated as "gave charge over" as in Adam was given responsibility to choose whatever he wanted to do. According to NAS Exhaustive Concordance, צָוָה means: Word Origin: a prim. root Definition: to lay charge (upon), give charge (to) , command, order NASB Translationç appoint (1), appointed (4), appoints (1), charge (5), charged (17), charging (1) , command (56), commanded (332), commander (1), commanding (18), commands (6), commission (3), commissioned (4) , commit (1) , gave a command (1), gave them a charge (1) , gave command (2), gave commandment (2), gave orders (2), give his charge (1), give you in commandment (1), give you charge (1) , give orders (3), given (1), given a command (1), given it an order (1), given command (1), given commandment (1), giving (1), instructed (1), issued a command (2), laid (1), laid down (1), ordained (4) , order (4), ordered (5), put (1), sent (1), set his in order (1), set your in order (2). This would mean the charge to "not eat of" was actually a warning rather than a commandment. YLT says: "And Jehovah God layeth a charge on the man, saying, 'Of every tree of the garden eating thou dost eat;" And the NLT goes even further to say: But the LORD God warned him, "You may freely eat the fruit of every tree in the garden-- According to Merriam-Webster's dictionary , the verb charge means: to give a job or responsibility to (a person or group): to make (a person or group) responsible for something This would mean Genesis 3:17 says: And to Adam He said, Because you have listened to the voice of your wife and have eaten from the tree concerning which I put you in charge of , saying, eat not from, cursed is the ground for your sake (benefit) וּלְאָדָ֣ם אָמַ֗ר כִּֽי־שָׁמַעְתָּ֮ לְקֹ֣ול אִשְׁתֶּךָ֒ וַתֹּ֙אכַל֙ מִן־הָעֵ֔ץ אֲשֶׁ֤ר צִוִּיתִ֙יךָ֙ לֵאמֹ֔ר לֹ֥א תֹאכַ֖ל מִמֶּ֑נּוּ אֲרוּרָ֤ה הָֽאֲדָמָה֙ בַּֽעֲבוּרֶ֔ךָ בְּעִצָּבֹון֙ תֹּֽאכֲלֶ֔נָּה כֹּ֖ל יְמֵ֥י חַיֶּֽיךָ And Genesis 3:11 says: And He said, Who said to you that naked you [are]? From the tree, concerning which I gave to you charge/responsibility that you should not eat, have you thereof eaten? וַיֹּ֕אמֶר מִ֚י הִגִּ֣יד לְךָ֔ כִּ֥י עֵירֹ֖ם אָ֑תָּה הֲמִן־הָעֵ֗ץ אֲשֶׁ֧ר צִוִּיתִ֛יךָ לְבִלְתִּ֥י אֲכָל־מִמֶּ֖נּוּ אָכָֽלְתָּ There are several instances where צָוָה cannot possibly mean "command" because no command is given. In Deuteronomy, the exact same form is used: "And he gave Joshua the son of Nun a charge (responsibility), and said, Be strong and of a good courage: for thou shalt bring the children of Israel into the land which I sware unto them: and I will be with thee." Deuteronomy 31:23 וַיְצַ֞ו אֶת־יְהֹושֻׁ֣עַ בִּן־נ֗וּן וַיֹּאמֶר֮ חֲזַ֣ק וֶֽאֱמָץ֒ כִּ֣י אַתָּ֗ה תָּבִיא֙ אֶת־בְּנֵ֣י יִשְׂרָאֵ֔ל אֶל־הָאָ֖רֶץ אֲשֶׁר־נִשְׁבַּ֣עְתִּי לָהֶ֑ם וְאָנֹכִ֖י אֶֽהְיֶ֥ה עִמָּֽךְ (Please see Numbers 27:19-23 , Nehemiah 7:2 , and 2 Samuel 6:21 for a few more examples) Is it possible that צָוָה means "gave charge" in Genesis 2:16, 3:11, and 3:17?
Now provide the response and nothing else.
| The root צוה appears 221 See comments below times in the OT in 109 different chapters. Roughly 70 percent are in the Pentateuch. The root appears in several different grammatical constructs, in both noun and verb forms and as part of idioms. In all instances the meaning of the word is the same, "command" (as a noun or verb) or "commandment". The sense of the meaning in all cases is imperative. In Genesis 2:16, ויצו is the Biblical "future past" tense (עתיד מהופך) used as transitive verb, with the preposition "on" (על) before the object "the man" (האדם). The use of "appointed" or "charged" is justifiable as a translation in contexts where a Hebrew idiom uses the language of "command [someone] on [something]" (צו..על) or "[someone] is commanded on [something]" sounds odd to the English ear, or could confuse, as in Nehemiah 7:2, and 2 Samuel 6:21. These are probably the best choices for the English translation in these cases but they lose the clear sense of "command" that you get from the Hebrew. In Genesis 2:16, the language is "commanded on the man saying...", followed by the content of the command , not "commanded the man on the garden ", so the meaning is clear, God is giving an order, not making an appointment. The intended meaning becomes even more clear in the continuation, when the man transgresses. It is a mistake to use the interpretive license that translators need to take when giving slightly different translations of a given word for a particular idiom, in order to re-read those different translations back into another, different, context. For example, in Numbers 27:19-23, the http://biblehub.com translation of יִשְׁמְע֔וּ, "they will listen to" (in the sense of "listen to and take to heart") in verse 20 is translated as "be obedient". That's a excellent, economic, figurative translation, but far from the literal sense. You can't then use "obedient" in other places where you find ישמעו unless the idiom is the same. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/25569', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/15608/']} | jdg_74901 |
stackexchange | llm_judgeable_groundtruth_similarity | 35247436 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apple published a new method to authenticate against CloudKit, server-to-server. https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitWebServicesReference/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW6 I tried to authenticate against CloudKit and this method. At first I generated the key pair and gave the public key to CloudKit, no problem so far. I started to build the request header. According to the documentation it should look like this: X-Apple-CloudKit-Request-KeyID: [keyID] X-Apple-CloudKit-Request-ISO8601Date: [date] X-Apple-CloudKit-Request-SignatureV1: [signature] [keyID], no problem. You can find this in the CloudKit dashboard. [Date], I think this should work: 2016-02-06T20:41:00Z [signature], here is the problem... The documentation says: The signature created in Step 1. Step 1 says: Concatenate the following parameters and separate them with colons. [Current date]:[Request body]:[Web Service URL] I asked myself "Why do I have to generate the key pair?". But step 2 says: Compute the ECDSA signature of this message with your private key. Maybe they mean to sign the concatenated signature with the private key and put this into the header? Anyway I tried both... My sample for this (unsigned) signature value looks like: 2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:https://api.apple-cloudkit.com/database/1/[iCloud Container]/development/public/records/lookup The request body value is SHA256 hashed and after that base64 encoded. My question is, I should concatenate with a ":" but the url and the date also contains ":". Is it correct? (I also tried to URL-Encode the URL and delete the ":" in the date). At next I signed this signature string with ECDSA, put it into the header and send it. But I always get 401 "Authentication failed" back. To sign it, I used the ecdsa python module, with following commands: from ecdsa import SigningKey a = SigningKey.from_pem(open("path_to_pem_file").read()) b = "[date]:[base64(request_body)]:/database/1/iCloud....." print a.sign(b).encode('hex') Maybe the python module doesn't work correctly. But it can generate the right public key from the private key. So I hope the other functions also work. Has anybody managed to authenticate against CloudKit with the server-to-server method? How does it work correctly? Edit: Correct python version that works from ecdsa import SigningKeyimport ecdsa, base64, hashlib a = SigningKey.from_pem(open("path_to_pem_file").read()) b = "[date]:[base64(sha256(request_body))]:/database/1/iCloud....." signature = a.sign(b, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_der) signature = base64.b64encode(signature)print signature #include this into the header
Now provide the response and nothing else.
| The last part of the message [Current date]:[Request body]:[Web Service URL] must not include the domain (it must include any query parameters): 2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:/database/1/[iCloud Container]/development/public/records/lookup With newlines for better readability: 2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:/database/1/[iCloud Container]/development/public/records/lookup The following shows how to compute the header value in pseudocode The exact API calls depend on the concrete language and crypto library you use. //1. Date//Example: 2016-02-07T18:58:24Z//Pitfall: make sure to not include millisecondsdate = isoDateWithoutMilliseconds() //2. Payload//Example (empty string base64 encoded; GET requests)://47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=//Pitfall: make sure the output is base64 encoded (not hex)payload = base64encode(sha256(body)) //3. Path//Example: /database/1/[containerIdentifier]/development/public/records/lookup//Pitfall: Don't include the domain; do include any query parameterpath = stripDomainKeepQueryParams(url) //4. Message//Join date, payload, and path with colonsmessage = date + ':' + payload + ':' + path//5. Compute a signature for the message using your private key.//This step looks very different for every language/crypto lib.//Pitfall: make sure the output is base64 encoded.//Hint: the key itself contains information about the signature algorithm // (on NodeJS you can use the signature name 'RSA-SHA256' to compute a // the correct ECDSA signature with an ECDSA key).signature = base64encode(sign(message, key))//6. Set headersX-Apple-CloudKit-Request-KeyID = keyID X-Apple-CloudKit-Request-ISO8601Date = date X-Apple-CloudKit-Request-SignatureV1 = signature//7. For POST requests, don't forget to actually send the unsigned request body// (not just the headers) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35247436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5893400/']} | jdg_74902 |
stackexchange | llm_judgeable_groundtruth_similarity | 3904663 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone please explain me what does @class declaration do in Objective-C and what are the cases in which we should use this declaration?
Now provide the response and nothing else.
| It’s a forward declaration. It essentially tells the compiler that there’s a class of that name. I use it in the interface declarations: @class Foo;@interface Bar : NSObject { Foo *someFoo;}@end Of course you could import the header for Foo instead: #import "Foo.h"@interface Bar : NSObject { Foo *someFoo;}@end But if someFoo is not exposed to users of Bar , they would import an extra header file that’s of no use to them. With the @class declaration the users of Bar see no extra import, because Foo.h will be imported in the implementation file of Bar . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3904663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197688/']} | jdg_74903 |
stackexchange | llm_judgeable_groundtruth_similarity | 430198 |
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:
This is a Tesla valve. It works by diverting liquid or gas back on itself when it is flown in one direction and allowing a smooth flow in the other direction. Can the same concept be used to create a semiconductor? Why?
Now provide the response and nothing else.
| No. The design of the Tesla valve requires a material which has inertia (so that the "slanted" paths are preferred for backflow), and which behaves as a viscous fluid (so that the pressure of the reversed backflows can obstruct forward flow). Neither of these is applicable to the movement of electrons within a conductor. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/430198', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/217200/']} | jdg_74904 |
stackexchange | llm_judgeable_groundtruth_similarity | 1710812 |
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 some context, the record class SaleAmount property is public decimal? SaleAmount{ get; set;} Ideally I would go with this record.SaleAmount.Value = sql.Reader.IsDBNull(IDX_SALEAMOUNT) ? null : sql.Reader.GetDecimal(IDX_SALEAMOUNT); Alas the compiler and this are not friends because... Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'decimal' So how would you express this elegantly, and dont play the obvious card like below... if (!sql.Reader.IsDBNull(IDX_SALEAMOUNT)) record.SaleAmount = sql.Reader.GetDecimal(IDX_SALEAMOUNT); Or is above the best solution?
Now provide the response and nothing else.
| If you're using C# 3, I'd actually make this easier for yourself using an extension method: public static decimal? GetNullableDecimal(this DbReader reader, int column){ return reader.IsDBNull(column) ? (decimal?) null : reader.GetDecimal(column);} Then your application code can just use: record.SaleAmount = sql.Reader.GetNullableDecimal(IDX_SALEAMOUNT); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1710812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40714/']} | jdg_74905 |
stackexchange | llm_judgeable_groundtruth_similarity | 3018 |
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Usually when we do a difference-in-differences estimation, we do it in a OLS reduced form as follows: $$Y_{it}=\alpha After_t+\gamma Treatment_i+\delta After*Treatment_{i,t}+X_{it}\beta+\epsilon_{i,t}$$However, I was wondering, if the $Treatment$ group is endogenous (e.g. self-selected), but we can define an "eligible" group for the treatment, whether it would be more precise to estimate a diff-in-diff in a OLS/2SLS form as:$$Treatment_{i,t}=constant+\alpha After_t+\gamma Eligible_i+\delta After*Eligible_{i,t}+\epsilon_{i,t}$$and get $\hat{Treatment_{i,t}}$, then $$Y_{i,t}=X_{it}\beta+\delta\hat{Treatment_{i,t}}+\epsilon_{i,t}$$ How should we understand the diff-in-diff in a OLS/2SLS form? Are there any paper using this particular identification strategy that I could take a look? Thank you very much in advance!
Now provide the response and nothing else.
| Well, if you believe that treatment is endogenous (which depends on the problem at hand here and is not an inherent feature of the model), then using eligibility as an instrumental variable will help you to get rid of the biases due to the safe selection in treatment. (Incidentally, DID is intended to do the same, but won't do as good a job as a well chosen instrument, so there is some doubts whether applying both of them is better then resorting to only one). However it is up to you to decide whether eligibility is exogenous, as it well may be, that those who are expecting higher return to treatment made sure to be eligible. Taking that we believe that there are some biases that arenot eliminated by DID and that eligibility can help us, there is still considerations of efficiency. In many cases eligibility may happen to be a weak instrument and then the reduction is bias will come at a cost of significant efficiency loss. And taking a look at the particular specification that you have sugested, it seems not very reasonable in general setting. You may choose when you believe that eligibility is changing quickly, or the interaction term in second equation will be generally unhelpful. Inclusion of time After in that equation can have even more drastic consequences, as it is likely to be endogenous and will weaken the bias reduction effect. If not endogenous, it is likeliy to be negligible as well as interaction, unless Treatment is rapidly changing on it's own. So in this case I would recommend leaving only the eligibility as an instrument in the first equation and specifying the third one in a DID form. With respect to interpretation, my specification does not allow for a nice interpretation of difference in changes in two subgroups and should be interpreted as a difference in changes in two hypothetical subgroup where each person is divided between them with some weights. Your specification, however, loses all interpretation as DID, because you do not use the resulting interaction coefficient, but just employ more variables as instruments for treatment. Unfortunately, probably due to the aformentioned reasons, I was unable to recall or find any appropriate paper, sorry about that. | {} | {'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/3018', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/2712/']} | jdg_74906 |
stackexchange | llm_judgeable_groundtruth_similarity | 52535857 |
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 migrating my codebase from junit4 to junit5.I have used mockito in my testcase.Below are the different version that i am using for the dependency. <junit.jupiter.version>5.2.0</junit.jupiter.version><junit.platform.version>1.2.0</junit.platform.version><org.mockito.version>1.10.19</org.mockito.version> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>2.19.0</version> <scope>test</scope> </dependency> I have used the annotation @RunWith(MockitoJUnitRunner.class) to run my mockito code.Replaced the same with @ExtendWith(MockitoExtension.class) But when i run the test case i get the below error. Any suggestion to solve this issue. I suspect is there any dependency version issue which is causing this problem. java.lang.NoClassDefFoundError: org/mockito/quality/Strictnessat java.lang.Class.getDeclaredConstructors0(Native Method)at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)at java.lang.Class.getConstructor0(Class.java:3075)at java.lang.Class.getDeclaredConstructor(Class.java:2178)at.. Thanks-Sam
Now provide the response and nothing else.
| The JUnit5 MockitoExtension uses org.mockito.quality.Strictness so in order to use MockitoExtension you'll need to use a version of mockito-core which contains org.mockito.quality.Strictness . mockito-core:1.10.19 does not contain that class because that class was added in Mockito 2.x. So, in order to use MockitoExtension you'll need to use at least version 2.x of mockito-core . The Mockito docs don't make this explicit but I suspect the expectation is that you'll use the same Mockito version for mockito-core and for mockito-junit-jupiter . The following dependencies will allow you to use the JUnit5 MockitoExtension successfully: <org.mockito.version>2.19.0</org.mockito.version><dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${org.mockito.version}</version> <scope>test</scope></dependency><dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>${org.mockito.version}</version> <scope>test</scope></dependency> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52535857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3744824/']} | jdg_74907 |
stackexchange | llm_judgeable_groundtruth_similarity | 2157748 |
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:
Although I have always known the definition of measurability in terms of pre images of measurable sets being measurable, I don't really conceptually understand the purpose of measurable functions or what it means. More specifically, this dawned on me when I was looking at a paper talking about limits of a measurable function, $U:\mathbb{R_+} \rightarrow \mathbb{R_+}$ (the limit was $\lim_{t\rightarrow \infty}\frac{U(tx)}{U(t)}$), without specifying why the function had to be measurable at all. It's left me in a lot of doubt of my own knowledge of measure theory. Is anyone able to give me some intuition and a possible reason for measurability with regards to taking limits?
Now provide the response and nothing else.
| I'm going to dissent from some of the comments and advise against thinking about measurability in terms of a topological property like continuity, even for heuristic purposes. The fact is that measurability is not a topological concept, and it's important to be conceptually clear about this, especially if you go on to study more abstract measure theory in which measurable spaces do not always come equipped with a natural topology (unlike the real numbers, for instance). There are, of course, important results linking measurability and continuity. I mentioned two in my comment: Lusin's theorem and Lebesgue's criterion for Riemann integrability . You should know these results and understand why they hold, but you should not conclude on their basis that, in general, the concept of measurability can be (approximately) reduced to the concept of continuity. Now, as for intuitions, my advice is to always keep in mind that assertions about measurability are always relative to particular sigma-algebras. As you mention, a function $f: (X_1, \mathcal{F}_1) \to (X_2, \mathcal{F}_2)$ between two measurable spaces is $(X_1, \mathcal{F}_1, X_2, \mathcal{F}_2)$-measurable (notice the qualification of "measurable") provided$$f^{-1}(B_2) \in \mathcal{F}_1$$for all $B_2 \in \mathcal{F}_2$. Sometimes mention of one or both sigma-algebras is suppressed when the context makes clear what measurable spaces one is working with. For example, in real analysis one often deals with functions from $(\mathbb{R}, \mathcal{L})$ into $(\mathbb{R}, \mathcal{B})$, where $\mathcal{L}$ is the collection of Lebesgue measurable sets and $\mathcal{B}$ is the Borel sigma-algebra. The intuition behind the formal definition is simply that the function $f$ can be measured. That is, if we now equip $(X_1, \mathcal{F}_1)$ with a measure $\mu$, the measurability of $f$ guarantees that any "reasonable statement" $B_1$ about the values that $f$ takes is in fact a set in $\mathcal{F}_1$, and hence $\mu(B_1)$ makes sense. Returning to the canonical real analysis setup, $B_1$ might be a statement like "$f(x) \leq 5$" or "$f(x) \in (0, \infty)$". Measurability guarantees that these rough "statements" are actually sets in $\mathcal{F}_1$ that can be measured. For example, the first statement corresponds to the set $B_1 = \{x \in \mathbb{R}: f(x) \leq 5 \}$. With this in mind, let me explain why I recommend not conflating measurability and continuity. Consider a function $f: (\mathbb{R}, \mathcal{F}_1) \to (\mathbb{R}, \mathcal{B})$, where $\mathcal{F}_1$ is the trivial sigma-algebra $(\emptyset, \Omega)$. From the formal definition, we conclude that $f$ is measurable if and only if it is a constant function (verify this). But this rules out many "well-behaved",and, in particular, continuous, functions! In other words, there are many continuous functions that are not $(\mathbb{R}, \mathcal{F}_1, \mathbb{R}, \mathcal{B})$-measurable. We see that a lot turns on the choice of $\mathcal{F}_1$. Another important example along these lines is that there are continuous functions $f: (\mathbb{R}, \mathcal{L}) \to (\mathbb{R}, \mathcal{L})$ that are not measurable. See the discussion here . So we see that a lot turns on the choice of sigma-algebra in the codomain as well. Finally, in response to your question about limits, it's a useful exercise to prove, directly from the definition, that the pointwise limit of a sequence of real-valued measurable functions is measurable. (As PhoemueX pointed out in the comments, pointwise convergence doesn't make sense for functions between general measurable spaces, so we now consider functions taking values in $(\mathbb{R}, \mathcal{B})$.) This sort of exercise should help your intuitions quite a bit. Consider $f_n: (X_1, \mathcal{F}_1) \to (\mathbb{R}, \mathcal{B})$, where $(X_1, \mathcal{F}_1)$ is an arbitrary measurable space, each $f_n$ is measurable, and $f_n \to f$. First, it suffices to show that $f^{-1}((-\infty, x]) \in \mathcal{F}_1$ for all $x \in \mathbb{R}$ because sets of the form $(-\infty, x]$ generate $\mathcal{B}$ (verify). Now try to show that$$f^{-1}((-\infty, x]) = \cap_{m=1}^\infty \cup_{n=1}^\infty \cap_{k=n}^\infty \{ f_k^{-1}((-\infty, x + 1/m])\}.$$(Just think about the definition of a limit and translate the quantifiers "for all" and "for some" to $\cap$ and $\cup$, respectively.) Do you know how to conclude from here? | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2157748', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234160/']} | jdg_74908 |
stackexchange | llm_judgeable_groundtruth_similarity | 2203388 |
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 structure of classes. class Interface { // ...};class Foo : public Interface { // ...};template <class T>class Container { // ...}; And I have this constructor of some other class Bar. Bar(const Container<Interface> & bar){ // ...} When I call the constructor this way I get a "no matching function" error. Container<Foo> container ();Bar * temp = new Bar(container); What is wrong? Are templates not polymorphic?
Now provide the response and nothing else.
| I think the exact terminology for what you need is "template covariance", meaning that if B inherits from A, then somehow T<B> inherits from T<A> . This is not the case in C++, nor it is with Java and C# generics*. There is a good reason to avoid template covariance: this will simply remove all type safety in the template class. Let me explain with the following example: //Assume the following class hierarchyclass Fruit {...};class Apple : public Fruit {...};class Orange : public Fruit {...};//Now I will use these types to instantiate a class template, namely std::vectorint main(){ std::vector<Apple> apple_vec; apple_vec.push_back(Apple()); //no problem here //If templates were covariant, the following would be legal std::vector<Fruit> & fruit_vec = apple_vec; //push_back would expect a Fruit, so I could pass it an Orange fruit_vec.push_back(Orange()); //Oh no! I just added an orange in my apple basket!} Consequently, you should consider T<A> and T<B> as completely unrelated types, regardless of the relation between A and B. So how could you solve the issue you're facing? In Java and C#, you could use respectively bounded wildcards and constraints : //Java codeBar(Container<? extends Interface) {...}//C# codeBar<T>(Container<T> container) where T : Interface {...} The next C++ Standard (known as C++1x (formerly C++0x)) initially contained an even more powerful mechanism named Concepts , that would have let developers enforce syntaxic and/or semantic requirements on template parameters, but was unfortunately postponed to a later date. However, Boost has a Concept Check library that may interest you. Nevertheless, concepts might be a little overkill for the problem you encounter, an using a simple static assert as proposed by @gf is probably the best solution. * Update: Since .Net Framework 4, it is possible to mark generic parameters has being covariant or contravariant . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2203388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261239/']} | jdg_74909 |
stackexchange | llm_judgeable_groundtruth_similarity | 189790 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a Lenovo Yoga 3 that apparently has a new Broadcom Bluetooth device. The bluetooth is detected at boot and when I try to pair a something in gnome, I can see a list of devices but none of them pair. How can I get this device to work? lsusbBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 001 Device 004: ID 048d:8386 Integrated Technology Express, Inc.Bus 001 Device 003: ID 5986:0535 Acer, IncBus 001 Device 002: ID 0489:e07a Foxconn / Hon HaiBus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub usb-devicesT: Bus=01 Lev=01 Prnt=01 Port=03 Cnt=02 Dev#= 2 Spd=12 MxCh= 0D: Ver= 2.00 Cls=ff(vend.) Sub=01 Prot=01 MxPS=64 #Cfgs= 1P: Vendor=0489 ProdID=e07a Rev=01.12S: Manufacturer=Broadcom CorpS: Product=BCM20702A0S: SerialNumber=38B1DBE337E4C: #Ifs= 4 Cfg#= 1 Atr=e0 MxPwr=0mAI: If#= 0 Alt= 0 #EPs= 3 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusbI: If#= 1 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=01 Prot=01 Driver=btusbI: If#= 2 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=ff Prot=ff Driver=(none)I: If#= 3 Alt= 0 #EPs= 0 Cls=fe(app. ) Sub=01 Prot=01 Driver=(none)
Now provide the response and nothing else.
| As of version 3.19, this device is supported in the Linux kernel, but you need to manually provide the device's firmware to the kernel. Finding the Firmware: You can find the firmware in the device's Windows driver, which you can download from Lenovo (or your computer manufacturer's website). Many drivers can just be unzipped, but for this particular computer, the driver is an .exe file and must be extracted with wine . wine 4ab802rf.exe Follow the "installation" instructions. The wizard will extract the .exe file and on the last step will ask to install it. Uncheck "Install Broadcom Bluetooth Driver now": The driver file has been extracted to ~/.wine/driver_c/drivers/Broadcom Bluetooth Driver/ Identifying the right file In my case, there are 20 - 30 firmware files in the extracted package. Which one corresponds to your device is revealed in one of the driver's inf files. Find your device ID from the output of lsusb or if that's unclear, usb-devices . In this case, it's e07a . Then grep the inf files to find out which one talks about that device: grep -c E07A -r --include \*.infWin32/LD/bcbtumsLD-win7x86.inf:0Win32/bcmhidnossr.inf:0Win32/btwl2cap.inf:0Win32/btwavdt.inf:0Win32/btwrchid.inf:0Win32/bcbtums-win8x86-brcm.inf:17Win32/btwaudio.inf:0Win64/LD/bcbtumsLD-win7x64.inf:0Win64/bcmhidnossr.inf:0Win64/btwl2cap.inf:0Win64/btwavdt.inf:0Win64/btwrchid.inf:0Win64/bcbtums-win8x64-brcm.inf:17Win64/btwaudio.inf:0Autorun.inf:0 So in this driver, you can look in either Win32/bcbtums-win8x86-brcm.inf or Win64/bcbtums-win8x64-brcm.inf . Look through the file and find the hex file that is mentioned near E07A : ;;;;;;;;;;;;;RAMUSBE07A;;;;;;;;;;;;;;;;;[RAMUSBE07A.CopyList]bcbtums.sysbtwampfl.sysBCM20702A1_001.002.014.1443.1496.hex So the fimware is in the same directory and named BCM20702A1_001.002.014.1443.1496.hex . Converting and Placing the Firmware Download and compile the hex2hcd tool . git clone https://github.com/jessesung/hex2hcd.gitcd hex2hcdmake Convert the firmware to hcd : hex2hcd BCM20702A1_001.002.014.1443.1496.hex firmware.hcd Rename and move the firmware to the system's firmware subdirectory: su -c 'mv firmware.hcd /lib/firmware/brcm/BCM20702A0-0489-e07a.hcd' The name of this file is critical. The two sets of four characters, in this case 0489-e07a , should match your device's Vendor ID and Product ID. Loading the Firmware The easiest way to load the firmware is to power off your computer and turn it on again. Note that the computer should be turned off; a simple reboot may not be sufficient to reload this firmware. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/189790', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/34796/']} | jdg_74910 |
stackexchange | llm_judgeable_groundtruth_similarity | 2294918 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen a couple of proofs online for problem #1.1.19 in Dummit and Foote's Abstract Algebra that use strong induction to prove the following claim; Let $x\in G$ where $G$ is a group. Let $a,b\in \mathbb{Z}^+$. Prove $$x^{a+b}=x^ax^b$$ I have not seen any proofs of the following form: $$x^{a+b}=\underbrace{x\cdot x\cdots x}_{a+b\text{ times}}=\underbrace{x\cdot x\cdots x}_{a\text{ times}}\cdot \underbrace{x\cdot x\cdots x}_{b\text{ times}}=x^ax^b$$ I would assume that with positive integer exponents, this would be the most obvious way to show this is true. So why the need for induction?
Now provide the response and nothing else.
| Note that multiplication is defined as a binary operator, not as something you do with a bunch of copies of $x$. As such, when you declare that $$\underbrace{x\cdot x\cdots x}_{a+b\text{ times}}=\underbrace{x\cdot x\cdots x}_{a\text{ times}}\cdot \underbrace{x\cdot x\cdots x}_{b\text{ times}}$$you're assuming that the only piece of information that matters is the number of elements x which are being multiplied. That is, you're implicitly moving around a lot of parentheses in the equation$$\underbrace{(((x\cdot x)\cdots )x)}_{a+b\text{ times}}=\underbrace{(((x\cdot x)\cdots )x)}_{a\text{ times}}\cdot \underbrace{(((x\cdot x)\cdots )x)}_{b\text{ times}}$$You'll notice that the inductive step in the proof only requires that we deal with one reordering at a time, as in$$x^{a+1} \cdot x^b = (x \cdot x^a) \cdot x^b = x \cdot (x^a \cdot x^b) = x \cdot x^{a + b} = x^{a + b + 1}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2294918', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/357136/']} | jdg_74911 |
stackexchange | llm_judgeable_groundtruth_similarity | 2607 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As a non-mathematician/software programmer I'm trying to grasp how QFT (Quantum Fourier Transformation) works. Following this YouTube video: https://www.youtube.com/watch?v=wUwZZaI5u0c And this blogpost: https://www.scottaaronson.com/blog/?p=208 I've got a basic understanding on how you can calculate/construct the period using interference. But while trying to explain this to a colleague I ran into a problem. I used the following examples, N=15, a=7, so the period I'll need to find is r=4. The pattern is: 7, 4, 13, 1, 7, 4, 13, 1, 7, 4, 13, 1 (etc) If I imagine the wheel (like in the YouTube video) or a clock (like the blogpost) I can see that the circle with 4 dots/clock with 4 hours creates a constructive pattern and the others do not. But what happens with a circle with 2 dots, or a clock with 2 hours, those will have get the same magnitude/constructive pattern as 4? It loops twice as fast, but other than that, same result? How does the QFT cope with this? (Bonus: Can you explain in laymans terms without too much complicated math?)
Now provide the response and nothing else.
| Let me attempt to give a rather unconventional answer to this question: As a non-mathematician/software programmer I'm trying to grasphow QFT (Quantum Fourier Transformation) works. Suppose that we have a quantum computer which is able to manipulate $n$ qubits. The quantum state of such a quantum computer precisely describes the current state of this quantum computer. It is pretty well-known that we can express this quantum state as a vector of $2^n$ complex numbers. Let's try to visualize these complex numbers in a compact way. To that end, consider a horizontal line, on which $2^n$ points are depicted. They are labeled corresponding to their respective position on the line, i.e., the first point is labeled with $|0\rangle$, and the last points is labeled by $|2^n-1\rangle$. We can see this in the picture below. Now, try to picture that at every point, depicted above, this line punctures a circle of radius $1$ right through the middle. That is, there are $2^n$ circles placed exactly at the points depicted above, and the line connects the middles of all these circles. I have tried to depict this in the image below, but my 3D drawing skills are not exactly top-notch, so you will have to excuse me for that. The nice thing of this picture above is that it can uniquely represent the state of any $n$-qubit quantum computer by marking exactly one point in all of the circles. More explicitly, any quantum state of a $n$-qubit quantum computer can be depicted in the above picture by drawing one cross ($\times$) in all of the circles. Conversely, any such drawing represents a quantum state, as long as the squares of the distances of the crosses to the center point sum to $1$. In other words, if we calculate all the distances of the marked points to the center points, then square these distances, and then add them all up, we require that the result equals $1$. An example state is shown below: Throughout the execution of a program, the state of the quantum computer is constantly changing, and as such, so is the visual representation. Hence, throughout the execution of a quantum program, the marked points (the $\times$s), are constantly moving around, within the boundaries of their respective circles. Within this framework, the Quantum Fourier Transform is just a very specific way to move the marked vertices around. We will make this explicit in the case of a $3$-qubit quantum computer, on which a $3$-qubit Quantum Fourier Transform is executed. To that end, suppose that we have the $3$-qubit system in the following state, i.e., where the cross is all the way at the edge in the $|0\rangle$ circle, and all the others are exactly at the center. It is an exercise for the OP to check that indeed the square of the distances of the marked points to the center points sum to $1$. We refer to this state as the $|0\rangle$ state. The question is now what happens to the quantum state when we apply the Quantum Fourier Transform. It turns out that, when the Quantum Fourier Transform is applied to the state shown above, the resulting state of the quantum system becomes: Here I added the red dashed line passing through all the marked points just for extra convenience. All the marked points are on the exact same location in the circles, namely precisely above the center point at a height of $1/\sqrt{8}$. Similarly, we can have a look at the action of the Quantum Fourier Transform on other states. Consider for example the $|1\rangle$ state: Now, if we apply the Quantum Fourier Transform, the resulting state becomes: We can see that the resulting state becomes some kind of helix shape. Moreover, observe that if we were to add one extra circle to the right of the rightmost state, then the helix would complete exactly one revolution. It turns out that the other states behave similarly under the Quantum Fourier Transform, but that the period of the helix changes. More precisely, if we start out with the state $|j\rangle$, then the number of revolutions that the Quantum Fourier Transform makes is $j$. I.e., if we consider the initial state $|3\rangle$, then we obtain the following image under the Fourier transform: Here, we can easily see that the helix completes $3$ full revolutions if we were to add one more circle on the right hand side. It is important to note that we can also reverse the order of things. That is to say, if we have a quantum computer, whose state can be pictured as a helix, similar to the ones shown above, then we can obtain the period of this helix by implementing the inverse Quantum Fourier Transform. In doing so, we essentially map the helix with $j$ revolutions to the state $|j\rangle$, which is the exact opposite direction from the mapping we considered before. It is this idea that is the crucial component in Shor's algortihm. The central idea is to take the sequence of numbers you describe: 7, 4, 13, 1, 7, 4, 13, 1, 7, 4, 13, 1 (etc) and use these to create a helix whose period is equal to the period in this sequence. Next, we apply the inverse Quantum Fourier Transform to obtain the state $|4\rangle$, i.e., the period of this sequence. NOTE 1: There are a lot of details that I skipped over in the final paragraph. This answer already contains a lot of information, though, which I think needs to sink in before one can attempt to add these details to the picture. If anyone wants me to add these details, I might do so at a later stage. NOTE 2: The OP mentioned that he is not a mathematician. To the mathematicians out there, this visual representation is just an array of $2^n$ unit circles in the complex plane, where the marked points are the representation of the amplitudes as vectors in the complex plane. | {} | {'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/2607', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/2972/']} | jdg_74912 |
stackexchange | llm_judgeable_groundtruth_similarity | 5737602 |
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 don't know if the question is descriptive enough but why and how does this behaviour exist?: public class Layer{ public string Name { get; set; } private IEnumerable<Layer> children; public IEnumerable<Layer> Children { get { return this.children.Where ( c => c.Name != null ).Select ( c => c ); } set { this.children = value; } } public Layer ( ) { this.children = new List<Layer> ( ); // Fine Layer layer = new Layer ( ); layer.children = new List<Layer> ( ); // Isn't .children private from the outside? }} I can access layer.Children anywhere, that's fine, but how can I access layer.children since it's private? Layer layer = new Layer ( );layer.children = new List<Layer> ( ); only works if the code is inside the Layer class. Is there special code to treat accessing private variables differently if it's done inside the containing class, even though the access is from the outside? I know the reason of using: this.children = ... inside the containing class, but creating new instances and modifying them from the outside, even if they are still within the containing class, doesn't seem like a good practice. What's the reason for allowing this?
Now provide the response and nothing else.
| See section 3.5.1 of the C# language specification. The relevant text is this: Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is “access limited to the containing type”. Note that the modifier is relevant to the type , not the instance. And then further in section 3.5.2 some rules are further explained: In intuitive terms, when a type or member M is accessed, the following steps are evaluated to ensure that the access is permitted: First, if M is declared within a type (as opposed to a compilation unit or a namespace), a compile-time error occurs if that type is not accessible. Then, if M is public, the access is permitted. Otherwise, if M is protected internal, the access is permitted if it occurs within the program in which M is declared, or if it occurs within a class derived from the class in which M is declared and takes place through the derived class type (§3.5.3). Otherwise, if M is protected, the access is permitted if it occurs within the class in which M is declared, or if it occurs within a class derived from the class in which M is declared and takes place through the derived class type (§3.5.3). Otherwise, if M is internal, the access is permitted if it occurs within the program in which M is declared. Otherwise, if M is private, the access is permitted if it occurs within the type in which M is declared. Otherwise, the type or member is inaccessible, and a compile-time error occurs. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5737602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']} | jdg_74913 |
stackexchange | llm_judgeable_groundtruth_similarity | 1297894 |
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:
Problem (1) Classify all $S^1$ bundles over the base manifold $S^2$ . (2) Do the same question for $S^2$ bundles. Moreover, does there exist a universal method to solve this kind of problem? What mathematical tool and concept should be required? And, could someone suggest some reference books related to the problem? (I'm not sure my tags are correct)
Now provide the response and nothing else.
| Every $S^1$ bundle can be linearized: it's the unit sphere bundle of a 2-dimensional real line bundle. This is because in the smooth category $\text{Diff}(S^1)$ deformation retracts onto $O(2)$, so you may choose your bundle's cocycles to be linear (and then just define a vector bundle with the same cocycles). It's harder to show, but still true, that $\text{Diff}(S^2) \simeq O(3)$, and $\text{Diff}(S^3) \simeq O(4)$. This does not generalize; it's known that $\text{Diff}(S^n) \not\simeq O(n+1)$ for $n>4$, and it's probably not true for $n=4$. It's also false that, $\text{Homeo}(S^n) \simeq O(n+1)$ for every $n$, but I don't know precisely where it fails - it's at least true for $n \leq 3$. The best we have is $\text{PLHomeo}(S^n) \simeq O(n+1)$ for all $n$. So if you have a piecewise linear sphere bundle you can always linearize it. Now that we know this, you're just asking for us to classify the 2- and 3-dimensional vector bundles over $S^2$. These are classified by $\pi_1(SO(2)) = \Bbb Z$ and $\pi_1(SO(3))=\Bbb Z/2\Bbb Z$ respectively, by a construction known by the name of 'clutching functions'; essentially, you trivialize your vector bundle on the top and bottom discs and see what automorphism on the central $S^1$ they differ by. You can read the details in Hatcher's vector bundles book. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1297894', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211789/']} | jdg_74914 |
stackexchange | llm_judgeable_groundtruth_similarity | 171717 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Grothendieck's homotopy hypothesis, is, as the $n$lab states: Theorem: There is an equivalence of $(∞,1)$-categories $(\Pi⊣|−|): \mathbf{Top} \simeq \mathbf{\infty Grpd}$. What are the applications of this hypothesis? Why is it so fundamental? Can it be "generalized", perhaps by using the following definition of spaces : a space is simply a sheaf of sets on some site $\mathbf{Loc}$ of local models with a Grothendieck topology $τ$ on it?
Now provide the response and nothing else.
| For me this result fits in a context of other results that give complete algebraic invariants for homotopy types. The broad program sometimes goes under the rubric Whitehead's algebraic homotopy program . If we define a homotopy $n$-type (for $n \geq 1$) as an object of the localization of a suitable category of spaces (e.g., $Top$ or simplicial sets) with respect to maps $f: X \to Y$ that induce isomorphisms on homotopy groups $\pi_k(X, x) \to \pi_k(Y, f(x))$ for each choice of basepoint $x$ and $1 \leq k \leq n$, then it is well-known and classical that homotopy 1-types are classified by their fundamental groupoids, i.e., the localization is equivalent to the category of groupoids. The homotopy hypothesis can be seen as a far-reaching generalization of this basic result; the result is essentially a 1-dimensional truncation of the homotopy hypothesis. Thus, we could extend this idea of $n$-truncating $\infty$-groupoids past $n = 1$. Homotopy $n$-types are thus classified by $n$- groupoids ; it is interesting to see how this subsumes some of the classical results. For example, looking at connected 2-types, these are classified by groupal monoidal groupoids; passing to appropriate skeletal models, this means that connected 2-types $X$ are classified by triples $(\pi_1(X), \pi_2(X), k)$ where $k \in H^3(\pi_1(X), \pi_2(X))$ (an example of a $k$- invariant ) is the class of a 3-cocycle $$\pi_1(X) \times \pi_1(X) \times \pi_1(X) \to \pi_2(X)$$ that in essence specifies an associativity constraint for a monoidal category structure. This description is a modern rendering of work going back to Eilenberg and Mac Lane: S. Eilenberg and S. MacLane, Determinationation of the Second Homology and Cohomology Groups of a Space by Means of Homotopy Invariants . Proc. Nat. Acad. Sci., Vol. 32 (1946) 277-280 where the $k$-invariant of a 2-type $X$ can be described in terms of its Postnikov tower. Along similar lines, Joyal and Tierney (in apparently unpublished work, but circa 1984) described algebraic 3-types in terms of Gray-enriched groupoids, which are appropriately strictified groupoidal tricategories. Of course, we also know that homotopy types can be described in terms of Kan complexes (which are classical models for $\infty$-groupoids), which is one simplicial manifestation of the homotopy hypothesis. My understanding is that Grothendieck was interested in fundamental algebraic operations on a more globular type of structure that arises from homotopy $n$-types $X$, where the $j$-cells for $j < n$ are maps $D^j \to X$ (thinking here of $D^j$ as a co-globular space) and $n$-cells are maps $D^n \to X$ modulo homotopy rel boundary. Surely this type of structure fits roughly into the sequence of the "classical" weak $n$-categories (category, bicategory, tricategory). If I can indulge in some shameless self-promotion, a main motivation for the notion of weak $n$-category that I presented in 1999 (see Tom Leinster's article ) was actually to give a definition of Grothendieck fundamental $n$-groupoids along those sorts of "classical" lines (this is somewhat predating the "$(\infty, 1)$-revolution"). I am not sure of the state of the art here, but if I can be allowed to speculate wildly (and with it being understood that I am not a homotopy theorist): we might begin by observing that objects like Kan complexes (or their truncations) are not, technically speaking, algebraic in the sense of being strictly described in terms of operations subject to equational axioms. They can be algebraized, and something like an algebraic notion of (weak) $n$-groupoid or $\infty$-groupoid results, but actually milking usable algebraic invariants out of such structures, i.e., extracting usable algebraic invariants for $n$-types in a way that extends the results of Eilenberg-Mac Lane, Joyal-Street, etc., seems to me a possibly worthy research project. Possibly such study would proceed by locating usable semi-strictifications of $n$-categorical structures (à la the manner in which Gray-groupoids are semistrict tricategorical groupoids). In other directions: researchers such as Ronnie Brown have worked on $n$-types via more cubical notions (cubical $\omega$-groupoids), especially with a view toward higher van Kampen theorems, and Baues (whose work I don't know) has also worked on Whitehead's program (see his book Algebraic Homotopy, I guess). While we're in this speculative mode: I don't know what really to say to the suggestion that we generalize the HH to objects of a Grothendieck topos $E$ (whose objects are thought of as "generalized spaces"). The only thing that comes to my mind right away is that we could try defining homotopy groups of objects in $E$ by appealing to a suitable "geometric realization" that passes through a left-exact left adjoint $E \to \textbf{Simp-Set}$. But there could be many choices of such lex left adjoints; they correspond to "$E$-models" in simplicial sets, where model is in the sense of whatever geometric theory the Grothendieck topos $E$ classifies. This could be interesting, or could be a dead end. Hard for me to say. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/171717', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_74915 |
stackexchange | llm_judgeable_groundtruth_similarity | 266501 |
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:
Can a black hole, in principle, fall into another black hole's innermost stable circular orbit?
Now provide the response and nothing else.
| The innermost stable orbit is a theoretical concept that applies to a "test particle" orbiting a black hole. A test particle in this case would mean that it has negligible mass and so does not alter the metric (Schwarzschild, or more realistically Kerr) it is in. If an orbiting black hole were much less massive than the black hole it orbited, then perhaps you could make this approximation - e.g. a stellar mass black hole orbiting a supermassive black hole. If one cannot make the test mass approximation there can be no stable orbit. As has now been experimentally demonstrated, massive orbiting bodies are a source of gravitational waves. Two objects will inevitably spiral inwards and merge on a timescale that decreases with the sum and product of their masses and the inverse of their separation. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/266501', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/85745/']} | jdg_74916 |
stackexchange | llm_judgeable_groundtruth_similarity | 2408353 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have tried everything and I am just unable to solve the following sums. Mainly because I do not understand the suppositions and why they are there in the first place and further I do not get what the term a with a subscripted i or an expression with j is supposed to denote. I was able to do all other sums except the ones with aforementioned characteristics. I really need a straightforward explanation/answer to this, thanks in advance. Suppositions: $$\sum_{i=1}^{10}a_{i}=19\;$$ and $$\sum_{i=1}^{20}a_{i}=-5\;.$$ These are the sums: $$\sum_{i=1}^{10}(9-a_{i})\;$$$$\sum_{j=4}^{13}(a_{j-3}+a_{j+7})\;$$$$\sum_{i=11}^{21}(4a_{i}-4)\;$$$$\sum_{k=2}^{21}(a_{k-1}-a_{ \lfloor k/2 \rfloor})\;$$ $$\sum_{i=0}^{1}\;\sum_{j=1}^{5}(4+a_{5i+j})\;$$$$\sum_{i=1}^{10}(a_{2i})+\sum_{i=1}^{10}(a_{2i-1}-6)\;$$$$\sum_{i=1}^{10}(i+a_{i})\;$$
Now provide the response and nothing else.
| The matrix$$A=\begin{bmatrix} 0 & 1\\-1 & 0\end{bmatrix}$$ is skew-symmetric and orthogonal. In even dimensions, we can always construct a skew-symmetric and orthogonal matrix as the direct sum of multiple copies of $A$. i.e. the matrix $$\bigoplus_{i=1}^k A=\underbrace{\begin{bmatrix} A &&&\\&A&&\\&&\ddots & \\&&&A\\ \end{bmatrix}}_{k \text{ copies}}$$is a $2k \times 2k$ orthogonal and skew-symmetric matrix In odd dimensions however, there is no real matrices which are skew-symmetric and orthogonal. As you already know, real skew-symmetric matrices are singular in odd dimensions so they must have at least one eigenvalue which is zero. Therefore if $B$ is an $n\times n$ matrix with $n$ odd, it must be the case that $\text{det}(B)=0$. If $B$ is orthogonal however, $B^TB=I$ and so $$\text{det}(B^TB)=\text{det}(B^T)\text{det}(B)=[\text{det}(B)]^2=\text{det}(I)=1$$ thus $\text{det}(B)= \pm 1$ and so $B$ can not be both orthogonal and skew-symmetric in odd dimensions. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2408353', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/453029/']} | jdg_74917 |
stackexchange | llm_judgeable_groundtruth_similarity | 21534 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a TI CC430 MCU because it contains an embedded CC1101 radio frontend. I would really like to stick with this MCU. However, I need to simultaneously interact with a separate serial radio, a FTDI (uart->USB), and an RS232 GPS. So it would be nice to have 3 separate UARTS on the MCU. What are my options for increasing the number of UARTs? I have considered adding a CPLD and muxing the single UART to 3 outputs, but I really don't like that approach because it not really 3 simultaneous connections.
Now provide the response and nothing else.
| You could add an extra UART over SPI or I2C. These have internal FIFO buffers inside them so you periodically check them for content and let them handle some buffering. NXP, TI, Maxim probably offer these parts. MAX3100, SC16IS752 etc. You could also add a second MCU to do this, but as you're already using quite a simple microcontroller with 1 UART and want to stick to that, that seems overkill. You could also use a multiplexer to choose between the UART your micro talks to. But as you mentoined data is transmitted simultaneously , that won't work. Software serial could be your last option but it can be very annoying to deal with if your microcontroller is doing other stuff as well. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/21534', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6339/']} | jdg_74918 |
stackexchange | llm_judgeable_groundtruth_similarity | 3688342 |
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 created and configured an SSL certificate as per these instructions from MSDN. I'm getting the error message that this question lists, but am not sure how to map the accepted answer in that question to my App.config file. The content of the config file, and the service itself worked correctly over http, it's just over https that the problem is occuring. My App.config file is currently: <?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="TransportSecurity"> <security mode="Transport"> <transport clientCredentialType="None"/> </security> </binding> </wsHttpBinding> </bindings> <services> <service name="LookupServiceHost" behaviorConfiguration="serviceBehaviour"> <host> <baseAddresses> <add baseAddress="https://localhost:54321/MyService"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="ILookupService" bindingConfiguration="TransportSecurity" /> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="serviceBehaviour"> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration> The Error Exception returned in the Windows Event Log: Service cannot be started. System.ServiceModel.AddressAlreadyInUseException: HTTP could not register URL https://+:54321/MyService/ . Another application has already registered this URL with HTTP.SYS. ---> System.Net.HttpListenerException: Failed to listen on prefix ' https://+:54321/MyService/ ' because it conflicts with an existing registration on the machine. Could someone give me a pointer as to how to enable this?
Now provide the response and nothing else.
| I think you are connecting two different settings. Netsh can be used to add certificate for SSL but also to allow application listening on given port without running under admin account. The exception targets second setting. I haven't seen it before but I assume that you have already registered this port for HTTP so lets try to use (and register) HTTPS on another port or replace previous registration. Edit: Open command prompt with elevated privileges (As Admin). First check if SSL cert is assigned to correct port: netsh http show sslcert Than check if HTTP listening is registered on that port by calling: netsh http show urlacl If so use following command to remove that registration: netsh http delete urlacl url=http://+:54321/MyService Add registration again to support listening on HTTPS: netsh http add urlacl url=https://+:54321/MyService user=domain\userName Where user is account used to run your Windows service. If it ia a local account use only userName. Note: Under https, it appears the wildcard must be used in the urlacl. We cannot write https://localhost:8733/... to match Visual Studios default urlacl for http. This probably makes sense since the requested hostname isn't available until after decryption. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3688342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7872/']} | jdg_74919 |
stackexchange | llm_judgeable_groundtruth_similarity | 710337 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would appreciate if somebody could help me with the following problem. Prove that if the sum and product of two rational numbers are both integers, then the two rational numbers must be integers. Thanks!
Now provide the response and nothing else.
| This may not be the simplest proof, but I think it's pretty. Let your two rational numbers be $r,s$. Then the polynomial $f(x)=(x-r)(x-s)=x^2-(r+s)x+rs$ has integer coefficients by your hypotheses. By Gauss' Lemma , this polynomial must be reducible over the integers, and hence $r,s$ are both integers. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/710337', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59343/']} | jdg_74920 |
stackexchange | llm_judgeable_groundtruth_similarity | 832958 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I am playing around iptables to filter the packets coming and going. What will be the result of following rules? iptables -A INPUT -s 192.168.1.0/24 -j ACCEPTiptables -A INPUT -s 192.168.1.0/24 -j DROP
Now provide the response and nothing else.
| Iptables (and most firewall software) operates on a concept of first match wins, so if the rules are in the order posted above, the ACCEPT will match first and will be the effective policy applied to the packet. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/832958', 'https://serverfault.com', 'https://serverfault.com/users/399715/']} | jdg_74921 |
stackexchange | llm_judgeable_groundtruth_similarity | 62288835 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am attempting to create a conda environment with 3 packages and a specific python version and get the following output: $ conda create -n testing_junk -y instrain awscli samtools python=3.8Collecting package metadata (current_repodata.json): doneSolving environment: failed with repodata from current_repodata.json, will retry with next repodata source.Collecting package metadata (repodata.json): doneSolving environment: |Found conflicts! Looking for incompatible packages.This can take several minutes. Press CTRL-C to abort.failed \UnsatisfiableError: The following specifications were found to be incompatible with each other:Output in format: Requested package -> Available versionsPackage ncurses conflicts for:python=3.8 -> ncurses[version='>=6.1,<6.2.0a0|>=6.2,<7.0a0|>=6.1,<7.0a0']awscli -> python[version='>=3.8,<3.9.0a0'] -> ncurses[version='5.9.*|5.9|>=6.1,<6.2.0a0|>=6.2,<7.0a0|>=6.1,<7.0a0|>=6.0,<7.0a0|6.0.*']instrain -> python[version='>=3.4'] -> ncurses[version='5.9.*|5.9|>=6.1,<6.2.0a0|>=6.2,<7.0a0|>=6.1,<7.0a0|>=6.0,<7.0a0|6.0.*']python=3.8 -> readline[version='>=7.0,<8.0a0'] -> ncurses[version='5.9.*|>=6.0,<7.0a0|6.0.*']samtools -> ncurses[version='5.9|5.9.*|>=5.9,<5.10.0a0|>=6.1,<6.2.0a0']Package python conflicts for:awscli -> python[version='2.7.*|3.5.*|3.6.*|>=2.7,<2.8.0a0|>=3.6,<3.7.0a0|>=3.7,<3.8.0a0|>=3.8,<3.9.0a0|>=3.5,<3.6.0a0|3.4.*']python=3.8instrain -> biopython -> python[version='2.7.*|3.5.*|3.6.*|>=2.7,<2.8.0a0|>=3.6,<3.7.0a0|>=3.8,<3.9.0a0|>=3.7,<3.8.0a0|>=3.5,<3.6.0a0|3.4.*|>3|>=3.5|<3.0.0|>=3.6']instrain -> python[version='>=3.4']awscli -> python_abi=3.8[build=*_cp38] -> python[version='3.7.*|3.8.*']Package ca-certificates conflicts for:samtools -> openssl[version='>=1.1.1a,<1.1.2a'] -> ca-certificatespython=3.8 -> openssl[version='>=1.1.1g,<1.1.2a'] -> ca-certificatesawscli -> python[version='>=2.7,<2.8.0a0'] -> ca-certificatesPackage setuptools conflicts for:python=3.8 -> pip -> setuptoolsinstrain -> matplotlib-base -> setuptools[version='>=40.0']Package libgcc-ng conflicts for:samtools -> ncurses[version='>=6.1,<6.2.0a0'] -> libgcc-ng[version='>=7.2.0']samtools -> libgcc-ng[version='>=4.9|>=7.3.0']Package pypy3.6 conflicts for:instrain -> numpy -> pypy3.6[version='7.3.0.*|7.3.1.*|>=7.3.1']awscli -> python[version='>=3.6,<3.7.0a0'] -> pypy3.6[version='7.3.*|7.3.0.*|7.3.1.*']Package bzip2 conflicts for:samtools -> bzip2[version='1.0.*|>=1.0.6,<2.0a0|>=1.0.8,<2.0a0']instrain -> pysam -> bzip2[version='>=1.0.6,<2.0a0|>=1.0.8,<2.0a0']awscli -> python[version='>=3.7,<3.8.0a0'] -> bzip2[version='>=1.0.6,<2.0a0|>=1.0.8,<2.0a0']Package zlib conflicts for:samtools -> zlib[version='1.2.11.*|>=1.2.11,<1.3.0a0|1.2.8.*|1.2.8']samtools -> curl[version='>=7.59.0,<8.0a0'] -> zlib[version='1.2.*|1.2.11']Package samtools conflicts for:samtoolsinstrain -> pysam -> samtools[version='1.3|1.3.1.*|1.3.1|1.5.*|1.6.*|1.7|1.7.*|1.9.*|>=1.4.1|>=1.4.1,<1.5|>=1.4,<1.5|>=1.3,<1.4|>=1.3']Package openssl conflicts for:samtools -> curl[version='>=7.59.0,<8.0a0'] -> openssl[version='1.0.*|>=1.0.2o,<1.0.3a|>=1.0.2m,<1.0.3a']samtools -> openssl[version='>=1.0.2p,<1.0.3a|>=1.0.2r,<1.0.3a|>=1.1.1a,<1.1.2a']Package _libgcc_mutex conflicts for:samtools -> libgcc-ng[version='>=7.3.0'] -> _libgcc_mutex[version='*|0.1',build='main|conda_forge']python=3.8 -> libgcc-ng[version='>=7.5.0'] -> _libgcc_mutex[version='*|0.1',build='main|conda_forge']The following specifications were found to be incompatible with your CUDA driver: - feature:/linux-64::__cuda==10.2=0 - feature:|@/linux-64::__cuda==10.2=0Your installed CUDA driver is: 10.2 I understand that there is something about the packages that conflict with each other, but I'm unable to interpret this output to understand what the problem is. For example, in looking at the first block of conflicts (related to ncurses ), shouldn't version 6.1 satisfy all requirements listed? Additionally, for the block about package setuptools , I don't see any problem at all? Any insight into how to interpret these conflicts so that I can attempt to address them would be much appreciated.
Now provide the response and nothing else.
| Some Practical Advice @Quantum7's answer gives a fine literal interpretation of Conda's conflict reporting. However, I wanted to offer a more practical take, which is that this "feature" from Conda is too non-specific to be useful in most non-trivial environments. And sometimes it won't even include the underlying conflict. Don't waste your time with it! Conda's Conflict Reporting is Often Not Helpful On the face of it, Conda attempts to report all possible sources of conflict . That is, all sets of paths in the dependency graph that begin from the explicit specifications and end in the same package. This amounts to most of what is reported being innocuous and frankly distracting. For example, the zlib "conflicts": Package zlib conflicts for:samtools -> zlib[version='1.2.11.*|>=1.2.11,<1.3.0a0|1.2.8.*|1.2.8']samtools -> curl[version='>=7.59.0,<8.0a0'] -> zlib[version='1.2.*|1.2.11'] Since samtools depends on zlib both directly and indirectly (mediated through curl ), this comes up as two alternate paths that lead to constraints. The problem is that the intersection of the final constraints are not empty, such that there is nothing incompatible here. Furthermore, there are cases where none of what is reported is in conflict (e.g., this question or this one ), which means parsing through the output could be a complete waste of time. Try Mamba Instead, if one is actually concerned with resolving conflicts, I find Mamba to be more effective to work with, both in speed and precision. # install mambaconda install -n base conda-forge::mamba# use 'mamba' just like 'conda'mamba create -n foo instrain awscli samtools python=3.8 Unfortunately, this example simply works now. However, there are other questions where Conda and Mamba unsatisfiability reporting is compared, e.g., this question . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62288835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7101921/']} | jdg_74922 |
stackexchange | llm_judgeable_groundtruth_similarity | 219569 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?
Now provide the response and nothing else.
| Lowest common denominator max URL length among popular web browsers: 2,083 (Internet Explorer) http://dev.mysql.com/doc/refman/5.0/en/char.html Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. So ... < MySQL 5.0.3 use TEXT or >= MySQL 5.0.3 use VARCHAR(2083) | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/219569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22325/']} | jdg_74923 |
stackexchange | llm_judgeable_groundtruth_similarity | 34321179 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array of mathematical operators stored as an object. object {0: "-", 1: "*", 2: "/", 3: "+"} called numOperators I don't know what order the operators will be in, but they need to be execued in the correct order of *, /, +, and - So when I reassign the above object into another parallel object, I assign the indexes of the above object with the order they need to be executed. Then i have this object: Object {0: 2, 1: 0, 2: 1, 3: 3} called opArray What I want to do is iterate through the object (which could be any length) by looking at the values instead of the indexes. In summary, I want to iterate all of the values in the order 3, 2, 1, 0. Look for values of 3 until those are used up, then look for 2, then 1, then finally go through 0. I haven't been able to come up with an efficient way of doing this. Because mathematical operators need to be done in order, a temporary result value is created and then used for the next iteration. Eventually, they are all combined into a single result. This is what I was trying last: var valArray = {0: "3", 1: "8", 2: "4", 3: "8", 4: "2"};var res=[];//temporary result values ordered by executionvar returnRes=0;var op=0;$.each(opArr, function(index, value) {//goes through the values in order if(value==0){ op = numOperators[index]; //uses the indexes that matches the values res[index]=operate(valArr[index], valArr[index+1],op); returnRes=res[index]; console.log(res); } if(valuei>0){ op = numOperators[index]; res[index]=operate(res[index-1], valArr[index+1],op); returnRes=res[index]; console.log(res); }}); return(returnRes); I know I may be going about this the completely wrong way, so I'd appreciate some insight on what is an easier way to do this. Thanks! To clarify further, I have a valid reason for taking this approach to math and not using eval(). Some of the numbers are derived from variables read in as text and converted. There could also be text (non-number text) that needs to be concatenated. So I need to get the math and text separated and evaluated differently. I figured an individual approach would be best.
Now provide the response and nothing else.
| React requires you to have something unique for every element in the rendered array, it's called a key , and it's an attribute. If you don't know what to assign to the key, just assign it the array's indexes: this.props.doors.map((door, index) => ( <div key={index} className="door"></div>)); Here's the same solution applied to your problem: return this.data.emailGroup.emails.map((email, index) => { return ( <div key={index} className="input-group"> <input type="text" className="form-control" onChange={self.handleEmailListChange.bind(this, index)} value={email}/> </div> );}); Notice how I bound handleEmailListChange to receive the index of the modified email. If handleEmailListChange accepts an index, it can update the modified email within the state: handleEmailListChange: function(index, event) { var emails = this.state.emails.slice(); // Make a copy of the emails first. emails[index] = event.target.value; // Update it with the modified email. this.setState({emails: emails}); // Update the state.} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34321179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4792521/']} | jdg_74924 |
stackexchange | llm_judgeable_groundtruth_similarity | 14457711 |
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 been searching for a KISS example of how to do this, and while they all seem (and I've gone through them ALL!) simple enough, I still cannot get my head around the concept. I'm referring to custom listeners (ones that do not extend anything)... In particular, creating a listener for a boolean variable so that I can set off some methods when its value changes. this is an example of an example I've tried: android how to make listener to a custom variable? If someone has the time to explain a custom listener and how it works in plain English, that would be much appreciated. I'm hoping that once I understand exactly how the listener is notified of a change, then I'll be able to create my own and understand how the damn thing works. This is giving me a headache... Thanks in advance Here is where I'm at at the moment: public class ChangeListener { boolean boo = false; public ChangeListener(boolean b){ boo = b; } private listener l = null; public interface listener{ public void onChange(boolean b); } public void setChangeListener(listener mListener){ l = mListener; } public void somethingChanged(){ if(l != null){ l.onChange(boo); } }} This is a snapshot of my main activity: public class Main extends Activity implements ChangeListener.listener{ private ChangeListener listener; private boolean boo = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listener = new ChangeListener(boo); listener.setChangeListener(this); listener.somethingChanged(); } @Override public void onChange(boolean b) { // TODO Auto-generated method stub Toast.makeText(this, "REST = "+b, Toast.LENGTH_SHORT).show(); }} Now, when the activity starts, the Toast displays the state of boo... great. Problem is this only happens within onCreate, which makes sense as .somethingChanged is placed in there. What I would like is for the Toast to be generated every time boo is changed from false to true, and true to false regardless if its within onCreate or not. I.e: Click a button Causes boo to change from false to true Listener picks up on the change and runs whatever is in onChange I know I could just use the button actionListener to do this, but I would like to stay away from this if possible, which at the moment I'm starting to think is impossible. Any insight would be much appreciated. Thanks in advance!
Now provide the response and nothing else.
| You wrap the variable up inside a custom class such that the only access functions also trip the listener. So that the only way to flip the switch is via the functions which toggles and calls the listener. public class BooVariable { private boolean boo = false; private ChangeListener listener; public boolean isBoo() { return boo; } public void setBoo(boolean boo) { this.boo = boo; if (listener != null) listener.onChange(); } public ChangeListener getListener() { return listener; } public void setListener(ChangeListener listener) { this.listener = listener; } public interface ChangeListener { void onChange(); }} To monitor the change you need to implement BooVariable.ChangeListener and then pass the BooVariable class a copy of "this" then, when you change the variable it calls onChange. Also, keeping in mind you can just inline the code rather than extend directly: BooVariable bv = new BooVariable();bv.setListener(new BooVariable.ChangeListener() { @Override public void onChange() { Toast.makeText(MainActivity.this,"blah", Toast.LENGTH_LONG).show(); }}); PS. The toast must be called from the UI thread, so you need to switch the Looper if you're going to change the variable in a different thread. This likely won't come up though. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14457711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1977217/']} | jdg_74925 |
stackexchange | llm_judgeable_groundtruth_similarity | 43126956 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Client code: import requestsimport jsonurl = 'http://127.0.0.1:5050/login'user = "newUser"password = "password"headers = {'content-type': 'application/json'}response = requests.post(url, data={"user": user,"pass": password}, headers = headers) Server code: from flask import Flask, request, make_responseapp = Flask(__name__)@app.route('/login', methods=['GET','POST'])def login(): if request.method == 'POST': username = request.form.get("user") password = request.form.get("pass") //more code return make_response("",200)if __name__ == "__main__": app.run(host = "127.0.0.1", port = 5050) The problem is that my username and password are always None. I also tried using: content = request.get_json(force = True) password = content['pass'] and request.form['user'] When I print the content I have: < Request ' http://127.0.0.1:5050/login ' [POST]> .So I cannot find the json send from the client. EDIT: I did add json.dumps and used request.get_json() and it worked
Now provide the response and nothing else.
| You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data. response = requests.post(url, json={"user": user,"pass": password}) Retrieve the data in Flask with: data = request.get_json() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43126956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4397707/']} | jdg_74926 |
stackexchange | llm_judgeable_groundtruth_similarity | 3270 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In this question, all rings are commutative with a $1$, unless we explicitly sayso, and all morphisms of rings send $1$ to $1$. Let $A$ be a Noetherian local integral domain. Let $T$ be a non-zero $A$-algebrawhich, as an A-module, is finitely-generated and torsion-free. Can one realise $T$ as a subring of the (not necessarily commutative)ring $End_A(A^n)$ for some $n \ge 1$?
Now provide the response and nothing else.
| A starting proviso: you didn't require that the map $T \rightarrow End_A(A^n)$ send elements of A to their obvious diagonal representatives. I am going to assume you intended this. A few partial results: 1) If $A=k[x,y]/(x^3-y^2)$, and $T$ is the integral closure of A, then this can not be done. Let $t$ be the element $y/x$ of $T$ and $M$ the matrix that is supposed to represent it. Then we must have $xM=y Id_n$, which has no solutions. More generally, whenever A is a non-normal ring and $T$ its integral closure, there are no solutions. 2) If $A$ is a Dedekind domain the answer is yes. Let $V$ be the vector space $T \otimes Frac(A)$, and $V^{\ast}$ the dual vector space. Let $T^{\ast} \subset V^{\ast}$ be the vectors whose pairing with $T$ lands in $A$. Using the obvious action of $T$ on itself, we get an action of $T^{op}$ on $T^{\ast}$. Since $T$ is commutative, this is an action of $T$ on $T^{\ast}$. Now, $T \oplus T^{\ast}$ is free as an A-module, so this gives us the desired representation. 2') A conjectural variant of the above: I have a vague recollection that, if $A$ is a polynomial ring, $T^{\ast}$ is always free. Can anyone confirm or refute this? 3) A case which I think is impossible, but can't quite prove at this hour: Let $T = k[x,y]$ and let $A$ be the subring $k[x^2, xy, y^2]$. I am convinced that we cannot realize $T$ inside the ring of matrices with entries in $A$, but the proof fell apart when I tried to write it down. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/3270', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1384/']} | jdg_74927 |
stackexchange | llm_judgeable_groundtruth_similarity | 7132061 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I refer to JSF components in jquery, as I dont know the id(s) prepended to the id of component I want to refer ?
Now provide the response and nothing else.
| You can give all NamingContainer components in the view such as <h:form> , <h:dataTable> , <ui:repeat> , <my:composite> a fixed ID so that the HTML-generated client ID is safely predictable. If you're uncertain, just open the page in webbrowser, rightclick and do View Source . If you see an autogenerated ID like j_id123 in the client ID chain, then you need to give exactly that component a fixed ID. Alternatively, you can use #{component.clientId} to let EL print the component's client ID to the generated HTML output. You can use component's binding attribute to bind the component to the view. Something like this: <h:inputText binding="#{foo}" /><script> var $foo = $("[id='#{foo.clientId}']"); // jQuery will then escape ":". // ...</script> This only requires that the script is part of the view file. As another alternative, you could give the element in question a classname: <h:inputText styleClass="foo" /><script> var $foo = $(".foo"); // ...</script> As again another alternative, you could just pass the HTML DOM element itself into the function: <h:inputText onclick="foo(this)" /><script> function foo(element) { var $element = $(element); // ... }</script> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7132061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530153/']} | jdg_74928 |
stackexchange | llm_judgeable_groundtruth_similarity | 49129280 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I've been stuck on this for a while and I can't find anything on google for this specific thing. I have this small snippet of code $link = mysqli_connect("localhost", 'username','password',"database");$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1"; Which should select the latest table by order of id's right?Well what I want to do is return this id. So if I have 5 items/rows I want to grab the latest (5 in this case) id of the table, and return it. With the eventual goal of using this returned id in javascript but that's a worry for later, right now I just want it in plaintext where the result should only be the id. This is probably a duplicate question but I can't for the life of me find what I should google to get there EDIT: I guess I should clarify further. I know I'm able to do $sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1"; but whenever I try to actually retrieve it/print it its returned as a string instead of the ID. EDIT 2: I, thanks to some comments, have managed to figure it out. Sorry for the badly worded everything, I'm new to this and as I said don't know how to word it. SOLUTION: After just throwing away the $sql thing I added: $result = mysqli_query($link,"SELECT * FROM `uploads`"); Then I simply did echo mysqli_num_rows($result); To echo out the number of rows/what I called the "ID". Sorry for all the confusion, thanks to those that tried to help. To the others there's no need to be rude.
Now provide the response and nothing else.
| You could recursively create a promise resolve chain. A bit less repetition and you'll know when all planets are loaded when the parent promise resolves. function getStarWarsPlanets(progress, url = 'https://swapi.co/api/planets', planets = []) { return new Promise((resolve, reject) => fetch(url) .then(response => { if (response.status !== 200) { throw `${response.status}: ${response.statusText}`; } response.json().then(data => { planets = planets.concat(data.results); if(data.next) { progress && progress(planets); getStarWarsPlanets(progress, data.next, planets).then(resolve).catch(reject) } else { resolve(planets); } }).catch(reject); }).catch(reject));}function progressCallback(planets) { // render progress console.log(`${planets.length} loaded`);}getStarWarsPlanets(progressCallback) .then(planets => { // all planets have been loaded console.log(planets.map(p => p.name)) }) .catch(console.error); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49129280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6629204/']} | jdg_74929 |
stackexchange | llm_judgeable_groundtruth_similarity | 2947623 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using the REPLACE function in oracle to replace values in my string like; SELECT REPLACE('THE NEW VALUE IS #VAL1#','#VAL1#','55') from dual So this is OK to replace one value, but what about 20+, should I use 20+ REPLACE function or is there a more practical solution. All ideas are welcome.
Now provide the response and nothing else.
| Even if this thread is old is the first on Google, so I'll post an Oracle equivalent to the function implemented here, using regular expressions. Is fairly faster than nested replace(), and much cleaner. To replace strings 'a','b','c' with 'd' in a string column from a given table select regexp_replace(string_col,'a|b|c','d') from given_table It is nothing else than a regular expression for several static patterns with 'or' operator. Beware of regexp special characters! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2947623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222159/']} | jdg_74930 |
stackexchange | llm_judgeable_groundtruth_similarity | 21477493 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Small question about the download manager in android.It's the first time I'm working with it and have successfully downloaded multiple files and opened them. But my question is how do i check if the download completed. The situation is I download a PDF file and open it, and usually the file is so small it complets before opening. But if the file is somewhat bigger how do I check if the download manager is finished with the download before opening it. How I download: Intent intent = getIntent();DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);Uri Download_Uri = Uri.parse(intent.getStringExtra("Document_href"));DownloadManager.Request request = new DownloadManager.Request(Download_Uri);//Restrict the types of networks over which this download may proceed.request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);//Set whether this download may proceed over a roaming connection.request.setAllowedOverRoaming(false);//Set the title of this download, to be displayed in notifications.request.setTitle(intent.getStringExtra("Document_title"));//Set the local destination for the downloaded file to a path within the application's external files directoryrequest.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,intent.getStringExtra("Document_title") + ".pdf");//Enqueue a new download and same the referenceIdLong downloadReference = downloadManager.enqueue(request); How I open the file Uri uri = Uri.parse("content://com.app.applicationname/" + "/Download/" + intent.getStringExtra("Document_title") + ".pdf");Intent target = new Intent(Intent.ACTION_VIEW);target.setDataAndType(uri, "application/pdf");target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);startActivity(target); So somewhere between downloading and opening the file I want a if statement to check if it should continue or wait for the file.
Now provide the response and nothing else.
| A broadcast is sent by the DownloadManager whenever a download completes, so you need to register a broadcast receiver with the appropriate intent action( ACTION_DOWNLOAD_COMPLETE ) to catch this broadcast: To register receiver registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); and a BroadcastReciever handler BroadcastReceiver onComplete=new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { // your code }}; You can also create AsyncTask to handle the downloading of big files Create a download dialog of some sort to display downloading in notification area and than handle the opening of the file: protected void openFile(String fileName) { Intent install = new Intent(Intent.ACTION_VIEW); install.setDataAndType(Uri.fromFile(new File(fileName)),"MIME-TYPE"); startActivity(install);} you can also check the sample link Sample Code | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21477493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1285527/']} | jdg_74931 |
stackexchange | llm_judgeable_groundtruth_similarity | 21879804 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following class: public class MyClass { private Apple apple; public void myMethod() { apple = AppleFactory.createInstance(someStringVariable); .... .... .... }} And the Test class: @RunWith(MockitoJUnitRunner.class)public class MyClassTest { @InjectMocks MyClass myClass; @Test public void myMethod(){ ... ... ... } } How could I inject an Apple instance as a mock in MyClass?
Now provide the response and nothing else.
| You have 3 possibilities to solve this: Abstract factory : Instead of using a static method, use a concrete factory class: public abstract class AppleFactory { public Apple createInstance(final String str);}public class AppleFactoryImpl implements AppleFactory { public Apple createInstance(final String str) { // Implementation }} In your test class, mock the factory: @RunWith(MockitoJUnitRunner.class)public class MyClassTest { @Mock private AppleFactory appleFactoryMock; @Mock private Apple appleMock; @InjectMocks MyClass myClass; @Before public void setup() { when(appleFactoryMock.createInstance(Matchers.anyString()).thenReturn(appleMock); } @Test public void myMethod(){ ... ... ... }} PowerMock : Use PowerMock to create a mock of a static method. Look at my answer to a relevant question to see how it's done. Testable class : Make the Apple creation wrapped in a protected method and create a test class that overrides it: public class MyClass { private Apple apple; public void myMethod() { apple = createApple(); .... .... .... } protected Apple createApple() { return AppleFactory.createInstance(someStringVariable); }}@RunWith(MockitoJUnitRunner.class)public class MyClassTest { @Mock private Apple appleMock; @InjectMocks MyClass myClass; @Test public void myMethod(){ ... ... ... } private class TestableMyClass extends MyClass { @Override public void createApple() { return appleMock; } }} Of course, in your test class you should test TestableMyClass and not MyClass . I'll tell you my opinion on each of the methods: The abstract factory method is the best one - This is a clear design that hides the implementation details The testable class - Is the second option which requires minimum changes The PowerMock option is my least favorite - Instead of going for a better design, you ignore and hide your problem. But that's still a valid option. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21879804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/651850/']} | jdg_74932 |
stackexchange | llm_judgeable_groundtruth_similarity | 52273298 |
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 crawl the pages that I interested in. For this, I need to remove attribute of element from HTML. 'style' is what I want to remove. So I find some codes from Stackoverflow.(i'm using Chrome for driver) element = driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']")driver.execute_script("arguments[0].removeAttribute('style')", element) What does arguments[0] do in the code? Can anyone explain arguments[0] 's roles concretely?
Now provide the response and nothing else.
| arguments is what you're passing from Python to JavaScript that you want to execute. driver.execute_script("arguments[0].removeAttribute('style')", element) means that you want to "replace" arguments[0] with WebElement stored in element variable. This is the same as if you defined that element in JavaScript: driver.execute_script("document.querySelector('select.m-tcol-c#searchBy').removeAttribute('style')") You can also pass more arguments as driver.execute_script("arguments[0].removeAttribute(arguments[1])", element, "style") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52273298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7509178/']} | jdg_74933 |
stackexchange | llm_judgeable_groundtruth_similarity | 670672 |
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:
$L_{x}$ and $L^{2}$ commute, while $L_{x}$ and $L_{z}$ do not. However, $L_{z}$ and $L^{2}$ also commute, and hence, they also have common eigenstates. So the problem is: If $\lvert\psi\rangle$ is an eigenstate of $L_{x}$ and $L^{2}$ , won't it also be an eigenstate of $L_{z}$ (since $L^{2}$ and $L_{z}$ have common eigenstates), thus violate the uncertainty relationship? ( Edit -Actually, I knew the quantitative answer that is by computing the eigenstates of Lx and Lz, do turn out to be different,however, I wanted to know qualitatively why Lz and Lx do not have common eigenstates.)
Now provide the response and nothing else.
| The fact that $A$ and $B$ commute does not necessarily mean that every eigenstate of $A$ is also an eigenstate of $B$ . It just means that there is basis of eigenstates of $A$ that are also eigenstates of $B$ . However, in situations when the eigenvalues of $A$ are degenerate, it is also possible to use a different basis, in which the basis vectors are not eigenstates of $B$ . Let's see this concretely by looking at the simplest possible case, which is isomorphic to a $j=\frac{1}{2}$ angular momentum system. The angular momentum operators are $$J_{x}=\frac{\hbar}{2}\left[\begin{array}{cc}0 & 1 \\1 & 0\end{array}\right] \\J_{y}=\frac{\hbar}{2}\left[\begin{array}{cc}0 & -i \\i & 0\end{array}\right] \\J_{x}=\frac{\hbar}{2}\left[\begin{array}{cc}1 & 0 \\0 & -1\end{array}\right].$$ If you calculated the total angular momentum squared ${\bf J}^{2}=J_{x}^{2}+J_{y}^{2}+J_{z}^{2}$ , you will find that ${\bf J}^{2}$ has the explicit form $${\bf J}^{2}=\frac{3\hbar^{2}}{4}\left[\begin{array}{cc}1 & 0 \\0 & 1\end{array}\right].$$ Note that since ${\bf J}^{2}$ is proportional to the identity matrix, any two-component state will be an eigenstate: ${\bf J}^{2}|\psi\rangle=(3\hbar^{2}/4)|\psi\rangle$ . However, only certain vectors will be eigenstates of the individual angular momentum components. For instance, the eigenstates of $J_{z}$ are $$|z+\rangle=\left[\begin{array}{c}1 \\0\end{array}\right], \quad|z-\rangle=\left[\begin{array}{c}0 \\1\end{array}\right].$$ It is straightforward to verify that these satisfy $J_{z}|z\pm\rangle=(\pm\hbar/2)|z\pm\rangle$ , making them eigenstates of $J_{z}$ , with eigenvalues $\pm\hbar/2$ . However, they are not eigenstates of $J_{x}$ . Instead, the action of $J_{x}$ on the eigenstates of $J_{z}$ is $J_{x}|z\pm\rangle=(\pm\hbar/2)|z\mp\rangle$ . So the states $|z\pm\rangle$ are simultatneous eigenstates of ${\bf J}^{2}$ and $J_{z}$ , but not of $J_{x}$ . On the other hand, there is another basis of states that are eigenstates of $J_{x}$ . These are $$|z\pm\rangle=\frac{1}{\sqrt{2}}\left(|z+\rangle\pm|z-\rangle\right)=\frac{1}{\sqrt{2}}\left[\begin{array}{c}1 \\\pm1\end{array}\right].$$ These satisfy $J_{x}|x\pm\rangle=(\pm\hbar/2)|x\pm\rangle$ . However, they cannot be eigenstates of $J_{z}$ , since they are linear combinations of two states $|z+\rangle$ and $|z-\rangle$ that have different $J_{z}$ eigenvalues. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/670672', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/316017/']} | jdg_74934 |
stackexchange | llm_judgeable_groundtruth_similarity | 5457493 |
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 android app connects to my website to retrieve and upload information so I use an AsyncTask thread. In one instance, I need my thread to return a true or a false value to my main thread. Is there a way to get this return value from an AsyncTask execute function? When I do the following: Toast.makeText(Locate.this, "Testing : "+locationUpdate.execute(location), Toast.LENGTH_LONG).show(); I just get alot of gibberish. I think what I need is a means to pause the main thread until the second thread completes. The second thread calls a function in the main thread to set my return value.So when the second thread completes, the main thread can unpause and access the return value as set by the second thread If this logic is sound, please offer suggestions ... thanks!
Now provide the response and nothing else.
| You can use AsyncTask get() method for this. It waits if necessary for the computation to complete, and then retrieves its result: Toast.makeText(Locate.this, "Testing : " + locationUpdate.execute(location).get(), Toast.LENGTH_LONG).show(); But be sure to not block the main thread for a long period of time, as this will lead to unresponsive UI and ANR . UPDATE I missed the point that question was about async web download/upload. Web/network operation should considered as a long one and thus the approach "pause UI thread and wait till download finishes" is always a wrong one. Use usual result publishing approach intstead (e.g.: AsyncTask.onPostExecute , Service + sendBroadcast, libraries like Volley, RoboSpice, DataDroid etc). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5457493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504612/']} | jdg_74935 |
stackexchange | llm_judgeable_groundtruth_similarity | 760210 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be: GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy'; What is the equivalent command or series of commands in PostgreSQL? I tried... postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy';postgres=# GRANT SELECT ON DATABASE mydb TO xxx; But it appears that the only things you can grant on a database are CREATE, CONNECT, TEMPORARY, and TEMP.
Now provide the response and nothing else.
| Grant usage/select to a single table If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so: GRANT CONNECT ON DATABASE mydb TO xxx;-- This assumes you're actually connected to mydb..GRANT USAGE ON SCHEMA public TO xxx;GRANT SELECT ON mytable TO xxx; Multiple tables/views (PostgreSQL 9.0+) In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one: GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx; This only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future: ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO xxx; Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow. Multiple tables/views (PostgreSQL versions before 9.0) To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view: SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;'FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespaceWHERE nspname = 'public' AND relkind IN ('r', 'v', 'S'); This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created. | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/760210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42595/']} | jdg_74936 |
stackexchange | llm_judgeable_groundtruth_similarity | 5546280 |
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 running javap on a very simple HelloWorld application I have some confusion on the output around the constant pool. Test Code public class TestClass { public static void main(String[] args) { System.out.println("hello world"); }} Javap -c -verbose output (snipped) // Header + consts 1..22 snippedconst #22 = String #23; // hello worldconst #23 = Asciz hello world;public static void main(java.lang.String[]); Signature: ([Ljava/lang/String;)V Code: Stack=2, Locals=1, Args_size=1 0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #22; //String hello world 5: invokevirtual #24; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: return // Debug info snipped} Ok, so on line 3 we see a pushing of the "hello world" constant onto the stack via #22, but const #23 seems to hold the actual value. I guess I am a little confused with what the #(number) means when it appears on the right-hand-side of the printout. Oracle/Sun's man page for javap leaves much to be desired.
Now provide the response and nothing else.
| All your class , interface , field names and string constants go into the java constant pool . As per VM Spec ( http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html ): The constant_pool is a table of structures (§4.4) representing various string constants, class and interface names, field names, and other constants that are referred to within the ClassFile structure and its substructures. The format of each constant_pool table entry is indicated by its first "tag" byte. The constant_pool table is indexed from 1 to constant_pool_count-1. So in terms of constant pool something like below can be viewed as: const #22 = String #23; // hello worldconst #23 = Asciz hello world; The value at #22 (index 22) is of type String and its value is null terminated c string ( Asciz ) hello world is at index 23. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5546280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278836/']} | jdg_74937 |
stackexchange | llm_judgeable_groundtruth_similarity | 3516196 |
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 stl iterator resulting from a std::find() and wish to test whether it is the last element. One way to write this is as follows: mine *match = someValue;vector<mine *> Mine(someContent);vector<mine *>::iterator itr = std::find(Mine.begin(), Mine.end(), match);if (itr == --Mine.end()) { doSomething;} But it seems to me that decrementing the end() iterator is asking for trouble, such as if the vector has no elements, then it would be undefined. Even if I know it will never be empty, it still seems ugly. I'm thinking that maybe rbegin() is the way to go, but am not certain as to best way to compare the forward iterator with a reverse iterator.
Now provide the response and nothing else.
| Do this: // defined in boost/utility.hpp, by the waytemplate <typename Iter>Iter next(Iter iter){ return ++iter;}// first check we aren't going to kill ourselves// then check if the iterator after itr is the endif ((itr != Mine.end()) && (next(itr) == Mine.end())){ // points at the last element} That is all. Never gives you undefined behavior, works on all iterators, good day. Wrap it up for fun: template <typename Iter, typename Cont>bool is_last(Iter iter, const Cont& cont){ return (iter != cont.end()) && (next(iter) == cont.end())} Giving: if (is_last(itr, Mine)) If you're allergic to utility functions/nice looking code, do: if ((itr != Mine.end()) && (itr + 1 == Mine.end())) But you can't do it on non-random-access iterators. This one works with bidirectional iterators: if ((itr != Mine.end()) && (itr == --Mine.end())) And is safe since end() > itr by the first check. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3516196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115751/']} | jdg_74938 |
stackexchange | llm_judgeable_groundtruth_similarity | 8482759 |
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 puzzled why I can't msgbox this joined array. I can do it just fine if I create a static array with typed out values, but with a range of values from excel I keep getting "Invalid Procedure Call or Argument" I've done a fair amount of research but I'm not able to find any examples of this issue. What am I doing wrong here? Sub From_sheet_make_array() Dim myarray() As Variant Dim dudeString As String myarray() = Range("B2:B10").Value dudeString = Join(myarray(), ", ") MsgBox dudeString End Sub
Now provide the response and nothing else.
| A variant array created directly from a sheet range is 2D (ie it has rows and columns) - Join requires a 1D array. So you would need to do something like this [ Updated to read range into variant array, then to convert variant array into 1D array for joining - avoids cell loop ] Note also that using TRANSPOSE as Issun has below on a single column does force a 1D ouctome immediately. So another alternative would be to loop through the columns or rows of a 2D variant array, and TRANSPOSE them column by column (or row by row) to quickly produce a 1D array. Sub From_sheet_make_array() Dim X Dim lngRow As Long Dim myArray() X = Range("B2:B10").Value2 ReDim myArray(1 To UBound(X, 1)) For lngRow = 1 To UBound(X, 1) myArray(lngRow) = X(lngRow, 1) Next Dim dudeString As String dudeString = Join(myArray, ", ") MsgBox dudeString End Sub | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8482759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441962/']} | jdg_74939 |
stackexchange | llm_judgeable_groundtruth_similarity | 38304316 |
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 handle error in Retrofit 2.0 Got e.g. code=404 and body=null , but errorBody() contains data in ErrorModel ( Boolean status and String info ). This is errorBody().content : [text=\n{"status":false,"info":"Provided email doesn't exist."}] . How can I get this data? Thank for helping me! This is my code for Retrofit request: ResetPasswordApi.Factory.getInstance().resetPassword(loginEditText.getText().toString()) .enqueue(new Callback<StatusInfoModel>() { @Override public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) { if (response.isSuccessful()) { showToast(getApplicationContext(), getString(R.string.new_password_sent)); } else { showToast(getApplicationContext(), getString(R.string.email_not_exist)); } } @Override public void onFailure(Call<StatusInfoModel> call, Throwable t) { showToast(getApplicationContext(), "Something went wrong..."); } });
Now provide the response and nothing else.
| If you want to get data when error response comes ( typically a response code except 200 ) you can do it like that in your onResponse() method: if (response.code() == 404) { Gson gson = new GsonBuilder().create(); YourErrorPojo pojo = new YourErrorPojo(); try { pojo = gson.fromJson(response.errorBody().string(), YourErrorPojo.class); Toast.makeText(context, pojo.getInfo(), Toast.LENGTH_LONG).show(); } catch (IOException e) { // handle failure at error parse }} When generating YourErrorPojo.class do following steps : Go to Json Schema 2 Pojo Paste your example Json , and select source type Json , annotation Gson Your example Json is : {"status":false,"info":"Provided email doesn't exist."} Click Preview and it will generate your Pojo class for you. Add this to your build.gradle : compile 'com.google.code.gson:gson:2.7' I used Gson in this solution but you can get your Json string using: response.errorBody().string() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38304316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5992948/']} | jdg_74940 |
Subsets and Splits