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 | 1287007 |
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 a question which states: $R = \{ (t,t), (t,v), (t,z), (u,t), (u,u), (u,v), (u,x), (u,z), (v,v), (w,w), (w,z), (x,t), (x,v), (x,w), (x,x), (x,y), (x,z), (y,w), (y,y), (y,z), (z,z) \}$ "Give a counter example to show $R$ is not transitive ... " I understand that $R$ is said to be transitive if $(a,b) \in R$ and $(b,c) \in R$, implies $(a,c) \in R$. If these conditions aren't met then the relation is not transitive. How could apply this in the example? Thank you.
Now provide the response and nothing else.
| Since $R$ is small, you can actually consider all possibilities for $a,b$, and $c$. However, this is easier if you have a systematic arrangement of the ordered pairs. One way is to represent them by a matrix: $$\begin{array}{c|ccc}&t&u&v&w&x&y&z\\ \hlinet&1&&1&&&&1\\u&1&1&1&&1&&1\\v&&&1\\w&&&&1&&&1\\x&1&&1&1&1&1&1\\y&&&&1&&1&1\\z&&&&&&&1\end{array}$$ Here there is a $1$ in row $t$, column $v$, for instance, because the pair $\langle t,v\rangle$ is in $R$. Each of the other $1$s represents one of the other ordered pairs in $R$. Now you want to find $a,b,c\in\{t,u,v,w,x,y,z\}$ such that $\langle a,b\rangle$ and $\langle b,c\rangle$ are in $R$, but $\langle a,c\rangle$ is not in $R$. Notice that $x$ is related by $R$ to almost everything – everything except $u$, in fact – so it’s easy to find pairs $\langle x,\star\rangle\in R$. The only pair with first element $x$ that is not in $R$ is $\langle x,u\rangle$; can you find a $\star$ such that $\langle x,\star\rangle$ and $\langle\star,u\rangle$ are in $R$? Added: That attempt fails, because the $u$ column has only $u$ in it, so we might try for $\langle u,\star\rangle$ and $\langle\star,w\rangle$, or $\langle u,\star\rangle$ and $\langle\star,y\rangle$; this time it turns out that both yield counterexamples. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1287007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/241242/']} | jdg_69941 |
stackexchange | llm_judgeable_groundtruth_similarity | 164225 |
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:
# Automatically generated file; DO NOT EDIT Is at the header of the kernel configuration file: /usr/src/linux/.config My question is why shouldn't you edit this file? If I know exactly what I need, or what I want to remove, then what is the problem with editing this file directly?
Now provide the response and nothing else.
| It's considered unsafe to edit .config because there are CONFIG -options which have dependencies on other options (needing some to be set, requiring others to be turned off, etc.). Other options aren't meant to be set by the user at all, but are set automatically by make config (resp. Kconfig to be correct) depending on architecture details, e.g. availability of some hardware dependant on architecture variant, like an MMU. Changing .config without using Kconfig has a high chance of missing some dependency, which will either result in a non-functioning kernel, build failures, or unexpected behaviour (i.e. the change being ignored, which usually is very confusing). | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/164225', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/68646/']} | jdg_69942 |
stackexchange | llm_judgeable_groundtruth_similarity | 3417685 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following game: you flip a coin (heads with probability $p$ ), and if you get heads you earn $1000$ dollars, and you can decide if you want to flip again. If not, you keep the money. However, if you get tails, the game is over and you go home with nothing. I am having trouble calculating an optimal strategy for this game: I would like to maximize the winning amount by stopping at turn $f(p)$ , but... what is $f(p)$ ? If you did not lose all the money when tails appears, the expected winning value would just be a standard geometric distribution $\sum_{i=0}^\infty i p^{i-1} (1-p) = \frac{1}{1-p}$ , but I am having trouble evaluating the risk at each turn. Clearly never stopping is a good strategy only when $p=1$ , but intuitively when $p$ is very close to $1$ then stopping after the first win is not the best strategy. I am confused on how to model this phenomenon.
Now provide the response and nothing else.
| You have to calculate the expected value of continuing. Suppose you have $x$ dollars in earnings, if you continue you can expect to earn $1000$ dollars at chance $p$ and lose $x$ dollars at chance $(1-p)$ , so your expected earnings are $1000p-(1-p)x$ . If this is value is positive carry on, if it is not quit. In this case this means you should stop if $x\geq 1000\frac{p}{1-p}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3417685', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/452865/']} | jdg_69943 |
stackexchange | llm_judgeable_groundtruth_similarity | 327716 |
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:
Not sure how to approach this, other than to say the following: Let $|A|$=n, and let $|B|=m$. $$|A\times B|=n\cdot m$$ $$|B\times A|=m\cdot n$$ By the laws of commutativity for multiplication, $n\cdot m=m\cdot n$, and therefore $|A\times B|=|B\times A|$. It feels too easy though. Am I missing something or is that about it?
Now provide the response and nothing else.
| If the sets are arbitrary then you can't assume they are finite. You need to work here with the definition of cardinality. To show that $|A\times B|=|B\times A|$ you must prove there exists a bijection $f:A\times B\to B\times A$. There is a very natural choice for such a function, when you think about what these sets are. (Be careful in case one of the $A$ or $B$ is empty.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/327716', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39748/']} | jdg_69944 |
stackexchange | llm_judgeable_groundtruth_similarity | 124811 |
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:
Does the command line have a way to get a recommended list of programs used to open a particular file, based on the file type? For example, a .pdf file would have an open with... recommendation using the programs Evince and Document Viewer . I use the command line for most things, but sometimes I forget the name of a program that I want to use to open a particular type of file. BTW I am using Ubuntu 13.10. pro-tip Thanks to @slm 's selected answer below, I made the following bash script in a file called openwith.sh : xdg-mime query default $(xdg-mime query filetype $1) Add as an alias or execute directly as an openwith command.
Now provide the response and nothing else.
| There isn't a command that I've ever seen that will act as "open with..." but you can use the command xdg-open <file> to open a given <file> in the application that's associated with that particular type of file. Examples Opening a text file: $ xdg-open tstfile.txt$ Resulting in the file tstfile.txt being opened in gedit : Opening a LibreOffice Writer document: $ xdg-open tstfile.odt $ Resulting in the file tstfile.odt being opened in Writer: What apps get used? You can use xdg-mime to query the system to find out what applications are associated to a given file type. $ xdg-mime query default $(xdg-mime query filetype tstfile.txt)gedit.desktop calibre-ebook-viewer.desktop$ xdg-mime query default $(xdg-mime query filetype tstfile.odt)libreoffice-writer.desktop calibre-ebook-viewer.desktop This is a 2 step operation. First I'm querying for the mime-type of a given file, xdg-mime query filetype tstfile.txt , which will return text/plain . This is then used to perform another lookup to find out the list of applications that are associated with this mime-type. As you can see above I have 2 apps associated, gedit and calibre , for .txt files. You can use xdg-mime to change the associations too. See man xdg-mime for more details. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/124811', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/59802/']} | jdg_69945 |
stackexchange | llm_judgeable_groundtruth_similarity | 226567 |
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, that I cannot delete with rmdir . I get always a permission denied error. But when list the directory (with ls -l ) I get this: drwxrwxrwx 2 user user 4096 Aug 28 09:34 directory stat gives me that: File: `directory/' Size: 4096 Blocks: 16 IO Block: 32768 directoryDevice: 12h/18d Inode: 102368771 Links: 2Access: (0777/drwxrwxrwx) Uid: ( 1000/ user) Gid: ( 1000/ user)Access: 2015-08-31 03:00:20.630000002 +0200Modify: 2015-08-28 09:34:16.772930001 +0200Change: 2015-08-31 12:25:04.920000000 +0200 So how delete that directory.
Now provide the response and nothing else.
| If you are trying to delete a directory foo/bar/ , the permissions of bar isn't the relevant factor. Removing the name bar from directory foo is a modification of foo . So you need write permissions on foo . In your case, check the current directory's permissions with ls -ld . You might find this answer to "why is rm allowed to delete a file under ownership of a different user?" enlightening. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/226567', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/116283/']} | jdg_69946 |
stackexchange | llm_judgeable_groundtruth_similarity | 22179119 |
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 some data I have sampled from a radar satellite image and wanted to perform some statistical tests on. Before this I wanted to conduct a normality test so I could be sure my data was normally distributed. My data appears to be normally distributed but when I perform the test Im getting a Pvalue of 0, suggesting my data is not normally distributed. I have attached my code along with the output and a histogram of the distribution (Im relatively new to python so apologies if my code is clunky in any way). Can anyone tell me if Im doing something wrong - I find it hard to believe from my histogram that my data is not normally distributed? values = 'inputfile.h5'f = h5py.File(values,'r')dset = f['/DATA/DATA']array = dset[...,0]print('normality =', scipy.stats.normaltest(array))max = np.amax(array)min = np.amin(array)histo = np.histogram(array, bins=100, range=(min, max))freqs = histo[0]rangebins = (max - min)numberbins = (len(histo[1])-1)interval = (rangebins/numberbins)newbins = np.arange((min), (max), interval)histogram = bar(newbins, freqs, width=0.2, color='gray')plt.show() This prints this: (41099.095955202931, 0.0). the first element is a chi-square value and the second is a pvalue. I have made a graph of the data which I have attached. I thought that maybe as Im dealing with negative values it was causing a problem so I normalised the values but the problem persists.
Now provide the response and nothing else.
| This question explains why you're getting such a small p-value. Essentially, normality tests almost always reject the null on very large sample sizes (in yours, for example, you can see just some skew in the left side, which at your enormous sample size is way more than enough). What would be much more practically useful in your case is to plot a normal curve fit to your data. Then you can see how the normal curve actually differs (for example, you can see whether the tail on the left side does indeed go too long). For example: from matplotlib import pyplot as pltimport matplotlib.mlab as mlabn, bins, patches = plt.hist(array, 50, normed=1)mu = np.mean(array)sigma = np.std(array)plt.plot(bins, mlab.normpdf(bins, mu, sigma)) (Note the normed=1 argument: this ensures that the histogram is normalized to have a total area of 1, which makes it comparable to a density like the normal distribution). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22179119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2868191/']} | jdg_69947 |
stackexchange | llm_judgeable_groundtruth_similarity | 588143 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to rearrange awk's output? If yes, what is the right way to do it? wolf@Linux:~$ ip a s | awk '/^[0-9]/ {print $2} /inet / {print $2}'lo:127.0.0.1/8enp0s3:10.1.1.1/24enp0s8:172.16.1.1/24enp0s9:o192.168. it2?1.1/24wolf@Linux:~$ Desired Output wolf@Linux:~$ ip a s | <awk syntax here>lo: 127.0.0.1/8enp0s3: 10.1.1.1/24enp0s8: 172.16.1.1/24enp0s9: 192.168.1.1/24wolf@Linux:~$
Now provide the response and nothing else.
| It boils down to the amount of work being done. Your tail | tr command ends up doing the following: in tail : read until a newline; output everything remaining, without caring about newlines; in tr , read, without caring about newlines, and output everything apart from ‘"’ (a fixed character). Your sed command ends up doing the following, after interpreting the given script: read until a newline, accumulating input; if this is the first line, delete it; replace all double quotes with nothing, after interpreting the regular expression; output the processed line; loop until the end of the file. Your Perl command ends up doing the following, after interpreting the given script: read until a newline, accumulating input; replace all double quotes with nothing, after interpreting the regular expression; if this is not the first line, output the processed line; loop until the end of the file. Looking for newlines ends up being expensive on large inputs. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/588143', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/409008/']} | jdg_69948 |
stackexchange | llm_judgeable_groundtruth_similarity | 210829 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is an NP-complete problem? Why is it such an important topic in computer science?
Now provide the response and nothing else.
| NP stands for Non-deterministic Polynomial time. This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete. The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time. Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/210829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15055/']} | jdg_69949 |
stackexchange | llm_judgeable_groundtruth_similarity | 14103082 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Got another simple question here that is eluding me. I have 2 classes: namespace Assets{ public class BaseAsset { // Code here }} And namespace Assets{ public class Asset : BaseAsset { // Code here }} I have a function that returns a collection of Asset from the database and I want another function to execute that function and return a collection of BaseAsset.I have tried this: public static Collection<BaseAsset> GetCategoryAssets(int CategoryId, string UserId, string CompanyId) { return (Collection<BaseAsset>)AssetData.getAssets(CategoryId, UserId, CompanyId); } but as you can guess, it doesn't work.If I was working with lists, I could do: public static List<BaseAsset> GetCategoryAssets(int CategoryId, string UserId, string CompanyId) { return AssetData.getAssets(CategoryId, UserId, CompanyId).Cast<BaseAsset>().ToList(); } But I would prefer to use a collection, can anyone come up with an elegant solution? Cheers,r3plica
Now provide the response and nothing else.
| This is a very frequently asked question. The name of the feature that you want is generic covariance ; that is, the feature that says "if a giraffe is a kind of animal then a list of giraffes is a kind of list of animals." The problem is that a list of giraffes is not a kind of list of animals. You can put a tiger into a list of animals, but you can't put a tiger into a list of giraffes, and therefore a list of giraffes cannot be used in any context where a list of animals is expected. The reason you should use IEnumerable<T> instead of Collection<T> is because as of C# 4, IEnumerable<T> is covariant in T, provided that the type arguments provided are both reference types. That is, a sequence of strings can be used as a sequence of objects, because both are reference types. But a sequence of ints cannot be used as a sequence of objects, because one is a value type. The reason this is safe is because there is no way to insert a tiger into an IEnumerable<Giraffe> . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14103082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1303170/']} | jdg_69950 |
stackexchange | llm_judgeable_groundtruth_similarity | 5074179 |
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 can define a variable (by var ) that is immutable: var x = scala.collection.immutable.Set("aaaaaa","bbbbbb")println(x.isInstanceOf[scala.collection.immutable.Set[String]])x += "cccc"println(x.isInstanceOf[scala.collection.immutable.Set[String]]) This results in: truetrue += method is not a member of scala.collection.immutable.Set , so what is happening?
Now provide the response and nothing else.
| The compiler looks for x.+= ... , and if it can't find it, then it tries to transform the statement into x = x + ... (which only succeeds if x is a var , or x desugars into a call to some update method). Since immutable.Set implements a + operator, and x is a var , this succeeds. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5074179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/582855/']} | jdg_69951 |
stackexchange | llm_judgeable_groundtruth_similarity | 1192180 |
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 this isn't strictly a programming question, but it is related to git. I accidentally have created a branch in git called --track (I got the order of options wrong when merging a remote branch) The regular command doesn't work: git branch -D "--track" I have tried to escape with quotes and backward slashes, however neither work. Any ideas?
Now provide the response and nothing else.
| Did you try git branch -D -- --track ? the " -- " is usually the convention for "what follows is not an option, whatever its name" From " The Art of Unix Programming ", section " Command-Line Options ": It is also conventional to recognize a double hyphen as a signal to stop option interpretation and treat all following arguments literally. You will find that convention in other (not necessary Unix-related) CLI (Command Line Interface) like cleartool : If a nonoption argument begins with a hyphen ( – ) character, you may need to precede it with a double-hyphen argument, to prevent it from being interpreted as an option: cleartool rmtype -lbtype -- -temporary_label- The P18 (a fast and flexible file preprocessor with macro processing capabilities and special support for internationalization) mentions that also and gives a good description of the general idea behind that convention: All option arguments passed to the commands start with a single hyphen. All option arguments (if any) must precede all non-option arguments. The end of the option arguments may be signaled using a double hyphen , this is useful if a non-option argument starts with a hyphen. Terminating the list of option arguments with a double hyphen works for all commands, even those that don't take any option arguments. The OptionParser tool written in ruby also lays it out quite plainly:* Option Parsing Termination It is convention that a double hyphen is a signal to stop option interpretation and to read the remaining statements on the command line literally. So, a command such as: app -- -x -y -z will not ‘see’ the three mode-flags. Instead, they will be treated as arguments to the application: #args = ["-x", "-y", "-z"] Note: sometimes, it takes three dashes and not two, especially when the CLI follows strictly the Gnu options styles: The Gnu style command line options provide support for option words (or keywords), yet still maintain compatibility with the Unix style options. The options in this style are sometimes referred to as long_options and the Unix style options as short_options . The compatibility is maintained by preceding the long_options with two dashes Similar to the Unix style double-hyphen ’ -- ’, the Gnu style has a triple-hyphen ’ --- ’ to signal that option parsing be halted and to treat the remaining text as arguments (that is, read literally from the command line) So... if ' -- ' is not enough (it should be with Git commands), try ' --- ' | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1192180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92650/']} | jdg_69952 |
stackexchange | llm_judgeable_groundtruth_similarity | 4200 |
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:
In the King James Version of Rev. 5:10 , we find the following phrase, And hast made us unto our God kings and priests: and we shall reign on the earth. If we examine the immediate context, the antecedent of the pronoun "us" appears to be "the four beasts and twenty-four elders" who "fell down before the Lamb" (Rev. 5:9). These same entities also sing to Christ ( Rev. 5:9 ), "You have redeemed us to God by your blood out of every kindred, and tongue, and people, and nation..." Greek text of the Textus Receptus : καὶ ἐποίησας ἡμᾶς τῷ θεῷ ἡμῶν βασιλεῖς καὶ ἱερεῖς καὶ βασιλεύσομεν ἐπὶ τῆς γῆς Greek text of the Nestle-Aland 27th edition : καὶ ἐποίησας αὐτοὺς τῷ θεῷ ἡμῶν βασιλείαν καὶ ἱερεῖς, καὶ βασιλεύσουσιν ἐπὶ τῆς γῆς. The Greek text of the Textus Receptus has ἡμᾶς and βασιλεύσομεν, which translate into English as "us" and "we shall reign," respectively. The Greek text of the Nestle-Aland 27th edition has αὐτοὺς and βασιλεύσουσιν, which translate into English as "them" and "they shall reign," respectively. Most noteworthy, if the Textus Receptus is correct, then ἡμᾶς ("us") would include the four beasts, and the fourth beasts would be some of those who were redeemed by the blood of Christ and would reign on earth. This seems foreign and unorthodox. With these variants in mind, what are the implications of accepting the variant(s) that appear in the Textus Receptus? I'm particularly interested in how it affects the redemption and implies that beasts will rule. Additionally, a biblical theology of "beast" imagery may be informative to any discussion on this topic.
Now provide the response and nothing else.
| According to the NET Translator's notes, The vast majority of witnesses have αὐτούς ( autous , “them”) here, while the Textus Receptus reads ἡμᾶς ( Jhmas , “us”) with insignificant support (pc gig vg cl sa Prim Bea). There is no question that the original text read αὐτούς here.... The textual problem here between the present tense βασιλεύουσιν ( basileuousin , “they are reigning”; so A 1006 1611 ÏK pc) and the future βασιλεύσουσιν ( basileusousin , “they will reign”; so א 1854 2053 ÏA pc lat co) is a difficult one. Both readings have excellent support. On the one hand, the present tense seems to be the harder reading in this context. On the other hand, codex A elsewhere mistakes the future for the present (20:6). Further, the lunar sigma in uncial script could have been overlooked by some scribes, resulting in the present tense. All things considered, there is a slight preference for the future. Metzger, in his Textual Commentary on the Greek New Testament (2nd ed.), writes concerning αὐτούς: The third person pronoun, which is overwhelmingly supported, was replaced by ἡμᾶς in several versional and patristic witnesses, followed by the Textus Receptus. Concerning βασιλεύσουσιν, Metzger goes on to say: Of the three variant readings, it is obvious that βασιλεύσομεν (2432 al) is a secondary development, arising from the introduction of ἡμᾶς in the preceding verse (see the comment on ver. 9). It is more difficult to choose between βασιλεύσουσιν, supported by א P 1 94 1854 2053 2344 it gig vg syr ph cop sa , bo arm al , and βασιλεύουσιν, supported by A 046 1006 1611 it 61 syr h al . A majority of the Committee, noting that in 20:6 codex Alexandrinus mistakenly reads βασιλεύουσιν for the future tense, preferred βασιλεύσουσιν here, as more suited to the meaning of the context. In summary, the NA 27 reading is most likely with a third-person plural pronoun and third-person plural verb (αὐτούς), but a third option exists for the verb that is not used by the NA 27 nor the Textus Receptus: βασιλεύουσιν. So the third-person reading is definitely most likely, but it is a tough call whether to go with the third-person plural present or future verb (βασιλεύουσιν or βασιλεύσουσιν, respectively). The NA 27 has chosen the latter on the basis that codex Alexandrinus elsewhere mistakes the future for the present, but sufficient evidence exists for both readings. But given that your question asks for which of the two readings is most likely (Textus Receptus or NA 27 ), it is clear that the NA 27 is most likely. Based solely on context, I think it's impossible to determine whether the present or future verb is best (six one way, half a dozen the other), but I still think the third-person plural reading makes the most sense (i.e. αὐτούς). In Revelation 1:5-6, the author states: καὶ ἀπὸ Ἰησοῦ Χριστοῦ, ὁ μάρτυς, ὁ πιστός, ὁ πρωτότοκος τῶν νεκρῶν καὶ ὁ ἄρχων τῶν βασιλέων τῆς γῆς. Τῷ ἀγαπῶντι ἡμᾶς καὶ λύσαντι ἡμᾶς ἐκ τῶν ἁμαρτιῶν ἡμῶν ἐν τῷ αἵματι αὐτοῦ , καὶ ἐποίησεν ἡμᾶς βασιλείαν, ἱερεῖς τῷ θεῷ καὶ πατρὶ αὐτοῦ, αὐτῷ ἡ δόξα καὶ τὸ κράτος εἰς τοὺς αἰῶνας [τῶν αἰώνων]· ἀμήν. ἡμᾶς in 1:6 (shown above) refers to John and the seven churches in Asia in 1:4 (Ἰωάννης ταῖς ἑπτὰ ἐκκλησίαις ταῖς ἐν τῇ Ἀσίᾳ), who were freed from their sins by Jesus' blood in 1:5 (λύσαντι ἡμᾶς ἐκ τῶν ἁμαρτιῶν ἡμῶν ἐν τῷ αἵματι αὐτοῦ). It states that Jesus made them a kingdom and priests to his God and Father (1:6). This description of ἡμᾶς in 1:6 seems to best correspond to the persons from every tribe and language and people and nation who were ransomed by Jesus' blood (καὶ ἠγόρασας τῷ θεῷ ἐν τῷ αἵματί σου ἐκ πάσης φυλῆς καὶ γλώσσης καὶ λαοῦ καὶ ἔθνους), a group to whom John and the seven churches in Asia belonged, since in both places they are called a kingdom and priests (1:6 and 5:10). Nowhere do we see the the four living creatures/beasts and the elders referred to as a kingdom nor as priests. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/4200', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/-1/']} | jdg_69953 |
stackexchange | llm_judgeable_groundtruth_similarity | 7185288 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to get the first paragraph of a Wikipedia article. What is the API query to do so?
Now provide the response and nothing else.
| See this section in the MediaWiki API documentation , specifically involving getting the contents of the page . use the sandbox to test the API call. These are the key parameters. prop=revisions&rvprop=content&rvsection=0 rvsection = 0 specifies to only return the lead section. See this example. http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=0&titles=pizza To get the HTML, you can use similarly use action=parse http://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&page=pizza Note that you'll have to strip out any templates or infoboxes. edit: If you want to extract the plain text (without wikilinks, etc), you can use the TextExtracts API . Use the available parameters there to adjust your output. https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=1&titles=pizza&explaintext=1&exsectionformat=plain | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7185288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333729/']} | jdg_69954 |
stackexchange | llm_judgeable_groundtruth_similarity | 8880461 |
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 run the following bash command in Python 3: ls -l I know that I can do the following: from subprocess import callcall(['ls', '-l']) How do I save this output to a file, or put it into lists or sets? [-rw-r--r--] [1] [name] [staff] [426] [14 Jan 21:52] [HelloWorld.class][-rw-r--r--@] [1] [name] [staff] [107] [14 Jan 21:51] [HelloWorld.java]...etc. I want to be able to access particular information directly, and then add it to the set, but I do not know how many items will be listed. Any hints, snippets, or examples would really help.
Now provide the response and nothing else.
| With >= python3.5 you can use subprocess.run : ls_lines = subprocess.run(['ls', '-l'], stdout=PIPE).stdout.splitlines() With >= python2.7 or >= python3.0 you can use subprocess.check_output : ls_lines = subprocess.check_output(['ls', '-l']).splitlines() Prior to python2.7, you need to use the lower level api, which is a bit more involved. ls_proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)ls_proc.wait()# check return codels_lines = ls_proc.stdout.readlines() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8880461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969617/']} | jdg_69955 |
stackexchange | llm_judgeable_groundtruth_similarity | 89600 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For a given real number $x$, let $R_x$ be the set of real numbers $r$ such that the inequality $$\displaystyle \left| x - \frac{p}{q} \right| < \frac{1}{q^r}$$has at most finitely many solutions with integers $p,q$. Define the irrationality measure of $x$, say $\mu(x)$, to be the infimum of $R_x$. It is known that if $x$ is algebraic and not rational, then $\mu(x)$ is 2, by Roth's Theorem. It is trivial that if $x$ is rational, then $\mu(x) = 1$. I believe it is also known that all real numbers except a set of measure 0 has irrationality measure of 2, but I am unsure of the reference. For some known transcendental numbers, upper bounds for $\mu$ are known. For example, we know that $\mu(\pi) < 7.6063$ (Salikhov, V. Kh. "On the Irrationality Measure of ." Usp. Mat. Nauk 63, 163-164, 2008. English transl. in Russ. Math. Surv 63, 570-572, 2008.) Are there any general results concerning a set of transcendental numbers $x$ with $\mu(x) = 2$? Are there any known, 'interesting' numbers (expressible in well-known functions or constants) $x$ with $\mu(x) = 2$?
Now provide the response and nothing else.
| If the elements $a_n$ of the simple continued fraction of the irrational number $x$ satisfy $a_n < c n + d$ for some positive constants $c$ and $d$, then $\mu(x) = 2$. Besides $e^{2/k}$ for positive integers $k$, interesting examples of such numbers include $\tanh(1/k)$, $\tan(1/k)$, and $I_0(1)/I_1(1)$ where $I_0$ and $I_1$ are modified Bessel functions. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/89600', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10898/']} | jdg_69956 |
stackexchange | llm_judgeable_groundtruth_similarity | 37346 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I create a class like so: // B.h#ifndef _B_H_#define _B_H_class B{private: int x; int y;};#endif // _B_H_ and use it like this: // main.cpp#include <iostream>#include <vector>class B; // Forward declaration.class A{public: A() { std::cout << v.size() << std::endl; }private: std::vector<B> v;};int main(){ A a;} The compiler fails when compiling main.cpp . Now the solution I know is to #include "B.h" , but I'm curious as to why it fails. Neither g++ or cl 's error messages were very enlightening in this matter.
Now provide the response and nothing else.
| The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*> , then the compiler wouldn't need to know how big B is because it knows how big a pointer is. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61/']} | jdg_69957 |
stackexchange | llm_judgeable_groundtruth_similarity | 31123190 |
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 simple angular service that returns a $resource . Lets say it looks like this: $resource '/users/:id/:options.json', {id: '@id', options: '@options'}, create_user: { method: 'POST' } Now in my controller I use this resource by creating a new instance of my user service: user = new UserService() user.name = $scope.user.name user.email = $scope.user.email user.password = $scope.user.password user.password_confirmation = $scope.user.password_confirmation user.$create_user() But when the last line is executed, the data is sent but it is not in a object. Now I have Devise managing my user account and looking into their registration controller, it seems they expect me to send the data in an object called: sign_up . How can I describe in the $resource , that I want my data to be encapsulated in my custom object? EDIT: This is what server gets. It is not happy with it and says that every value is missing. Parameters: {"name"=>"foo", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "registration"=>{"name"=>"foo", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}} EDIT2: Working server log with .erb registration: Parameters: {"utf8"=>"✓", "authenticity_token"=>"xMEDtMWf72yuTwbkaq21c0ZKynoBSWnSypXfm+xJYvNph1d4iKqLIBwwe0DSA3I/YCU+pAHDd23ylc4y7ximEQ==", "user"=>{"name"=>"lol", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Now provide the response and nothing else.
| The Java compiler doesn't see what you and I see -- that either status gets set to "OK" or it gets set to "BAD" . It assumes that status can be set and an exception is thrown, in which case it gets assigned twice, and the compiler generates an error. To workaround this, assign a temporary variable for the try - catch block, and assign the final variable once afterwards. final String status;String temp;try { method1(); method2(); method3(); temp = "OK";} catch (Exception e) { temp = "BAD";}status = temp; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31123190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3209693/']} | jdg_69958 |
stackexchange | llm_judgeable_groundtruth_similarity | 1330759 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to derive the LU decomposition time complexity for an $n \times n$ matrix. Eliminating the first column will require $n$ additions and $n$ multiplications for $n-1$ rows. Therefore, the number of operations for the first column is $2n(n-1)$. For the second column, we have $n-1$ additions and $n-1$ multiplications, and we do this for $(n-2)$ rows giving us $2(n-1)(n-2)$. Therefore, the total number of operations required for the full decomposition can be written as $$\sum_i^n 2(n-i) (n-i+1)$$ How do we get from this sum to a total cost of $\frac{2}{3}n^3$?
Now provide the response and nothing else.
| An easy transformation ($j = n-i+1$) easily shows that\begin{align}\sum_{i=1}^n 2(n-i) (n-i+1) &= 2 \sum_{j=0}^{n-1}j(j+1)\\ &= 2 \sum_{j=0}^{n-1}(j^2+j)\\ &= 2 \left(\frac{1}{3} n^{3} - \frac{1}{3} n\right)\end{align} Then, since we are interested only in the asymptotic behaviour, we drop the $\frac{2}{3}n$ part, and what's left is $\frac{2}{3} n^{3}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1330759', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/212039/']} | jdg_69959 |
stackexchange | llm_judgeable_groundtruth_similarity | 7070082 |
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 curious about the get(long, java.util.concurrent.TimeUnit) function in AsyncTask, but I'm having a hard time locating an example of it's usage. get(long, java.util.concurrent.TimeUnit) Can anyone provide an example of it's use?
Now provide the response and nothing else.
| It appears as though AsyncTask.get() blocks the caller thread, where AsyncTask.execute() does not. You might want to use AsyncTask.get() for test cases where you want to test a particular Web Service call, but you do not need it to be asynchronous and you would like to control how long it takes to complete. Or any time you would like to test against your web service in a test suite. Syntax is the same as execute: private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); }}new DownloadFilesTask().get(5000, TimeUnit.MILLISECONDS); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7070082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194753/']} | jdg_69960 |
stackexchange | llm_judgeable_groundtruth_similarity | 56773329 |
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 achieve a following layout using Swift UI… struct ContentView : View { var body: some View { List(1...5) { index in HStack { HStack { Text("Item number \(index)") Spacer() }.padding([.leading, .top, .bottom]) .background(Color.blue) Text("i") .font(.title) .italic() .padding() .aspectRatio(1, contentMode: .fill) .background(Color.pink) }.background(Color.yellow) } }} I'd like the Text("i") to be square, but setting the .aspectRatio(1, contentMode: .fill) doesn't seem to do anything… I could set the frame width and height of the text so it's square, but it seems that setting the aspect ratio should achieve what I want in a more dynamic way. What am I missing?
Now provide the response and nothing else.
| I think this is what you're looking for: List(1..<6) { index in HStack { HStack { Text("Item number \(index)") Spacer() } .padding([.leading, .top, .bottom]) .background(Color.blue) Text("i") .font(.title) .italic() .frame(maxWidth: .infinity, maxHeight: .infinity) .aspectRatio(1, contentMode: .fill) .background(Color.pink) .fixedSize(horizontal: true, vertical: false) .padding(.leading, 6) } .padding(6) .background(Color.yellow) } The answer being said, i don't recommend giving SwiftUI too much freedom to decide the sizings. one of the biggest SwiftUI problems right now is the way it decides how to fit the views into each other. if something goes not-so-good on SwiftUI's side, it can result in too many calls to the UIKit's sizeToFit method which can slowdown the app, or even crash it. but, if you tried this solution in a few different situations and it worked, you can assume that in your case, giving SwiftUI the choice of deciding the sizings is not problematic. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56773329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123632/']} | jdg_69961 |
stackexchange | llm_judgeable_groundtruth_similarity | 25956178 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have some count data that looks like this: library(tidyr)library(dplyr)X.raw <- data.frame( x = as.factor(c("A", "A", "A", "B", "B", "B")), y = as.factor(c("i", "ii", "ii", "i", "i", "i")), z = 1:6)X.raw# x y z# 1 A i 1# 2 A ii 2# 3 A ii 3# 4 B i 4# 5 B i 5# 6 B i 6 I'd like to tidy and summarise like this: X.tidy <- X.raw %>% group_by(x, y) %>% summarise(count = sum(z))X.tidy# Source: local data frame [3 x 3]# Groups: x## x y count# 1 A i 1# 2 A ii 5# 3 B i 15 I know that for x=="B" and y=="ii" we have observed count of zero, rather than a missing value. i.e. the field worker was actually there, but because there wasn't a positive count no row was entered into the raw data. I can add the zero count explicitly by doing this: X.fill <- X.tidy %>% spread(y, count, fill = 0) %>% gather(y, count, -x)X.fill# Source: local data frame [4 x 3]# # x y count# 1 A i 1# 2 B i 15# 3 A ii 5# 4 B ii 0 But that seems a little bit of a roundabout way of doing things. Is there a cleaner idiom for this? Just to clarify: My code already does what I need it to do, using spread then gather , so what I'm interested in is finding a more direct route within tidyr and dplyr .
Now provide the response and nothing else.
| Since dplyr 0.8 you can do it by setting the parameter .drop = FALSE in group_by : X.tidy <- X.raw %>% group_by(x, y, .drop = FALSE) %>% summarise(count=sum(z))X.tidy# # A tibble: 4 x 3# # Groups: x [2]# x y count# <fct> <fct> <int># 1 A i 1# 2 A ii 5# 3 B i 15# 4 B ii 0 This will keep groups made of all the levels of factor columns so if you have character columns you might want to convert them (thanks to Pake for the note). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25956178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/943612/']} | jdg_69962 |
stackexchange | llm_judgeable_groundtruth_similarity | 10200751 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to get ActionBarSherlock and the ViewPagerIndicator libraries set up for my projects, but I seem to be running into a few issues. I sent Jake Wharton (The developer) a few messages earlier about it, and got a few replies but couldn't get anywhere - and I think he got busy with a few other things. What my issue is, For both VPI and ABS Both libraries open up without any errors, and I'm using compiler version 1.6 for all as is required. The funny thing is, if I load in the samples that are provided - they work fine and link to his library; but when I go to add the library to my project - the above happens.
Now provide the response and nothing else.
| Where to store the actual library project does not matter, as long as you use a relative link to reference it. Check out the Library Projects - Development considerations : Library project storage location There are no specific requirements on where you should store a library project, relative to a dependent application project, as long as the application project can reference the library project by a relative link. What is important is that the main project can reference the library project through a relative link. You should always use the Eclipse ADT plugin to select and set up Library Project Reference, i.e. right-click project -> Properties -> Android -> Add, then in the opened Project Selection window, select the Library Project list here (of cause you should import them in the same Eclipse workspace as your Main Project). This will add a android.library.reference using relative path into project.properties as well as show relative path in the Android preference window: android.library.reference.2=../../../../../Documents and Settings/yorkw/Desktop/JakeWharton-Android-ViewPagerIndicator-f09acb0/library If you directly alter it using absolute path from project.properties as below: android.library.reference.1=C:\\Documents and Settings\\yorkw\\Desktop\\JakeWharton-Android-ViewPagerIndicator-f09acb0\\library Then after Eclipse refresh your project, you get the exact error described in your question, see my screenshot below: Hope this helps. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10200751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125714/']} | jdg_69963 |
stackexchange | llm_judgeable_groundtruth_similarity | 7747587 |
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 sonar to measure code quality. One thing that I do not know is the steps to measure code coverage using Cobertura. I followed the steps from http://cobertura.sourceforge.net/anttaskreference.html and was able to generate xml files. How do I get these xml files into SONAR? Is there an easier way to use Cobertura in SONAR? I am running the code coverage (Cobertura) in a different server than my SONAR server. Both servers are running under LINUX. Thanks for the help!
Now provide the response and nothing else.
| You configure the Sonar task to upload unit test and cobertura reports generated by other parts of your build logic. This is in contrast to Maven which has a standard build life-cycle that Sonar is able to leverage. Unit test and code coverage The following logic runs the unit tests with cobertura instrumented classes. An XML coverage report is generated by cobertura at the end: <target name="instrument-classes" depends="compile-tests"> <taskdef resource="tasks.properties" classpathref="test.path"/> <cobertura-instrument todir="${instrumented.classes.dir}" datafile="${build.dir}/cobertura.ser"> <fileset dir="${classes.dir}"/> </cobertura-instrument></target><target name="junit" depends="instrument-classes"> <junit printsummary="yes" haltonfailure="yes"> <classpath> <path refid="test.path"/> <pathelement path="${instrumented.classes.dir}"/> <pathelement path="${test.classes.dir}"/> </classpath> <formatter type="xml"/> <batchtest fork="yes" todir="${test.reports.dir}"> <fileset dir="${test.src.dir}"> <include name="**/*Test*.java"/> <exclude name="**/AllTests.java"/> </fileset> </batchtest> </junit></target><target name="test" depends="junit"> <cobertura-report format="xml" datafile="${build.dir}/cobertura.ser" destdir="${cobertura.reports.dir}"/> </target> Invoking Sonar I normally use a very simple Sonar target: <target name="sonar" depends="test"> <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml" classpathref="sonar.path"/> <sonar:sonar key="${sonar.project.key}" version="${sonar.project.version}" xmlns:sonar="antlib:org.sonar.ant"/></target> And use a properties file to control all aspects of Sonar's behaviour: sonar.project.key=org.demo:demosonar.project.version=1.0-SNAPSHOTsonar.projectName=Demo projectsonar.host.url=http://myserver:9000sonar.jdbc.url=jdbc:mysql://myserver:3306/sonar?useUnicode=true&characterEncoding=utf8sonar.jdbc.driverClassName=com.mysql.jdbc.Driversonar.jdbc.username=sonarsonar.jdbc.password=sonarsonar.sources=${src.dir}sonar.tests=${test.src.dir}sonar.binaries=${classes.dir}sonar.dynamicAnalysis=reuseReportssonar.surefire.reportsPath=${test.reports.dir}sonar.java.coveragePlugin=coberturasonar.cobertura.reportsPath=${cobertura.reports.dir}/coverage.xml Demonstrates how Sonar can be configured to pick up the unit test reports created by junit and the code coverage report generated by cobertura. The build does not have to run on the same server as Sonar. In that case one must provide the remote Sonar URL and JDBC credentials. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7747587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423594/']} | jdg_69964 |
stackexchange | llm_judgeable_groundtruth_similarity | 733983 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The requirement for sigma-algebra is that. It contains the empty set. If A is in the sigma-algebra, then the complement of A is there. 3. It is closed under countable unions. My question relates to 3. When we define the measure-function, it has to be disjoint countable unions, but not when we define a sigma-algebra. I have tried to prove that if we require instead that the sigma algebra is closed under countable unions of disjoint sets, then it is closed under sets that are not disjoint. But this must be false, I think. Is there a way to prove this? That is I want to show that if I define a sigma algebra to be: It contains the empty set. If A is in the sigma-algebra, then the complement of A is there. It is closed under countable unions of disjoint sets. Then it is not nececarrily closed under countable unions if the sets are not disjoint. I guess this can be shown by creating a a set that satisfies the new definition, but is not closed under countable unions where what we take union over is not disjoint. But is it difficult to create a counterexample like this? If they don't exist then the definitions are equal, but I don't think they are?
Now provide the response and nothing else.
| Note that if $A_n$ is any family of sets, then$$ \bigcup_{n\in\mathbb N}A_n = \bigcup_{n\in\mathbb N}\bigl(A_n\setminus\bigcup_{k=0}^{n-1} A_k\bigr)$$where the summands on the right-hand side are disjoint, and each of them is constructed from finitely many of the $A_i$s by a sequence of complements and finite unions. So if you choose you can restrict yourself to requiring countable unions of disjoint set, if you also require that the algebra is closed under finite unions of arbitrary sets. A Dynkin system that is not a $\sigma$-algebra: If you don't require arbitrary finite unions, what you get is not necessarily a $\sigma$-algebra. Consider for example the system of subsets of $\mathbb R$ consisting of $\varnothing$, $\{0,x\}$ for every $x\ne 0$, and the complements of these sets. It is closed under your proposed axioms, because the only nontrivial disjoint union there is to take is $\{0,x\} \cup \{0,x\}^\complement = \mathbb R$. A small finite example is$$ \bigl\{\varnothing, \{0,2\}, \{0,3\}, \{1,2\}, \{1, 3\}, \{0,1,2,3\} \bigr\} $$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/733983', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/119615/']} | jdg_69965 |
stackexchange | llm_judgeable_groundtruth_similarity | 9421938 |
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 the following piece of code and I believed it would crash if I tried to access the members of a struct for which I didn't even allocate memory. But I was quite suprised that C++ automatically allocated memory for the struct. Is that normal behavior? For comparison, if you declare a pointer to an object and then try to access any members without actually creating the object with the operator "new", the program would crash. I'm just curious about why it works when I believe it shouldn't. This is my program: #include <stdio.h>struct Produto{ int codigo; float preco;};int main(){ struct Produto* sabonete; sabonete->codigo = 654321; sabonete->preco = 0.85; printf( "Codigo = %i\n", sabonete->codigo ); printf( "Preco = R$ %.2f\n", sabonete->preco ); return 0;} OS: Windows 7 Compiler: MinGW GCC 4.6.1
Now provide the response and nothing else.
| C++ did not automatically allocate memory; the pointer holds an arbitrary value which just happened to be a valid address in your program's memory space so you didn't get a segfault. Your program exhibits undefined behavior and it might not work the next time you run it. Undefined behavior does not guarantee a crash, that's why it's called undefined. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9421938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1124684/']} | jdg_69966 |
stackexchange | llm_judgeable_groundtruth_similarity | 1049210 |
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 change the primary key of a table to an identity column, and there's already a number of rows in table. I've got a script to clean up the IDs to ensure they're sequential starting at 1, works fine on my test database. What's the SQL command to alter the column to have an identity property?
Now provide the response and nothing else.
| You can't alter the existing columns for identity. You have 2 options, Create a new table with identity & drop the existing table Create a new column with identity & drop the existing column Approach 1. ( New table ) Here you can retain the existing data values on the newly created identity column. Note that you will lose all data if 'if not exists' is not satisfied, so make sure you put the condition on the drop as well! CREATE TABLE dbo.Tmp_Names ( Id int NOT NULL IDENTITY(1, 1), Name varchar(50) NULL )ON [PRIMARY]goSET IDENTITY_INSERT dbo.Tmp_Names ONgoIF EXISTS ( SELECT * FROM dbo.Names ) INSERT INTO dbo.Tmp_Names ( Id, Name ) SELECT Id, Name FROM dbo.Names TABLOCKXgoSET IDENTITY_INSERT dbo.Tmp_Names OFFgoDROP TABLE dbo.NamesgoExec sp_rename 'Tmp_Names', 'Names' Approach 2 ( New column ) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number. Alter Table NamesAdd Id_new Int Identity(1, 1)GoAlter Table Names Drop Column IDGoExec sp_rename 'Names.Id_new', 'ID', 'Column' See the following Microsoft SQL Server Forum post for more details: How to alter column to identity(1,1) | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1049210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15691/']} | jdg_69967 |
stackexchange | llm_judgeable_groundtruth_similarity | 6028128 |
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 rotate text in css to get following output: hi, Edit: Thanks for quick suggestion. I have added my sample code in jsfidle: http://jsfiddle.net/koolkabin/yawYM/ HTML: <div class="mainWrapper"> <div class="rotateObj"> <div class="title active">First Text Title</div> <div class="content"> Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... </div> <div class="title">First Text Title</div> <div class="content hide"> Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... </div> <div class="title">First Text Title</div> <div class="content hide"> Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... </div> <div class="title">First Text Title</div> <div class="content hide"> Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... </div> <div class="title">First Text Title</div> <div class="content hide"> Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... Here goes my bla bla bla text and more stuffs... </div> </div></div> CSS: .mainWrapper{margin:0 auto; width:960px; background:#EFEFEF;} .rotateObj{position:relative; height:400px;} .rotateObj .title{ float:left; background:gray; width:50px; height:100%; /** Rounded Border */ border-radius:5px;-moz-border-radius:5px; /** Rotation */ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); transform:rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); } .rotateObj .active{background:green;} .rotateObj .content{float:left;width:600px;height:100%;padding:20px;} .hide{display:none;} The problem I am facing is that when we rotate the text then it breaks the alignment and positions. So what is causing that, and how can I manage them?
Now provide the response and nothing else.
| You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use. One example for webkit browsers is -webkit-transform: rotate(-90deg); Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div , but simply the text inside it. If you remove your rotation, the <div> s are in the correct position and all you need to do is wrap the text in an element and rotate that instead. There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-) Edit 2: I had anticipated the text center problem and have already updated my demo . There is a height/width constraint though, so longer text could still break the layout. Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality. Hope this helps! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6028128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178301/']} | jdg_69968 |
stackexchange | llm_judgeable_groundtruth_similarity | 43263 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the general reason for functions which can only be defined implicitly? Is this because they are multivalued (in which case they aren't strictly functions at all)? Is there a proof? Clarification of question. The second part has been answered with example of single value function which cannot be given explicitly. The third part was automatically answered because there can't be a proof that necessarily implicit functions are all multivalued by way of the example of one that wasn't. I don't think that the first part has yet been addressed. Stating that the answer can't be expressed in "elementary functions" seems tantamount to saying that it a necessarily implicit function, unless I'm missing something about the definition of "elementary functions". Such answers seem to imply that the equation could be solved in terms of "non-elementary" functions.If this is correct than I need to find out about them and how they could be used to calculate the dependent variable solely in terms of the independent one (my notion of an explicit function). This would seem to violate the notion of a function which could only be defined implicitly. I am also not concerned with whether or not the solution is closed or open form (by which I mean finite number of terms or infinite).
Now provide the response and nothing else.
| Not necessarily. Consider the graph $G$ in ${\mathbb R}^2$ of the points $(x,y)$ such that $$ y^5+16y-32x^3+32x=0. $$ This example comes from the nice book " The implicit function theorem " by Krantz and Parks. Note that this is the graph of a function: Fix $x$ , and let $F(y)=y^5+16y-32x^3+32x$ . Then $F'(y)=5y^4+16>0$ so $F$ is strictly increasing. Since $F(y)\to-\infty$ as $y\to-\infty$ and $F(y)\to\infty$ as $y\to\infty$ , the equation $F(y)=0$ has at least one solution (by the intermediate value theorem), but then it has precisely one. This means that the graph $G$ describes a function (in the strict, traditional sense, not a multivalued function). However, there is no formula (in the traditional sense) giving us $y$ explicitly as a function of $x$ . This specific example shows one of the reasons why this may happen. Here, we have $y$ as a solution of a quintic equation, but in general there is no algebraic formula that gives us these solutions; this is a deep result of Abel and Galois . There are similar results stating that certain equations do not have elementary solutions (for example, certain differential equations), so they may define a function but we may not have a "formula" for it. In fact, the concept of what a "function" is underwent a few revisions before reaching its current modern form, precisely as we realized the need for versions more general than "given by an explicit formula". A nice account of the evolution of the term is in the paper by Penelope Maddy, "Does $V$ equal $L$ ?", J. Symbolic Logic 58 (1993), no. 1, 15–41. jstor , doi: 10.2307/2275321 | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/43263', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11752/']} | jdg_69969 |
stackexchange | llm_judgeable_groundtruth_similarity | 57798033 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ValueError Traceback (most recent call last)<ipython-input-30-33821ccddf5f> in <module> 23 output = model(data) 24 # calculate the batch loss---> 25 loss = criterion(output, target) 26 # backward pass: compute gradient of the loss with respect to model parameters 27 loss.backward()C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs) 487 result = self._slow_forward(*input, **kwargs) 488 else:--> 489 result = self.forward(*input, **kwargs) 490 for hook in self._forward_hooks.values(): 491 hook_result = hook(self, input, result)C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target) 593 self.weight, 594 pos_weight=self.pos_weight,--> 595 reduction=self.reduction) 596 597 C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight) 2073 2074 if not (target.size() == input.size()):-> 2075 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size())) 2076 2077 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1])) I am training a CNN. Working on the Horses vs humans dataset. This is my code . I am using criterion = nn.BCEWithLogitsLoss() and optimizer = optim.RMSprop(model.parameters(), lr=0.01 ). My final layer is self.fc2 = nn.Linear(512, 1) . Out last neuron, will output 1 for horse and 0 for human, right? or should I choose 2 neurons for output? 16 is the batch size. Since the error says ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1])) . I don't understand, where do I need to make change, to rectify the error.
Now provide the response and nothing else.
| target = target.unsqueeze(1) , before passing target to criterion, changed the target tensor size from [16] to [16,1] . Doing it solved the issue. Furthermore, I also needed to do target = target.float() before passing it to criterion, because our outputs are in float. Besides, there was another error in the code. I was using sigmoid activation function in the last layer, but I shouldn’t because the criterion I am using already comes with sigmoid builtin. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/57798033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10240085/']} | jdg_69970 |
stackexchange | llm_judgeable_groundtruth_similarity | 216404 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have data of the following form data={{6, 23.3}, {6.1, 19.8}, {6.2, 25.1}, {6.3, 25.5}, {6.4, 24.5}, {6.5, 28.1}, {6.6, 24.9}, {6.7, 26.3}, {6.8, 27.3}, {6.9, 27.7}, {7, 33.9}, {7.1, 26.6}, {7.2, 31.3}, {7.3, 26.8}, {7.4, 31.5}, {7.5, 30.2}, {7.6, 29.8}, {7.7, 25.5}, {7.8, 31.5}, {7.9, 28.9}, {8, 28.1},...,} This is a very long list of pairs, which are of the form $(t,B)$ , time and magnetic field magnitude. Then I used a code to find relevant points that I need to use. Namely the peaks of the magnetic field. With the help of FindPeak I found that the Peak Magnetic moments are peaks={{15, 31.5}, {99, 31.6}, {170, 45.7}, {224, 15.7}, {281, 15.6}, {319, 13.1}, {345, 10.5}, {349, 11.1}, {437, 8.4}} I also found the corresponding time using peaktime = data[[First /@ peaks, 1]] What I wish is to create a list of pairs, of the form $(t_p,B_p)$ such that $t_p$ and $B_p$ are the peak times and magnetic field magnitudes, respectively. For this I used a For loop, which is the following: v = {};For[i = 1, i <= Length[peaktime], i++, u = Position[data[[All, 1]], peaktime[[i]]][[1]]; v = Union[v, u]]peakscouuple = data[[v, All]]; This works, but it is too messy, Is there a cleaner way to do this?
Now provide the response and nothing else.
| data = {{6, 23.3}, {6.1, 19.8}, {6.2, 25.1}, {6.3, 25.5}, {6.4, 24.5}, {6.5, 28.1}, {6.6, 24.9}, {6.7, 26.3}, {6.8, 27.3}, {6.9, 27.7}, {7, 33.9}, {7.1, 26.6}, {7.2, 31.3}, {7.3, 26.8}, {7.4, 31.5}, {7.5, 30.2}, {7.6, 29.8}, {7.7, 25.5}, {7.8, 31.5}, {7.9, 28.9}, {8, 28.1}};Pick[data, PeakDetect[data[[All, 2]]], 1] {{6, 23.3}, {6.5, 28.1}, {7, 33.9}, {7.2, 31.3}, {7.4, 31.5}, {7.8, 31.5}} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/216404', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/68675/']} | jdg_69971 |
stackexchange | llm_judgeable_groundtruth_similarity | 48920135 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class App extends Component { constructor(props) { ... } onChange = (e) => this.setState({term: e.target.value}) onSubmit(e){ e.preventDefault(); const api_key = "C1hha1quJAQZf2JUlK"; const url = `http://api.giphy.com/v1/gifs/search?q=${this.state.term}&api_key=${api_key}`; } render() { return ( <div> <form onSubmit={this.onSubmit}> <input value={this.state.term} onChange={this.onChange}/> <button>Search!</button> </form> </div> ); }} What is the difference between the two type of functions declared in the class (onChange and onSubmit) . I get an error on referencing this.sate in const url if I declare it as an ES6 class method but changing it to arrow function fixes it. I want to know how exactly 'this' is handled in both the cases Also, how do I do it the other way? Say, if I want to use the same onSubmit function (ES6 class method) but want to handle this when I call it (in the form element), how do I do it ? Using this.onSubmit.bind(this) ?
Now provide the response and nothing else.
| It's important to know that this syntax: class A { method = () => {}} is just syntactic sugar for creating an instance method in the class constructor: class A { constructor() { this.method = () => {} }} Note: This syntax is not an official part of the JavaScript language yet ( currently in stage 3 ) so you must use a transpiler like Babel to handle it . The value of this within method is the class A because that is what this points to in the constructor (since arrow functions inherit the context from the scope they are defined in): class A { constructor() { this.method = () => this; }}const instance = new A();console.log(instance.method() === instance); // true Defining a regular (non-arrow function) method on the class creates a method on the class prototype (not instance) but sets no rules on what this will be (since this is dynamic in JS and depends on how a function is called, not how it's defined ). class A { method() {}}console.log(new A().method === A.prototype.method); // true If methods defined in either of these ways are called on the class instance (via the . ), as per the rule of how this is bound when a function is called as a method of an object, this will point to the class instance in both cases: class A { constructor() { this.methodOnInstance = () => this; } methodOnPrototype() { return this; }}const instance = new A();console.log( instance.methodOnInstance() === instance.methodOnPrototype(), // true instance.methodOnPrototype() === instance // true); One major difference between the two method declarations above is that the instance method has this always fixed to the class instance while the class (prototype) method does not (we can change it by using Function.prototype.apply or Function.prototype.call ) class A { constructor() { this.methodOnInstance = () => this; } methodOnPrototype() { return this; }}const instance = new A();console.log( instance.methodOnInstance() === instance.methodOnPrototype(), // true instance.methodOnPrototype.call('new this') === 'new this' // true); A common occurrence where the this changes is within an event handler, where the event handler calls the function passed into it and binds the context to the element on which the event happened (so overrides the value of this to be the element that was clicked or whatever the event was) This happens in React as well for all ( synthetic ) DOM event handlers. Therefore, if we want our method's context to always point to the instance of the React component, we can use the instance method. Another way of restricting the context but not using the special instance method syntax that requires Babel is to directly create an instance method ourselves by creating a new function from the class (prototype) method with a bound context (using Function.prototype.bind ): class A { constructor() { this.methodOnInstance = this.methodOnPrototype.bind(this); } methodOnPrototype() { return this; }}const instance = new A();console.log( instance.methodOnInstance() === instance.methodOnPrototype(), // true instance.methodOnPrototype() === instance // true); This allows us to arrive to the same result as using the special instance method syntax but with the currently available tools (ES2017 and under). If for some reason we want a method that is always bound to something that is not an instance of the class, we can do that as well: class A { constructor() { this.method = this.method.bind(console); } method() { return this; }}const instance = new A();console.log( instance.method() === console // true); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48920135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7439761/']} | jdg_69972 |
stackexchange | llm_judgeable_groundtruth_similarity | 43095 |
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'm applying the Trott-Strzebonski technique in order to replace inside a held expression . x = Hold[1 + 1, 2 + 2, 3 + 3];y = Hold[foo@bar[2]];y /. bar[j_] :> With[{eval = x[[j]]}, eval /; True](* Hold[foo[4]] *) However, I'd like the replacing expression to remain held during substitution: (* Hold[foo[2 + 2]] *) The unwanted evaluation of 2 + 2 seemed to be occurring during the Part statement, x[[j]] . So, I tried using Extract instead: y /. bar[j_] :> With[{eval = Extract[x, {j}, Unevaluated]}, eval /; True](* Hold[foo[Unevaluated[2 + 2]]] *) I thought Unevaluated would disappear as an argument of the Set function, but this was not so. (Perhaps I still don't quite understand Unevaluated .) I then thought of removing that head, Unevaluated , through another replacement, but that seems rather convoluted. Succinctly, how does one replace parts of a held expression with held parts of another expression?
Now provide the response and nothing else.
| One way to achieve this is to use a "vanishing" wrapper. The idea is to temporarily wrap the substituted expression with a holding symbolic head, and then remove that head in a second replacement: Module[{h}, SetAttributes[h, HoldAll]; y /. bar[j_] :> RuleCondition[Extract[x, {j}, h]] /. h[x_] :> x](* Hold[foo[2+2]] *) Module is used to ensure that the vanishing symbol does not conflict with any of the symbols in the target expression. This solution is essentially equivalent to the exhibited use of Unevaluated , but forcibly removes the wrapper explicitly instead of relying upon the evaluator to do it. This trick can be especially handy in more complex substitutions and can be scaled to use multiple wrappers, each with more elaborate semantics than simple vanishing. The single-wrapper idiom can be made more convenient with a helper macro: SetAttributes[vanishing, HoldAll]vanishing[{h_}, body_] := Module[{h} , SetAttributes[h, HoldAll] ; body /. h[x_] :> x ] It is used thus: vanishing[{h}, y /. bar[j_] :> RuleCondition[Extract[x, {j}, h]]](* Hold[foo[2+2]] *) | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/43095', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6944/']} | jdg_69973 |
stackexchange | llm_judgeable_groundtruth_similarity | 4774420 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering what use an rvalue reference member has class A { // ... // Is this one useful? Foo &&f;}; Does it have any benefits or drawbacks compared to an lvalue reference member? What is a prime usecase of it?
Now provide the response and nothing else.
| I've seen one very motivating use case for rvalue reference data members, and it is in the C++0x draft: template<class... Types>tuple<Types&&...>forward_as_tuple(Types&&... t) noexcept; Effects: Constructs a tuple of references to the arguments in t suitable for forwarding as arguments to a function. Because the result may contain references to temporary variables, a program shall ensure that the return value of this function does not outlive any of its arguments. (e.g., the program should typically not store the result in a named variable). Returns: tuple<Types&&...>(std::forward<Types>(t)...) The tuple has rvalue reference data members when rvalues are used as arguments to forward_as_tuple, and otherwise has lvalue reference data members. I've found forward_as_tuple subsequently helpful when needing to catch variadic arguments, perfectly forward them packed as a tuple, and re-expand them later at the point of forwarding to a functor. I used forward_as_tuple in this style when implementing an enhanced version of tuple_cat proposed in LWG 1385: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1385 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4774420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34509/']} | jdg_69974 |
stackexchange | llm_judgeable_groundtruth_similarity | 33609406 |
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 question is basically when to choose QVector and when to choose QList as your Qt container. What I already know: Qt docs: QList class For most purposes, QList is the right class to use. Its index-based API is more convenient than QLinkedList's iterator-based API, and it is usually faster than QVector because of the way it stores its items in memory. It also expands to less code in your executable. The same is written is this very popular Q&A: QVector vs QList . It also favors QList. But: on recent Qt World Summit 2015 KDAB presented "Why QList is harmful", this is basically here: QList considered harmful Don't use QList, use Q_DECLARE_TYPEINFO As far as I understand the idea is that QList for almost all types is inefficient when allocating new elements in heap. Each time you are adding new element, it calls new (once per element) and this is inefficient compared to QVector . This is why now I am trying to understand: is it QVector which we should choose as default container?
Now provide the response and nothing else.
| Qt advertises QList as the "jack of all trades", but the other half of that saying is "master of none". I'd say QList is a good candidate if you plan on appending to both ends of the list, and those are no larger than than a pointer, as QList reserves space before and after. That's about it, I mean as far as good reasons to use QList are concerned. QList will automatically store "large" objects as pointer and allocate the objects on the heap, which may be considered a good thing if you are a baby, which doesn't know how to declare a QVector<T*> and use dynamic allocation. This is not necessarily a good thing, and in some cases it will only bloat the memory usage and add extra indirection. IMO it is always a good idea to be explicit about what you want, whether it is pointers or instances. Even if you do want heap allocation, it is always better to allocate it yourself and simply add the pointer to the list than construct the object once, then have have copy construct that on the heap. Qt will return you a QList in a lot of places where it comes with overhead, for example when getting a QObject 's children or you search for children. In this case it doesn't make sense to use a container that allocates space before the first element, as it is a list of objects which are already there, not something you are likely to prepend to. I also don't much like the absence of a resize() method. Imagine a situation where you have an object with size of 9 bytes and byte alignment on a 64 bit system. It is "far too much" for QList so instead it will use 8 byte pointer + CPU overhead for the slow heap allocation + memory overhead for the heap allocation. It will use twice the memory and with an extra indirection for access it will hardly offer performance advantages as advertised. As of why QVector cannot suddenly become the "default" container - you don't change horses mid-race - it is a legacy thing, Qt being such an old framework, and even though a lot of stuff has been deprecated, making changes to widely used defaults is not always possible, not without breaking a lot of code, or producing undesired behavior. Good or bad, QList will likely continue being the default all the way throughout Qt 5, and likely in the next major release as well. The same reason Qt will continue using "dumb" pointers, for years after smart pointers have become a must and everybody is crying about how bad plain pointers are and how they should not be used ever. That being said, nobody is forcing you to use QList in your design. There is no reason why QVector should not be your default container. I myself don't use QList anywhere, and in the Qt functions which return a QList I merely use as a temporary to move stuff into a QVector . Furthermore, and this is only my personal opinion, but I do find a lot of design decisions in Qt that don't necessary make sense, be that performance or memory use efficiency or ease of use wise, and overall there are a a lot of frameworks and languages which like promoting their ways of doing things, not because it is the best way to do it, but because it is their way to do it. Last but not least: For most purposes, QList is the right class to use. It really boils down to how you understand this. IMO in this context, "the right" does not stand for "the best" or "the optimal", but for "good enough" as in "it will do, even if not the best". Especially if you know nothing about different container classes and how they work. For most purposes, QList will do. To sum things up: QList PROs you intend to prepend objects no larger than the size of a pointer, since it reserves some space in the front you intend to insert in the middle of the list objects (substantially) larger than a pointer (and I am being generous here, since you can easily use QVector with explicit pointers to achieve the same and cheaper - no extra copy), since when resizing the list, no objects will be moved, only pointers QList CONs doesn't have a resize() method, reserve() is a subtle trap, since it will not increase the valid list size, even if index access works it falls in the UB category, also you will not be able to iterate that list does an extra copy and heap allocating when object is larger than a pointer, which might also be an issue if object identity matters uses extra indirection to access objects larger than a pointer has CPU time and memory usage overheads due to the last two, also less cache friendly comes with additional overhead when used as a "search" return value, since you are not likely to prepend or even append to that only makes sense if index access is a must, for optimal prepend and insert performance a linked list might be a better option. The CON's marginally outweigh the PROs, meaning that while in "casual" use QList might be acceptable, you definitely don't want to use it in situations where CPU time and/or memory usage are a critical factor. All in all, QList is best suited for lazy and careless use, when you don't want to make the consideration of optimal storage container for the use case, which would typically be a QVector<T> , a QVector<T*> or a QLinkedList (and I exclude "STL" containers, since we are talking Qt here, Qt containers are just as portable, sometimes faster, and most certainly easier and cleaner to use, whereas std containers are needlessly verbose). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33609406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462639/']} | jdg_69975 |
stackexchange | llm_judgeable_groundtruth_similarity | 435643 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I find myself slightly frustrated when I'm reading a NASA page and they claim they have “nailed down the curvature of space to within 0.4% of "flat" Euclidean” 0.4% of what? Mathematically this statement is un-useful as you can extract no information out of it. This is equivalent to saying the neutrino mass is measured within 0.4% to be zero, an equally meaningless statement. What researchers DO report are upper and lower bounds on Neutrino (and other particle) masses such as the title of this paper : “On the improvement of cosmological neutrino mass bounds” which actually tells you something you can quickly jump to a table and absorb the information from it. In the same spirit the spatial curvature of our universe should be described by a statment like (for a made up example): “ Our analysis concludes that the spatial radius of curvature of our universe $R$ is bounded by: $$\frac{1}{\mid R\mid}\leq9\cdot10^{-46}m^{-1}\pm error$$ How can I get this data from their study? (If I remember right R here should correspond to spatial components of the Ricci tensor (at cosmological scales anyway)).
Now provide the response and nothing else.
| The statement is not meaningless. The curvature parameter, $\Omega_k$ , used in cosmology is a dimensionless parameter. So the statement that it is flat to within 0.4% means that the parameter has been measured to be between -0.004 and +0.004. It is a dimensionless number so the number has meaning on its own and does not need an “of what” qualifier. The writers of the press release just (reasonably) decided that a message to the public saying “within 0.4% of flat” would be more generally understandable than “ $\Omega_k = -0.0027 ^{+0.0039}_{-0.0038}$ ” See here for the actual paper: https://arxiv.org/abs/1212.5226 | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/435643', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/100917/']} | jdg_69976 |
stackexchange | llm_judgeable_groundtruth_similarity | 30095689 |
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 seen some answers before but nothing really helped me out. I also have a class DecideModel (This will be a dataset retrieved from DB, but for purpose of this question, I have added an ObservableCollection) which contains static DecideModel() { All = new ObservableCollection<DecideModel> { new DecideModel { DatePerformed = new DateTime(2015, 4, 06), Result = "Maybe" }, new DecideModel { DatePerformed = new DateTime(2015, 4, 05), Result = "No" }, new DecideModel { DatePerformed = new DateTime(2015, 4, 04), Result = "Yes" } }; } public DateTime DatePerformed { set; get; } public string Result { set; get; } public static IList<DecideModel> All { set; get; }} In my XAML code I have <ContentPage.Resources> <ResourceDictionary> <Color x:Key="Maybe">#ffddbc21</Color> <Color x:Key="Yes">#3CB371</Color> <Color x:Key="No">#B22222</Color> <Color x:Key="Depends">#ffd78800</Color> </ResourceDictionary></ContentPage.Resources><Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{StaticResource {BindingSource Result}}" /> I am trying to dynamically set the background color of the label with respect to what result I have obtained from the Object. Please let me know if you have any idea on how to do it. I am looking for any useful option available.
Now provide the response and nothing else.
| What you probably need is a ValueConverter . What you are doing now is setting the background color to 'Maybe', 'No' or 'Yes', which clearly isn't a color. What you need to do is convert that value to a color. You can do it like this. Create a new class that implements the IValueConverter interface. It will probably look something like this: public class YesNoMaybeToColorConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { switch(value.ToString().ToLower()) { case "yes": return Color.Green; case "no": return Color.Red; case "maybe": return Color.Orange; } return Color.Gray; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // You probably don't need this, this is used to convert the other way around // so from color to yes no or maybe throw new NotImplementedException(); }} Then add this class as a static resource to your XAML page like this: <ContentPage.Resources> <!-- Add this line below --> <local:YesNoToBooleanConverter x:Key="YesNoMaybeToColorConverter" /> <!-- You can remove the underneath --> <!--<ResourceDictionary> <Color x:Key="Maybe">#ffddbc21</Color> <Color x:Key="Yes">#3CB371</Color> <Color x:Key="No">#B22222</Color> <Color x:Key="Depends">#ffd78800</Color> </ResourceDictionary>--></ContentPage.Resources> Now in your binding you have to tell him what converter to use. Do it like this: <Label Text="{Binding Result}" HorizontalOptions="FillAndExpand" BackgroundColor="{Binding Result, Converter={StaticResource YesNoMaybeToColorConverter}}" /> It should now see the value in the Result field, put it through the converter you have defined and return the color that you corresponded to that value. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30095689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1570456/']} | jdg_69977 |
stackexchange | llm_judgeable_groundtruth_similarity | 6345769 |
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 rule of thumb as to when one should use path parameters for a URL versus when you should use query parameters? Say I've got a table Invoice with the fields company(PK),InvoiceNo(PK), Invoiceline, invoiceValue, noOfLines, salesPerson My current thinking is that your URL should be along the lines of /Invoice/ Which would display all invoices /Invoice/{company} Which would display all invoices for the company. /Invoice/{company}/{InvoiceNo} Displays that specific invoice and /Invoice/{company}/{InvoiceNo}?invoiceLineNo=23 displays only line 23. The way I'm thinking is that Primary key fields should be part of the path and any other fields that you would filter on are part of the query parameter. Does this sound like a reasonable way of distinguishing between the two?
Now provide the response and nothing else.
| My personal rule of thumb that the PathParam leads upto the entity type that you are requesting. /Invoices // all invoices/Invoices?after=2011 // a filter on all invoices/Invoices/52 // by 52/Invoices/52/Items // all items on invoice 52/Invoices/52/Items/1 // Item 1 from invoice 52/Companies/{company}/Invoices?sort=Date/Companies/{company}/Invoices/{invoiceNo} // assuming that the invoice only unq by company? To quote Mr Rowe : Path parameters for grouping data, query parameters for filtering | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6345769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709399/']} | jdg_69978 |
stackexchange | llm_judgeable_groundtruth_similarity | 65016590 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a textbox with an autocomplete feature that pulls suggestions from an API but having trouble updating the state after I receive the array from the API. I am modifying code from here: https://blog.bitsrc.io/building-a-react-autocomplete-component-from-scratch-b78105324f4c I think I have to use ComponentDidMount() but I am not sure how to apply it to an onChange Function. class App extends React.Component { render() { return ( <div className="App"> <Autocomplete/> </div> ); } } class Autocomplete extends React.Component{ state = { activeOption: 0, filteredOptions: [], showOptions: false, userInput: '' }; onChange = (e) => { const userInput = e.currentTarget.value; fetch("/places", { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(userInput) }). then(response => response.json()) .then(data => data.filter(element => element.PlaceName.toLowerCase().indexOf(userInput.toLowerCase()) > -1)) .then(filteredOptions => this.setState( { activeOption: 0, filteredOptions: filteredOptions, showOptions: true, userInput: e.currentTarget.value })); };.... render() { const { onChange, onClick, onKeyDown, state: { activeOption, filteredOptions, showOptions, userInput } } = this; let optionList; if (showOptions && userInput) { console.log(filteredOptions) if (filteredOptions.length) { optionList = ( <ul className="options"> {filteredOptions.map((optionName, index) => { let className; if (index === activeOption) { className = 'option-active'; } return ( <li className={className} key={optionName} onClick={onClick}> {optionName} </li> ); })} </ul> ); } else { optionList = ( <div className="no-options"> <em>No Option!</em> </div> ); } } return ( <React.Fragment> <div className="search"> <input type="text" className="search-box" onChange={onChange} onKeyDown={onKeyDown} value={userInput} /> <input type="submit" value="" className="search-btn" /> </div> {optionList} </React.Fragment> ); } } ReactDOM.render(<App />, document.querySelector("#app")); Once I try and run this, I get two errors: one for a synthetic event being reused for performance issues and one for a component changing an controlled input
Now provide the response and nothing else.
| I know I am a little late, but since you don't seem to have accepted any of the other answers I'd figure I'd give it a shot too, maybe this is the one that helps you. Shouldn't it be when useRef.current changes, the stuff in useEffect gets run? Short answer, no . The only things that cause a re-render in React are the following: A state change within the component (via the useState or useReducer hooks) A prop change A parent render (due to 1. 2. or 3.) if the component is not memoized or otherwise referentially the same (see this question and answer for more info on this rabbit hole) Let's see what happens in the code example you shared: export default function App() { const myRef = useRef(1); useEffect(() => { console.log("myRef current changed"); // this only gets triggered when the component mounts }, [myRef.current]); return ( <div className="App"> <button onClick={() => { myRef.current = myRef.current + 1; console.log("myRef.current", myRef.current); }} > change ref </button> </div> );} Initial render myRef gets set to {current: 1} The effect callback function gets registered React elements get rendered React flushes to the DOM (this is the part where you see the result on the screen) The effect callback function gets executed, "myRef current changed" gets printed in the console And that's it. None of the above 3 conditions is satisfied, so no more rerenders. But what happens when you click the button? You run an effect . This effect changes the current value of the ref object, but does not trigger a change that would cause a rerender (any of either 1. 2. or 3.). You can think of refs as part of an "effect". They do not abide by the lifecycle of React components and they do not affect it either. If the component was to rerender now (say, due to its parent rerendering), the following would happen: Normal render myRef gets set to {current: 1} - Set up of refs only happens on initial render, so the line const myRef = useRef(1); has no further effect. The previous effect's cleanup function gets executed (here there is none) The effect callback function gets registered React elements get rendered React flushes to the DOM if necessary The effect callback function gets executed, "myRef current changed" gets printed in the console. If you had a console.log(myRef.current) inside the effect callback, you would now see that the printed value would be 2 (or however many times you have pressed the button between the initial render and this render) All in all, the only way to trigger a re-render due to a ref change (with the ref being either a value or even a ref to a DOM element) is to use a ref callback (as suggested in this answer) and inside that callback store the ref value to a state provided by useState . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65016590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14710929/']} | jdg_69979 |
stackexchange | llm_judgeable_groundtruth_similarity | 2891803 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand some Functional Analysis concepts from Geometrical point of view. So I know that Metric ($d(a,b)$) is the distance between elements, Norm ($||a||$) is the length of element. So I'd like to know how Operator Norm ($||A||$, $A: X \to Y$) could be represented as Geometrical concept.
Now provide the response and nothing else.
| If $A:X\to Y$ is a linear bounded operator between the normed spaces $X,Y$, then the norm of $A$ is, loosely speaking, the factor by which the unit ball of $X$ gets inflated or deflated. More precisely, it is the smallest number $\alpha>0$ by which you need to dilate the unit ball of $Y$, so that $\alpha B_Y$ will contain the image of the unit ball of $X$ under the mapping $A$. For example, a diagonal matrix $D=\{d_i\}_{i=1}^n$ in $\mathbb{R}^n$ maps the Euclidean unit ball to an ellipsoid, whose principal axis have lengths $2|d_i|$. The maximum of $|d_i|$ is of course the norm of this diagonal operator as a map between $\ell_2^n$ and itself. It is also the smallest number by which you need to multiply the unit ball of $\ell_2^n$ in order that the inflated ball will contain the ellipsoid $D(B_2^n)$, where $B_2^n$ is the unit ball of $\ell_2^n$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2891803', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/586399/']} | jdg_69980 |
stackexchange | llm_judgeable_groundtruth_similarity | 959670 |
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 tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data. I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify. One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing). I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?
Now provide the response and nothing else.
| In pure javascript, this would not be an easy task, but jQuery makes it very easy to do: $("#myform :input").change(function() { $("#myform").data("changed",true);}); Then before saving, you can check if it was changed: if ($("#myform").data("changed")) { // submit the form} In the example above, the form has an id equal to "myform". If you need this in many forms, you can easily turn it into a plugin: $.fn.extend({ trackChanges: function() { $(":input",this).change(function() { $(this.form).data("changed", true); }); } , isChanged: function() { return this.data("changed"); }}); Then you can simply say: $("#myform").trackChanges(); and check if a form has changed: if ($("#myform").isChanged()) { // ...} | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/959670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33436/']} | jdg_69981 |
stackexchange | llm_judgeable_groundtruth_similarity | 41725737 |
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 using the Minimum Edit Distance algorithm to determine how closely two strings are related. I've implemented it to run on the CPU and it works great when you have hundreds of strings, but it is a source of slow down when you are comparing thousands of strings, multiple times. So I thought it might be useful to off load on to the GPU since it could perform multiple comparisons at once. Is this possible? The Metal resources I've come across are mainly for graphics which aren't helpful. Or maybe they are?
Now provide the response and nothing else.
| What you want to do is possible, at least for certain problem sizes, but it's not particularly straightforward. What you'll need to do is express the algorithm in a way that can be run on the GPU, and on iOS, that probably means using Metal. Specifically, you'll need to write one or more compute kernels in the Metal shading language that implement the minimum edit distance algorithm, then dispatch them using a Metal compute command encoder. There are several resources on compute programming with Metal around the Web. I'm not aware of an existing Metal implementation of MED, but there is at least one CUDA implementation , and you can read a longer explanation of MED on the GPU here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41725737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3259732/']} | jdg_69982 |
stackexchange | llm_judgeable_groundtruth_similarity | 7968451 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There're 3 ways to get current interface orientation that I know of: self.interfaceOrientation [[UIApplication sharedApplication] statusBarOrientation] [[UIDevice currentDevice] orientation] What are the differences among them?
Now provide the response and nothing else.
| self.interfaceOrientation returns UIInterfaceOrientation, current orientation of the interface. It is a property in UIViewController, you can access to this one only in UIViewController classes. [[UIApplication sharedApplication] statusBarOrientation] returns UIInterfaceOrientation, current orientation of the application's status bar. You can access to that property in any point of your application. My experience shows that it's more effective way to retrieve real interface orientation. [[UIDevice currentDevice] orientation] returns UIDeviceOrientation , device orientation. You can access to that property in any point of your application. But note that UIDeviceOrientation is not always UIInterfaceOrientation. For example, when your device is on a plain table you can receive unexpected value. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7968451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/607/']} | jdg_69983 |
stackexchange | llm_judgeable_groundtruth_similarity | 27968963 |
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 testing Visual Studio 2015 with C# 6.0 but the language features are not working. In an MVC web application, the following code does compile: if (!string.IsNullOrWhiteSpace(Model.Profile?.TypeName)){ // More logic here...} However, when I run the application via Debug and IIS Express, I get the following error: CS1525: Invalid expression term '.' How do I enable these features?
Now provide the response and nothing else.
| This works in MVC 5 (tested 5.2.3), you just need to add the roslyn code dom Nuget package CodeDOM Providers for .NET Compiler... Replacement CodeDOM providers that use the new .NET Compiler Platform ("Roslyn") compiler as a service APIs. This provides support for new language features in systems using CodeDOM (e.g. ASP.NET runtime compilation) as well as improving the compilation performance of these systems. PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform https://www.nuget.org/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/ | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/27968963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195620/']} | jdg_69984 |
stackexchange | llm_judgeable_groundtruth_similarity | 36829176 |
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 an option to delete the cache of all Apps or certain Apps in Android M ? Seems like most ways don't work anymore in Android M. As a reference I used this Code out of this discussion : Android: Clear Cache of All Apps? PackageManager pm = getPackageManager();// Get all methods on the PackageManagerMethod[] methods = pm.getClass().getDeclaredMethods();for (Method m : methods) { if (m.getName().equals("freeStorage")) { // Found the method I want to use try { long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space m.invoke(pm, desiredFreeStorage , null); } catch (Exception e) { // Method invocation failed. Could be a permission problem } break; }} Combined with this permission <uses-permission android:name="android.permission.CLEAR_APP_CACHE"/> This Code works fine on devices lower than Android 6.0. But on devices with Android 6.0 it results in this exception java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2 There is an open source cleaner on GitHub, which stopped development with this reason: Partial incompatibility with Android 6.0 and newer Starting with Android 6.0, CLEAR_APP_CACHE permission seems to be no longer available to regular applications and since this permission is required for cleaning of internal cache, Cache Cleaner is not able to clean internal cache on Android 6.0 and newer. However, cleaning of external cache is still supported. Is there really no way, to delete App Cache on devices with Android M ? How does the Google Setting App handle it ?It can't be the new method: public abstract void freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi) because I think it does not delete the Cache of certain apps, but of enough apps to clear the expected ram size... But the Settings app can clear the Cache of certain apps UPDATE Like the excepted answer explains, there seems to be no way to delete tha App Cache without root on Devices with Android M and above. But I will post it here if I find a way....
Now provide the response and nothing else.
| Is there an option to delete the cache of all apps or certain apps in Android M? A third-party app cannot delete the cache of another app in Android 6.0+. The protection level of Manifest.permission.CLEAR_APP_CACHE changed from "dangerous" to "signature|privileged" or "system|signature" in Android 6.0+. Now, only apps signed with the firmware's key can hold this permission. Is there really no way to delete app cache on devices with Android M? Unless the app is installed as a system app or you have root access, there is no way to delete app cache on Android 6.0+. How does the Settings app handle it? Android is, of course, open source. Lets look at the code. In AppStorageSettings.java lines 172 - 178 we find: if (v == mClearCacheButton) { // Lazy initialization of observer if (mClearCacheObserver == null) { mClearCacheObserver = new ClearCacheObserver(); } mPm.deleteApplicationCacheFiles(mPackageName, mClearCacheObserver);} So, the Settings app is using the hidden method PackageManager#deleteApplicationCacheFiles(String, IPackageDataObserver) . It can do this because it holds the system level permission "android.permission.CLEAR_APP_USER_DATA" ( a permission a third-party app cannot hold ). External Cache However, cleaning of external cache is still supported. This is still possible on Android 6.0+. I haven't looked at the source code for the app you mentioned but I would assume all you need to do is request the WRITE_EXTERNAL_STORAGE permission, get all installed packages using PackageManager , get the app's external cache directory , and delete the directory. Root Access Of course, if you have root access you can delete another app's cache. Here is a quick example of using root access to delete all app cache. You can use Chainfire's libsuperuser to run commands in a root shell: PackageManager pm = getPackageManager();List<ApplicationInfo> installedApplications = pm.getInstalledApplications(0);for (ApplicationInfo applicationInfo : installedApplications) { try { Context packageContext = createPackageContext(applicationInfo.packageName, 0); List<File> directories = new ArrayList<>(); directories.add(packageContext.getCacheDir()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Collections.addAll(directories, packageContext.getExternalCacheDirs()); } else { directories.add(packageContext.getExternalCacheDir()); } StringBuilder command = new StringBuilder("rm -rf"); for (File directory : directories) { command.append(" \"" + directory.getAbsolutePath() + "\""); } Shell.SU.run(command.toString()); } catch (PackageManager.NameNotFoundException wtf) { }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36829176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2992462/']} | jdg_69985 |
stackexchange | llm_judgeable_groundtruth_similarity | 16845624 |
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 a node.js newbie and I'm trying to understand how I can organize some logic in the non-blocking way node likes it. I have a set of environments ['stage','prod'], and another set of parameters called brands ['A','B','C'] and a set of devices ['phone','tablet']. In node's callback-driven world I have this: brands.forEach( function(brand) { devices.forEach( function(device) { var tapeS = getTape('stage',brand,device); // bad example...tapeS never set var tapeP = getTape('prod' ,brand,device); })} )// more stuff herefunction getTape(env,brand,device) { var req = http.request(someOptions,function(resp) { // ok, so we handle the response here, but how do I sequence this with all the other // responses, also happening asynchronously? });} I'm trying to build a report with blocks for each environment: A: Stage -- report Prod -- report B: ... My problem is that since everything here is so async, especially inside getTape, which calls node's http.request. How can I serialize everything at the end of all this async wonderment so I can create the report in the order I want? I heard something about javascript Promises. Would that help, i.e. some way to collect all these Promises then wait for them all to complete, then get the data they collected?
Now provide the response and nothing else.
| Q is the dominant promise implementation in node.js. I also have my own super light weight promises library Promise . My library doesn't implement all the features I've used in these examples, but it could be made to work with minor adaptation. The underpinning specification for how promises work and ineroperate is Promises/A+ . It defines the behavior for a .then method and is pretty readable, so definitely give it a look at some point (not necessarily straight away). The idea behind promises is that they encapsulate an asynchronous value. This makes it easier to reason about how to convert synchronous code into asynchronous code because there are usually nice parallels. As an introduction to these concepts I would recommend my talk on Promises and Generators or one of Domenic Denicola's talks (such as Promises, Promises or Callbacks, Promises, and Coroutines (oh my!) ). The first thing to decide is whether you want to make your requests in parallel, or one at a time sequenctially. From the question I'm going to guess that you want to do them in parallel. I'm also going to assume you're using Q which means you'll have to install it with: npm install q and require it at the top of each file in which you use it: var Q = require('q'); Thinking about the ideal data structure to be using to print out that report, I think you'd have an array of brands, with an array of devices which would be objects with properties stage and prod , something like: [ { brand: 'A', devices: [ { device: 'phone', stage: TAPE, prod: TAPE }, { device: 'tablet', stage: TAPE, prod: TAPE } ... ] }, { brand: 'B', devices: [ { device: 'phone', stage: TAPE, prod: TAPE }, { device: 'tablet', stage: TAPE, prod: TAPE } ... ] } ...] I'm going to assume that if you had that then you would have no trouble printing out the desired report. Promised HTTP Request Lets start by looking at the getTape function. Are you expecting it to return a node.js stream or a buffer/string containing the entire downloaded file? Either way, you're going to find it a lot easier with the help of a library. If you're new to node.js I'd recommend request as a library that just does what you'd expect. If you're feeling more confident, substack's hyperquest is a much smaller library and arguably neater, but it requires you to handle things like redirects manually, which you probably don't want to get in to. Streaming (difficult) The streaming approach is tricky. It can be done and will be needed if your tapes are 100s of MB long, but promises are then probably not the right way to go. I'm happy to look into this in more detail if it's an issue you actually have. Buffering with request (easy) To create a function that does a buffering HTTP request using request and returns a promise, it's fairly simple. var Q = require('q')var request = Q.denodeify(require('request')) Q.denodeify is just a shortcut for saying: "take this function that normally expects a callback and give me a function that takes a promise". To write getTape based off of that we do something like: function getTape(env, brand, device) { var response = request({ uri: 'http://example.com/' + env + '/' + brand + '/' + device, method: 'GET' }) return response.then(function (res) { if (res.statusCode >= 300) { throw new Error('Server responded with status code ' + res.statusCode) } else { return res.body.toString() //assuming tapes are strings and not binary data } })} What's happening there is that request (via Q.denodeify ) is returning a promise. We're calling .then(onFulfilled, onRejected) on that promise. This returns a new transformed promise. If the response promise was rejected (equivalent to throw in synchronous code) then so is the transformed promise (because we didn't attach an onRejected handler). If you throw in one of the handlers, the transformed promise is rejected. If you return a value from one of the handlers then the transformed promise is "fulfilled" (also sometimes referred to as "resolved") with that value. We can then chain more .then calls on the end of our transformed promise. We return the transformed promise as the result of our function. Making the requests JavaScript has a really helpful function called .map . It's like .forEach but returns a transformed array. I'm going to use that to stay as close as possible to the original synchronous code. var data = brands.map(function (brand) { var b = {brand: brand} b.devices = devices.map(function (device) { var d = {device: device} d.tapeS = getTape('stage',brand,device); // bad example...tapeS never set d.tapeP = getTape('prod' ,brand,device); return d })}) Now we have code that gives us the data structure I proposed at the start, except we have Promise<TAPE> instead of TAPE . Waiting for the requests Q has a really helpful method called Q.all . It takes an array of promises and waits for them all to complete, so lets turn our data structure into an array of promises to pass to Q.all. One way to do this is at the end, we can go through each item and wait for the promises to resolve. var updated = Q.all(data.map(function (brand) { return Q.all(brand.devices.map(function (device) { return Q.all([device.tapeS, device.tapeP]) .spread(function (tapeS, tapeP) { //update the values with the returned promises device.tapeS = tapeS device.tapeP = tapeP }) })}))//if you add a line that reads `updated = updated.thenResolve(data)`,//updated would become a promise for the data structure (after being resolved)updated.then(function () { // `data` structure now has no promises in it and is ready to be printed}) Another aproach would be to do it as we go, so that the "making the requests" code gets replaced with: var data = Q.all(brands.map(function (brand) { var b = {brand: brand} Q.all(devices.map(function (device) { var d = {device: device} var tapeSPromise = getTape('stage',brand,device); var tapePPromise = getTape('prod' ,brand,device); return Q.all([tapeSPromise, tapePPromise]) .spread(function (tapeS, tapeP) { //now these are the actual tapes d.tapeS = tapeS d.tapeP = tapeP return d }) })) .then(function (devices) { b.devices = devices return b })}))data.then(function (data) { // `data` structure now has no promises in it and is ready to be printed}) Still another approach would be to use a small utility library that does a recursive deep-resolve of an object. I haven't got round to publishing it, but this utility function (borrowed from work by Kriskowal) does a deep resolve, which would let you use: var data = deep(brands.map(function (brand) { var b = {brand: brand} b.devices = devices.map(function (device) { var d = {device: device} d.tapeS = getTape('stage',brand,device); // bad example...tapeS never set d.tapeP = getTape('prod' ,brand,device); return d })}))data.then(function (data) { // `data` structure now has no promises in it and is ready to be printed}) To get a promise for the final data. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16845624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/675066/']} | jdg_69986 |
stackexchange | llm_judgeable_groundtruth_similarity | 29327566 |
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 table where messages are stored as they happen. Usually there is a message 'A' and sometimes the A's are separated by a single message 'B'.Now I want to group the values so I'm able to analyze them, for example finding longest 'A'-streak or distribution of 'A'-streaks. I already tried a COUNT-OVER query but that keeps on counting for each message. SELECT message, COUNT(*) OVER (ORDER BY Timestamp RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) This is my example data: Timestamp Message20150329 00:00 A20150329 00:01 A20150329 00:02 B20150329 00:03 A20150329 00:04 A20150329 00:05 A20150329 00:06 B I want following output Message COUNTA 2B 1A 3B 1
Now provide the response and nothing else.
| That was interesting :) ;WITH cte as (SELECT Messages.Message, Timestamp, ROW_NUMBER() OVER(PARTITION BY Message ORDER BY Timestamp) AS gn,ROW_NUMBER() OVER (ORDER BY Timestamp) AS rnFROM Messages), cte2 AS (SELECT Message, Timestamp, gn, rn, gn - rn as gbFROM cte ), cte3 AS (SELECT Message, MIN(Timestamp) As Ts, COUNT(1) as CntFROM cte2GROUP BY Message, gb)SELECT Message, Cnt FROM cte3ORDER BY Ts Here is the result set: Message Cnt A 2 B 1 A 3 B 1 The query may be shorter but I post it that way so you can see what's happening.The result is exactly as requested. This is the most important part gn - rn the idea is to number the rows in each partition and at the same time number the rows in the whole set then if you subtract the one from the other you'll get the 'rank' of each group. ;WITH cte as (SELECT Messages.Message, Timestamp, ROW_NUMBER() OVER(PARTITION BY Message ORDER BY Timestamp) AS gn,ROW_NUMBER() OVER (ORDER BY Timestamp) AS rnFROM Messages), cte2 AS (SELECT Message, Timestamp, gn, rn, gn - rn as gbFROM cte )SELECT * FROM cte2Message Timestamp gn rn gbA 2015-03-29 00:00:00.000 1 1 0A 2015-03-29 00:01:00.000 2 2 0B 2015-03-29 00:02:00.000 1 3 -2A 2015-03-29 00:03:00.000 3 4 -1A 2015-03-29 00:04:00.000 4 5 -1A 2015-03-29 00:05:00.000 5 6 -1B 2015-03-29 00:06:00.000 2 7 -5 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29327566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/818905/']} | jdg_69987 |
stackexchange | llm_judgeable_groundtruth_similarity | 1203209 |
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 Google yields plenty of example of adding and deleting entries in an F# dictionary (or other collection). But I don't see examples to the equivalent of myDict["Key"] = MyValue; I've tried myDict.["Key"] <- MyValue I have also attempted to declare the Dictionary as Dictionary<string, mutable string> as well several variants on this. However, I haven't hit on the correct combination yet... if it is actually possible in F#. Edit: The offending code is: type Config(?fileName : string) = let fileName = defaultArg fileName @"C:\path\myConfigs.ini" static let settings = dict[ "Setting1", "1"; "Setting2", "2"; "Debug", "0"; "State", "Disarray";] let settingRegex = new Regex(@"\s*(?<key>([^;#=]*[^;#= ]))\s*=\s*(?<value>([^;#]*[^;# ]))") do File.ReadAllLines(fileName) |> Seq.map(fun line -> settingRegex.Match(line)) |> Seq.filter(fun mtch -> mtch.Success) |> Seq.iter(fun mtch -> settings.[mtch.Groups.Item("key").Value] <- mtch.Groups.Item("value").Value) The error I'm getting is: System.NotSupportedException: This value may not be mutated at [email protected]_Item(K key, V value) at <StartupCode$FSI_0036>[email protected](Match mtch) at Microsoft.FSharp.Collections.SeqModule.iter[T](FastFunc`2 action, IEnumerable`1 sequence) at FSI_0036.Utilities.Config..ctor(Option`1 fileName) at <StartupCode$FSI_0041>.$FSI_0041.main@()stopped due to error
Now provide the response and nothing else.
| f# has two common associative data structures: The one you are most used to, the mutable Dictionary which it inherits that's to it's presence in the BCL and uses a hashtable under the hood. let dict = new System.Collections.Generic.Dictionary<string,int>()dict.["everything"] <- 42 The other is known as Map and is, in common functional style, immutable and implemented with binary trees. Instead of operations that would change a Dictionary, maps provide operations which return a new map which is the result of whatever change was requested. In many cases, under the hood there is no need to make an entirely new copy of the entire map, so those parts that can be shared normally are. For example: let withDouglasAdams = Map.add "everything" 42 Map.empty The value withDouglasAdams will remain forever as an association of "everything" to 42. so if you later do: let soLong = Map.remove "everything" withDouglasAdams Then the effect of this 'removal' is only visible via the soLong value. F#'s Map is, as mentioned, implemented as a binary tree. Lookup is therefore O(log n) whereas a (well behaved) dictionary should be O(1). In practice a hash based dictionary will tend to outperform the tree based one in almost all simple (low number of elements, low probability of collision) as such is commonly used. That said the immutable aspect of the Map may allow you to use it in situations where the dictionary would instead require more complex locking or to write more 'elegant' code with fewer side effects and thus it remains a useful alternative. This is not however the source of your problem. The dict 'operator' returns an explicity immutable IDictionary<K,T> implementation (despite not indicating this in it's documentation). From fslib-extra-pervasives.fs (note also the use of options on the keys): let dict l = // Use a dictionary (this requires hashing and equality on the key type) // Wrap keys in an Some(_) option in case they are null // (when System.Collections.Generic.Dictionary fails). Sad but true. let t = new Dictionary<Option<_>,_>(HashIdentity.Structural) for (k,v) in l do t.[Some(k)] <- v let d = (t :> IDictionary<_,_>) let c = (t :> ICollection<_>) let ieg = (t :> IEnumerable<_>) let ie = (t :> System.Collections.IEnumerable) // Give a read-only view of the dictionary { new IDictionary<'key, 'a> with member s.Item with get x = d.[Some(x)] and set (x,v) = raise (NotSupportedException( "This value may not be mutated")) ... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1203209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128432/']} | jdg_69988 |
stackexchange | llm_judgeable_groundtruth_similarity | 299764 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm learning about dependency injection and while I can see the appeal of it when writing functional libraries, I fail to see how it solves anything when you'll also be the one using the libraries. It makes testing the library much simpler, because there isn't much to test. But you will eventually have to test your injected function when you use the library and have to deal with mocking and stubbing functions from the standard library. This is a concrete case I'm dealing with in Node.js : function compile(options) { var files = options.files; var texCompiler = options.texCompiler; var pdfMerger = options.pdfMerger; return Promise.all(files.map(texCompiler(files))) .then(pdfMerger);} That is trivial to test: injecting mock objects or spies as the texCompiler and pdfMerger is a piece of cake because the function really doesn't do much at all. All I can test is that both functions are called in the right sequence. It doesn't save me from testing my texCompiler and pdfMerger functions eventually though. They look something like that: var tex2Pdf = Promise.method(function tex2Pdf(tex_doc) { var latex_command = 'pdflatex'; var pdf_output_filename = path.parse(tex_doc).name + '.pdf'; var cmd = latex_command + ' ' + tex_doc; var options = { cwd: path.resolve(tex_doc, '..') // pdflatex will only look for custom // cls files in the cwd and includes relative to the cwd }; child_process.spawn(cmd, options) .on('end', function() { console.log('tex2Pdf finish'); debugger; return path.resolve(tex_doc, '..', pdf_output_filename); }) .on('error', function(e) { throw e; });});var mergeTwoPdf = Promise.method(function mergeTwoPdf(pdf_files) { var output_file = randomId() + '.pdf'; var cmd = 'gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=' + output_file + ' ' + pdf_files[0] + ' ' + pdf_file[1]; child_process.spawn(cmd) .on('finish', function() { return output_file; }) .on('error', function(e) { throw (e); });}); This is the real thing, and it is a bigger pain to test. I have to mock child_process.spawn with a spy to make sure it gets called with the right arguments, but it doesn't actually do anything, because I don't want to actually merge any PDF file when running the tests and my mocks have to emit the right events so the function isn't stuck. These are problems I would have had if I didn't inject the dependency in my first snippet and used these functions instead. And it really feels like I'm pushing the problem further down without solving it. Am I misunderstanding dependency injection? Am I doing it wrong?
Now provide the response and nothing else.
| You're missing the point of testing it seems. That is trivial to test: injecting mocks or spies as the texCompiler and pdfMerger is a piece of cake because the function really doesn't do much at all. All I can test is that both functions are called in the right sequence. Awesome! If the function is doing trivial work, then the test should be trivial. Likewise, if all that function is actually doing is calling A then B, you're not validating much of your code. The entire point of good tests are to isolate what you're testing, so when the test fails, you can better know what went wrong. Dependency injection helps that. And it really feels like I'm pushing the problem further down without solving it. Sure, in this case you're not "solving it" because your code has nasty dependencies that are hard to isolate. You need to work with the filesystem. You need to call these external processes. Sometimes that is the nature of the beast. Dependency Injection doesn't remove dependencies, it just flips them around so that you can choose what they are. That helps isolate code for testing. It helps the code be more flexible when those dependencies inevitably change. But it does not kill them - your code still needs to be able to do all the same things somewhere . | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/299764', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/199400/']} | jdg_69989 |
stackexchange | llm_judgeable_groundtruth_similarity | 712689 |
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 navigation bar on the left hand side of my page, and I want it to stretch to 100% of the page height. Not just the height of the viewport, but including the areas hidden until you scroll. I don't want to use javascript to accomplish this. Can it be done in HTML/CSS?
Now provide the response and nothing else.
| Here is the solution I finally came up with when using a div as a container for a dynamic background. Remove the z-index for non-background uses. Remove left or right for a full height column. Remove top or bottom for a full width row. EDIT 1: CSS below has been edited because it did not show correctly in FF and Chrome. moved position:relative to be on the HTML and set the body to height:100% instead of min-height:100% . EDIT 2: Added extra comments to CSS. Added some more instructions above. The CSS: html{ min-height:100%;/* make sure it is at least as tall as the viewport */ position:relative;}body{ height:100%; /* force the BODY element to match the height of the HTML element */}#cloud-container{ position:absolute; top:0; bottom:0; left:0; right:0; overflow:hidden; z-index:-1; /* Remove this line if it's not going to be a background! */} The html: <!doctype html><html><body> <div id="cloud-container"></div></body></html> Why? html{min-height:100%;position:relative;} Without this the cloud-container DIV is removed from the HTML's layout context. position: relative ensures that the DIV remains inside the HTML box when it is drawn so that bottom:0 refers to the bottom of the HTML box. You can also use height:100% on the cloud-container as it now refers to the height of the HTML tag and not the viewport. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/712689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85008/']} | jdg_69990 |
stackexchange | llm_judgeable_groundtruth_similarity | 14799434 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list of data.frame objects which i would like to row append to one another, ie merge(..., all=T) . However, merge seems to remove the row names which I need to be kept intact. Any ideas? Example: x = data.frame(a=1:2, b=2:3, c=3:4, d=4:5, row.names=c("row_1", "another_row1"))y = data.frame(a=c(10,20), b=c(20,30), c=c(30,40), row.names=c("row_2", "another_row2"))> merge(x, y, all=T, sort=F) a b c d 1 1 2 3 4 2 2 3 4 5 3 10 20 30 NA 4 20 30 40 NA
Now provide the response and nothing else.
| Since you know you are not actually merging, but just rbind-ing, maybe something like this will work. It makes use of rbind.fill from "plyr". To use it, specify a list of the data.frame s you want to rbind . RBIND <- function(datalist) { require(plyr) temp <- rbind.fill(datalist) rownames(temp) <- unlist(lapply(datalist, row.names)) temp}RBIND(list(x, y))# a b c d# row_1 1 2 3 4# another_row1 2 3 4 5# row_2 10 20 30 NA# another_row2 20 30 40 NA | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14799434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/714319/']} | jdg_69991 |
stackexchange | llm_judgeable_groundtruth_similarity | 6156656 |
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 this class: class DateTime(year: Int, month: Int, day: Int)(hour: Int, minute: Int, second: Int) how would the unapply method look like, if I would like to match against something like: dt match { case DateTime(2012, 12, 12)(12, _, _) => // December 12th 2012, 12 o'clock /* ... */} I tried this: def unapply(dt: DateTime) = Some((dt.year, dt.month, dt.day),(dt.hour, dt.minute, dt.second)) But that didn't really work.
Now provide the response and nothing else.
| Case classes match (and do their other nifty things) only on the first set of parameters: scala> case class A(i: Int)(j: Int) { }defined class Ascala> A(5)(4) match { case A(5) => "Hi" }res14: java.lang.String = Hiscala> A(5)(4) == A(5)(9)res15: Boolean = true If it's not a case class, you can define the unapply to be anything you want, so it's really up to the implementer of the class. By default, there is no unapply, so you can match only on the type. If you want to use the nifty case class features including being able to match and do equality on everything, but have some sort of division, you could nest case classes: case class Time(hour: Int, minute: Int, second: Int) { }case class Date(year: Int, month: Int, day: Int) { }case class DateTime(date: Date, time: Time) { }scala> val dt = DateTime(Date(2011,5,27), Time(15,21,50))scala> dt match { case DateTime(Date(2011,_,_),Time(h,m,50)) => println(h + ":" + m) }15:21 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6156656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297776/']} | jdg_69992 |
stackexchange | llm_judgeable_groundtruth_similarity | 4788461 |
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 my WebView loading all links inside the webview - but when I select an email link it tries to load it in the webview instead of launching an email app on the phone. How do I resolve that? the links are mailto://[email protected] Here is my code - the WebView itself works right and everything loads inside the webview, including mailto:, etc. Need the mailto links to load elsewhere package com.apps.jerdog.crcc;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.KeyEvent;import android.webkit.WebView;import android.webkit.WebViewClient;@SuppressWarnings("unused")public class mainActivity extends Activity { /** Called when the activity is first created. */ /**@Override */ WebView webview; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setSupportZoom(true); webview.getSettings().setBuiltInZoomControls(true); webview.setWebViewClient(new WebViewClient()); webview.loadUrl("http://www.cedarridge.cc"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); return true; } return super.onKeyDown(keyCode, event); } private class myWebViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("mailto:") || url.startsWith("tel:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } view.loadUrl(url); return true; } }}
Now provide the response and nothing else.
| I assume you are already overriding shouldOverrideUrlLoading, you just need to handle this special case. mWebClient = new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.startsWith("mailto:")){ MailTo mt = MailTo.parse(url); Intent i = newEmailIntent(MyActivity.this, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc()); startActivity(i); view.reload(); return true; } else{ view.loadUrl(url); } return true; } }; mWebView.setWebViewClient(mWebClient); public static Intent newEmailIntent(Context context, String address, String subject, String body, String cc) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { address }); intent.putExtra(Intent.EXTRA_TEXT, body); intent.putExtra(Intent.EXTRA_SUBJECT, subject); intent.putExtra(Intent.EXTRA_CC, cc); intent.setType("message/rfc822"); return intent;} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4788461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561377/']} | jdg_69993 |
stackexchange | llm_judgeable_groundtruth_similarity | 2186747 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I create a system/multiprocess Mutex to co-ordinate multiple processes using the same unmanaged resource. Background: I've written a procedure that uses a File printer, which can only be used by one process at a time. If I wanted to use it on multiple programs running on the computer, I'd need a way to synchronize this across the system.
Now provide the response and nothing else.
| You can use the System.Threading.Mutex class, which has an OpenExisting method to open a named system mutex. That doesn't answer the question: How can I create a system/multiprocess Mutex To create a system-wide mutex, call the System.Threading.Mutex constructor that takes a string as an argument. This is also known as a 'named' mutex. To see if it exists, I can't seem to find a more graceful method than try catch: System.Threading.Mutex _mutey = null;try{ _mutey = System.Threading.Mutex.OpenExisting("mutex_name"); //we got Mutey and can try to obtain a lock by waitone _mutey.WaitOne();}catch { //the specified mutex doesn't exist, we should create it _mutey = new System.Threading.Mutex("mutex_name"); //these names need to match.} Now, to be a good programmer, you need to, when you end the program, release this mutex _mutey.ReleaseMutex(); or, you can leave it in which case it will be called 'abandoned' when your thread exits, and will allow another process to create it. [EDIT] As a side note to the last sentence describing the mutex that is abandoned, when another thread acquires the mutex, the exception System.Threading.AbandonedMutexException will be thrown telling him it was found in the abandoned state. [EDIT TWO] I'm not sure why I answered the question that way years ago; there is (and was) a constructor overload that is much better at checking for an existing mutex. In fact, the code I gave seems to have a race condition! (And shame on you all for not correcting me! :-P ) Here's the race condition: Imagine two processes, they both try to open the existing mutex at the same time, and both get to the catch section of code. Then, one of the processes creates the mutex and lives happily ever after. The other process, however, tries to create the mutex, but this time it's already created! This checking/creating of a mutex needs to be atomic. http://msdn.microsoft.com/en-us/library/bwe34f1k(v=vs.90).aspx So... var requestInitialOwnership = false;bool mutexWasCreated;Mutex m = new Mutex(requestInitialOwnership, "MyMutex", out mutexWasCreated); I think the trick here is that it appears that you have an option that you don't actually have (looks like a design flaw to me). You sometimes can't tell if you own the mutex if you send true for requestInitialOwnership . If you pass true and it appears that your call created the mutex, then obviously you own it (confirmed by documentation). If you pass true and your call did not create the mutex, all you know is that the mutex was already created, you don't know if some other process or thread which perhaps created the mutex currently owns the mutex. So, you have to WaitOne to make sure you have it. But then, how many Release s do you do? If some other process owned the mutex when you got it, then only your explicit call to WaitOne needs to be Release d. If your call to the constructor caused you to own the mutex, and you called WaitOne explicitly, you'll need two Release s. I'll put these words into code: var requestInitialOwnership = true; /*This appears to be a mistake.*/bool mutexWasCreated;Mutex m = new Mutex(requestInitialOwnership, "MyMutex", out mutexWasCreated);if ( !mutexWasCreated ){ bool calledWaitOne = false; if ( ! iOwnMutex(m) ) /*I don't know of a method like this*/ { calledWaitOne = true; m.WaitOne(); } doWorkWhileHoldingMutex(); m.Release(); if ( calledWaitOne ) { m.Release(); }} Since I don't see a way to test whether you currently own the mutex, I will strongly recommend that you pass false to the constructor so that you know that you don't own the mutex, and you know how many times to call Release . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2186747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16487/']} | jdg_69994 |
stackexchange | llm_judgeable_groundtruth_similarity | 274416 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Faraday electromagnetic tensor is anti-symmetric. What is the physical meaning of this anti-symmetry?
Now provide the response and nothing else.
| Abstract In this answer we'll show that the physical meaning of the anti-symmetry of the electromagnetic tensor is the demand for the electromagnetic (Lorentz) force to be pure, where a force is called pure if it doesn't change the rest mass $\:m_{o}\:$ of any particle moving with any (subluminal) velocity. This demand is equivalent to the Minkowski pseudo-orthogonality of the electromagnetic force 4-vector $\:\mathbf{F}\:$ to any velocity 4-vector $\:\mathbf{U}$. The elements of the proof of this statement are interspersed in "Introduction to Special Relativity" by Wolfrang Rindler, Ed.1982. 1. The force 4-vector. Pure and Heatlike forces In the textbook we have the relation between the force 4-vector $\:\mathbf{F}$, the momentum 4-vector $\:\mathbf{P}\:$ and the velocity 4-vector $\:\mathbf{U}$ \begin{equation}\mathbf{F}=\dfrac{\mathrm{d}\mathbf{P}}{\mathrm{d}\tau}=\dfrac{\mathrm{d}}{\mathrm{d}\tau}\left(m_{o}\mathbf{U}\right)\tag{35.3}\end{equation} Then the definition of the (relativistic) three-force by \begin{equation}\mathbf{f}=\dfrac{\mathrm{d}\mathbf{p}}{\mathrm{d}t}=\dfrac{\mathrm{d}\left(m\mathbf{u}\right)}{\mathrm{d}t}\tag{35.4}\end{equation}where $\:\mathbf{p},m\:$ the relativistic momentum and mass of the particle on which $\:\mathbf{f}\:$ acts. Then the expression of (35.3) in the form \begin{equation}\mathbf{F}=\gamma\left(u\right)\dfrac{\mathrm{d}}{\mathrm{d}t}\left(mc,\mathbf{p}\right)=\gamma\left(u\right)\left(c\dfrac{\mathrm{d}m}{\mathrm{d}t},\mathbf{f}\right)\tag{35.5}\end{equation} Now the author considers a particle with 4-velocity $\:\mathbf{U}=\gamma\left(u\right)\left(c,\mathbf{u}\right)\:$ being subjected to a 4-force $\:\mathbf{F}=\gamma\left(u\right)\left(c\;\mathrm{d}m/ \mathrm{d}t,\mathbf{f}\right)\:$. Their inner product in Minkowski space is \begin{equation}\mathbf{U} \boldsymbol{\cdot}\mathbf{F}=\gamma^{2}\left(u\right) \left( c^{2}\dfrac{\mathrm{d}m}{\mathrm{d}t}-\mathbf{f}\cdot \mathbf{u} \right)=c^{2}\dfrac{\mathrm{d}m_{o}}{\mathrm{d} \tau}=\gamma\left(u\right) c^{2}\dfrac{\mathrm{d}m_{o}}{\mathrm{d} t}\tag{35.7}\end{equation}where the second equation results from specializing the first to the rest frame of the particle, and the third is a consequence of (23.2) : \begin{equation}\dfrac{ \mathrm{d} t }{ \mathrm{d} \tau}= \left( 1 - \dfrac{u^{2}}{ c^{2}} \right)^{-1/2}=\gamma\left(u\right)\tag{23.2}\end{equation} After these the author proceeds as follows :We shall call a force pure if it does not change a particle's rest mass, and heatlike if it does not change a particle's velocity. For observe from (35.4) that a particle which is at rest but being heated (e.g.by a candle held under it) in one frame, experiences a 'force' $\:\mathbf{f} = \left(\mathrm{d}m_{o}/\mathrm{d}t \right) \gamma\left(u\right)\mathbf{u} \:$ in every other frame. (2) The necessary and sufficient condition for a force to be pure follows at once from (35.7): \begin{equation}\mathbf{U} \boldsymbol{\cdot}\mathbf{F}=0 \quad \Longleftrightarrow \quad m_{o}=\text{constant}\tag{35.9}\end{equation}while that for a force to be heatlike is $\:\mathbf{A}=\boldsymbol{0}\:$ (by $\:\mathbf{A}\:$ the author means the 4-acceleration vector). 2. The electromagnetic tensor and its anti-symmetry In a next Section ( 38. The formal structure of Maxwell's theory ) the author refers that the simplest case is that of a force which everywhere depends linearlyon the velocity of the particles on which it acts. In special relativity it is natural to make this requirement on the respective 4-vectors $\:\mathbf{F}\:$ and $\:\mathbf{U}\:$ : \begin{equation}F_{\mu}=\dfrac{q}{c}\;E_{\mu\nu}\;U^{\nu}\tag{38.1}\end{equation}where the 'coefficients' $\;E_{\mu\nu}\;$ in this linear relation must be tensorial to make it Lorentz-invariant if - as is natural - we takethe charge $\:q\:$ of the particle in question to be a scalar invariant. If we next demand that the force (38.1) be pure, we need \begin{equation}F_{\mu}U^{\mu}=(q/c)\;E_{\mu\nu}\;U^{\mu}U^{\nu}=0,\nonumber\end{equation}for all $\:U^{\mu}\:$, and hence \begin{equation}E_{\mu\nu} = - E_{\nu\mu}\tag{38.2}\end{equation}i.e. the field tensor must be anti-symmetric . (1) (1) ADDENDUM A 3-dimensional analogue of this 4-dimensional anti-symmetry is this :Let $\:\mathrm{\Omega}\:$ a $\:3\times 3\:$ real matrix\begin{equation}\mathrm{\Omega}=\begin{bmatrix}a_{11} & a_{12} & a_{13} \\a_{21} & a_{22} & a_{23} \\a_{31} & a_{32} & a_{33}\end{bmatrix}, \quad a_{\imath \jmath} \in \mathbb{R}\tag{A-01}\end{equation}with the following property\begin{equation}\langle\mathrm{\Omega}\mathbf{x},\mathbf{x}\rangle=0, \quad \text{ for any } \mathbf{x}=\left( x_{1},x_{2},x_{3} \right) \in \mathbb{R}^{3}\tag{A-02}\end{equation}What this property does mean for $\:\mathrm{\Omega}\:$? The inner product of (A-02) is explicitly\begin{align}\langle\mathrm{\Omega}\mathbf{x},\mathbf{x}\rangle &=a_{11}x^{2}_{1}+a_{22}x^{2}_{2}+a_{33}x^{2}_{3}\tag{A-03}\\ & +\left( a_{12}+a_{21} \right)x_{1}x_{2}+\left( a_{23}+a_{32} \right)x_{2}x_{3}+\left( a_{31}+a_{13} \right)x_{3}x_{1}=0\nonumber\end{align} In order for this equality to be valid for any $\:\mathbf{x}=\left( x_{1},x_{2},x_{3} \right) \in \mathbb{R}^{3}\:$ we must have\begin{align}a_{11}=a_{22}=a_{33} & =0\tag{A-04a}\\a_{21}=-a_{12} & = \omega_{3}\tag{A-04b}\\a_{32}=-a_{23} & = \omega_{1}\tag{A-04c}\\a_{13}=-a_{31} & = \omega_{2}\tag{A-04d}\end{align}and so\begin{equation}\mathrm{\Omega}=\begin{bmatrix} 0 & -\omega_{3} & \omega_{2} \\ \omega_{3} & 0 & -\omega_{1} \\ -\omega_{2} & \omega_{1} & 0\end{bmatrix}=\boldsymbol{\omega}\boldsymbol{\times}\tag{A-05}\end{equation}that is the matrix $\:\mathrm{\Omega}\:$ is anti-symmetric and represents the outer product $\:\boldsymbol{\omega}\boldsymbol{\times}\:$. Now it's clear why (A-02) could be valid for any $\:\mathbf{x}=\left( x_{1},x_{2},x_{3} \right) \in \mathbb{R}^{3}\:$ : the 3-vector $\:\boldsymbol{\omega}\boldsymbol{\times}\mathbf{x}\:$ is always orthogonal to $\:\mathbf{x}\:$. (2) FIGURE In the rest system $\:\mathcal{S}_{o}\:$ of a particle, see ($\alpha$), heat is transfered to the particle with rate $\:\dot{\mathrm{q}}_{o}\:$. This rate is with respect to the proper time $\:\tau\:$ and this heat power changes the rest mass $\:m_{o}\:$ of the particle:\begin{equation}\dot{\mathrm{q}}_{o}=\dfrac{\mathrm{d}\left(m_{o}c^{2}\right)}{\mathrm{d}\tau}=c^{2}\dfrac{\mathrm{d}m_{o}}{\mathrm{d}\tau}\tag{B-01}\end{equation}In an other inertial system $\:\mathcal{S}\:$ moving with constant 3-velocity $\:-\mathbf{w}\:$ with respect to $\:\mathcal{S}_{o}\:$, the particle is moving with constant velocity $\:\mathbf{w}\:$, see ($\beta$), under the influence of a 'force'\begin{equation}\boldsymbol{\mathcal{h}}=\dfrac{\dot{\mathrm{q}}_{o}}{c^{2}}\mathbf{w}=\dfrac{\mathrm{d}m_{o}}{\mathrm{d}\tau}\mathbf{w}=\gamma(w)\dfrac{\mathrm{d}m_{o}}{\mathrm{d} t}\mathbf{w}\tag{B-02}\end{equation}This 'force' $\:\boldsymbol{\mathcal{h}}\:$, although acting on the particle, keeps its velocity $\:\mathbf{w}\:$ constant. So, its 3-acceleration is $\:\mathbf{a}=\mathrm{d}\mathbf{w}/\mathrm{d}t =\boldsymbol{0}\:$ and consequently its 4-acceleration $\:\mathbf{A}=\boldsymbol{0}$. This 'force' is defined as heatlike . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/274416', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/127275/']} | jdg_69995 |
stackexchange | llm_judgeable_groundtruth_similarity | 305728 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been looking at Microservices for a while now. The concept is not new but it's communicated in a lightweight manner. So, I am very excited about this. However, there is a question that I am not sure what the answer is: is each microservice supposed to have its own isolated data storage model completely? Consider the below: Note: This is probably not a good example as the seperation here is done based on read/writes whereas the good approach would be to separate the business concerns. products-write-service: responsible for dealing with creation and edits of the products. Knows MongoDB and writes data to there. products-lookup-service: responsible for dealing with retrieving products by their identifiers, providing basic listing of products based on categories, etc. Knows MongoDB and reads data from there. products-search-service: responsible for dealing with search requests on products. Knows Elasticsearch and reads data from there. Here, we have two separate data storage techs between three services. However: products-write-service and products-lookup-service works on the same data storage model. There is a tried relationship between two services. at the end of the day, there should be a process to do ETL from MongoDB to Elasticsearch for products-search-service to function. In some sense, three microservices have their own data storage model but there is a middle process which knows about these two models. What do you say about this model? Is the separation completely wrong here?
Now provide the response and nothing else.
| I think that each service should have its own storage . Otherwise you're missing a point of (micro-)services - you can't quickly evolve the service if you're limited by storage shared with other service. Why are you splitting read and write logic into separate services? That's a bit of a smell for me. There's nothing saying that a service couldn't have multiple storages. Maybe you're looking at a single service with multiple storages? Updating a product could result in simultaneous updates to both MongoDB and ES. Based on a limited domain knowledge I would provision 2 services: Product Catalog with MongoDB and Product Search with ES as backend. How you transfer data between services is a separate question: ETL as you've suggested (would have to understand both storages - quick and dirty) Domain Events - Product Search service could subscribe to events published from Product Catalog service (that would be my preferred choice) Batch process that would use services' API instead of going directly to the storage (probably better than 1. but will require developing richer APIs) | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/305728', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/22417/']} | jdg_69996 |
stackexchange | llm_judgeable_groundtruth_similarity | 389237 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently came by a seemingly trivial architectural problem. I had a simple repository in my code that was called like this (code is in C#): var user = /* create user somehow */;_userRepository.Add(user);/* do some other stuff*/_userRepository.SaveChanges(); SaveChanges was a simple wrapper that commits changes to database: void SaveChanges(){ _dataContext.SaveChanges(); _logger.Log("User DB updated: " + someImportantInfo);} Then, after some time, I needed to implement new logic that would send email notifications every time a user was created in the system. Since there were many calls to _userRepository.Add() and SaveChanges around the system, I decided to update SaveChanges like this: void SaveChanges(){ _dataContext.SaveChanges(); _logger.Log("User DB updated: " + someImportantInfo); foreach (var newUser in dataContext.GetAddedUsers()) { _eventService.RaiseEvent(new UserCreatedEvent(newUser )) }} This way, external code could subscribe to UserCreatedEvent and handle the needed business logic that would send notifications. But it was pointed out to me that my modification of SaveChanges violated the Single Responsibility principle, and that SaveChanges should just save and not fire any events. Is this a valid point? It seems to me that the raising an event here is essentially the same thing as logging: just adding some side functionality to the function. And SRP does not prohibit you from using logging or firing events in your functions, it just says that such logic should be encapsulated in other classes, and it is OK for a repository to call these other classes.
Now provide the response and nothing else.
| Sending a notification that the persistent data store changed seems like a sensible thing to do when saving. Of course you shouldn't treat Add as a special case - you'd have to fire events for Modify and Delete as well. It's the special treatment of the "Add" case that smells, forces the reader to explain why it smells, and ultimately leads some readers of the code to conclude it must violate SRP. A "notifying" repository that can be queried, changed, and fires events on changes, is a perfectly normal object. You can expect to find multiple variations thereof in pretty much any decently sized project. But is a "notifying" repository actually what you need? You mentioned C#: Many people would agree that using a System.Collections.ObjectModel.ObservableCollection<> instead of System.Collections.Generic.List<> when the latter is all you need is all kinds of bad and wrong, but few would immediately point to SRP. What you are doing now is swapping your UserList _userRepository with an ObservableUserCollection _userRepository . If that's the best course of action or not depends on the application. But while it unquestionably makes the _userRepository considerably less lightweight, in my humble opinion it doesn't violate SRP. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/389237', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/211802/']} | jdg_69997 |
stackexchange | llm_judgeable_groundtruth_similarity | 558283 |
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 installed apache2 on ubuntu 13.10.If I try to restart it using sudo /etc/init.d/apache2 restart I get this message: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message So I read that I should edit my httpd.conf file. But, since I can't find it in /etc/apache2/ folder, I tried to locate it using this command: /usr/sbin/apache2 -V But the output I get is this: [Fri Nov 29 17:35:43.942472 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined[Fri Nov 29 17:35:43.942560 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_PID_FILE} is not defined[Fri Nov 29 17:35:43.942602 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_RUN_USER} is not defined[Fri Nov 29 17:35:43.942613 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_RUN_GROUP} is not defined[Fri Nov 29 17:35:43.942627 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOG_DIR} is not defined[Fri Nov 29 17:35:43.947913 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOG_DIR} is not defined[Fri Nov 29 17:35:43.948051 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOG_DIR} is not defined[Fri Nov 29 17:35:43.948075 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOG_DIR} is not definedAH00526: Syntax error on line 74 of /etc/apache2/apache2.conf:Invalid Mutex directory in argument file:${APACHE_LOCK_DIR} Line 74 of /etc/apache2/apache2.conf is this: Mutex file:${APACHE_LOCK_DIR} default I gave a look at my /etc/apache2/envvar file, but I don't know what to do with it. What should I do?
Now provide the response and nothing else.
| [Fri Nov 29 17:35:43.942472 2013] [core:warn] [pid 14655] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined This message is displayed because you directly executed the apache2 binary.In Ubuntu/Debian the apache config relies on the envvar file which is only activated. If you start apache with the init script or apachectl. Your original problem is that you have no a proper hostname (fqdn) for your machine. If you can't change it, change the ServerName variable in /etc/apache2/apache2.conf to localhost or your prefered FQDN. | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/558283', 'https://serverfault.com', 'https://serverfault.com/users/200993/']} | jdg_69998 |
stackexchange | llm_judgeable_groundtruth_similarity | 13855 |
Below is a question asked on the forum physics.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Does it make any difference in using https://physics.meta.stackexchange.com/q/13855/305718 instead of https://physics.meta.stackexchange.com/questions/13855/proper-formatting-of-links ?(Link is of this post as an example) I've seen several times that the second one had been replaced by the first one.
Now provide the response and nothing else.
| There’s no difference for the person clicking the link, but there are minor differences for the person posting it, and for a hypothetical person who might read the URL but not click. The magic number that’s common in your two examples, 13855 , is the database identifier of your post. When you visit a link of the first form, your browser is redirected to a URL of the second form, with an appropriate #anchor to the middle of the page if the link is to an answer rather than to the question. You generate links of the first form by copying from the browser URL field. You generate links of the second form by clicking the “Share” button under a post. The other number in the first form, here 305718 , is the user ID of the person who has clicked that button – which you can verify by clicking on your profile name and looking at that URL. That user ID is used to award the Announcer , Booster , and Publicist badges. So if you’re motivated by badges and gamification, you might prefer to click the “Share” button instead of copying the URL. A person who is reading the link, but not clicking, can divine the content of the question from the first form, because it includes a version of the title of the question. However, if the title of the question is edited, the old links will still work. The only valuable part of the long-form link is the question/answer ID; everything after that slash is ignored. That means that you can in principle deceive people about the content of the link with the long form: the URL https://physics.meta.stackexchange.com/questions/13855/im-a-big-dumb-poopy-head also redirects to this question, even though no one here is a big dumb poopy head. A person who is reading the link, but not clicking, can determine your user account on the site from the short form. So if you were to send an email to your boss that said hey this SO question solves our problem https://stackoverflow.com/a/952952/1650379 then your boss could, if motivated, visit your Stack Overflow profile page, notice from your list of linked accounts that you sometimes write long answers on Physics during so-called “working hours,” and give you grief about that. Someone who was more concerned about privacy than about Announcer badges might strip their user ID from the short-form links. | {} | {'log_upvote_score': 4, 'links': ['https://physics.meta.stackexchange.com/questions/13855', 'https://physics.meta.stackexchange.com', 'https://physics.meta.stackexchange.com/users/305718/']} | jdg_69999 |
stackexchange | llm_judgeable_groundtruth_similarity | 2353473 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am dealing with Windows here. I know you can use the $_SERVER['HTTP_USER_AGENT'] variable to detect the OS of the browser viewing the page, but is the any way that PHP can detect the server's OS? For my program's UI I am using a PHP webpage. I need to read a key in the registry that is in a different location on a 64-bit OS (It is under the Wow6432Node Key). Can PHP tell what OS it is running on? Can PHP tell if the OS is 64-bit or 32-bit?
Now provide the response and nothing else.
| Note: This solution is a bit less convenient and slower than @Salman A's answer . I would advice you to use his solution and check for PHP_INT_SIZE == 8 to see if you're on a 64bit os. If you just want to answer the 32bit/64bit question, a sneaky little function like this would do the trick (taking advantage of the intval function's way of handling ints based on 32/64 bit.) <?phpfunction is_64bit(){ $int = "9223372036854775807"; $int = intval($int); if ($int == 9223372036854775807) { /* 64bit */ return true; } elseif ($int == 2147483647) { /* 32bit */ return false; } else { /* error */ return "error"; }}?> You can see the code in action here: http://ideone.com/JWKIf Note: If the OS is 64bit but running a 32 bit version of php, the function will return false (32 bit)... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2353473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148256/']} | jdg_70000 |
stackexchange | llm_judgeable_groundtruth_similarity | 12807075 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been working on moving over to OOP in PHP. I have reading explanations on php.net, but I was hoping I could get some specific answers here. I tried to create the following example to illustrate my question. Say I have "Database", "Products", and "Users" classes, and I want to display products if a user has access. So I call the "Products" class "showProducts()" function, which in turn creates an instance of the "User" class, which creates an instance of the "Database" object and checks the users access level. If the user has access, then the "showProducts()" function creates another instance of the "Database" object, and queries the database. class Database{ public function query(){ //runs query here } public function __construct() { //sets up connection here }}class User{ public function checkAccess(){ $db = new Database(); $db->query( //pass in query to check access ) //does stuff, then returns true or false }}class Products{ public function showProducts(){ $user = new User(); if($user->checkAccess()) $db = new Database(); $db->query( //pass in query to get products ) }} I was hoping someone could illustrate how to do this the proper way. I would like to have some sort of controller class, that creates one "Database" object, that is available to all of the classes that need to access it, without having to create multiple instances of the "Database" object. I would like the same thing with the users class, so there is one $users object that all the classes can access, without having to create a new object every time I need to use something in the "User" class. I apologize if my question is not clear, and thanks in advance for any responses!! Thanks to everybody for the replies!
Now provide the response and nothing else.
| When moving form procedural to Object Oriented programming you should grasp more then just how to build classes. OOP is not writing classes, its about following best practices, principles and patterns in OOP. You should not instantiate new objects inside another, you should give the User object, his Database object that User depends on, through constructor, or setter method. That is called Dependency Injection. The goal is to give objects to a class that needs them through constructor or setter method. And they should be instanciated from outside of that class, so its easier to configure class. And when building a class you want its easy to see what dependencies that class have. You can read about Inversion of Control principle here: IoC So then your code would look like this: <?php// User object that depends on Database object, and expects it in constructor.class User{ protected $database; public function __construct($database) { $this->database = $database; } // -- SNIP --}?> Now to use that user class you do this: <?php $database = new Database($connParams); $user = new User($database);?> You can also use Dependency Injection using setter methods to set dependencies, but Il let you google that for yourself :) Thats it, joust read about Inversion of Controll principle, and about Dependency Injection and Dependency Injection Containers, these are the best ways to manage classes. I have seen lots of PHP code that is "OOP" and in fact they are only using Classes as functionality namespaces :) So joust learn about OOP principles and patterns. Have fun! :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12807075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1582882/']} | jdg_70001 |
stackexchange | llm_judgeable_groundtruth_similarity | 479200 |
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:
Since we can plug anything consistent with a cdf, I would like to clarify whether we are implying that each of the underlying marginals are gaussian when we use gaussian copula? thanks
Now provide the response and nothing else.
| There are various ways a negative binomial distribution can come about. One of them, as Robert Long comments , is as a Poisson distribution whose parameter is itself Gamma distributed. The Wikipedia page gives the derivation of this result. So this covers parts (i) and (ii) of your model. This is an example of compound-distributions , which are often also called "mixtures" (e.g. a "Poisson-Gamma mixture" in the present case). This can be confusing, since a "mixture" has at least one related but distinct meaning in statistics. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/479200', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/252526/']} | jdg_70002 |
stackexchange | llm_judgeable_groundtruth_similarity | 6636107 |
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 question about Haskell polymorphism. As I've learned, there are two types of polymorphism: Parametric : where you do not specify the input type. Example: functionName :: [a] -> a Overloading : as imperative programming, i.e. passing different arguments to the same function. My problem is: how does Haskell handle overloading ?
Now provide the response and nothing else.
| Overloading in Haskell is done using type classes. For example, let's say you want to overload a function foo that returns an Int : class Fooable a where foo :: a -> Intinstance Fooable Int where foo = idinstance Fooable Bool where foo _ = 42 However, they are more powerful than the overloading mechanisms found in most languages. For example, you can overload on the return type: class Barable a where bar :: Int -> ainstance Barable Int where bar x = x + 3instance Barable Bool where bar x = x < 10 For more examples, have a look at the predefined type classes in Haskell. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6636107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/296231/']} | jdg_70003 |
stackexchange | llm_judgeable_groundtruth_similarity | 3026351 |
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 done some programming and I have used Mercurial for source control. I now need to send all of my code to someone else (because they are going to take over). Since all copies of a mercurial repository is a full and real repository my first thought is to first do a clone of my repository without an update and then zipping and emailing that clone. Is this a good way, or is there a better way? For example when using the TortoiseHg Repository Explorer I can right-click on a changeset and under Export there are various options that looks like they could be doing something interesting, but I don't quite understand them or know which one to use.
Now provide the response and nothing else.
| What you've suggested will work fine, but you can also use hg bundle to create a changegroup file encapsulating a compressed copy of the entire repository (see hg help bundle for the full details, or this page: http://www.selenic.com/mercurial/hg.1.html#bundle ). On your machine: hg -R /path/to/repo bundle --all my_repo.hg Then send my_repo.hg off to the other developer, who can clone directly from that: hg clone my_repo.hg /path/to/new/clone (Note: this sort of assumes you're working with linux, but I imagine TortoiseHg supports something similar, since this is a basic feature of Mercurial). EDIT: Looks like the equivalent using TortoiseHg would be to export a range of changesets as a bundle (see here: http://tortoisehg.bitbucket.io/manual/2.9/patches.html#export-patches ). In this case, you want to select the very first changeset all the way up through the tip, and export as a bundle. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3026351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']} | jdg_70004 |
stackexchange | llm_judgeable_groundtruth_similarity | 31964930 |
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 do exactly the following: >>> x = (1,2)>>> y = 'hello'>>> '%d,%d,%s' % (x[0], x[1], y)'1,2,hello' However, I have a long x , more than two items, so I tried: >>> '%d,%d,%s' % (*x, y) but it is syntax error. What would be the proper way of doing this without indexing like the first example?
Now provide the response and nothing else.
| str % .. accepts a tuple as a right-hand operand, so you can do the following: >>> x = (1, 2)>>> y = 'hello'>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`'1,2,hello' Your try should work in Python 3 , where Additional Unpacking Generalizations is supported, but not in Python 2.x: >>> '%d,%d,%s' % (*x, y)'1,2,hello' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31964930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547820/']} | jdg_70005 |
stackexchange | llm_judgeable_groundtruth_similarity | 204363 |
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 create a simple 3D model (for example in 3DS MAX) and then import it to Android?
Now provide the response and nothing else.
| That's where I got to: I've used Google's APIDemos as a starting point - there are rotating cubes in there, each specified by two arrays: vertices and indices. I've build my model using Blender and exported it as OFF file - it's a text file that lists all the vertices and then faces in terms of these vertices (indexed geometry) Then I've created a simple C++ app that takes that OFF and writes it as two XMLs containing arrays (one for vertices and one for indices) These XML files are then copied to res/values and this way I can assign the data they contain to arrays like this: int vertices[] = context.getResources().getIntArray(R.array.vertices); I also need to manually change the number of faces to be drawn in here: gl.glDrawElements(GL10.GL_TRIANGLES, 212*6, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); - you can find that number (212 in this case) on top of the OFF file Here you can find my project page, which uses this solution: Github project > vsiogap3d | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/204363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3037/']} | jdg_70006 |
stackexchange | llm_judgeable_groundtruth_similarity | 360036 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array of unique integers, for example: {1,3,,7,9,31,46,...}, which I want to compress. I have found compression techniques and algorithms for the list of integers, where some integers are repeated but I couldn't find any compression technique for list of unique integers. I would appreciate if anyone could help me to get an idea so that I could start with. I have 1024 datasets of size 512 where where each value is a distinct integer between 1 and N (or 0 and N-1), i.e., a permutation of a set of N consecutive integers. I also assume that there is given a tolerance x and so, I want to find a compressed representation that allows the original values to be recovered with deviations no greater than x.Thanks.
Now provide the response and nothing else.
| You have to consider that compression - by which I assume you mean lossless compression - equates to the removal of redundant information . If you write 12,12,12,12,12 there's redundance and you can write it as 12*5. So you need to find the information that you can make redundant. For example the sequence 1,2,3,4,5,6,7,18,19,20,21 is nonrepeating, yet there is redundance and you can "compress" it as 1,7,18,4 (storing the first element of an increasing sequence and the number of elements) or 1,7,18,21 (storing the first and last elements of all sequences). Then you must keep in mind that this kind of compression a trade - instead of using a set of symbols with some known occurrence probability you use another set, with a different spectrum, organized so that the most likely sequences map to the shortest symbols , even if on average the symbols are bulkier. But there will always be a killer sequence to which your compression will be applied with little result, or even catastrophic results (as whatsitsname remarked, most random sequences will turn out to become larger ; which is why applying a compression unsuited for your data will likely avail little). For example in the "1,2,3..." sequence, if you get 1,3,5,7,9,11,13 you're forced to store it as 1,1,3,1,5,1,7,1,9,1,13,1 -- doubling the sequence size. For the same reason if you rename a .zip file as .dat (to prevent Zip from refusing to compress it) and try to compress it, you'll notice that once compressed, the file actually gets larger . Perhaps by very little, perhaps just by that handful of bits necessary to store the information "This file is stored uncompressed!" - but larger nonetheless. Finally you need to state what you mean by compression . Are you referring to the number of integers in the sequence? Or the number of characters in its text representation? Say you have 1,7,9,5,11. You notice that no number is larger or equal to 12. So no product of any two numbers A and B will be larger than 11*A+B (actually a product of N 0 , N 1 , ...N n can be translated as 11 n *N n +...+11 0 *N 0 ). Using Horner's algorithm, n integers become one (larger) integer. Using a larger base for clarity (100 instead of 12), 1,7,9,11 becomes 1070911. In characters, you haven't gained that much - eleven characters have become seven (using 12 as base, 1-7-9-11 becomes 2855 which is four characters). Counting integers, four have become one - or rather two, as you need to account for the need of storing the 12 also. If you have an increasing sequence, you can store the first number and the differences (1-3-7-9-31-46 becomes 1-2-4-2-22-15), which may yield smaller numbers, which might be useful, though they'll now be probably non-monotonic. Finally, a sequence with no redundancy because there is no relation between the previous numbers and the next one, so that each number provides 100% information on itself - in other words, a random sequence - will never be losslessly compressible, because there is nothing to squeeze out. You will be able to compress its textual representation, but this is not what your question seems to suggest. So, without more information on the sequence's characteristics and your specific scenario, I'm afraid there's very little that can be done for you. Case in point You need to deal with VERY large numbers (N=512, and you don't want to manipulate (N-1)! without heavy duty gloves). But the main problem is that the permutation is essentially random, so compressing the numbers is not going to work reliably; I think we might have better luck with some ad hoc coding. Now every integer in itself holds 9 bits of information (512 = 2 9 ), so your data set is at a first glance actuality composed of 4608 bits (or 4599, since the last number is uniquely identified by the other 511 - it's the only one missing from the set). But this is assuming that it's not a permutation but a combination, that every integer is free to assume any value; we do not exploit the uniqueness constraint, which adds at least 511 bits more information, or in other words requires 2 n *(n-1)+1 bytes, not 2 n * n. Let's look at it more closely. The first number (0) has 512 possible positions which we can code in 9 bits (2 9 = 512). The next number can only go in one of the remaining 511 positions, which still requires 9 bits. In short, the first 256 numbers all need 9 bits. When the number of positions remaining drop below 256, we can use 8 bits. So, the next 128 numbers can be coded into the remaining 256 positions using 8 bits, until the number of free positions becomes 127. And so on, until the 511th number can only go in either of two positions and requires one bit. One number is left and it can only go in the last place, so it adds no information and it makes for a further 0 bits. So we need 256*9 + 128*8 + 64*7 + 32*6 + 16*5 + 8*4 + 4*3 + 2*2 + 1*1 bits == 2304 + 1024 + 448 + 192 + 80 + 32 + 12 + 4 + 1 == 4097 bits which is 2 n * (n-1)+1 (in this case it looks like 2 14 +1). You can represent those 4097 bits using 133 dword integers from 0 to 2147483648 if you want to code them in the smallest possible number of integers . If you want to code them in the smallest possible number of decimal digits , then you want to find a power of ten which is the nearest possible to the immediately lesser power of two. With a number of bits below 32, this happens with three: 2 3 is 8, which requires one digit, and in one decimal digit you can code at the most the number 9. But taking into account the separator , a single digit requires two characters each three bits, if you also need the comma (you mightn't, because one digit needs no separator). The best becomes then 2 23 or 8388608, seven digits (plus one comma, eight). So your 512 numbers (1940 characters) become (4097/23) * 8 = 1432 numeric characters and commas. Or it is an uninterrupted sequence of (4097/3) * 1 = 1366 digits. Using 63 bits and numbers up to 2 63 -1 or 9223372036854775807, we get around (4097/63)(19+1) = 1300 characters. At best, you can code the sequence into 683 base64 characters, or a 65% reduction, which makes your 1024 dataset 684 Kb in total. (Or you can binary-code it into 513 bytes). The algorithm Let BUFFER be your sequence of numbers (137, 410, 128, ...)initialize a vector POSITION[512]for i = 0 to 511 included: # The position of number BUFFER[i] (e.g. 128) is 2. POSITION[BUFFER[i]] = inext = 256for i = 0 to 510 included: POS = POSITION[i] # How many unchecked positions are between 0 and POS? Q = 0 for j = 0 to POS: if COPYOFBUFFER[j] >= 0: Q = Q + 1 # Mark the POS-th address as "checked" by setting it to -1 COPYOFBUFFER[POS] = -1; # Or you could set it to the first unused number, 512, as MAXVAL, and # modify the previous cycle to check that COPYOFBUFFER[j] < MAXVAL # Now, i-th number is uniquely identified by Q # And Q is uniquely identified by a diminishing number of bits output(Q, bits) if (i == next): bits = bits - 1 next = next / 2 The function "output" will output 8 bits (one character) or maybe 6 bits (one Base64 digit) and keep the rest internally, prepending said rest to the next call. You will need to make a last call to flush any remaining bits. This is a not too efficient C implementation. /** * outputs N bits (maximum N depends on integer type) * @param n number of bits * @param val value holding the bits in its "n" least significant bits */void output_bits(int n, int val) { static int buffer = 0; static int bits = 0; if (0 == n) { // The request to output 0 bits makes no sense and is used // to mean "flush the buffer". // If the buffer contains 5 bits, we need 3 additional bits. if (0 == bits) { // buffer is already flushed. return; } n = 8 - bits; val = 0; } int mask = 1 << n; // we have 000111 (so, 7) and 3 bits. We get 0100 (4) while (n--) { // shift buffer by 1 bit left to accommodate next bit. buffer = buffer <<= 1; if (val & mask) { // We have a 1. buffer |= 1; } bits++; if (0 == (bits % 8)) { // We have a full byte. output_byte(buffer & 0xff); } // Shift the mask right to get the next bit. mask >>= 1; }} To reconstruct the array, proceed in reverse: as soon as you've gathered enough bits to retrieve a Q, move into the buffer by Q empty positions and place the number there: |__________________________________________| read first byte: 23, but we need 9 bits read second byte: 139, so the first number is 23*2+(139/128) = 47 and the remainder is (139-27) = 112 read first Q: 47 ...so the first number, 1, goes into slot 47 |______________________1___________________| now read third byte: 34, so the second number is 112*2+(34/128) = 224 the second number, 2, should go into the 224th empty slot, which is number 225 because slot 47 is already taken |______________________1__________________2____| ...and so on. Another algorithm You can squeeze some more bits out of the sequence by operating as follows. You code the position of the first number among the 512 still free spaces in the sequence using 9 bits. Then, the second number's position requires a number from 0 to 511 to identify the p- th free slot in the sequence. 511 is 8.99718... bits. You have now need of coding fractional bits , and you can google those and look e.g. phase-in codes . The sequence will now size which is rounded to 3867, from the original naive estimate of 4599, or a reduction of around 16% to 484 bytes. Decoding will be quite slow as you need to walk the whole sequence to translate a number to its true position. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/360036', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/287280/']} | jdg_70007 |
stackexchange | llm_judgeable_groundtruth_similarity | 650286 |
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 know that $\vec a\cdot(\vec b+\vec c)=\vec a\cdot\vec b+\vec a\cdot\vec c$, but is it also true that $\vec a\cdot(\vec b-\vec c)=\vec a\cdot\vec b-\vec a\cdot\vec c$?
Now provide the response and nothing else.
| Let $c' = -c$. Then $b-c = b+c'$ Then $a\cdot (b-c) = a\cdot (b+c') = a\cdot b + a\cdot c' = a\cdot b -a\cdot c$. So, yes. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/650286', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/107827/']} | jdg_70008 |
stackexchange | llm_judgeable_groundtruth_similarity | 24838669 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have made two tables : Member(member_id,name,contact) Registration(loan_id,member_id,witness1_id,witness2_id,status)primary key of Member,registration table are member_id and loan_id respectively. The witness1_id and witness2_ id are the member_id in member table which means each member have two witnesses who are themselves the member of the organization.I want to make a query which gives the list of members along with the witnesses details whose status is 1, output should be in the following schema : (member_id,name_of_member,witness1_name,witness1_contact,witness2_name, witness2_contact) To make the problem easy to understand, I have not included the full schema rather I have used the required fields. example :Membermember_id name contact1 xyz 11111111112 abc 22222222223 pqr 33333333334 efg 4444444444Registrationloan_id member_id witness2_id witness2_id status123 1 2 3 1124 2 1 3 0125 4 2 1 1output/resultmember_id name witness1_name witness1_contact witness2_name witness2_contact1 xyz abc 22222222 pqr 3333333334 efg abc 22222222 xyz 111111111
Now provide the response and nothing else.
| I've found fix for Icon_Selector for PagerSlidingTabStrips within it's closed issues. Modify PagerSlidingTabStrips.java and add following code private int currentPageSelected = 0; //Fix : ICON SELECTOR Append on NotifyDataSetChanged method inside OnGlobalLayoutListener currentPosition = pager.getCurrentItem(); tabsContainer.getChildAt(currentPosition).setSelected(true); //ADDED THESE scrollToChild(currentPosition, 0); Modified the onPageSelected() : @Overridepublic void onPageSelected(int position) {tabsContainer.getChildAt(currentPageSelected).setSelected(false);currentPageSelected = position;tabsContainer.getChildAt(position).setSelected(true);if (delegatePageListener != null) { delegatePageListener.onPageSelected(position }} IconSelector <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/tab_icon_zname_call_log_selected" android:state_selected="true"/> <item android:drawable="@drawable/tab_icon_zname_call_log_selected" android:state_pressed="true"/> <item android:drawable="@drawable/tab_icon_zname_call_log"/> </selector> PagerSlidingTabStrips.java import java.util.Locale;import android.annotation.SuppressLint;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Typeface;import android.os.Build;import android.os.Parcel;import android.os.Parcelable;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.util.AttributeSet;import android.util.DisplayMetrics;import android.util.TypedValue;import android.view.Gravity;import android.view.View;import android.view.ViewTreeObserver.OnGlobalLayoutListener;import android.widget.HorizontalScrollView;import android.widget.ImageButton;import android.widget.LinearLayout;import android.widget.TextView;import com.netdoers.zname.R;public class PagerSlidingTabStrip extends HorizontalScrollView { public interface IconTabProvider { public int getPageIconResId(int position); } // @formatter:off private static final int[] ATTRS = new int[] { android.R.attr.textSize, android.R.attr.textColor }; // @formatter:on private LinearLayout.LayoutParams defaultTabLayoutParams; private LinearLayout.LayoutParams expandedTabLayoutParams; private final PageListener pageListener = new PageListener(); public OnPageChangeListener delegatePageListener; private LinearLayout tabsContainer; private ViewPager pager; private int tabCount; private int currentPosition = 0; private float currentPositionOffset = 0f; private Paint rectPaint; private Paint dividerPaint; private int currentPageSelected = 0; //Fix : ICON SELECTOR private int indicatorColor = 0xFF666666; private int underlineColor = 0x1A000000; private int dividerColor = 0x1A000000; private boolean shouldExpand = false; private boolean textAllCaps = true; private int scrollOffset = 52; private int indicatorHeight = 8; private int underlineHeight = 2; private int dividerPadding = 12; private int tabPadding = 24; private int dividerWidth = 1; private int tabTextSize = 12; private int tabTextColor = 0xFF666666; private Typeface tabTypeface = null; private int tabTypefaceStyle = Typeface.BOLD; private int lastScrollX = 0; private int tabBackgroundResId = R.drawable.background_tab; private Locale locale; public PagerSlidingTabStrip(Context context) { this(context, null); } public PagerSlidingTabStrip(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFillViewport(true); setWillNotDraw(false); tabsContainer = new LinearLayout(context); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(tabsContainer); DisplayMetrics dm = getResources().getDisplayMetrics(); scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm); indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm); underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm); dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm); tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm); dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm); tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm); // get system attrs (android:textSize and android:textColor) TypedArray a = context.obtainStyledAttributes(attrs, ATTRS); tabTextSize = a.getDimensionPixelSize(0, tabTextSize); tabTextColor = a.getColor(1, tabTextColor); a.recycle(); // get custom attrs a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip); indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor); underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor); dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor); indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight); underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight); dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding); tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding); tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId); shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand); scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset); textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps); a.recycle(); rectPaint = new Paint(); rectPaint.setAntiAlias(true); rectPaint.setStyle(Style.FILL); dividerPaint = new Paint(); dividerPaint.setAntiAlias(true); dividerPaint.setStrokeWidth(dividerWidth); defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); if (locale == null) { locale = getResources().getConfiguration().locale; } } public void setViewPager(ViewPager pager) { this.pager = pager; if (pager.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } pager.setOnPageChangeListener(pageListener); notifyDataSetChanged(); } public void setOnPageChangeListener(OnPageChangeListener listener) { this.delegatePageListener = listener; } public void notifyDataSetChanged() { tabsContainer.removeAllViews(); tabCount = pager.getAdapter().getCount(); for (int i = 0; i < tabCount; i++) { if (pager.getAdapter() instanceof IconTabProvider) { addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i)); } else { addTextTab(i, pager.getAdapter().getPageTitle(i).toString()); } } updateTabStyles(); getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { getViewTreeObserver().removeOnGlobalLayoutListener(this); } currentPosition = pager.getCurrentItem(); tabsContainer.getChildAt(currentPosition).setSelected(true);//Fix : ICON SELECTOR scrollToChild(currentPosition, 0); } }); } private void addTextTab(final int position, String title) { TextView tab = new TextView(getContext()); tab.setText(title); tab.setGravity(Gravity.CENTER); tab.setSingleLine(); addTab(position, tab); } private void addIconTab(final int position, int resId) { ImageButton tab = new ImageButton(getContext()); tab.setImageResource(resId); addTab(position, tab); } private void addTab(final int position, View tab) { tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); tab.setPadding(tabPadding, 0, tabPadding, 0); tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); } private void updateTabStyles() { for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); if (v instanceof TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); // setAllCaps() is only available from API 14, so the upper case is made manually if we are on a // pre-ICS-build if (textAllCaps) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString().toUpperCase(locale)); } } } } } private void scrollToChild(int position, int offset) { if (tabCount == 0) { return; } int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset; if (position > 0 || offset > 0) { newScrollX -= scrollOffset; } if (newScrollX != lastScrollX) { lastScrollX = newScrollX; scrollTo(newScrollX, 0); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isInEditMode() || tabCount == 0) { return; } final int height = getHeight(); // draw indicator line rectPaint.setColor(indicatorColor); // default: line below current tab View currentTab = tabsContainer.getChildAt(currentPosition); float lineLeft = currentTab.getLeft(); float lineRight = currentTab.getRight(); // if there is an offset, start interpolating left and right coordinates between current and next tab if (currentPositionOffset > 0f && currentPosition < tabCount - 1) { View nextTab = tabsContainer.getChildAt(currentPosition + 1); final float nextTabLeft = nextTab.getLeft(); final float nextTabRight = nextTab.getRight(); lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft); lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight); } canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint); // draw underline rectPaint.setColor(underlineColor); canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint); // draw divider dividerPaint.setColor(dividerColor); for (int i = 0; i < tabCount - 1; i++) { View tab = tabsContainer.getChildAt(i); canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint); } } private class PageListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { currentPosition = position; currentPositionOffset = positionOffset; scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); invalidate(); if (delegatePageListener != null) { delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { scrollToChild(pager.getCurrentItem(), 0); } if (delegatePageListener != null) { delegatePageListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { /** * Fix : ICON SELECTOR */ tabsContainer.getChildAt(currentPageSelected).setSelected(false); currentPageSelected = position; tabsContainer.getChildAt(position).setSelected(true); /** * Fix : ICON SELECTOR */ if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } } public void setIndicatorColor(int indicatorColor) { this.indicatorColor = indicatorColor; invalidate(); } public void setIndicatorColorResource(int resId) { this.indicatorColor = getResources().getColor(resId); invalidate(); } public int getIndicatorColor() { return this.indicatorColor; } public void setIndicatorHeight(int indicatorLineHeightPx) { this.indicatorHeight = indicatorLineHeightPx; invalidate(); } public int getIndicatorHeight() { return indicatorHeight; } public void setUnderlineColor(int underlineColor) { this.underlineColor = underlineColor; invalidate(); } public void setUnderlineColorResource(int resId) { this.underlineColor = getResources().getColor(resId); invalidate(); } public int getUnderlineColor() { return underlineColor; } public void setDividerColor(int dividerColor) { this.dividerColor = dividerColor; invalidate(); } public void setDividerColorResource(int resId) { this.dividerColor = getResources().getColor(resId); invalidate(); } public int getDividerColor() { return dividerColor; } public void setUnderlineHeight(int underlineHeightPx) { this.underlineHeight = underlineHeightPx; invalidate(); } public int getUnderlineHeight() { return underlineHeight; } public void setDividerPadding(int dividerPaddingPx) { this.dividerPadding = dividerPaddingPx; invalidate(); } public int getDividerPadding() { return dividerPadding; } public void setScrollOffset(int scrollOffsetPx) { this.scrollOffset = scrollOffsetPx; invalidate(); } public int getScrollOffset() { return scrollOffset; } public void setShouldExpand(boolean shouldExpand) { this.shouldExpand = shouldExpand; requestLayout(); } public boolean getShouldExpand() { return shouldExpand; } public boolean isTextAllCaps() { return textAllCaps; } public void setAllCaps(boolean textAllCaps) { this.textAllCaps = textAllCaps; } public void setTextSize(int textSizePx) { this.tabTextSize = textSizePx; updateTabStyles(); } public int getTextSize() { return tabTextSize; } public void setTextColor(int textColor) { this.tabTextColor = textColor; updateTabStyles(); } public void setTextColorResource(int resId) { this.tabTextColor = getResources().getColor(resId); updateTabStyles(); } public int getTextColor() { return tabTextColor; } public void setTypeface(Typeface typeface, int style) { this.tabTypeface = typeface; this.tabTypefaceStyle = style; updateTabStyles(); } public void setTabBackground(int resId) { this.tabBackgroundResId = resId; } public int getTabBackground() { return tabBackgroundResId; } public void setTabPaddingLeftRight(int paddingPx) { this.tabPadding = paddingPx; updateTabStyles(); } public int getTabPaddingLeftRight() { return tabPadding; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); currentPosition = savedState.currentPosition; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPosition = currentPosition; return savedState; } static class SavedState extends BaseSavedState { int currentPosition; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPosition = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPosition); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; }} ViewPagerAdapter.java which we need to supply to ViewPager import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import com.netdoers.zname.R;import com.netdoers.zname.utils.PagerSlidingTabStrip.IconTabProvider;/** * @author Vikalp Patel ([email protected]) * @category Ui Helper * */public class ViewPagerAdapter extends FragmentPagerAdapter /** * PAGERSLIDINGTABSTIPS */implements IconTabProvider { // Declare the number of ViewPager pages// final int PAGE_COUNT = 5; final int PAGE_COUNT = 3; /** * PAGERSLIDINGTABSTRIPS */ private final int[] ICONS = { R.drawable.tab_icon_zname_contact_selector, R.drawable.tab_icon_zname_friends_selector, R.drawable.tab_icon_zname_call_log_selector }; /** * SLIDINGTABLAYOUT */ /*private int[] imageResId = { R.drawable.tab_icon_zname_contact_selector, R.drawable.tab_icon_zname_friends_selector, R.drawable.tab_icon_zname_call_log_selected }; @Override public CharSequence getPageTitle(int position) { Drawable image = Zname.getApplication().getApplicationContext().getResources().getDrawable(imageResId[position]); image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight()); SpannableString sb = new SpannableString(" "); ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM); sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return sb; }*/ /** * SLIDINGTABLAYOUT */ /** * @param fm */ public ViewPagerAdapter(FragmentManager fm) { super(fm); } /* (non-Javadoc) * @see android.support.v4.app.FragmentPagerAdapter#getItem(int) */ @Override public Fragment getItem(int item) { switch (item) { // Open HomeFragment.java case 0: ContactsFragment homeFragment = new ContactsFragment(); return homeFragment; // Open PlaceOrderFragment.java case 1: GroupsFragment groupsFragment = new GroupsFragment(); return groupsFragment; case 2: CallLogsFragment callLogsFragment = new CallLogsFragment(); return callLogsFragment; } return null; } /* (non-Javadoc) * @see android.support.v4.view.PagerAdapter#getCount() */ @Override public int getCount() { // TODO Auto-generated method stub return PAGE_COUNT; } /** * PAGERSLIDINGTABSTRIPS */ @Override public int getPageIconResId(int position) { // TODO Auto-generated method stub return ICONS[position]; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24838669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026618/']} | jdg_70009 |
stackexchange | llm_judgeable_groundtruth_similarity | 9887 |
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:
My camera, which is powered by two AA batteries in series, would not power on. I removed the batteries, exchanged their locations, and the device worked again - for another 15 minutes or so. The temperature of the batteries did not change, and only about few minutes passed before I discovered this. Is there a physical explanation for this phenomenon?
Now provide the response and nothing else.
| First, your camera is not designed to work with batteries below a certain voltage. When it detects an excessively low battery voltage it turns itself off. That circuit stays in the "off" state until voltage is completely removed from the circuit. When you operate your camera, the current required by your camera varies according to what you do with it. So the typical current required by your camera is less than the maximum current. Theoretically batteries are supposed to have a voltage which doesn't depend on the current you draw from them, but this is only an approximation. In fact, all batteries have a negative V-I curve; if you increase the current taken from them, their voltage decreases. This effect is like having a resistor in series with the battery. It is called the "internal resistance" or impedance sometimes. Usually it is a very small effect but the dead voltage sensor in your camera can be very sensitive and so small effects can make a big difference. In addition, as a battery runs out of juice, its internal resistance increases [also see] and so the slope of its IV curve increases. As you use a camera, the current requirement goes up and down. As the batteries run out of power, eventually the maximum current usage will give a voltage that is too low for your battery's voltage detection circuit. At that time your camera will turn itself off. Your swapping the batteries had no effect on their voltage. (Okay, there might have been a very very slight effect from your hands warming the batteries slightly, but this effect is probably quite small compared to the effect I'm describing here.) Instead, what you did was to reset the dead-battery circuit. After 15 minutes, either you did something that increased the battery current enough to again trigger the dead-battery circuit, or possibly the small current drain caused the battery to become even more dead than it already was. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/9887', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2809/']} | jdg_70010 |
stackexchange | llm_judgeable_groundtruth_similarity | 1338892 |
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:
As a tourist in NY, I want to go from the Grand Central Station (42nd street and 4th Avenue) to Times Square (47th street and 7th Avenue). I needed my morning coffee, and wanted to go to a Starbucks that's located at 44th street and 5th avenue. If I only walk West and North, how many ways are there for me to get there?
Now provide the response and nothing else.
| I agree with Ofir's answer and would like to suggest an alternative, more general way to compute the number of ways to go from the cafe to Times square. Clearly, the total number of steps is $5$. Clearly, exactly two of those steps are in the direction west. You just need to choose these two steps, and the number of possible choices is $$\left(\begin{array}{c}5\\2\end{array}\right)=10.$$In general, if you need to go $n$ steps to the north and $k$ steps to the west, the number of possible ways for that will be$$\left(\begin{array}{c}n+k\\k\end{array}\right)=\left(\begin{array}{c}n+k\\n\end{array}\right)=\frac{(n+k)!}{n!k!}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1338892', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45247/']} | jdg_70011 |
stackexchange | llm_judgeable_groundtruth_similarity | 2114960 |
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 $1+x\ln(x+\sqrt{x^2+1})\geq \sqrt{1+x^2}\;\forall x \geq 0$ $\bf{My\; Try::}$ Means we have to prove $x\ln(x+\sqrt{x^2+1})\geq \sqrt{1+x^2}-1$ Put $\sqrt{x^2+1}+x = t\geq 1\;,$ Then $\displaystyle (\sqrt{x^2+1}-x) = \frac{1}{t}.$ So we get $\displaystyle x = \frac{t^2-1}{2t}$ and $\displaystyle \sqrt{x^2+1} = \frac{t^2+1}{2t}$ So we have to prove $\displaystyle \left(\frac{t^2-1}{2t}\right)\ln (t)\geq \frac{t^2+1-2t}{2t}\Rightarrow (t^2-1)\ln t \geq (t-1)^2$ So we have to prove $\displaystyle \ln(t)\geq \frac{t-1}{t+1}\forall t \geq 1$ Help required for proving above statement, Thanks
Now provide the response and nothing else.
| Let $p(x) = \sum_{k=0}^n a_kx^k$. If $A, B$ are similar, there is an invertible $S$ such that $B = SAS^{-1}$. Let $p(A) = P$. What is $p(B)$ ? $$p(B) = \sum_{k=0}^n a_kB^k = \sum_{k=0}^n a_k(SAS^{-1})^k = \\\sum_{k=0}^n a_kSA^kS^{-1} = S\left(\sum_{k=0}^n a_kA^k\right)S^{-1} = Sp(A)S^{-1} = SPS^{-1}$$ and the matrices are similar. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2114960', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']} | jdg_70012 |
stackexchange | llm_judgeable_groundtruth_similarity | 17541682 |
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 printf("%d",*(++(*a))); Undefined? Here a is pointer to a pointer to integer. I do not have anymore code other than this.It is an extension of This question which had created lots of confusions.Just want to know what is happening in this print.Does it depend on Architechture(32 Vs 64) or compiler versions. Hoping answers will be descriptive and clear.
Now provide the response and nothing else.
| If you break it down, it does this: Take the value of what a is pointing at: *a Increment by one ++(*a) Dereference that *(++(*a)) So, if the value+1 of what is stored at a is a valid pointer, this will work. Otherwise, the result is undefined and will most likely result in a runtime error. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17541682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2339452/']} | jdg_70013 |
stackexchange | llm_judgeable_groundtruth_similarity | 25154495 |
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 wondering why is the following code allowed in Java, without getting compilation error?In my opinion, this code breaks method signature by not returning any String .Could someone explain what I'm missing here? public class Loop { private String withoutReturnStatement() { while(true) {} } public static void main(String[] a) { new Loop().withoutReturnStatement(); }}
Now provide the response and nothing else.
| The final } of the method is unreachable - you only get a compilation error if it's possible to get to the end of the method without returning a value. This is more useful for cases where the end of the method is unreachable due to an exception, e.g. private String find(int minLength) { for (String string : strings) { if (string.length() >= minLength) { return string; } } throw new SomeExceptionIndicatingTheProblem("...");} The rule for this is in the JLS section 8.4.7 : If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1). Your method can't complete normally, hence there's no error. Importantly, it's not just that it can't complete normally, but the specification recognizes that it can't complete normally. From JLS 14.21 : A while statement can complete normally iff at least one of the following is true: The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true . There is a reachable break statement that exits the while statement. In your case, the condition expression is a constant with value true , and there aren't any break statements (reachable or otherwise) so the while statement can't complete normally. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25154495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3114613/']} | jdg_70014 |
stackexchange | llm_judgeable_groundtruth_similarity | 12045893 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are a lot different media queries for mobile screen sizes. It can be overwhelming to accomodate all of them when designing a responsive mobile site. Which are the most important ones to use when designing for mobile? I found this article that does a pretty good job of outlining the available media queries: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/ . /* Smartphones (portrait and landscape) ----------- */@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {/* Styles */}/* Smartphones (landscape) ----------- */@media only screen and (min-width : 321px) {/* Styles */}/* Smartphones (portrait) ----------- */@media only screen and (max-width : 320px) {/* Styles */}/* iPads (portrait and landscape) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {/* Styles */}/* iPads (landscape) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {/* Styles */}/* iPads (portrait) ----------- */@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {/* Styles */}/* Desktops and laptops ----------- */@media only screen and (min-width : 1224px) {/* Styles */}/* Large screens ----------- */@media only screen and (min-width : 1824px) {/* Styles */}/* iPhone 4 ----------- */@mediaonly screen and (-webkit-min-device-pixel-ratio : 1.5),only screen and (min-device-pixel-ratio : 1.5) {/* Styles */}
Now provide the response and nothing else.
| I'd recommend taking after Twitter's Bootstrap with just these four media queries: /* Landscape phones and down */@media (max-width: 480px) { ... }/* Landscape phone to portrait tablet */@media (max-width: 767px) { ... }/* Portrait tablet to landscape and desktop */@media (min-width: 768px) and (max-width: 979px) { ... }/* Large desktop */@media (min-width: 1200px) { ... } Edit: The original answer (above) was taken from Bootstrap version 2. Bootstrap has since changed their media queries in version 3. Notice that is there is no explicit query for devices smaller than 768px. This practice is sometimes called mobile-first. Everything outside of any media query is applied to all devices. Everything inside a media query block extends and overrides what is available globally as well as styles for all smaller devices. Think of it as progressive enhancement for responsive design. /* Extra small devices (phones, less than 768px) *//* No media query since this is the default in Bootstrap *//* Small devices (tablets, 768px and up) */@media (min-width: 768px) { ... }/* Medium devices (desktops, 992px and up) */@media (min-width: 992px) { ... }/* Large devices (large desktops, 1200px and up) */@media (min-width: 1200px) { ... } Check it out on Bootstrap 3's docs . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12045893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1460983/']} | jdg_70015 |
stackexchange | llm_judgeable_groundtruth_similarity | 46724260 |
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 compiles: int main() { const int x = 123; auto g = []() { std::cout << x << "\n"; }; g();} But this: int main(){ const float x = 123; auto g = []() { std::cout << x << "\n"; }; g();} produces: "error: 'x' is not captured" Why? I've tested it on both GCC (various versions from 5.0.0 to 8.0.0) and Clang (various versions from 4.0.0 to 6.0.0). It behaves the same in all cases.
Now provide the response and nothing else.
| Lambda's scope can implicitly capture variables within its reaching scope. Your variables are in the reaching scope, since they are local to the (main) function that defines the lambda. However, there are certain criteria in which variables can be captured via this mechanism, as mentioned in [expr.prim.lambda]/12 : A lambda-expression with an associated capture-default that does not explicitly capture this or a variable with automatic storage duration [..], is said to implicitly capture the entity (i.e., this or a variable ) if the compound-statement: -odr-uses ([basic.def.odr]) the entity, or - names the entity in a potentially-evaluated expression ([basic.def.odr]) where the enclosing full-expression depends on a generic lambda parameter declared within the reaching scope of the lambda-expression . The most important part is in [expr.const]/2.7 : A conditional-expression e is a core constant expression unless the evaluation of e , [..] would evaluate one of the following expressions: an lvalue-to-rvalue conversion ([conv.lval]) unless it is applied to: a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression. So const int is a core constant expression while const float is not. Moreover [expr.const]1826 mentions: A const integer initialized with a constant can be used in constant expressions, but a const floating point variable initialized with a constant cannot . Read more in Why is a const variable sometimes not required to be captured in a lambda? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46724260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1601719/']} | jdg_70016 |
stackexchange | llm_judgeable_groundtruth_similarity | 6330431 |
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 something in jquery that would allow me to differentiate between behavior on double click and single click? When I bind both to same element only the single click gets executed. Is there a way that wait for some time before execution of the single click to see if the user clicks again or not? Thanks :)
Now provide the response and nothing else.
| I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click. I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/ . Thanks for the foundation, John. I hope this alternate version is useful to others. var DELAY = 700, clicks = 0, timer = null;$(function(){ $("a").on("click", function(e){ clicks++; //count clicks if(clicks === 1) { timer = setTimeout(function() { alert("Single Click"); //perform single-click action clicks = 0; //after action performed, reset counter }, DELAY); } else { clearTimeout(timer); //prevent single-click action alert("Double Click"); //perform double-click action clicks = 0; //after action performed, reset counter } }) .on("dblclick", function(e){ e.preventDefault(); //cancel system double-click event });}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6330431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/632316/']} | jdg_70017 |
stackexchange | llm_judgeable_groundtruth_similarity | 824234 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is a callback function?
Now provide the response and nothing else.
| Developers are often confused by what a callback is because of the name of the damned thing. A callback function is a function which is: accessible by another function, and is invoked after the first function if that first function completes A nice way of imagining how a callback function works is that it is a function that is " called at the back " of the function it is passed into. Maybe a better name would be a "call after" function. This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes. Pseudocode: // A function which accepts another function as an argument// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)funct printANumber(int number, funct callbackFunction) { printout("The number you provided is: " + number);}// a function which we will use in a driver function as a callback functionfunct printFinishMessage() { printout("I have finished printing numbers.");}// Driver methodfunct event() { printANumber(6, printFinishMessage);} Result if you called event(): The number you provided is: 6I have finished printing numbers. The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first. Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked. Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc). | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/824234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_70018 |
stackexchange | llm_judgeable_groundtruth_similarity | 2881967 |
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:
First question on this site. Hope to ask/answer many more in the future. I'm currently self-studying An Introduction to Mathematical Logic by Richard E. Hodel and came across an interesting exercise. This is how it is introduced: Let F be a formal system, let FOR be the set of formulas of F, and let THM be the set of theorems of F. A subset I of FOR is said to be inductive if it satisfies these two conditions: (a) Every axiom of the formal system F is in I ; (b) If A 1 , ... , A n / B is a rule of inference of F, and each of the hypotheses A 1 , ... , A n are in I , then B is also in I . The exercise leads one to prove that THM is a subset of any arbitrary inductive set I , and that THM is the smallest inductive subset of FOR, which I already worked out successfully. The exercise does not imply, however, that THM = I . So my question is then, what would be an example of a member of an inductive set that is not a member of THM? And, more generally, when does a formula fail to be a theorem, but succeed in being a member of I ? I'm still on chapter 1 of the book, so maybe my question will be answered down the line, but I am still curious and think that this would help me understand the definitions of a formal system. So any help is appreciated. Thanks
Now provide the response and nothing else.
| An example of an inductive set is the set FOR of all formulas. This is strictly larger than THM in most cases of interest. (I see I've just repeated Daniel Schepler's comment here.) More generally, suppose that not every formula is a theorem, i.e. $\text{THM}\subsetneq\text{FOR}$. Then pick any formula $\varphi\in \text{FOR}\setminus \text{THM}$, and add it to $F$ as an additional axiom, obtaining a new formal system $F'$. Then the set $\text{THM}'$ of theorems of $F'$ is an inductive set which is larger than $\text{THM}$, since it includes $\varphi$. In fact, you can add any set of formulas to $F$ as new axioms, and the resulting set of theorems will be an inductive set. The case of $\text{FOR}$ occurs when you take every formula as an axiom, or just enough axioms to make the system inconsistent. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2881967', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/584030/']} | jdg_70019 |
stackexchange | llm_judgeable_groundtruth_similarity | 612568 |
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'd like to inline the following 2 commands: big_query_that_returns_text > in.txt$ printf '%s\n' "foo" "bar" | grep -f /dev/stdin in.txt that do work by finding foo and bar in in.txt but when I try to printf '%s\n' "foo" "bar" | grep -f /dev/stdin big_query_that_returns_text I receive zsh: argument list too long: grep I also tried var=`big_query_that_returns_text`printf '%s\n' "foo" "bar" | grep -f /dev/stdin $varprintf '%s\n' "foo" "bar" | grep -f /dev/stdin "$var" but I receive the same error.
Now provide the response and nothing else.
| This is a place for a process substitution : it's a block of code that acts like a file Pipe the big query results to grep's stdin big_query_that_returns_text | grep -f <(printf '%s\n' "foo" "bar") If the command to produce "foo" and "bar" is more complicated, you can help readability with arbitrary newlines inside the process substitution: big_query_that_returns_text \| grep -f <( printf '%s\n' "foo" "bar" ) | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/612568', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/435266/']} | jdg_70020 |
stackexchange | llm_judgeable_groundtruth_similarity | 10239346 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get a unique random number but i always get the same number every time i run the code. i will get 14 first then 6 but my list for holding all the used numbers doesn't seem to work.adding the 14 manually works but when i add randInt it doesn't work. const int numCards = 32; List<int> usedCards = new List<int>(); int randInt = 0; Random rand = new Random(numCards); usedCards.Add(14); do { randInt = rand.Next(0, numCards); MessageBox.Show(randInt.ToString(), "End Game", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } while (usedCards.Contains(randInt)); usedCards.Add(randInt);
Now provide the response and nothing else.
| Replace: Random rand = new Random(numCards); with Random rand = new Random(); Supplying a fixed seed value ( numCards always has the same value) in the Random constructor call will result in a predictable , reproducible sequence which is always the same for the same seed value, just like this (not quite but still the point is valid): For example using a fixed seed of 1 and drawing 10 numbers ranging from 0 to 100, on my machine always produces the sequence 24,11,46,77,65,43,35,94,10,64 Using no seed value on the other hand, the sequence becomes unpredictable. Without a seed value passed in, Random will generate a new seed value based on the current time, that's what you want to get a new sequence of random numbers - provided you don't initialize it again in fast order, that's why you should re-use Random instances instead of re-creating them every time. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10239346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1345363/']} | jdg_70021 |
stackexchange | llm_judgeable_groundtruth_similarity | 804115 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need some help/suggestions solving the following math problem. I don't know how to continue from step 2. Find x. 1.) $\displaystyle\left|\frac{x+1}{x}\right|< 1$ 2.) $\displaystyle\frac{|x+1|}{|x|} < 1$
Now provide the response and nothing else.
| $$\left|\frac{x+1}{x}\right|< 1$$ $$\left|1 + \frac{1}{x}\right|<1\\-1<1 + \frac{1}{x}<1\\ -2<\frac{1}{x}<0 \\\left(\frac{1}{x} >-2\right) \wedge \left(\frac{1}{x}<0\right)$$ Dismiss $\displaystyle x>0$ because of the second inequality. Hence $\displaystyle x<0$. From first inequality, $\displaystyle 1 < -2x\\\displaystyle x<-\frac{1}{2}$ Therefore $\displaystyle x<-\frac{1}{2}$ is the only solution. Credit to Zarrax who helped me realise what I had originally missed. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/804115', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114141/']} | jdg_70022 |
stackexchange | llm_judgeable_groundtruth_similarity | 30733 |
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 remember learning in school that one can construct any logical circuit from solely NAND or NOR gates. First of all, I am wondering if this is how it's actually done: i.e. when Intel makes a CPU, do they build all the registers, etc. using NAND / NOR gates, or do they have some other fancier way of doing things? Secondly, I'm wondering if constructing everything in this manner increases propagation delay compared to a circuit made using AND / OR / NOT gates as well. I know that when using PMOS / NMOS configurations to build gates, an AND or an OR comes out as 2 stages as opposed to a NAND or a NOR which are both only 1. Since I know you can make an AND from 2 cascaded NAND s and an OR from 2 cascaded NOR s, it seems as though propagation delay would not increase as long as manufacturers were using both NAND s and NOR s. Does anybody have any insight on all this, especially as to what is really done on manufactured ICs?
Now provide the response and nothing else.
| First of all, I am wondering if this is how it's actually done: i.e. when Intel makes a CPU, do they build all the registers, etc. using NAND / NOR gates, or do they have some other fancier way of doing things? Registers aren't made out of gates, most often they are dedicated circuits. They can be seen as made with inverters ( NOT ), but only to a certain extent. In CMOS technology, everlogic circuit is based on the inverter: NOR and NAND gates are just inverters with multiple inputs arranged in a clever way, basically. So the inverting gates are faster than non inverting ones, which are just inverting gates with a NOT at the output. Also in dynamic logic, it's simpler to cascade two inverting blocks than putting NOT gates everywhere. Consider that in some cases a circuit may be made out of separated blocks, so there may be a case in which the output is interfaced through one or more inverters for buffering. And there is another advantage in that: integration . Having a small number of different gates helps in laying out the circuit, and uniforming the performance. Often libraries include logic blocks at different levels of complexity: transistor, gate, operator, or higher. So, briefly, yes, fast processors are mostly using inverting gates. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/30733', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/9453/']} | jdg_70023 |
stackexchange | llm_judgeable_groundtruth_similarity | 552497 |
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:
When doing hypothesis testing, we calculate the distribution of test statistic (for example z ) under null hypothesis and then compare the actual z (one calculated from our data) to it. Why can't we instead calculate the distribution of z statistic from our data (by bootstraping mean, for example) (or calculate 95% CI) and compare it to 0, like it is shown below. I'd also see an example (or a simulation) where this fails, not just a theory behind it.
Now provide the response and nothing else.
| It is both meaningful and (usually) correct You are overcomplicating this by bringing probability into a simple non-probabilistic assertion. You need not invoke an omniscient deity in order to accept that there is a reality that exists independently of knowledge of it. (You seem to be operating under the assumption that reality is only admissible to discussion if there is an omniscient being with total knowledge of it; this is a reasonably common misconception of probability, which is examined in this related question .) The simplest rigorous examination of this statement is a non-statistical analysis based on looking at the underlying population of values pertaining to all the balls Babe Ruth ever hit. Let $X_1,...,X_N$ be the ordered career outcomes of all balls faced by Babe Ruth, with $X_i = \bullet$ denoting a strike and $X_i = \diamond$ denoting a home-run (we need not specify the notation for other possible outcomes). At the end of ball $n$ the number of balls until the next home-run is: $$B_n \equiv \min \{ k \in \mathbb{N} | X_{n+k} = \diamond \}.$$ Now, we know that a strike and a home-run are mutually exclusive --- i.e., no single ball can be both. Consequently, if ball $n+1$ is a strike (i.e., if $X_{n+1} = \bullet$ ) and if $B_n<\infty$ (i.e., if Babe has at least one home-run left in his career) then we can easily show that $B_{n+1} = B_n-1$ . This confirms Babe's statement that his strike brings him (one ball) closer to his next home-run. The only exception to this is when Babe gets to the point where he has already hit his last home-run, so that there are no more home-runs left to come in his career. At this point with have $B_n = \infty$ and getting a strike on ball $n+1$ still gives $B_{n+1} = \infty$ . In this latter case Babe is no closer to the next home-run, because there is no next home-run. Of course, at the time of Babe's last home-run, he probably didn't know that would be his last. (According to this historical account , Babe's last home-run was on 25 March 1935. He went on to play five more times without another home-run.) At that point his saying would be wrong, and looking back in hindsight we now know this. Ultimately, this statement by Babe Ruth is no more controversial than if he asserted, "The elapsing of time spent not getting a home-run brings me closer to my next home-run". That is of course also true, setting aside the situation where he has no future home-runs to get closer to. Finally, I do not agree with other comments/answers here that assert that this is the gambler's fallacy. It could (but might not) be a manifestation of the gambler's fallacy if he instead said, "Every strike makes it more likely that I will get a home-run in the future". That could be an example of the gambler's fallacy because it would assert that a bad outcome now makes a good outcome in the future more likely. (On the other hand, if strikes are not independent then it might not be.) In any case, merely asserting that the elapsing of time required for a bad outcome to occur now makes a subsequent good outcome closer in time is not the gambler's fallacy, and is not a fallacy at all. | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/552497', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/172965/']} | jdg_70024 |
stackexchange | llm_judgeable_groundtruth_similarity | 3389169 |
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 the Apache log configuration it is possible to specify that the HTTP auth user name should be logged. Most PHP scripts have their own, cookie-based authentication. Is it possible in PHP to provide Apache with a HTTP auth username for logging purposes, even if the authentication is cookie-based? If yes, how would the code look like? If not, what are alternatives?
Now provide the response and nothing else.
| Apache passes data between modules in notes . If you run PHP as an Apache module, you can use apache_note() to get and set notes. You can then include the %{note_name}n log format string to write this to the access log. This will not "leak" any data back to the client. In PHP: apache_note( 'username', $username ); In your server configuration: LogFormat "%h %l %{username}n %t \"%r\" %>s %b" common_with_php_usernameCustomLog logs/access_log common_with_php_username | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3389169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130121/']} | jdg_70025 |
stackexchange | llm_judgeable_groundtruth_similarity | 13937298 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
rather that populate a dropdown list with a query based on a look-up table, is there a way to have all the records from the look-up as the datasource and simply "go to" the record which would have been found in the query? thanks
Now provide the response and nothing else.
| What you're looking for is Kleisli category . It was originally developed to show that every monad can be constructed from two adjoint functors. The problem is that Haskell Functor is not a generic functor, it's an endo-functor in the Haskell category. So we need something different (AFAIK) to represent functors between other categories: {-# LANGUAGE FunctionalDependencies, KindSignatures #-}import Control.Arrowimport Control.Category hiding ((.))import qualified Control.Category as Cimport Control.Monadclass (Category c, Category d) => CFunctor f c d | f -> c d where cfmap :: c a b -> d (f a) (f b) Notice that if we take -> for both c and d we get an endo-functor of the Haskell category, which is just the type of fmap : cfmap :: (a -> b) -> (f a -> f b) Now we have explicit type class that represents functors between two given categories c and d and we can express the two adjoint functors for a given monad. The left one maps an object a to just a and maps a morphism f to (return .) f : -- m is phantom, hence the explicit kind is requirednewtype LeftAdj (m :: * -> *) a = LeftAdj { unLeftAdj :: a }instance Monad m => CFunctor (LeftAdj m) (->) (Kleisli m) where cfmap f = Kleisli $ liftM LeftAdj . return . f . unLeftAdj -- we could also express it as liftM LeftAdj . (return .) f . unLeftAdj The right one maps an object a to object m a and maps a morphism g to join . liftM g , or equivalently to (=<<) g : newtype RightAdj m a = RightAdj { unRightAdj :: m a }instance Monad m => CFunctor (RightAdj m) (Kleisli m) (->) where cfmap (Kleisli g) = RightAdj . join . liftM g . unRightAdj -- this can be shortened as RightAdj . (=<<) g . unRightAdj (If anybody know a better way how to express this in Haskell, please let me know.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13937298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299138/']} | jdg_70026 |
stackexchange | llm_judgeable_groundtruth_similarity | 4480195 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know how you can get the length of a polyline in google maps v3? At the moment I am using Haversine fomula but if the polyline meets the start then it calculates the shortest length. Does anyone know how I can calculate the polyline lenght? Thanks a lot. Mark
Now provide the response and nothing else.
| Extend Google Maps API with these functions: google.maps.LatLng.prototype.kmTo = function(a){ var e = Math, ra = e.PI/180; var b = this.lat() * ra, c = a.lat() * ra, d = b - c; var g = this.lng() * ra - a.lng() * ra; var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos (c) * e.pow(e.sin(g/2), 2))); return f * 6378.137; }google.maps.Polyline.prototype.inKm = function(n){ var a = this.getPath(n), len = a.getLength(), dist = 0; for (var i=0; i < len-1; i++) { dist += a.getAt(i).kmTo(a.getAt(i+1)); } return dist; } and then you can call: var length_in_km = yourPoly.inKm(); source: http://groups.google.com/forum/#!topic/google-maps-js-api-v3/Op87g7lBotc | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4480195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/359425/']} | jdg_70027 |
stackexchange | llm_judgeable_groundtruth_similarity | 7258993 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
>>> import os>>> os.chdir('c:/python27')>>> os.listdir('c:')['Tools', 'include', 'python.exe', 'libs', 'DLLs', 'Lib', 'NEWS.txt','w9xpopen.exe', 'Doc', 'pythonw.exe', 'LICENSE.txt', 'README.txt', 'tcl']>>> os.listdir('c:/')['users', 'Program Files', 'Python27', 'windows'] Why is the "/" after "c:" affecting the outcome? Is there a way to get os.listdir('c:') to return the contents of "c:/"?
Now provide the response and nothing else.
| This is not specific to Python, it's a Windows question at heart. In Windows C: and C:\ (or, alternatively C:/ ) have quite different meanings: C: refers to the current directory on the drive C: C:\ (and C:/ ) refers to the root directory of the drive C: While UNIX-like operating systems simply have a "current directory", Windows has two separate notions: the current drive and the current directory per drive So the current drive could be D: , the current directory on C: could be \Windows (effectively C:\Windows ) and the current directory on D: could be \Data (effectively D:\Data ). In this scenario resolution would work like this: . would refer to D:\Data \ would refer to D:\ C: would refer to C:\Windows C:\Foo would refer to C:\Foo So if you want to have information about a specific directory, you should always use a full path including both a drive and a directory, such as C:\ . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7258993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/794960/']} | jdg_70028 |
stackexchange | llm_judgeable_groundtruth_similarity | 8958310 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I match subject via a PHP preg_match() regular expression pattern in this HTML code: <table border=0> <tr> <td> <h2>subject</h2> </td> All the whitespaces and newlines are left on purpose. So the problem is in extracting subject name using some multiple line pattern.
Now provide the response and nothing else.
| If you're looking for (e.g.) a h2 tag nested within a td tag where there's only whitespace in between the two, just use \s which includes spaces, newlines, etc. eg:: preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#i',$str,$matches);// result is in $matches[1] See it in action here . For your interest, here is a list of different modifiers you can pass in to preg_* functions. Flags that may interest you are: s ("dotall") : this one makes . match every character, including newlines. So, say your <h2>.....</h2> was spread over multiple lines. Then you'd have to do preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#is',$str,$matches); in order to have the .* go over multiple lines (see the extra s at the end of the regex?). m ("multiline") : this one just lets ^ and $ match start/end of line instead of just the start/end of string . You only really need it if you're using ^ and $ in your pattern and want them to match the start/end of each individual line in your input. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8958310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1115626/']} | jdg_70029 |
stackexchange | llm_judgeable_groundtruth_similarity | 2465328 |
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 AVAudioRecorder in the iPhone SDK can be used to get the peak and average power for a channel, in decibels. The range is between 0db to 160db. What is the calculation used to convert this into a scale between 0 - 10 or something similar that can be used for an audio level meter?
Now provide the response and nothing else.
| The range is from -160 dB to 0 dB. You probably want to display it in a meter that goes from -90 dB to 0 dB. Displaying it as decibels is actually more useful than as a linear audio level, because the decibels are a logarithmic scale, which means that it more closely approximates how loud we perceive a sound. That said, you can use this to convert from decibels to linear: linear = pow (10, decibels / 20); and the reverse: decibels = log10 (linear) * 20; The range for the above decibels is negative infinity to zero, and for linear is 0.0 to 1.0. When the linear value is 0.0, that is -inf dB; linear at 1.0 is 0 dB. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2465328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257550/']} | jdg_70030 |
stackexchange | llm_judgeable_groundtruth_similarity | 960389 |
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 encountered a problem in a C program running on an AVR microcontroller (ATMega328P). I believe it is due to a stack/heap collision but I'd like to be able to confirm this. Is there any way I can visualise SRAM usage by the stack and the heap? Note: the program is compiled with avr-gcc and uses avr-libc. Update: The actual problem I am having is that the malloc implementation is failing (returning NULL ). All malloc ing happens on startup and all free ing happens at the end of the application (which in practice is never since the main part of the application is in an infinite loop). So I'm sure fragmentation is not the issue.
Now provide the response and nothing else.
| You say malloc is failing and returning NULL: The obvious cause which you should look at first is that your heap is "full" - i.e, the memory you've asked to malloc cannot be allocated, because it's not available. There are two scenarios to bear in mind: a: You have a 16 K heap, you've already malloced 10 K and you try and malloc a further 10K. Your heap is simply too small. b: More commonly, you have a 16 k Heap, you've been doing a bunch of malloc/free/realloc calls and your heap is less than 50% 'full': You call malloc for 1K and it FAILS - what's up? Answer - the heap free space is fragmented - there isn't a contigous 1K of free memory that can be returned. C Heap managers can not compact the heap when this happens, so you're generally in a bad way. There are techniques to avoid fragmentation, but it's difficult to know if this is really the problem. You'd need to add logging shims to malloc and free so that you can get an idea of what dynamic memory operations are being performed. EDIT: You say all mallocs happen at startup, so fragmentation isn't the issue. In which case, it should be easy to replace the dynamic allocation with static. old code example: char *buffer;void init(){ buffer = malloc(BUFFSIZE);} new code: char buffer[BUFFSIZE]; Once you've done this everywhere, your LINKER should warn you if everything cannot fit into the memory available. Don't forget to reduce the heap size - but beware that some runtime io system functions may still use the heap, so you may not be able to remove it entirely. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/960389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4023/']} | jdg_70031 |
stackexchange | llm_judgeable_groundtruth_similarity | 12652798 |
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 load a png image as a drawable from my device sd card.I use the following function but it doesn't work: public Drawable getDrawable(){return new BitmapDrawable(imagePath);} The image path is: mnt/sdcard/MyFolder/image.png The app crashes when I try calling that method, how should I load my png image located in my sdcard and cast it into a Drawable object?
Now provide the response and nothing else.
| There is actually a BitmapDrawable constructor straight from file path. The method you are using is depricated. Try: Drawable myDrawable = new BitmapDrawable(getResources(), pathName); If this doesnt work, Try getting a bitmap and creating a drawable from it: The bitmap can be created with decodeFile You can use it like this: Bitmap myBitmap = BitmapFactory.decodeFile(pathName); Then you can use the bitmap for drawing etc. to convert Bitmap to drawable use Drawable myDrawable = new BitmapDrawable(getResources(), myBitmap); Take a look Here (Bitmaps) and Here (Bitmap Drawables) for more info. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12652798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203043/']} | jdg_70032 |
stackexchange | llm_judgeable_groundtruth_similarity | 282451 |
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 .net transaction with a SQL insert to a SQL Server 2005 database. The table has an identity primary key. When an error occurs within the transaction, Rollback() is called. The row inserts are rolled back correctly, however the next time I insert data to the table, the identity is incremented as if the rollback never occurred. So essentially there are gaps in the identity sequence. Is there any way to have the Rollback() method reclaim the missing identity? Am I not approaching this the right way?
Now provide the response and nothing else.
| If you think about it, the auto-increment number should not be transactional. If other transactions had to wait to see if the auto-number was going to be used or "rolled back", they would be blocked by the existing transaction using the auto-number. For example, consider my psuedo code below with table A using an auto-number field for the ID column: User 1------------begin transactioninsert into A ...insert into B ...update C ...insert into D ...commitUser 2-----------begin transactioninsert into A ...insert into B ...commit If user 2's transaction starts a millisecond after user 1's, then their insert into table A would have to wait for user 1's entire transaction to complete just to see if the auto-number from the first insert into A was used. This is a feature, not a bug. I would recommend using another scheme to generate auto-numbers if you need them to be tightly sequential. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/282451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19763/']} | jdg_70033 |
stackexchange | llm_judgeable_groundtruth_similarity | 12628585 |
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 add some calculation inside my case statement to dynamically create the contents of a new column but I get the error: Column 'Test1.qrank' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. This is the code I'm working on case when test1.TotalType = 'Average' then Test2.avgscore when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank)) else cntend as displayscore I did try to group but it didn't work. Any hints?
Now provide the response and nothing else.
| The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select. Example This one works! SELECT t.device, SUM(case when transits.direction = 1 then 1 else 0 end) , SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t where t.device in ('A','B') group by t.device This one not (omitted t.device from the select) SELECT SUM(case when transits.direction = 1 then 1 else 0 end) , SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t where t.device in ('A','B') group by t.device This will produce your error complaining that I'm grouping for something that is not included in the select Please, provide all the query to get more support. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12628585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/953726/']} | jdg_70034 |
stackexchange | llm_judgeable_groundtruth_similarity | 20091826 |
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 WCF layer and my Domain Model is behind this WCF layer. I am using Nhibernate as an ORM tool and all my business logic/ Data Access etc will be behind this WCF layer. I am exposing DTO to my clients. I have below questions 1) Should i create DTOs? is there any harm in exposing entities directly to wcf clients as my entities would also have business logic methods also in doing so i would have to corrupt my entitiy object with WCF attributes which i think is not good? 2) If i expose DTO, should i be validating DTO as well as Entity. If i validate only DTO then i am not providing any input validations for my Enitity object . is this ok? 3) Should i consider validating the DTO in the Application Service layer (WCF layer) using Schema validation? or Should i use IValidator Approach given in article [blog]: http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/ as shown by Jimmy Bogard Having DTO at times seem redundant to me but i can use it to club details from one or more entities. I would be exposing this service to various client and thus my DTO will be deriving from some base dto having credential details which i would check for each incoming request before my actual wcf method call (probably using IEndpointBehaviour and IParamInspector) Edit Based on the response I kind of now agree to retain the DTO layer, Here is an exmaple so that scenario become more explicit Say I have CreateCustomer method accepting CustomerDetailsDTO in my WCF Application Service Layer which may be called by an MVC application.There are some input validations like Input Validations: i)Name length should be greater than 2 but less than 50ii) Age is mandatory and cann not be less than 18(Different other field validations)etc Business Validations: There could then be some business rules to check for dupliate customer based on say email or some other factor whcih i think should be part of my Domain business logic and should reside in CustomerEntity class. Should Input Validation be only applied at service interface layer as we get DTO from client or it should also be applied on CustomerEntity
Now provide the response and nothing else.
| 1) Should i create DTOs? is there any harm in exposing entities directly to wcf clients as my entities would also have business logic methods also in doing so i would have to corrupt my entitiy object with WCF attributes which i think is not good? Yes, SOA requires data contracts. They can be more or less formalized (CSV, JSON, XSD, WSDL, WADL even HTML or a txt file) but if you can't find an agreement on such contracts, you shouldn't adopt any "service" technology or technique (nor any other IPC for what it matter). Remoting was the only technology that tried to avoid such requirement. It was an amazing idea, in abstract, but concretely it didn't work. 2) If i expose DTO, should i be validating DTO as well as Entity. If i validate only DTO then i am not providing any input validations for my Enitity object . is this ok? You should validate the "contract", not the business rules. For example a WCF DTO can require some fields to be populated, and I would use ArgumentNullException in the constructors. But you should remember that DTOs serve to transfer data. If you have a numeric field that for some strange reason have to be transferred as a string, you can validate it, for example preventing the inizialization of the DTO. 3) Should i consider validating the DTO in the Application Service layer (WCF layer) using Schema validation? or Should i use IValidator Approach given in article [blog]: http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/ as shown by Jimmy Bogard If you need a domain model (that means that you need to hire an expert to understand the application purpose), it has to be the only responsible for business rules . Thus for simple validations, you shouldn't need any validation framework. What you need are expressive exceptions that can be mapped easily to properly defined faults. edit to answer the new questions In WCF, I often use input validation in the DTO constructors, so that the client can not send "invalid requests". This has many advantages, for example the client can't use invalid input to configure a DOS attack, for example. Moreover if you have a large number of clients this can reduce the network load, and make the user experience a bit better since he doesn't need to wait for a server response just to know that he forgot a the @ in an email field. But actually being older than 18 is a business rule, not an input rule. An input rule could be: "the Age field must be greater than Zero", because negative age are not possible, and a zero age sound too much like an user error (and it is the int32 default value). However contract validation is not enough . If the age is relevant in your domain you will have a Age struct, wrapping an UInt32 (thus the input rule before). Why wrap an UInt32 ? For example because in your domain model you know that the sum of two users's age has no meaning. Yes, you check that number at most 3 times (one on the client and two on the server), but that's the right thing to do, here. The DTOs could evolve indipendently of the domain model, and a domain model cannot risk unexpected behaviour (or you don't need a domain model at all). To get an idea of a business rule, think of a medical record application that keep track of some specialized kind of therapy: the command void Prescribe(Age patientAge, AntibioticPrescription prescription) could check both the patientAge argument to be greater than the previous prescription's age. That's a business rule. Another business rule should check for dangerous interactions between the current prescription and the previous one. If so, this command should document and throw 3 exceptions: ArgumentNullException , when the prescription is null (assuming it's a reference type) InconsistentAge , when the patientAge provided is lower than the last one MortalPrescription , when such prescription could kill the patient. Such exceptions express preconditions that are business rules (except the argument null, that is there to fail as fast as possible when programmers introduce some kind of bugs). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20091826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2717616/']} | jdg_70035 |
stackexchange | llm_judgeable_groundtruth_similarity | 39923 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This should be a trivial question for mathematicians but not for typical physicists. I know that the spectrum of a linear operator on a Banach space splits into the so-called "point," "continuous" and "residual" parts [I gather that no boundedness assumption is needed but I could be wrong]. I further know that the point spectrum coincides with the set of eigenvalues of the operator. It seems from the terminology that the point spectrum is a discrete set of isolated point and that the eigenvalues cannot form a continuum. But I haven't been able to find a clear statement in a math reference about this. Actually, I'm mostly interested in self-adjoint operators on a Hilbert space; so a simpler version of my question would be: Can a self-adjoint operator have a continuous set of eigenvalues? And if yes, under what conditions do the eigenvalues have to be discrete? I appreciate any help.
Now provide the response and nothing else.
| Eigenvectors for different eigenvalues of a self-adjoint operator are orthogonal. In a separable Hilbert space, any orthogonal set is countable. So a self-adjoint operator on separable Hilbert space has only countably many eigenvalues. (As noted, this does not mean the spectrum is countable.) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/39923', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9504/']} | jdg_70036 |
stackexchange | llm_judgeable_groundtruth_similarity | 49202 |
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 am plotting to data curves using ListLinePlot. I like the look of Filling, but this is going to be printed, so I want something both black and white friendly, but giving more definition and separation than changing the opacity of the filling. Ideally, I would either have one hatched and the other filled solid gray, or both hatched in opposite directions or something such that they can be identified separately. This is what I have so far that I may just use if I can't find anything better: data1 = exPDMIABSA[[1]];data2 = exPDMIAwater[[1]];ListLinePlot[{data1, data2}, PlotStyle -> {Black, Directive[Dashed, Black]}, Filling -> Axis, FillingStyle -> Directive[Opacity[0.7], Gray]] Three related questions I've found are RegionPlot (or FillingStyle) using hash lines? and Filling a polygon with a pattern of insets and How can I make hatching filling of plot but none seems to address this situation. They seem to be dealing with shapes and (region)plots and not ListPlots. While it is entirely possible that they are very closely related, I'm not sure how to use any of those answers for my situation. Thanks
Now provide the response and nothing else.
| This is what I've ended up doing. data1 = exPDMIABSA[[1]];data2 = exPDMIAwater[[1]];Show[ListLinePlot[{data1, data2}, PlotStyle -> {Directive[Dashed, Black], Black}, Filling -> {2 -> Axis}, FillingStyle -> Gray], RegionPlot[ y < Interpolation[data1, InterpolationOrder -> 1][x] && y > 0, {x, 300, 375}, {y, 0, 17000}, Mesh -> 50, MeshFunctions -> {1000 #1 - #2 &}, BoundaryStyle -> None, MeshStyle -> Thickness[.005], PlotStyle -> Transparent]] The RegionPlot is based on this question after a suggestion in the comments to the question by Szabolcs . Of course the same could be done for the other region in the opposite direction by switching the sign in the MeshFunctions . Also, because of the scale, the slope of the MeshFunctions was changed. The number of hatchings can be changed by changing Mesh . The default lines were a little thin for me so I thickened them with MeshStyle -> Thickness[.005] . For certain circumstances, it might be easier to define interpolation functions for each data set such as data1func = Interpolation[data1, InterpolationOrder -> 1] and just Plot that. To me this seemed a little simpler, faster, and more general than the answer by Kuba to this question. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/49202', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/14780/']} | jdg_70037 |
stackexchange | llm_judgeable_groundtruth_similarity | 37912 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It is my understanding that the state and national government of the United States are separate entities (that's what federalism is, combining smaller states into a larger one). Could unhappy citizens overthrow a state government while still remaining on favorable terms with the national government? Could state militaries overthrow their own state government and establish a new state government and still be on good terms with the national government? Has this been done in the past? Has this happened in other federations around the world?
Now provide the response and nothing else.
| Can state governments be overthrown without national government involvement? Yes. It happens sometimes when there's an election. Could state militaries over throw their own state government and establish a new state government and still be on good terms with the national government? Most likely no. Each state also has a constitution, and prescribes how changing the makeup of each state government should occur. Should a state's national guard (or other state-level militia) attempt a state level "coup," the Supreme Court of the state would most likely rule that such an action violated the state's constitution. In all likelihood, the action from the perspective of the federal government I believe would be viewed not much differently as general insurrection and would be responded to. Of course, each state is different and has different constitutions. For example, New Hampshire's contains the Right of Revolution : Government being instituted for the common benefit, protection, and security, of the whole community, and not for the private interest or emolument of any one man, family, or class of men; therefore, whenever the ends of government are perverted, and public liberty manifestly endangered, and all other means of redress are ineffectual, the people may, and of right ought to reform the old, or establish a new government. The doctrine of nonresistance against arbitrary power, and oppression, is absurd, slavish, and destructive of the good and happiness of mankind. Since this is part of the state constitution, the state Supreme Court may be swayed by the arguments of the state militia depending on the exact circumstances. Other state constitutions contain similar clauses, a good listing of states with a positive right of revolution can be found on Wikipedia . If the state Supreme Court isn't swayed, the federal Supreme Court might, but the wording presents a bit of a conundrum since if we're appealing to the courts then by definition that means that redress is available. This redress also becomes available every time there is an election. As long as the people have faith in their state level elections, then the choice of the make-up of a government still belongs to the people. See also Article 4, Clause 1 of the U.S. Constitution: The United States shall guarantee to every State in this Union a Republican Form of Government [...] A military overthrowing a popularly elected government is not a republican form of government. Has this been done in the past? Not in the manner are describing, but the legislatures of many states attempted to dissolve the union between them during the Civil War, which was later ruled unconstitutional by the Supreme Court. I doubt a state-level militia would get favorable treatment for attempting to do something similar. | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/37912', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/24505/']} | jdg_70038 |
stackexchange | llm_judgeable_groundtruth_similarity | 248545 |
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 listbox, and I have the following ItemTemplate for it: <DataTemplate x:Key="ScenarioItemTemplate"> <Border Margin="5,0,5,0" Background="#FF3C3B3B" BorderBrush="#FF797878" BorderThickness="2" CornerRadius="5"> <DockPanel> <DockPanel DockPanel.Dock="Top" Margin="0,2,0,0"> <Button HorizontalAlignment="Left" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /> <Label Content="{Binding Path=Name}" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="white" /> <Label HorizontalAlignment="Right" Background="#FF3C3B3B" Content="X" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /> </DockPanel> <ContentControl Name="designerContent" Visibility="Collapsed" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"> </ContentControl> </DockPanel> </Border></DataTemplate> As you can see the ContentControl has Visibility set to collapsed. I need to define a trigger that causes the Visibility to be set to "Visible" when the ListItem is selected, but I can't figure it out. Any ideas? UPDATE: Of course I could simply duplicate the DataTemplate and add triggersto the ListBox in question to use either one or the other, but I want to prevent duplicating this code.
Now provide the response and nothing else.
| You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected: <ContentControl x:Name="designerContent" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"> <ContentControl.Style> <Style TargetType="{x:Type ContentControl}"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style></ContentControl> Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this: <DataTemplate x:Key="ScenarioItemTemplate"> <DataTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"> <Setter TargetName="designerContent" Property="Visibility" Value="Visible"/> </DataTrigger> </DataTemplate.Triggers> ...</DataTemplate> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/248545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/28149/']} | jdg_70039 |
stackexchange | llm_judgeable_groundtruth_similarity | 1541239 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any techniques/proposals to enforce unique constraints? Yes, we can create key that's unique, but we cannot change key and keys and also this approach is not suitable for complicated validation (separate unique login, separate unique email, etc...) For example, an Account should haveunique login and email. Deriving a keyfrom this fields will result ininconsistency: key1: "[email protected]", { email: "[email protected]", login: "john"}key2: "[email protected]", { email: "[email protected]", login: "mary"} Looking good, but: key1: "[email protected]", { email: "[email protected]", login: "mary"}key2: "[email protected]", { email: "[email protected]", login: "mary"} Oops, now we have 2 accounts with login: "mary"
Now provide the response and nothing else.
| This is one of the less fun bits of CouchDB. The best way I've found for handling unique fields that can change (like in your user example) is to create "pointer" documents with the unique values as a component of the key, and then use those to let you claim unique values. The important part of doing this is having a predictable key for the primary document, then saving the unique field claim documents prior to saving the primary (and letting key conflicts prevent the primary document from saving). Given a user with a unique username and unique email, your primary documents might look like this: user-1234: { username: "kurt", email: "kurt@localhost" }user-9876: { username: "petunia", email: "[email protected]" } The unique field pointers would look something like this: user-username-kurt: { primary_doc: "user-1234" }user-email-kurt@localhost: { primary_doc: "user-1234" }user-username-petunia: { primary_doc: "user-9876" }[email protected]: { primary_doc: "user-9876" } Creating or updating a user would take these steps: Prep your user document, generate a key for it if necessary Save a "pointer" document for each changed unique field If saving any of those fails, stop and fix errors Save primary user document Step 3 will take some thought. For instance, you won't want to try claim unique values for fields that haven't changed. You could, but then you'd have to put some additional logic in to handle a case where you're claiming a value for a user that already owns that value. Step 3 would be a good place to let people take old claimed values as well. If one user has "released" the username kurt, for instance, I can just update that particular document to point to my new key after verifying that it's no longer in use. The alternative is to clear out claimed unique values when they change. I'm not sure which would be less work, really. Leaving stale claimed values in makes the most sense to me. The interesting thing about this solution is that you don't need to use those pointer documents for anything once they're created. You can create views as normal on your user docs, and use them to query by email or username. This setup also allows you to do relationships without having to worry about cascading user keys. I don't know about you, but my user documents are referenced by just about every other document in the system. Changing a user key would be a massive pain in the ass. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1541239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152326/']} | jdg_70040 |