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
5935546
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: HI I want to align the radio buttons horizontally. By default django forms displays in vertical format. feature_type = forms.TypedChoiceField(choices = formfields.FeatureType, widget = forms.RadioSelect) Is there any special parameter that we can pass for radio buttons alignment? Thanks in advance Now provide the response and nothing else.
Thats the behavior of the RadioField . If you want it rendered horizontally, create a horizontal renderer, like something as follows: from django.utils.safestring import mark_safeclass HorizontalRadioRenderer(forms.RadioSelect.renderer): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))class ApprovalForm(forms.Form): approval = forms.ChoiceField(choices=APPROVAL_CHOICES, initial=0, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer), )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5935546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727495/']}
jdg_80741
stackexchange
llm_judgeable_groundtruth_similarity
160196
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: apt is using two locations to store downloaded packages and other files: /var/lib/apt/lists/var/cache/apt/archives These folders can get quite big, even when using apt-get clean regularly. My /var is on a separate partition and is relatively small. Is it possible to configure apt, so that is stores its files somewhere ales (i.e. in /home/apt/ ? Now provide the response and nothing else.
You have a few options. Change the settings in /etc/apt/apt.conf dir::state::lists /path/to/new/directory;dir::cache::archives /path/to/new/directory; Mount a larger partitions at the current directories (if you have spare space for a partition): # mount /dev/sda5 /var/lib/apt # mount /dev/sda6 /var/cache/apt Of course, for the above to work, you'll need to create partitions and filesystems first. Symlink to another location (if you have no space for new partitions, but space within current partitions): # ln -s /home/apt/lib /var/apt/lib# ln -s /home/apt/cache /var/apt/cache Or as above, but using bind mounts: # mount --bind /home/apt/lib /var/apt/lib# mount --bind /home/apt/cache /var/apt/cache
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/160196', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/43007/']}
jdg_80742
stackexchange
llm_judgeable_groundtruth_similarity
3124615
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: Q) Let, $a_{n} \;=\; \left ( 1-\frac{1}{\sqrt{2}} \right ) ... \left ( 1- \frac{1}{\sqrt{n+1}} \right )$ , $n \geq 1$ . Then $\lim_{n\rightarrow \infty } a_{n}$ (A) equals $1$ (B) does not exist (C) equals $\frac{1}{\sqrt{\pi }}$ (D) equals $0$ My Approach :- I am not getting a particular direction or any procedure to simplify $a_{n}$ and find its value when n tends to infinity. So, I tried like this simple way to substitute values and trying to find the limiting value :- $\left ( 1-\frac{1}{\sqrt{1+1}} \right ) * \left ( 1-\frac{1}{\sqrt{2+1}} \right )*\left ( 1-\frac{1}{\sqrt{3+1}} \right )*\left ( 1-\frac{1}{\sqrt{4+1}} \right )*\left ( 1-\frac{1}{\sqrt{5+1}} \right )*\left ( 1-\frac{1}{\sqrt{6+1}} \right )*\left ( 1-\frac{1}{\sqrt{7+1}} \right )*\left ( 1-\frac{1}{\sqrt{8+1}} \right )*.........*\left ( 1-\frac{1}{\sqrt{n+1}} \right )$ = $(0.293)*(0.423)*(0.5)*(0.553)*(0.622)*(0.647)*(0.667)* ....$ =0.009*... So, here value is tending to zero. I think option $(D)$ is correct. I have tried like this $\left ( \frac{\sqrt{2}-1}{\sqrt{2}} \right )*\left ( \frac{\sqrt{3}-1}{\sqrt{3}} \right )*\left ( \frac{\sqrt{4}-1}{\sqrt{4}} \right )*.......\left ( \frac{\sqrt{(n+1)}-1}{\sqrt{n+1}} \right )$ = $\left ( \frac{(\sqrt{2}-1)*(\sqrt{3}-1)*(\sqrt{4}-1)*.......*(\sqrt{n+1}-1)}{{\sqrt{(n+1)!}}} \right )$ Now, again I stuck how to simplify further and find the value for which $a_{n}$ converges when $n$ tends to infinity . Please help if there is any procedure to solve this question. Now provide the response and nothing else.
The hint: $$0<a_n=\prod_{k=1}^n\left(1-\frac{1}{\sqrt{k+1}}\right)<\prod_{k=1}^n\left(1-\frac{1}{k+1}\right)=\frac{1}{n+1}\rightarrow0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3124615', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/559765/']}
jdg_80743
stackexchange
llm_judgeable_groundtruth_similarity
28065569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: using a example from here I just come up with part of a solution. Now I can sum the values with the value of the above row, but in this case I just need to sum values for the same SE_NOME column. Here is a example on sqlfiddle: It's a balance, not a total as below. | SE_NOME | PNT |BALANCE||---------|-----|-------|| ARP | 100 | 100 || ARP | 500 | 600 || DEE | 200 | 200 || DEE | 200 | 400 || DEE | 200 | 800 || DFF | 300 | 300 || HGG | 400 | 400 || HGG | 400 | 800 || HGG | 400 | 1200 | Now provide the response and nothing else.
You can use doesntHave and specify the boolean operator: $products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get(); Actually you only need whereDoesntHave if you want to pass in a closure to filter the related models before checking if any of them exist. In case you want to do that you can pass the closure as third argument: $products = Product::doesntHave('categories', 'or', function($q){ $q->where('active', false);})->doesntHave('countries', 'or')->get();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28065569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4475288/']}
jdg_80744
stackexchange
llm_judgeable_groundtruth_similarity
3820666
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to find the links on a page. my regex is: /<a\s[^>]*href=(\"\'??)([^\"\' >]*?)[^>]*>(.*)<\/a>/ but seems to fail at <a title="this" href="that">what?</a> How would I change my regex to deal with href not placed first in the a tag? Now provide the response and nothing else.
Reliable Regex for HTML are difficult . Here is how to do it with DOM : $dom = new DOMDocument;$dom->loadHTML($html);foreach ($dom->getElementsByTagName('a') as $node) { echo $dom->saveHtml($node), PHP_EOL;} The above would find and output the "outerHTML" of all A elements in the $html string. To get all the text values of the node, you do echo $node->nodeValue; To check if the href attribute exists you can do echo $node->hasAttribute( 'href' ); To get the href attribute you'd do echo $node->getAttribute( 'href' ); To change the href attribute you'd do $node->setAttribute('href', 'something else'); To remove the href attribute you'd do $node->removeAttribute('href'); You can also query for the href attribute directly with XPath $dom = new DOMDocument;$dom->loadHTML($html);$xpath = new DOMXPath($dom);$nodes = $xpath->query('//a/@href');foreach($nodes as $href) { echo $href->nodeValue; // echo current attribute value $href->nodeValue = 'new value'; // set new attribute value $href->parentNode->removeAttribute('href'); // remove attribute} Also see: Best methods to parse HTML DOMDocument in php On a sidenote: I am sure this is a duplicate and you can find the answer somewhere in here
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3820666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338183/']}
jdg_80745
stackexchange
llm_judgeable_groundtruth_similarity
7828867
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: a = [1, 2, 3, 1, 2, 3]b = [3, 2, 1, 3, 2, 1] a & b should be considered equal, because they have exactly the same elements, only in different order. The thing is, my actual lists will consist of objects (my class instances), not integers. Now provide the response and nothing else.
O(n) : The Counter() method is best (if your objects are hashable): def compare(s, t): return Counter(s) == Counter(t) O(n log n) : The sorted() method is next best (if your objects are orderable): def compare(s, t): return sorted(s) == sorted(t) O(n * n) : If the objects are neither hashable, nor orderable, you can use equality: def compare(s, t): t = list(t) # make a mutable copy try: for elem in s: t.remove(elem) except ValueError: return False return not t
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7828867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/995421/']}
jdg_80746
stackexchange
llm_judgeable_groundtruth_similarity
22706765
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 fully bind twitter bootstrap modal with knockout. By fully bind I mean that I want every close interaction with modal dialog to work with knockout. I have seen some of the questions , which partially bind them (for example this one does not allow esc). I am using almost identical binding (which I actually found elsewhere) ko.bindingHandlers.modal = { init: function (element, valueAccessor) { $(element).modal({ show: false }); }, update: function (element, valueAccessor) { var value = valueAccessor(); if (ko.utils.unwrapObservable(value)) { $(element).modal('show'); } else { $(element).modal('hide'); } }} But the problem is that not everything work in my Fiddle . As you see if you close Modal with Close button, you can fire this modal again. But if you close it with Esc key, or with clicking on background, or on the X button, you can not open Modal again. I know that the problem is due to the fact that when I close modal with other means (it is not changing observable and therefore when I fire it for the second time - nothing changes). But I can not figure out how to do this properly. Here is my hack :-), where everything works. I am giving new value each time. But is there a better way? Now provide the response and nothing else.
bootstrap modal provided events, you just need to hook up event 'hidden.bs.modal'. BTW, do proper disposal too. http://jsfiddle.net/C8w8v/377/ ko.bindingHandlers.modal = { init: function (element, valueAccessor) { $(element).modal({ show: false }); var value = valueAccessor(); if (ko.isObservable(value)) { // Update 28/02/2018 // Thank @HeyJude for fixing a bug on // double "hide.bs.modal" event firing. // Use "hidden.bs.modal" event to avoid // bootstrap running internal modal.hide() twice. $(element).on('hidden.bs.modal', function() { value(false); }); } // Update 13/07/2016 // based on @Richard's finding, // don't need to destroy modal explicitly in latest bootstrap. // modal('destroy') doesn't exist in latest bootstrap. // ko.utils.domNodeDisposal.addDisposeCallback(element, function () { // $(element).modal("destroy"); // }); }, update: function (element, valueAccessor) { var value = valueAccessor(); if (ko.utils.unwrapObservable(value)) { $(element).modal('show'); } else { $(element).modal('hide'); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22706765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090562/']}
jdg_80747
stackexchange
llm_judgeable_groundtruth_similarity
1825105
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i have a strange problem with IE8 installed in xp. i was trying to launch IE using an System.Diagnostics.Process.Start method in c#. And i have a requirement to trap the exited event of the IE and do some operation. But i ended up in a rather strange problem where the IE immediately fires the exited event after launch. this is the sample code Process objProcess = Process.Start("IEXPLORE.EXE", "http://google.com"); if (objProcess != null) { objProcess.EnableRaisingEvents = true; objProcess.Exited += new EventHandler(myProcess_Exited); } public static void myProcess_Exited(object sender, System.EventArgs e) { MessageBox.Show("You exited"); } But the above code perfectly works when laucnching different process (ex:notepad) and it fires the exit event when i close the exe. this only gives problem launching IE 8. Can someone clarify me what is the problem?? UPDATE Most friends replied my post and saying why you can't just use an URL? why stick with IE? here the reason the ultimate aim of the app is to launch an URL from the windows application and will hide an exe when working on the IE. And show the exe after closing the IE. Thanks Now provide the response and nothing else.
Most probably is that you have IE already running as a process, so when you try to launch it again as a new process it looks that there are IE running already, tells it that user initiated a new window (so the initial IE will create a "new" window rather than a new one) and exit. Possible solution: try starting the process with "-nomerge" command line option: Process objProcess = Process.Start("IEXPLORE.EXE", "-nomerge http://google.com/"); Interesting observation : objProcess.ExitCode (for IE8 at least) will be equal to 0 if exited passing control to another instance, and 1 if it was actually closed by user.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1825105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97572/']}
jdg_80748
stackexchange
llm_judgeable_groundtruth_similarity
307644
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 $1000!$ has $\frac{1000}{5}+\frac{1000}{25}+\frac{1000}{125}+\frac{1000}{625}=249$ terminal zeros in decimal notation, but what if we write $1000!$ in base $24$, how many terminal zeros would it have? Is there a way to compute it? Regards Now provide the response and nothing else.
The power of $2$ in $1000!$ is $$a=\left\lfloor \frac{1000}{2}\right\rfloor+\left\lfloor\frac{1000}{4}\right\rfloor+\left\lfloor\frac{1000}{8}\right\rfloor+\left\lfloor\frac{1000}{16}\right\rfloor+\left\lfloor\frac{1000}{32}\right\rfloor+\left\lfloor\frac{1000}{64}\right\rfloor+\left\lfloor\frac{1000}{128}\right\rfloor+\left\lfloor\frac{1000}{256}\right\rfloor+\left\lfloor \frac{1000}{512}\right\rfloor$$The power of $3$ in $1000!$ is $$b=\left\lfloor\frac{1000}{3}\right\rfloor+\left\lfloor\frac{1000}{9}\right\rfloor+\left\lfloor\frac{1000}{27}\right\rfloor+\left\lfloor\frac{1000}{81}\right\rfloor+\left\lfloor\frac{1000}{243}\right\rfloor+\left\lfloor\frac{1000}{729}\right\rfloor$$ Thus the number of zeroes is $\min \{ \lfloor \frac{a}{3} \rfloor, b \}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/307644', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43164/']}
jdg_80749
stackexchange
llm_judgeable_groundtruth_similarity
842451
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Some backup software vendors propose making weekly "full backups" in addition to daily "incremental backups". Point in case: http://novabackup.novastor.com/blog/differential-incremental-backup/ I have the following problem with this: If you do trust your incremental backups you should not need "full" backups If you don't trust your incremental backups then you should take "full" backups daily and don't use incremental backups at all Why would you take both incremental and full backups as suggested in the blog post linked above? Now provide the response and nothing else.
Well, the reason for that is not trust in the backup. It's the amount of work for a restore (among many other considerations that go in a backup scheme). If you have only one full and 300 incremental backups, you need to restore first the full and then every single incremental backup to get to the actual data. If you have weekly full + incremental, you need to restore at max 7 backups.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/842451', 'https://serverfault.com', 'https://serverfault.com/users/58798/']}
jdg_80750
stackexchange
llm_judgeable_groundtruth_similarity
33983980
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Problemset: Context Menu should show filter variables dynamically and execute a function with parameters defined inside the callback.Generic descriptions show properly, but function call is always executed with last set option. What I have tried: #!/usr/bin/env pythonimport Tkinter as tkimport ttkfrom TkTreectrl import MultiListboxclass SomeClass(ttk.Frame): def __init__(self, *args, **kwargs): ttk.Frame.__init__(self, *args, **kwargs) self.pack(expand=True, fill=tk.BOTH) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.View=MultiListbox(self) __columns=("Date","Time","Type","File","Line","-","Function","Message") self.View.configure(columns=__columns, expandcolumns=(0,0,0,0,0,0,0,1)) self.View.bind("", self.cell_context) self.View.grid(row=0, column=0, sticky=tk.NW+tk.SE) self.__recordset = [] self.__recordset_filtered = False #Some dummy values self.__recordset.append(["Date", "Time", "INFO", "File", "12", "-", "Function", "Message Info"]) self.__recordset.append(["Date", "Time", "DEBUG", "File", "12", "-", "Function", "Message Info"]) self.__recordset.append(["Date", "Time", "WARNING", "File", "12", "-", "Function", "Message Info"]) self.__refresh() def cleanView(self): self.View.delete(0, tk.END) def __refresh(self): self.cleanView() for row in self.__recordset: self.View.insert(tk.END, *row) def filter_records(self, column, value): print("Filter Log Recordset by {column} and {value}".format(**locals())) # Filter functionality works as expected # [...] def cell_context(self, event): __cMenu=tk.Menu(self, tearoff=0) if self.__recordset_filtered: __cMenu.add_command(label="Show all", command=lambda: filter_records(0, "")) else: column=2 options=["INFO", "WARNING", "DEBUG"] for i in range(len(options)): option=options[i] __cMenu.add_command(label="{}".format(option), command=lambda: self.filter_records(column, option)) # Also tried using for option in options here with same result as now __cMenu.post(event.x_root, event.y_root)if __name__=="__main__": root=tk.Tk() app=SomeClass(root) root.mainloop() The current output i get is: Filter Log Recordset by 2 and DEBUG No matter which of the three options i choose. I assume it has sth to do with the garbage collection that only the last option remains but i cannot figure out how to avoid this. Any help is recommended. Now provide the response and nothing else.
Please read about minimal examples . Without reading your code, I believe you have run into a well known issue addressed in previous questions and answers that needs 2 lines to illustrate. Names in function bodies are evaluated when the function is executed. funcs = [lambda: i for i in range(3)]for f in funcs: print(f()) prints '2' 3 times because the 3 functions are identical and the 'i' in each is not evaluated until the call, when i == 2. However, funcs = [lambda i=i:i for i in range(3)]for f in funcs: print(f()) makes three different functions, each with a different captured value, so 0, 1, and 2 are printed. In your statement __cMenu.add_command(label="{}".format(option), command=lambda: self.filter_records(column, option)) add option=option before : to capture the different values of option . You might want to rewrite as lambda opt=option: self.filter_records(column, opt) to differentiate the loop variable from the function parameter. If column changed within the loop, it would need the same treatment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33983980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4198514/']}
jdg_80751
stackexchange
llm_judgeable_groundtruth_similarity
1353819
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let us consider any $n \times n$ matrix $A$. My question is, what are the eigenvalues of \begin{equation}\mathcal{A} = \begin{bmatrix} 0 & A \\ A^* & 0 \end{bmatrix}. \end{equation} Of course since $\mathcal{A}$ is traceless Hermitian, if $\lambda$ is an eigenvalue, $-\lambda$ is also an eigenvalue. Motivation & further questions: If $A$ is Hermitian with eigenvalues $\lambda_j$, then the eigenvalues of $\mathcal{A}$ are $\pm \lambda_j$. Can we say something similar when $A$ is not Hermitian? Granted, $A$ may not be diagonalizable, can we say something in terms of singular values? What if, for a simple case, all eigenvalues of $A$ be real, though $A$ may not be Hermitian? Advanced thanks for any help/ suggestions. Now provide the response and nothing else.
If $A$ is hermitean and its eigenvalues are $\{\lambda_1,\dots,\lambda_n\}$, then $\mathcal A$ is also hermitean and its eigenvalues are $\{-\lambda_1,+\lambda_1,\dots,-\lambda_n,+\lambda_n\}$.(This is true also allowing repeated eigenvalues; the multiplicities behave as you would guess.)If $v\in\mathbb C^n$ is an eigenvector of $A$ with eigenvalue $\lambda$, then $(v,\pm v)\in\mathbb C^{2n}$ is an eigenvector of $\mathcal A$ with eigenvalue $\pm\lambda$.Counting dimensions shows that these form an eigenbasis for $\mathbb C^{2n}$. Consider then a more general $A$.If $w\in\mathbb C^{2n}$ satisfies $\mathcal Aw=\mu w$ for some $\mu\in\mathbb R$, then $\mathcal A^2w=\mu^2w$.The reason for considering the square is that$$\mathcal A^2=\begin{pmatrix}AA^*&0\\0&A^*A\end{pmatrix}.$$The matrices $AA^*$ and $A^*A$ are positive semidefinite and hermitean, so their eigenvalues are positive real numbers.The squared eigenvalues of $\mathcal A$ are thus the eigenvalues of $AA^*$ and $A^*A$ (squared singular values of $A$), counted with multiplicity. Since $\mathcal A$ is traceless and hermitean, its eigenvalues must add up to zero (with multiplicity).This strongly suggests (but does not fully prove) that if $\lambda$ is an eigenvalue of $\mathcal A$, then $-\lambda$ is an eigenvalue with the same multiplicity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1353819', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28724/']}
jdg_80752
stackexchange
llm_judgeable_groundtruth_similarity
5341
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: It might sound stupid but seriously I couldn't find why? We have a mass with a constant speed, which is acted on by a unit force which is always at right angles to its direction of motion. Why do the mass travels a circular path!? Now provide the response and nothing else.
As Newton did in his Principia Mathematica with an example similar to yours, imagine what happens over a short time $dt$ to the velocity of the mass. Using $F = m\,dv/dt$ gives $dv = F\,dt/m$ The force is at right angles to $v$ and so $dv$ is at right angles to, rather than along $v$. Do the same for the next $dt$ and so on, adding up all the contributions of $dv$ for one complete revolution and you will get $\sum dv = 0$. The additional wobble to the circular motion becomes zero as $dv \rightarrow 0$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/5341', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2002/']}
jdg_80753
stackexchange
llm_judgeable_groundtruth_similarity
2576022
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 usual pattern for a singleton class is something like static Foo &getInst(){ static Foo *inst = NULL; if(inst == NULL) inst = new Foo(...); return *inst; } However, it's my understanding that this solution is not thread-safe, since 1) Foo's constructor might be called more than once (which may or may not matter) and 2) inst may not be fully constructed before it is returned to a different thread. One solution is to wrap a mutex around the whole method, but then I'm paying for synchronization overhead long after I actually need it. An alternative is something like static Foo &getInst(){ static Foo *inst = NULL; if(inst == NULL) { pthread_mutex_lock(&mutex); if(inst == NULL) inst = new Foo(...); pthread_mutex_unlock(&mutex); } return *inst; } Is this the right way to do it, or are there any pitfalls I should be aware of? For instance, are there any static initialization order problems that might occur, i.e. is inst always guaranteed to be NULL the first time getInst is called? Now provide the response and nothing else.
Your solution is called 'double checked locking' and the way you've written it is not threadsafe. This Meyers/Alexandrescu paper explains why - but that paper is also widely misunderstood. It started the 'double checked locking is unsafe in C++' meme - but its actual conclusion is that double checked locking in C++ can be implemented safely, it just requires the use of memory barriers in a non-obvious place. The paper contains pseudocode demonstrating how to use memory barriers to safely implement the DLCP, so it shouldn't be difficult for you to correct your implementation.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2576022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168715/']}
jdg_80754
stackexchange
llm_judgeable_groundtruth_similarity
2868834
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 want to prove that the following identity is true for any positive integers $x,y,z$: $$\Big\lfloor{x}/({y}\cdot{z})\Big\rfloor=\Big\lfloor{\lfloor{x}/{y}\rfloor}/{z}\Big\rfloor$$ Here is a script that I wrote in Python 3 to test it: for x in range(1,100): for y in range(1,100): for z in range(1,100): print(x, y, z) assert x // (y * z) == x // y // z So empirically it seems to hold, but I'm finding it hard to establish a formal proof. Any idea? Now provide the response and nothing else.
$$\begin{array}{rc}& \left\lfloor \dfrac {\lfloor x/y \rfloor} z \right\rfloor = u \\\iff& uz \le \lfloor x/y \rfloor < (u+1)z \\\iff& uz \le \lfloor x/y \rfloor \le (u+1)z-1 \\\iff& uyz \le x < ((u+1)z-1+1)y \\\iff& uyz \le x < (u+1)yz \\\iff& \left\lfloor \dfrac x {yz} \right\rfloor = u \\\end{array}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2868834', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/402209/']}
jdg_80755
stackexchange
llm_judgeable_groundtruth_similarity
41829146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Its straightforward process; Here is the origin render method I want it to be(I want my table outside of div): but jsx compiler dont allow it for some reason? but if i move the table inside of div element;everything looks ok. so only diff is place of table. why jsx interfere this process ? why its necessary ? Now provide the response and nothing else.
In JSX , we can return only one html element from return , can't return multiple elements, if you want to return multiple elements then wrap all the html code in a div or by any other wrapper component. Same thing is happening in your 1st case, you are returning 2 elements, one div and one table . when you are wrapping them in one div everything is working properly. Same rule you have to follow for conditional rendering of components. Example: Correct: { 1==1 /* some condition */ ? <div> True </div> : <div> False </div>} Wrong: { 1==1 /* some condition */ ? <div> True 1 </div> <div> True 2 </div> : <div> False 1 </div> <div> False 2 </div>}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/41829146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2959783/']}
jdg_80756
stackexchange
llm_judgeable_groundtruth_similarity
21009834
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After installation of a wildcard SSL certificate into the certificate store, the certificate does not appear in the IIS certificate list for use with site bindings. The certificate was installed correctly, but apparently no key was included with the certificate. How can you fix this issue without doing a new request or contacting someone for the key (if, for instance, it's the day before a launch? ;-) ) Now provide the response and nothing else.
I ran into this problem today. Due to the timeframe and some other issues, getting the key from the provider was not possible. I found the following solution here (under pixelloa's comment) and thought it would be good to have the answer on Stack Overflow as well. If the certificate does not have a private key, you can fix this by doing the following: To fix this, use the MMC snapin to import the cert into PERSONAL store of the computer account, click it and grab the serial # line. Go to dos, run certutil -repairstore my "paste the serial # in here" (you need the quotes unless you remove the spaces from the serial number) then refresh MMC with personal certs, right click it - export - select everything except DELETE PRIVATE KEY, hit ok. Then go to IIS and IMPORT cert instead of finish request. For what it's worth, all I actually had to do was run the certutil -repairstore command, and my certificate worked. I did run the export and set a password for the export itself, but I did not have to reimport the certificate. The certificate now shows up in IIS's list of certificates and can be used for HTTPS bindings. I hope this helped someone.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21009834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_80757
stackexchange
llm_judgeable_groundtruth_similarity
427684
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am trying to come up with a generalisation of the Kelly formula for optimal fractional betting but and have hit a roadblock. The Kelly criterion is usually explained via a game that ends in 1 of 2 states (e.g. a coin flip) and gives the optimal fraction of your wealth $f$ that should be bet each round to maximise growth. I'm trying to extend this to get $f$ for a game with N possible end states. Here's what I have so far. Each round of the game ends in 1 of N possible states. The probability of getting any $n$ result is $p_n$ ( $\sum_{n=1}^N p_n = 1$ ) and the payout is $b_n$ such that you wealth $X$ would change by $X_1 = X_0(1 + b_n f)$ on an outcome of $n$ . The expected return after each round is given by: $${X_1 \over X_0} = \prod_{n=1}^N(1+b_n f)^{p_n}$$ Taking the natural log of both sides (as per the original Kelly idea): $$ln\left({X_1 \over X_0}\right) = \sum_{n=1}^N p_n \ln(1+b_n f)$$ Differentiating and setting to zero gives: $$\sum_{n=1}^N{ {p_n b_n} \over {1+b_n f}} = 0$$ This is where I am stuck. I would like to get $f$ in terms of some function of the $b_n$ and $p_n$ terms? So far I've been unsuccessful. Any idea mathematical tools/approach I can use? I should add there there is no functional relationship between any of the $p_n$ and $b_n$ values that could be used to simplify here (except the relationship $\sum_{n=1}^N p_n = 1$ ). Also note that $b_n$ can be positive or negative. Thanks! Now provide the response and nothing else.
The kind of completely regular space you are looking for is an $F$ -space. Suppose that $X$ is a completely regular space. Then we say that a subset $A\subseteq X$ is $C^*$ -embedded if whenever $f:A\rightarrow\mathbb{R}$ is bounded and continuous, there is a continuous $g:X\rightarrow\mathbb{R}$ with $g|_A=f$ . We say that a subset of $X$ of the form $f^{-1}[\{0\}]^c$ for some continuous $f:X\rightarrow\mathbb{R}$ is a cozero set. An $F$ -space is a space where every cozero set is $C^*$ -embedded. Proposition: Let $X$ be a completely regular space. Then the following are equivalent: $X$ is an $F$ -space whenever $f,g:X\rightarrow\mathbb{R}$ are continuous with $0\leq f\leq g$ there is some continuous $h:X\rightarrow\mathbb{R}$ with $f=gh$ . whenever $f,g:X\rightarrow\mathbb{R}$ are bounded and continuous with $0\leq f\leq g$ there is some continuous $h:X\rightarrow\mathbb{R}$ with $f=gh$ . Proof: $2\rightarrow 3$ follows since in (3) we strengthen the premises. $1\rightarrow 2$ Suppose that $X$ is an $F$ -space, and $0\leq f\leq g$ . Then let $\ell:g^{-1}[\{0\}]^c\rightarrow\mathbb{R}$ be the function defined by letting $\ell(x)=f(x)/g(x)$ . Then $g^{-1}[\{0\}]^c$ is a cozero set, and $\ell$ is bounded, so $\ell$ extends to a bounded continuous function $h:X\rightarrow\mathbb{R}$ . Observe that $f=gh$ . $3\rightarrow 1$ . Let $U$ be a cozero set, and let $\ell:U\rightarrow[0,1]$ be a continuous function. Let $g:X\rightarrow[0,1]$ be a continuous function where $U=g^{-1}[\{0\}]^c$ . Then let $f:X\rightarrow[0,1]$ be the continuous function such that $f(x)=g(x)\ell(x)$ whenever $x\in U$ and $f(x)=0$ elsewhere. We observe that $0\leq f\leq g\leq 1$ , so there must be a continuous function $h:X\rightarrow[0,1]$ with $f=gh$ . However, this means that $h(x)=\ell(x)$ whenever $x\in U$ , so $h$ is a continuous extension of the function $\ell$ . Q.E.D. There are plenty of other characterizations of the $F$ -spaces. If $X$ is a completely regular space, then let $C(X)$ denote the ring of all continuous functions $f:X\rightarrow\mathbb{R}$ . If $A,B\subseteq X$ , then we say that $A,B$ are completely separated if there is a continuous function $f:X\rightarrow[0,1]$ with $A\subseteq f^{-1}[\{0\}],B\subseteq f^{-1}[\{1\}]$ . The following fact can be found in the standard text Rings of Continuous Functions by Gillman and Jerison. Let X be a completely regular space. The following are equivalent: $X$ is an $F$ -space. The Stone-Cech compactification $\beta X$ is an $F$ -space. Every finitely generated ideal in $C(X)$ is principal. Every ideal in $C(X)$ is convex. For all $f\in C(X)$ , there is a $g\in C(X)$ with $f=g\cdot |f|$ . If $f\in C(X)$ , then the sets $\{x\in X\mid f(x)>0\}$ and $\{x\in X\mid f(x)<0\}$ are completely separated. If $M\subseteq C(X)$ is a maximal ideal, then the set of all prime ideals $P$ in $C(X)$ with $P\subseteq M$ is linearly ordered. If $f,g\in C(X),$ then $\langle f,g\rangle=\langle|f|+|g|\rangle.$ Comparison with other properties If $X$ is an $F$ -space, then every countable subset of $X$ is $C^*$ -embedded. Therefore, every compact $F$ -space has a homeomorphic copy of $\beta\omega$ . A basically disconnected space is a completely regular space where every cozero set has open closure. Every basically disconnected space is an $F$ -space, but $(\beta\omega)\setminus\omega$ is an $F$ -space that is not basically disconnected. There are also some connected $F$ -spaces.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/427684', 'https://mathoverflow.net', 'https://mathoverflow.net/users/488916/']}
jdg_80758
stackexchange
llm_judgeable_groundtruth_similarity
2271453
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to make sure that I delete required files.I have code something like dir="/some/path/"file = "somefile.txt"cmd_rm= "rm -rf "+dir + fileos.system(cmd_rm) The dir and file values are fetched from a database. How can I make sure I never end up running rm -rf / ? What things should I check before doing rm -rf ? Now provide the response and nothing else.
Don't use the -r switch if you just want to remove a single file. Also, there could be spaces in the file name. Better use the functions in Python's os module instead: dirname = "/some/path/"filename = "somefile.txt"pathname = os.path.abspath(os.path.join(dirname, filename))if pathname.startswith(dirname): os.remove(pathname) Normalizing the path with abspath and comparing it against the target directory avoids file names like "../../../etc/passwd" or similar.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2271453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246365/']}
jdg_80759
stackexchange
llm_judgeable_groundtruth_similarity
4124503
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a proof of identity 4.223.3 from Gradshteyn and Ryzhik's Tables of Integrals, Series and Products , namely $$\int_0^\infty\ln(1 + 2e^{-x}\cos t + e^{-2x})\,dx = \frac{\pi^2}{6} - \frac{t^2}{2} \qquad (\lvert t\rvert < \pi)$$ (I suspect it holds for $\lvert t\rvert = \pi$ as well). Unlike the proceeding formulas 4.223.1 and 4.223.2 for $\int_0^\infty\ln(1 \pm e^{-x})\,dx$ , its proof does not appear in part 9 of Amdeberhan et al.'s Integrals in Gradshteyn and Ryzhik . The reference in GR is for table 256 of the 1867 work Nouvelles tables d'intégrales définies ( large pdf ). One reason I'm interested in the derivation is that the integral looks related to $$\int_0^\infty \ln(1 - 2xe^{-x} - e^{-2x})\,dx,$$ which is equivalent to the integral asked in a previous unanswered question . Now provide the response and nothing else.
Another approach is to notice that the integral is \begin{align*}& \int_0^{ + \infty } {\log \left| {1 + e^{ - (x + it)} } \right|^2 dx} = 2\int_0^{ + \infty } {\Re \log (1 + e^{ - (x + it)} )dx} \\ & = 2\Re \int_0^{ + \infty } {\log (1 + e^{ - (x + it)} )dx} = 2\Re \int_0^{ + \infty } {\sum\limits_{n = 1}^\infty {( - 1)^{n + 1} \frac{{e^{ - (x + it)n} }}{n}} dx} \\ & = 2\Re \sum\limits_{n = 1}^\infty {\frac{{( - 1)^{n + 1} e^{ - i nt } }}{n}\int_0^{ + \infty } {e^{ - nx} dx} } \\ & = 2\Re \sum\limits_{n = 1}^\infty {( - 1)^{n + 1} \frac{{e^{ - itn} }}{{n^2 }}} = 2\sum\limits_{n = 1}^\infty {( - 1)^{n + 1} \frac{{\cos (nt)}}{{n^2 }}} \end{align*} which is the Fourier series of $\frac{\pi^2}{6}-\frac{t^2}{2}$ , $|t|<\pi$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4124503', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5051/']}
jdg_80760
stackexchange
llm_judgeable_groundtruth_similarity
63631998
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I open the Hackerrank example test and play around with methods one might use to make an AJAX call. XMLHttpReq , fetch , etc. None of them work; XHR and fetch methods are unavailable. First fetch : async function myFetch() { let response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); let data = await response.json(); console.log(data);} Hackerrank throws an error because fetch is not a function. I also tried window.fetch and global.fetch to no avail. I tried XHR : function myXHR() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { console.log(this.responseText); // or JSON.parse(this.responseText); } }; xmlhttp.open('GET', 'https://jsonplaceholder.typicode.com/todos/1'); xmlhttp.send();} Hackerrank says XMLHttpRequest is not defined. Hackerrank is executing Node.JS code, that explains why XHR isn't available, I have to require myself perhaps. Except I can't npm install anything, all I have access to is their little IDE. How do you make an AJAX call in this platform with JavaScript? Now provide the response and nothing else.
I've passed the HackerRank REST API certification and had the same issue. HackerRank uses a NodeJs environnement to run you code (it's said in the langage selection), so neither XMLHttpRequest nor fetch are available ( as these are Browser only ). I suggest you use the request npm package , HackerRank allows you to require it.One downside is that request doesn't support Promises & Async/Await unless you import other packages (which HackerRank doesn't seem to recognize). Here's what I used : const request = require('request');function myFetch(url) { return new Promise((resolve, reject) => { request(url, function (error, response, body) { if(error) reject(error) else resolve(body) }); });} Note : request package has been recently deprecated, but it will still work well for your use case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63631998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9407819/']}
jdg_80761
stackexchange
llm_judgeable_groundtruth_similarity
141999
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $n,p \in \mathbb{N}_+$ with $p \leq n.$ Let $\mathcal{P}$ denote the set of partitions of $\{1, \ldots, n\}$ into $p$ nonempty sets. How can I efficiently sample uniformly from $\mathcal{P}$? Now provide the response and nothing else.
The sets you're interested in are counted by Stirling Numbers of the Second Kind , which satisfy the recursion$$\left\{{n \atop k}\right \}=\left\{{n-1 \atop k-1}\right \}+k \left\{{n-1 \atop k}\right \}$$Here the first term represents those partitions where $n$ is its own set, and the remaining term represents inserting $n$ into a partition of $\{1, \dots, n-1\}$. This recursion can also be used to generate a set partition recursively: With probability $\left\{{n-1 \atop k-1}\right \}/\left\{{n \atop k}\right \}$ put $n$ in its own set, and make the rest a partition of $n-1$ elements into $k-1$ sets chosen uniformly at random. Otherwise generate a uniform random partition of $n-1$ elements into $k$ sets, and insert $n$ into a set uniformly chosen from those sets. The algorithm would run in time on the order of $nk$, with the main overhead being computing (or looking up) all of the Stirling Numbers up to $\left\{{n \atop k}\right \}$ at the start of the algorithm.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/141999', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2586/']}
jdg_80762
stackexchange
llm_judgeable_groundtruth_similarity
14203272
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 modify this function so that the result will merely be a blank cell rather than having #N/A show up if B2 has nothing in that cell? I think I might need something like an ISERROR check but I don't 100% know what I'm doing. =VLOOKUP(B2,Index!A1:B12,2,FALSE) Thanks! Now provide the response and nothing else.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e. =IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE)) or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e. =IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"") in earlier versions you need to repeat the VLOOKUP, e.g. =IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14203272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1949698/']}
jdg_80763
stackexchange
llm_judgeable_groundtruth_similarity
44811
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading about SSL/TLS for the last few days and looks like it has never been practically cracked. Given SSL/TLS is used for all communications between client application and the server, and given the password/API key is random and strong and securely stored on the server-side (bcryted, salted), do you think Basic Auth is secure enough, even for banking services? I see a lot of people disliking the idea of username/password getting sent on the wire with every request. Is this a real weak point of Basic Auth (even with SSL/TLS used), or is it just out of irrational fear? Now provide the response and nothing else.
HTTP Basic Authentication is not much used in browser-server connections because it involves, on the browser side, a browser-controlled login popup which is invariably ugly. This of course does not apply to server-server connections, where there is no human user to observe any ugliness, but it contributes to a general climate of mistrust and disuse for Basic Authentication. Also, in the 1990s, before the days of SSL, sending plaintext passwords over the wire was considered a shooting offence, and, in their folly, people considered that challenge-response protocols like HTTP Digest were sufficient to ensure security. We now know that it is not so; regardless of the authentication method, the complete traffic must be at least cryptographically linked to the authentication to avoid hijack by active attackers. So SSL is required . But when SSL is in force, sending the password "as is" in the SSL tunnel is fine. So, to sum up, Basic Authentication in SSL is strong enough for serious purposes, including nuclear launch codes, and even money-related matters. One should still point out that security relies on the impossibility of Man-in-the-Middle attacks which, in the case of SSL (as is commonly used) relies on the server's certificate. The SSL client (another server in your case) MUST validate the SSL server's certificate with great care, including checking revocation status by downloading appropriate CRL. Otherwise, if the client is redirected to a fake server, the fake server owner will learn the password... In that sense, using something like HTTP Digest adds some extra layer of mitigation in case the situation got already quite rotten, because even with HTTP Digest, a fake server doing a MitM can still hijack the connection at any point. If we go a bit further, we may note that when using password-based authentication, we actually want password-based mutual authentication. Ideally, the SSL client and the SSL server should authenticate each other based on their knowledge of the shared password. Certificates are there an unneeded complication; theoretically, SSL client and server should use TLS-PSK or TLS-SRP in that situation, and avoid all the X.509 certificate business altogether. In particular, in SRP, what the server stores is not the password itself but a derivative thereof (a hash with some extra mathematical structure). One shall note an important point: in the case of a Web API, both the client and the server are machines with no human involved. Therefore, the "password" does not need to be weak enough to be remembered by the meat bags. That password could be, say, a sequence of 25 random characters, with an entropy gone through the roof. This makes the usual password hashing methods (slow hashing, salts) kind of useless. We still want to avoid storing in the server's database (thus as a prey to potential SQL injections) the passwords "as is", but, in that case , a simple hash would be enough. This points to the following: ideally, for a RESTful API to be used by one server to talk to another, with authentication based on a shared (fat) secret, the communication shall use TLS with SRP. No certificate, only hashes stored on the server. No need for HTTP Basic Auth or any other HTTP-based authentication, because all the work would have already occurred on the SSL/TLS level. Unfortunately, the current state of deployment of SRP-able SSL/TLS implementations usually means that you cannot use SRP yet. Instead, you will have to use a more mundane SSL/TLS with an X.509 certificate on the server side, that the client dutifully validates. As long as the validation is done properly, there is no problem in sending the password "as is", e.g. as part of HTTP Basic Authentication.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/44811', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/32724/']}
jdg_80764
stackexchange
llm_judgeable_groundtruth_similarity
3431801
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A Field $F$ is defined such that: There is a first operation, say $+$ (addition), that is closed, associative and commutative over $F$ , and has an identity element $0 \in F$ and an inverse element $-x \in F$ for each $x \in F$ (that is, $(F, +)$ is a commutative group); There is a second operation, say $\cdot$ (multiplication), that is closed, associative and commutative over $F \setminus \{0\}$ , and has an identity element $1 \in F \setminus \{0\}$ and an inverse $1/x \in F \setminus \{0\}$ for each $x \in F \setminus \{0\}$ (that is, $(F\setminus \{0\}, \cdot)$ is a commutative group); The second operation distributes over the first operation. My question is this : Is it possible to define a third operation, say $*$ , for $F$ such that $(F\setminus \{0,1\}, *)$ , is a commutative group and $*$ distributes over multiplication? In other words, is it possible to have $(F, +, \cdot, *)$ where both $(F,+, \cdot)$ and $(F\setminus \{0\},\cdot, *)$ are fields? My gut feeling is no. In all fields I am familiar with $(\mathbb{Q,R,C,Z}_p)$ , the multiplication is provably equivalent to that field's analytic continuation of iterated addition, but the analytic continuation of iterated multiplication (that is, exponentiation) is provably not a commutative group operation on $(F \setminus \{0,1\})$ (and catastrophically so, it fails on all counts! It's not even well-defined!) However, the coincidence that multiplication is equivalent to iterated addition feels like just that, a coincidence, as the definition of field makes no claims about the relation between the two operations other than the distributive property. Is my gut feeling correct, or am I right to be skeptical? Now provide the response and nothing else.
Among finite fields with characteristic $\neq 2$ , David's example is unique. Specifically: Suppose $F$ is a finite field with char $F\neq 2$ which has an extra operation $\ast$ as described by the OP. Then $F = \mathbb{Z}_3$ with $a\ast b = \min\{a,b\}$ . Proof: Suppose $F$ a finite field of characteristic $\neq 2$ . Then $-1\neq 1\in F$ . However, $(-1)\cdot (-1) =1$ . Thus, the field $(F- \ \{0\}, \cdot, \ast)$ is characteristic $2$ , so $|F -\{0\}| = 2^n$ for some $n \geq 1$ . On the other hand, the multiplicative group of a finite field is cyclic (see, e.g. this MSE question ). Since the fields whose additive structure is cyclic are exactly the prime fields, we deduce that $n = 1$ . Thus, in this case, $|F| = 3$ . This already implies that $F = \mathbb{Z}_3$ . It remains to compute $\ast$ . We know that $\ast$ must have the property that $2\ast 2 = 2$ since $\ast$ maps $F -\{0,1\}$ to itself, and we also know that $1\ast 1 = 1$ because it's the additive identity of the field ( $F-\{0\}, \cdot, \ast).$ Next, we see that \begin{align*} 2 &= 2\ast 2\\ &= 2\ast(1\cdot 2)\\ &= (2\ast 1) \cdot (2\ast 2)\\ &= (2\ast 1) \cdot 2,\end{align*} so $2 = (2\ast 1) \cdot 2$ , so $2\ast 1 = 1$ . Thus, $2\ast 1 = \min \{1,2\}$ . Likewise, \begin{align*}2\ast 0 &= 2\ast(0\cdot 2)\\ &= (2\ast 0) \cdot (2\ast 2)\\&= (2\ast 0)\cdot 2.\end{align*} If $2\ast 0\neq 0$ , we can divide by it to learn $2 = 1$ , which is absurd, so $2\ast 0 = 0 $ . That is, $2\ast 0 = \min\{0,2\}$ . Moreover, \begin{align*} 1\ast 0 &= (2\cdot 2)\ast 0\\ &= (2\ast 0) \cdot (2\ast 0)\\ &= 0.\end{align*} Finally, \begin{align*} 0\ast 0 &= 0\ast (0\cdot 1)\\ &= (0\ast 0)\cdot (0\ast 1)\\ &= 0,\end{align*} so $0\ast 0 = \min\{0,0\}$ . Thus, $a\ast b = \min\{a,b\}$ in all cases. $\square$ What about lonza's examples? Suppose $F_{2^n}$ is a finite field of characteristic $2$ which supports an operation $\ast$ as described by the OP. Then $2^n - 1$ is a Mersenne prime. (I am not claiming lonza's operation $\ast$ is unique. I have no idea.) Proof: Suppose $F_{2^n}$ is a finite field with $2^n$ elements. If $n = 1$ , (i.e., $|F| = 2$ ), then $F-\{0,1\}$ is the empty set, so $(F-\{0,1\},\ast)$ doesn't form a group since it doesn't have an identity. Thus, we may assume $n\geq 2$ . Now, $F-\{0\}$ is again the underlying space of a field, so $|F-\{0\}| = p^m$ for some prime $p$ . Thus, $p^m + 1 = 2^n$ , so $1 = 2^n - p^m$ . By Mihalescu's Theorem , there is no solution to $2^n - p^m = 1$ with $m > 1$ , so $m = 1$ . Thus, $2^n - 1 = p$ is a Mersenne prime. $\square$ Finally, what about infinite fields? No infinite field $F$ supports such an operation $\ast$ . Proof: As Geoffrey notes in his answer, $F$ must have characteristic $0$ , so it contains a copy of $\mathbb{Q}$ . Further, since $-1\neq 1$ and $(-1)^2 = 1$ , $F-\{0\}$ must be characteristic $2$ . This means that $a\cdot a = 1$ for any $a\in F - \{0\}$ . But this is false when $a=2\in \mathbb{Q}-\{0\}\subseteq F-\{0\}.$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3431801', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/412735/']}
jdg_80765
stackexchange
llm_judgeable_groundtruth_similarity
94731
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm sure this is a very straightforward question but it came up in my work today and I could not think of the reasoning behind it. I had two sets of numeric values (A & B) and was looking at the median of their ratio and noticed that median(A)/median(B) is not equal to median(A/B) and I was wondering if someone could explain why not. Seems like one might assume they are equal, but this is not true. I also noted that it seems when the range of A & B respectively are small the median(A/B) is quite near median(A)/median(B), but with a large range the two values seem to diverge. Now provide the response and nothing else.
This is a property of mathematics, it is actually rare that the order of operations does not matter, e.g. the log of the square root is not the same as the square root of the log (except for a few special cases). We often focus on some of those special cases where due to operations distributing, associating, and commuting (flashbacks to algebra, oh no!) we can do things in either order. For example to compute a mean we can either add the numbers together then divide the sum by $n$, or we can divide each number by $n$ then sum those values. This is because division (multiplication) distributes over addition. With paired data we have the fact that the mean of the differences is the difference of the means. But these are the rarer cases, not the rule. So in general you should not expect to get the same result when you do things in a different order, it is also not true that the mean of the ratios is the ratio of the means, so why should it be true for the median?
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/94731', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/35130/']}
jdg_80766
stackexchange
llm_judgeable_groundtruth_similarity
2979392
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 read lots of programmers saying and writing when programming in C/C++ there are lots of issue related to memory. I am planning to learn to program in C/C++. I have beginner knowledge of C/C++ and I want to see some short sample why C/C++ can have issues with memory management. Please Provide some samples. Now provide the response and nothing else.
There are many ways you can corrupt or leak memory in C or C++. These errors are some of the most difficult to diagnose, because they are often not easily reproducible. For example, it is simple to fail to free memory you have allocated. For example, this will do a "double free", trying to free a twice and failing to free b : char *a = malloc(128*sizeof(char));char *b = malloc(128*sizeof(char));b = a;free(a);free(b); // will not free the pointer to the original allocated memory. An example buffer overrun, which corrupts arbitrary memory follows. It is a buffer overrun because you do not know how long str is. If it is longer than 256 bytes, then it will write those bytes somewhere in memory, possible overwriting your code, possibly not. void somefunc(char *str) { char buff[256]; strcpy(buff, str);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2979392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346659/']}
jdg_80767
stackexchange
llm_judgeable_groundtruth_similarity
2868665
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am learning cakephp by myself. I tried to create a user controller with a changepassword function. It works, but I am not sure if this is the best way, and I could not googled up useful tutorials on this.Here is my code: class UsersController extends AppController { var $name = 'Users'; function login() { } function logout() { $this->redirect($this->Auth->logout()); } function changepassword() { $session=$this->Session->read(); $id=$session['Auth']['User']['id']; $user=$this->User->find('first',array('conditions' => array('id' => $id))); $this->set('user',$user); if (!empty($this->data)) { if ($this->Auth->password($this->data['User']['password'])==$user['User']['password']) { if ($this->data['User']['passwordn']==$this->data['User']['password2']) { // Passwords match, continue processing $data=$this->data; $this->data=$user; $this->data['User']['password']=$this->Auth->password($data['User']['passwordn']); $this->User->id=$id; $this->User->save($this->data); $this->Session->setFlash('Password changed.'); $this->redirect(array('controller'=>'Toners','action' => 'index')); } else { $this->Session->setFlash('New passwords differ.'); } } else { $this->Session->setFlash('Typed passwords did not match.'); } } }} password is the old password, passwordn is the new one, password2 is the new one retyped.Is there any other, more coomon way to do it in cake? Now provide the response and nothing else.
I see that you validate and manipulate data in the controller. Doing this in a model is generally a better practice. I implemented similar functionality just a few days ago. My change_password() method looks somewhat like this: # app/controllers/users_controller.phpfunction change_password() { if (!empty($this->data)) { if ($this->User->save($this->data)) { $this->Session->setFlash('Password has been changed.'); // call $this->redirect() here } else { $this->Session->setFlash('Password could not be changed.'); } } else { $this->data = $this->User->findById($this->Auth->user('id')); }} And here's a stripped down version of the view used with that method: # app/views/users/change_password.ctpecho $this->Form->create('User');echo $this->Form->input('id');echo $this->Form->input('current_password');echo $this->Form->input('password1');echo $this->Form->input('password2');echo $this->Form->end('Submit'); The code that does something interesting is in the model. I added the fields from the form to the validate property and wrote custom validation methods . This allows me to use password1 and password2 fields in any other place in the application, for example, on the registration form. # app/models/user.phpvar $validate = array( 'current_password' => array( 'rule' => 'checkCurrentPassword', 'message' => '...' ), 'password1' => array( 'rule' => 'checkPasswordStrength', 'message' => '...', ), 'password2' => array( 'rule' => 'passwordsMatch', 'message' => '...', )); Finally, in the beforeSave() callback of the model I set password to the hash of password1 to prepare the data to be stored it in the database.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2868665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262985/']}
jdg_80768
stackexchange
llm_judgeable_groundtruth_similarity
416512
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: In a comment on Mechanism of quantum entanglement; proof of quantumness , Emilio Pisanty stated, There's many types of entanglement, and only a few can be traced to any sort of conservation law. Replying to a request to point out some examples of types of entanglement, he suggested that the request probably deserves its own thread. So, my question: What types of entanglement are not the result of conservation principles? Now provide the response and nothing else.
The notion that entanglement is due to conservation laws is an unfortunate misconception caused by a popular way to explain the concept at the general-audience level. That argument goes something like the following: You take two particles, which are known to have total spin $S_z=0$, and then you separate them. Then if you measure particle A and it has spin $S_z=+1/2$, then you know that particle B must have spin $S_z=-1/2$, and the particles are entangled. As general-audience presentations go, it's not that bad, particularly if it is embedded in a larger piece that must juggle other concepts as well and cannot devote that much space to a detailed explanation of entanglement. There's a few things to say about this argument: The good: this argument does represent (though not in enough detail to fully specify it) one possible way to get entanglement. More specifically, if you know that particles A and B share a spin singlet state $|\psi⟩ = \tfrac{1}{\sqrt{2}}\big(|{↑↓}⟩-|{↓↑}⟩\big)$, and you spatially separate them, then yes, you do get an entangled pair. The bad: That said, however, the real argument relies on the spin-singlet state, and not on its $S_z=0$ aspect. In particular, you could have an identical argument if you started in the spin triplet state, $|\psi_+⟩ = \tfrac{1}{\sqrt{2}}\big(|{↑↓}⟩+|{↓↑}⟩\big)$, which has an opposite sign in the superposition, but it is absolutely critical that you know what that phase is. If all you have is a box that produces $|\psi⟩$ and $|\psi_+⟩$ with 50% probability but without telling you which, then $S_z=0$ is still true, but you have completely destroyed the entanglement. Moreover, that argument ignores the fact that there are perfectly valid pure states, such as the bare $|↑↓⟩=|↑⟩\otimes|↓⟩$, that are consistent with the $S_z=0$ property but don't have any entanglment at all. Even worse, basing the argument on the conservation law sets the reader up for one of the biggest misconceptions of all when it comes to quantum entanglement $-$ that entanglement is like JS Bell's description of Bertlmann's socks , or, in other words, that entanglement can be explained by a hidden-variable theory , where each particle has a well-determined spin before we look, and the observation merely reveals that value. This is provably wrong! We know from Bell's theorem that such a description of entangled states (generally known as 'local and realist') is incompatible with the predictions of quantum mechanics, and we know from experiments that nature follows the QM predictions and it is not bound by the constraints imposed by local realism. In addition to that, the presentation structure of that argument is of the form what is entanglement? well, here is one way to produce entangled states and, if not handled properly, leads the reader directly into a faulty generalization . No matter how solidly the case for the method has been established, the argument says nothing about whether there are other ways to produce entangled states. And, indeed, there are such other methods. More to the point: Entanglement is generic Any time you have two quantum systems A and B interacting with a nontrivial hamiltonian $\hat H_\mathrm{AB}$, the generic outcome is that they will come out entangled with each other, i.e. something of the form$$U(|\psi\rangle\otimes|\varphi\rangle)\longrightarrow |\Psi\rangle.$$(Contrary to what was stated in the comments, this does not need to involve any conservation laws at all.) Entanglement is simply a product of interactions, and it does not require particularly symmetric conditions, or configurations that are amenable to a simple conservation-law analysis, to appear. On the other hand, there is an important difference to be drawn between controlled entanglement, i.e. the entangled states which are technologically useful and experimentally verifiable, and entangled states where we don't have enough of a controllable handle on the state to make it do anything useful. When we don't have such a handle, entanglement morphs into the other side of the coin - decoherence , which is nothing less than an uncontrolled entanglement with parts of the environment that we cannot address. As the top answer to the linked question makes clear, this type of entanglement is something we'd very happily have less of, in a ton of different circumstances. Controlled entanglement, on the other hand, is relatively fragile, because there are all sorts of factors that can mess it up (such as dephasing on the superpositions degrading the quality, or entanglement with other degrees of freedom that we don't want to include). This is why ( controlled ) entanglement is often considered a valuable resource - but if you drop the qualifiers, it's not that hard to get.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/416512', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/183212/']}
jdg_80769
stackexchange
llm_judgeable_groundtruth_similarity
956669
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to MSDN documentation, SetupDiGetClassDevs can be passed a device instance ID to obtain a device information set for a specific device: To return only a specific device, set the DIFCF_DEVICEINTERFACE flag and use the Enumerator parameter to supply the device instance ID of the device. I get the device instance ID by parsing the symbolic name from the WM_DEVICECHANGE message DBT_DEVICEARRIVAL event, and I have verified the resulting ID by comparing it to that returned from SetupDiGetDeviceInstanceId . Even passing the OS supplied device instance ID does not work (i.e. the SetupDiGetClassDevs call fails with ERROR_INVALID_PARAMETER ). My current workaround to fetch a SP_DEVINFO_DATA structure for the newly arrived device is to enumerate all devices in the same class and compare the result of SetupDiGetDeviceInstanceId to the symbolic name. However, I don't see why this should be necessary according to the documentation... Has anyone gotten SetupDiGetClassDevs to work in this way? Is there a better method for getting further information for a device using data in the DBT_DEVICEARRIVAL event? Now provide the response and nothing else.
It seems you have to either specify the DIGCF_ALLCLASSES flag to find all classes that match the given device instance id, or else specify the ClassGuid and use the DIGCF_DEFAULT flag. This worked for me: void error(DWORD err){ WCHAR buf[0x200]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buf, 0x200, NULL); wprintf(L"%x: %s\n", err, buf);}int _tmain(int argc, _TCHAR* argv[]){ PCWSTR devinst = L"HID\\VID_413C&PID_2105\\6&22CE0F66&0&0000"; HDEVINFO hinfo = SetupDiGetClassDevs(NULL, devinst, NULL, DIGCF_DEVICEINTERFACE | DIGCF_ALLCLASSES); if (hinfo == INVALID_HANDLE_VALUE) { error(GetLastError()); return 1; } SP_DEVINFO_DATA dinfo; dinfo.cbSize = sizeof(dinfo); int ix = 0; while (SetupDiEnumDeviceInfo(hinfo, ix++, &dinfo)) { wprintf(L"Match\n"); } error(GetLastError()); SetupDiDestroyDeviceInfoList(hinfo); return 0;} With output: Match103: No more data is available.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/956669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1491/']}
jdg_80770
stackexchange
llm_judgeable_groundtruth_similarity
918752
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I just purchased a server from Hetzner, with two 4TB hard drives and one 1TB SSD. I want to setup the two hard drives (/dev/sda & /dev/sdb) in RAID1 and install the OS on them, and have the SSD (/dev/sdc) as an extra drive. Until now, all my tentatives failed. The installimage script runs fine, and tells me that I just need to reboot. But when I reboot, I have this error: I tried fixing the error without luck and gave up, as I suspect that the problem comes from my installimage script config. Here's the configs I used for all my tries: DRIVE1 /dev/sdaDRIVE2 /dev/sdb#DRIVE3 /dev/sdc # commented to exclude it from the RAID setupSWRAID 1SWRAIDLEVEL 1BOOTLOADER grubHOSTNAME EX51 And here are the different partitioning schemes I tried: 1°) Nearly the default config PART swap swap 32GPART /boot ext3 512MPART / ext4 all 2°) A try with LVM PART /boot ext3 512MPART lvm vg0 allLV vg0 swap swap swap 4GLV vg0 root / ext4 all 3°) Partitions smaller than 2TB in case that the system does not use grub2 (is it?) PART swap swap 32GPART /boot ext3 512MPART / ext4 1TPART /p1 ext4 1TPART /p2 ext4 1TPART /p3 ext4 all What am I doing wrong? Thanks! EDIT: disabling RAID works. Now provide the response and nothing else.
So I finally got it working. I don't remember exactly what went wrong, but here's what I'm doing now: 1°) Use the following config: DRIVE1 /dev/sdaDRIVE2 /dev/sdb#DRIVE3 /dev/sdcSWRAID 1SWRAIDLEVEL 1BOOTLOADER grubHOSTNAME EX61PART swap swap 32GPART /boot ext3 512MPART / ext4 all 2°) Once installimage finished, but before rebooting , create mount folder & update fstab: Create the mount folder: mkdir /mountFolder Update fstab: cat > /etc/fstab Paste: proc /proc proc defaults 0 0/dev/md/0 none swap sw 0 0/dev/md/1 /boot ext3 defaults 0 0/dev/md/3 / ext4 defaults 0 0/dev/sdc1 /mountFolder ext4 defaults 0 0 Then reboot. 3°) If the /dev/md2 error occurs, format the SSD: parted /dev/sdc mklabel gptparted /dev/sdc print unit MB print free Note the size of the disk for the next command parted --align optimal /dev/sdc mkpart primary ext4 0% 960197MB // replace the size heremkfs.ext4 /dev/sdc1 Check if fstab needs to be updated again, if so do it: cat /etc/fstab (paste the same as in step 2) Finally create the mount folder and mount the drive: mkdir /mountFoldermount -a
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/918752', 'https://serverfault.com', 'https://serverfault.com/users/475942/']}
jdg_80771
stackexchange
llm_judgeable_groundtruth_similarity
131218
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: Between clear tempered glass (see through,thick & very strong) Vs. coloured plastic material, which would result in more degradation of GPS signals if used to make a box? The box contains a positioning module and a GSM module with an antenna. The thickness of the plastic i'm thinking is about 5mm. But of course, its just a rough figure. If I am to involve tempered glass, my intention is to use the same only on top of the area of the antenna, may be for the botton top half of the box. Is there other known fairly strong material (may be even rubber) that will do a better job? This is only a prototype design. Your responses will be so much helpful and appreciated. Now provide the response and nothing else.
There are a few things to consider with a radome over a GPS antenna. the reflection that occurs at the interfaces with air. the loss inside the radome. the near-field effect the radome has on the tuning of the antenna. Dielectric effects and reflection The radome is a sheet of dielectric, which has a permeability different to that of air. There will be a reflection of the wave as it enters the material, and as it leaves. In a thin radome, much less than 1/4 wavelength, these two effects can be combined. The reflection depends on the thickness of the material, and the dielectric constant. Most plastics have an \$\epsilon_r\$ of about 2.1, and glass is about 4.0 (tempering doesn't matter). For a thin skin, the effect is approximately linear with thickness and dielectric, so a 1 mm radome has half the impact of a 2 mm radome, and a 5 mm plastic radome has the same effect as a 2.5 mm plate glass radome. I can't find the equations online or in my textbooks, so you'll have to go with my memory for now, which is that for normal incidence, a 5 mm sheet of plastic should not cause a significant transmission loss at GPS frequencies . But that's not all. At increasing angles of incidence, the plate becomes "thicker" to the incident wave, the reflection becomes stronger and the transmission weaker. Also, the two polarisation components have different transmission coefficients, so the circular polarisation of the antenna will be degraded. A GPS antenna needs to operate with signals from as low as 10 degrees above the horizon, 80 degrees from normal incidence, and at this angle, even a thin sheet of plastic has a significant effect . The best solution is to have a dome or even hemispherical radome, made from the best thin dielectric. The definition of best is the highest \$strength / (thickness * \epsilon_r) \$. 2. Losses in the material If the material is lossy, that will reduce the signal transmitted. This should drive your choice of materials towards pure plastics, or high-glass-fraction composites. Again, in proportion to the thickness of the material - a glass-loaded plastic can be made much thinner than a pure plastic, for the same strength, so it may be even less lossy. RF Cafe has a table of dielectric constants and loss tangents The big thing to watch out for is the effect of additives in the plastic. Black plastic is usually bad as it is often coloured with carbon black. Cheap regrind plastic has a particularly high percentage of this black pigment. UV-stabilisers can also increase the loss. Translucent pigments that colour the plastic will have no effect. Nylon is a common strong plastic that is unfortunately not ideal for radomes, as it absorbs a significant amount of moisture, which raises the dielectric constant, and increases the loss. 3. dielectric loading of the GPS antenna The dielectric in the radome has a third effect - by interacting with the near fields of the antenna, it affects the tuning of the antenna, decreasing its sensitivity in the GPS band. For a patch antenna, it is probably sufficient to keep the radome at least 20 mm away, for minimum effect. If you need to get closer, some manufacturers sell test kits, with a range of patches designed for different radome thicknesses. You can evaluate all of the options and then specify the module with the best tuning in your exact situation. Testing what you have built You can evaluate the radome solution you have built by recording some detailed information about the GPS signal strength for all satellites, with the antenna in the open air, and in the box. Plot the signal strength of satellites against elevation angle, and observe the change in performance at the zenith, which should be small, and the effects near the horizon, which will be bigger. My opinion is that tempered glass is not a good radome material, unless you have other very pressing requirements for it. It's transparent so the sun will heat up the electronics. It's strong, but for its dielectric impact, not as good as glass-filled plastic. It is probably only available from 5 mm thickness, which is quite thick for a GPS radome. It would be better to choose a glass-filled plastic.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/131218', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/46528/']}
jdg_80772
stackexchange
llm_judgeable_groundtruth_similarity
128735
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can one convert an SSL cert provided by an authority to another authority, so one can generate "valid" certs for different domains? Now provide the response and nothing else.
What you are looking for is to modify the certificate in a way that it contains the ability to be a CA, i.e. set the CA flag to true. Fortunately you cannot simply modify a certificate, because any kind of modification invalidates the signature and thus nobody will trust this certificate anymore. This is essential because otherwise everybody could just create certificates for sites they don't own and this do man in the middle attacks.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/128735', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/111166/']}
jdg_80773
stackexchange
llm_judgeable_groundtruth_similarity
28534462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently, I got some help modifying my .htaccess file to hide the .php extension in the url. After I got it working, a few bugs occurred with my site. For whatever reason, any php page in a sub directory returns a 404 error. For example: mywebsite.com/test/test.php (this 404's) but mywebsite.com/test/test.html (this works just fine) Since this only started occurring after my .htaccess file was modified, I am assuming the problem lies there. The file contains as follows: RewriteEngine On# Unless directory, remove trailing slashRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([^/]+)/$ http://www.mywebsite.com/$1 [R=301,L]# Redirect external .php requests to extensionless urlRewriteCond %{REQUEST_METHOD} !POSTRewriteCond %{THE_REQUEST} /.+?\.php [NC]RewriteRule ^(.+?)\.php$ /$1 [R=301,L,NE]# Resolve .php file for extensionless php urlsRewriteRule ^([^/.]+)$ $1.php [L]ErrorDocument 404 /404.phpDirectoryIndex index.php If there is any more information I can provide to help solve this, please let me know! Thank you for all the help. Now provide the response and nothing else.
data = open(module_path+'/data/ex-fire.xslt')xslt_content = data.read() This implicitly decodes the bytes in the file to Unicode text, using the default encoding. (This might give wrong results, if the XML file isn't in that encoding.) xslt_root = etree.XML(xslt_content) XML has its own handling and signalling for encodings, the <?xml encoding="..."?> prolog. If you pass a Unicode string starting with <?xml encoding="..."?> to a parser, the parser would like to reintrepret the rest of the byte string using that encoding... but can't, because you've already decoded the byte input to a Unicode string. Instead, you should either pass the undecoded byte string to the parser: data = open(module_path+'/data/ex-fire.xslt', 'rb')xslt_content = data.read()xslt_root = etree.XML(xslt_content) or, better, just have the parser read straight from the file: xslt_root = etree.parse(module_path+'/data/ex-fire.xslt')
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28534462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4388132/']}
jdg_80774
stackexchange
llm_judgeable_groundtruth_similarity
4245231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When using the jQuery.ajax() method, I am struggling to filter the data that is returned to get exactly what I need. I know this is easy using .load() and probably the other jQuery AJAX methods but I need to use .ajax() specifically. For example I know that this works; var title = $(data).filter('title'); // Returns the page title But what if I just want the contents of a div with id="foo"? var foo = $(data).filter('#foo'); // None of these workvar foo = $(data).find('#foo'); //var foo = $('#foo', data); // Ideally, I want one method into which I can pass a normal jQuery selector, which will work for selecting titles, divs, or any other element that jQuery can select. This is so that I can pass in any string into my own ajax function - eg; myApp.ajax({ url: 'myPage.html', filterTitle: 'title', filterContent: '#main-content'}); Any help would be greatly appreciated. Now provide the response and nothing else.
The use of filter() vs. find() depends on the structure of your retrieved HTML page. For example, if this is the retrieved page: <!DOCTYPE html><html><head> <title>Foo</title></head><body> <div id="wrap"> <div id="header"> <h1>Foo</h1> </div> <div id="body"> content </div> </div> <div id="tooltip"> tooltip </div></body></html> If you want to select the top-level elements = elements that are direct children of <body> - in this example: #wrap or #tooltip - then you have to use filter() . If you want to select other elements - in this example: #header , <h1> , #body , ... - then you have to use find() . I you don't know whether your element is a child of <body> or not, you could use this "hack": $("<div>").html(data).find( selector ); By using this work-around, you always get the elements via find() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4245231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516001/']}
jdg_80775
stackexchange
llm_judgeable_groundtruth_similarity
4066
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: A couple of commentaries mention that scholars dispute that Elijah was fed by ravens and instead think the word in 1 Kings 17:4-6 ought to be translated black arabs or perhaps " Orbites , i.e., inhabitants of Orbo." I'm also told though: In support of the received rendering is the very powerful consideration, that it is the interpretation of all the versions (except the Arabic) and of Josephus, who, beyond all question, represented the belief current in his own time (Ant. viii. 13. 2). 1 Kings. 1909 (H. D. M. Spence-Jones, Ed.). The Pulpit Commentary (382). London; New York: Funk & Wagnalls Company. Is there any merit to translating this as something other than ravens? Or is it simply an attempt to accommodate the story to something consider more historically plausible (i.e. non-miraculous)? Or perhaps an incredulity that someone so zealous as Elijah would eat what unclean birds brought him? Now provide the response and nothing else.
This is an ancient question... The rabbis of the Talmud [BT Hullin 5a] discuss both opinions: What is meant by ‘the ravens’ [ 'orevim ]? Ravina said: It means actual ravens. R. Ada ben Manyomi said to him: "Could it not mean two men whose names were Orev?" He replied, "How could it have happened that both were named Orev?" "But perhaps they were so named after the town in which they lived?"... "If so, the verse should read Orebites [ 'orevi'im ]." A similar back-and-forth is found in Genesis Rabba 33:5 [a compilation of rabbinic commentary, probably 5th-6th century CE]. There is no philological basis for translating it as anything but "ravens". The hesitation is, as you noted, that ravens are unclean scavengers and thus perhaps unfit (not, in my opinion, a particularly strong argument), and also that having humans feed Elijah here makes a nice parallel to the widow of Sarephath who feeds him a few verses later. But in my opinion it's a stretch.
{}
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/4066', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/33/']}
jdg_80776
stackexchange
llm_judgeable_groundtruth_similarity
43114
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: $\delta(t)$ is a singular function and when I'm learning Signals and Systems I learned that $\delta(t)$ is an even function, and all of its odd order derivatives are odd function. Then we have $\delta^{'}(t)=-\delta^{'}(-t)$, let t=0 then $\delta^{'}(0)=0$. This is obviously wrong! But Where? And if it's wrong,then $\delta^{'}(0)$=? Now provide the response and nothing else.
Short answer: $\delta$ isn't a function, it is a "generalized function" supported at $0$, which can be defined as a "weak derivative" of the step function. Because it isn't a function, you can't evaluate it at points, and you can't evaluate the derivatives at points, so it doesn't really make sense to say they are "even" or "odd" functions. Long answer: When first introduced, or when seen in the context of an engineering class, people often gloss over the fact that $\delta(t)$ is not quite a function. It is the "derivative" of the step function, or it is the "limit" of a bunch of rectangular looking functions that get taller and thinner. And for what you tend to want to do with it, these work as definition and intuition. But they are not quite correct, and so some things (like what you tried to do) don't quite work. So what is $\delta(t)$? The best way to define it is as a "generalized function" or "distribution," namely a linear functional which takes in a function and spits out a value. In this case, $\delta(f)=f(0)$. But if the delta function isn't really a function, what does it mean to take its derivative? First, we need to look at a wide class of functionals, which explains why they are called generalized functions. Let $f$ smooth and bounded function. Define an operator $\Lambda_f$ which takes a smooth compactly supported function $g$ and returns $$\displaystyle \Lambda_f(g)=\int_{\mathbb R} fg dx.$$ We want to define the derivative of a functional such that $D\Lambda_f = \Lambda_{Df}$. We would therefore like to find a way to define $\Lambda_{Df}$ without using $Df$. (Note, by $Df$ I just mean $f'$, but the prime is hard to read in the subscript) We can do this using integration by parts. Because $g$ is compactly supported, we won't get any boundary terms, and so we get$$\int_{\mathbb R} f'g dx = \int_{\mathbb R} f(-g') dx$$ Thus, given an arbitrary functional $\Lambda$, we can define $D\Lambda$ by the formula $D\Lambda(g)=-\Lambda(g')$. This "derivative" is called the weak derivative . If $f$ is differentiable, the weak derivative yields the derivative, but for functions that aren't differentiable (like the step function), this gives a new notion of derivative. In this case, we get "generalized functions" which are NOT of the form $\Lambda_f$ for some function $f$. A quick word of warning: we equip some sort of norm on our space of functions, and when we look at functionals, we only want to think about the ones which are bounded operators . Thus, while we can define the weak derivative of any functional, the weak derivative of a bounded functional might no longer be bounded, and hence the weak derivative doesn't always "exist" where we want it to. In any case, $\delta$ is the weak derivative of the step function, and it satisfies $\delta(f)=f(0)$. We can take the derivative to get $D\delta(g)=-\delta(g')=-g'(0)$, and similarly $D^n\delta(g)=(-1)^ng^{(n)}(0)$. There isn't really a good sense in which you could call these odd or even "functions", as you don't really evaluate them at points, but rather at functions, although the even derivatives do vanish when you plug in an odd function and vice versa. Generalized functions and their weak derivatives enjoy a lot of nice properties (all the nice properties of derivatives, and more!), and are quite useful for expressing ideas that are intuitive but hard to make rigorous otherwise. How much you really want to worry about the details depends almost entirely on whether you plan on being an analyst.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/43114', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5971/']}
jdg_80777
stackexchange
llm_judgeable_groundtruth_similarity
4235131
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: In the book Asymptotics and Special Functions by Frank Olver, an integral formula of Legendre reads $$\int_0^\infty{\frac{\sin(\lambda x)\mathrm{d}x}{e^{2\pi x}-1}}=\frac{1}{2(e^\lambda-1)}-\frac{1}{2\lambda}+\frac{1}{4}\text{ for }\lambda>0$$ Which is then used to prove an already-well-known integral(by repeatedly differentiating with respect to $\lambda$ and setting $\lambda=0$ in the formula above): $$\int_0^\infty{\frac{x^{2s-1}\mathrm{d}x}{e^{2\pi x}-1}}=(-1)^{s-1}\frac{B_{2s}}{4s}\text{ for }s>1$$ However, the author introduced, that the first formula can be obtained by straightforwardly integrating the function $\frac{e^{-i\lambda{z}}}{e^{2\pi{z}}-1}$ , in which $\lambda>0$ , around a rectangle with vertices at $0,K,K+i,i$ , and indentations at $0$ and $i$ . Then let $K\to\infty$ and the indentations shrink to zero. I literally don't see how this works, if simply applied residue theorem, and how are the integrals combined. Could someone please show me more details about the process producing the first formula through such integration? Very appreciative. Ps. I'm not a native English speaker, so I got confused with what he intrinsically meant by the term "indentations", the contour wasn't drawn so there's not an illustration ;) EDIT. HUUUGE gratitude to Mark Viola, I finally figured out the method. The core is to only consider the imaginary part of the integral, which won't diverge. (Added) Here's a modified version of my first approach following Mark's answer: (Equivalent) Choose $0<\delta<\frac{1}{2}$ $$I=\int_\delta^K{\frac{e^{-i\lambda{x}}\mathrm{d}x}{e^{2\pi x}-1}}+\int_K^\delta{\frac{e^{-i\lambda(x+i)}\mathrm{d}x}{e^{2\pi(x+i)}-1}}+\int_K^{K+i}{\frac{e^{-i\lambda{x}}\mathrm{d}x}{e^{2\pi{x}}-1}}+e^\lambda\int_0^{\frac{3}{2}\pi}{\frac{e^{-i\lambda\delta{e^{i\theta}}}i\delta{e^{i\theta}}\mathrm{d}\theta}{e^{2\pi\delta{e^{i\theta}}}-1}}+\int_{\frac{\pi}{2}}^{2\pi}{\frac{e^{-i\lambda\delta{e^{i\theta}}}i\delta{e^{i\theta}}\mathrm{d}\theta}{e^{2\pi\delta{e^{i\theta}}}-1}}+\int_{\delta{i}}^{i-\delta{i}}{\frac{e^{-i\lambda x}\mathrm{d}x}{e^{2\pi x}-1}}=I_1+I_2+I_3+I_4+I_5+I_6$$ $I=i(e^\lambda+1)$ by residue theorem. Taking the limit, $$\Im(I_1+I_2)=\int_0^\infty{\Im(\frac{e^{-i\lambda{x}}}{e^{2\pi x}-1})\mathrm{d}x}(1-e^\lambda)=(e^\lambda-1)\int_0^\infty{\frac{\sin(\lambda x)\mathrm{d}x}{e^{2\pi x}-1}}$$ $$\left|I_3\right|\le\max_{0\le{x}\le1}{\left|\frac{e^{-i\lambda(ix+K)}}{e^{2\pi(ix+K)}-1}\right|}\to 0$$ $$\Im(I_4)=e^{\lambda}\int_0^{\frac{3}{2}\pi}{\Im(\frac{ie^\lambda}{2\pi}+O(\delta))\mathrm{d}\theta}=\frac{3e^\lambda}{4}$$ $$\Im(I_5)=\int_{\frac{\pi}{2}}^{2\pi}{\Im(\frac{ie^\lambda}{2\pi}+O(\delta))\mathrm{d}\theta}=\frac{3}{4}$$ $$\Im(I_6)=-\int_\delta^{1-\delta}{\Im(i\frac{e^{\lambda x}}{e^{2\pi ix}-1})\mathrm{d}x}=-\int_\delta^{1-\delta}{-\frac{e^{\lambda x}}{2}\mathrm{d}x}=_{\delta\to0}\frac{e^\lambda-1}{2\lambda}$$ Combine the results and we get the result. Now provide the response and nothing else.
We begin by writing the integral around the prescribed contour $C$ as the sum of six integrals. Proceeding, we obtain $$\begin{align}\int_{C}\frac{e^{-i\lambda z}}{e^{2\pi z}-1}\,dz&=\int_{\varepsilon}^K \frac{e^{-i\lambda x}}{e^{2\pi x}-1}\,dx-\int_{\varepsilon}^K \frac{e^{-i\lambda (x+i)}}{e^{2\pi x}-1}\,dx\\\\&+\int_0^1 \frac{e^{-i\lambda (K+iy)}}{e^{2\pi (K+iy)}-1}\,i\,dy-\int_{\varepsilon}^{1-\varepsilon}\frac{e^{-i\lambda(iy)}}{e^{2\pi(iy)}-1}\,i\,dy\\\\&-\int_0^{\pi/2}\frac{e^{-i\lambda(\varepsilon e^{i\phi})}}{e^{2\pi (\varepsilon e^{i\phi})}-1}\,i\varepsilon e^{i\phi}\,d\phi-\int_{3\pi/2}^{2\pi}\frac{e^{-i\lambda(i+\varepsilon e^{i\phi})}}{e^{2\pi \varepsilon e^{i\phi}}-1}\,i\varepsilon e^{i\phi}\,d\phi\tag1\end{align}$$ As $K\to \infty$ , it is straightforward to show that the sum of the first three integral, $I_1$ , $I_2$ , and $I_3$ , respectively, on the right-hand side of $(1)$ is given by $$\lim_{K\to\infty}(I_1+I_2+I_3)=(1-e^{\lambda})\int_\varepsilon^\infty \frac{e^{-i\lambda x}}{e^{2\pi x}-1}\,dx\tag2$$ Taking the imaginary part of $(2)$ and letting $\varepsilon\to 0^+$ , we find $$\lim_{K\to\infty \\ \varepsilon \to 0^+}\text{Im}(I_1+I_2+I_3)=-(1-e^{\lambda})\int_\varepsilon^\infty \frac{\sin(\lambda x)}{e^{2\pi x}-1}\,dx\tag3$$ The fourth integral can be written as $$\begin{align}I_4&=-i\int_{\varepsilon}^{1-\varepsilon}\frac{e^{\lambda y}}{e^{2\pi(iy)}-1}\,dy\\\\&=-\frac i2\int_{\varepsilon}^{1-\varepsilon} \frac{e^{\lambda y}((\cos(2\pi y)-1)-i\sin(2\pi y))}{1-\cos(2\pi y)}\,dy\\\\&=\frac i2 \int_{\varepsilon}^{1-\varepsilon} e^{\lambda y}\,dy+\frac12 \int_{\varepsilon}^{1-\varepsilon} \frac{e^{\lambda y}\sin(2\pi y)}{1-\cos(2\pi y)}\,dy \tag4\end{align}$$ Taking the imaginary part of $(4)$ and letting $\varepsilon\to 0^+$ reveals $$\lim_{\varepsilon \to 0^+}\text{Im}(I_4)=\frac{e^{\lambda}-1}{2\lambda}\tag5$$ For the fifth and sixth integrals on the right-hand side of $(1)$ it easy easy to show that as $\varepsilon\to 0^+$ we have $$\lim_{\varepsilon \to 0^+}\text{Im}(I_5+I_6)=-\frac12+\frac{1-e^{\lambda}}{4}\tag6$$ Combining $(3)$ , $(5)$ , and $(6)$ and aplying Cauchy'y Integral Theorem yields the result $$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \frac{\sin(\lambda x)}{e^{2\pi x}-1}\,dx=\frac1{2(e^{\lambda}-1)}-\frac1{2\lambda}+\frac14}$$ as was to be shown!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4235131', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/653168/']}
jdg_80778
stackexchange
llm_judgeable_groundtruth_similarity
414139
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There are many models for $(\infty,1)$ -categories: simplicial categories, Segal categories, complete Segal spaces, and quasi-categories. Doubtlessly the model most used to do higher category theory in is the model of quasi-categories, due to the work of Lurie ( Higher Topos Theory , Kerodon ), who calls them $\infty$ -categories. Just browsing through these books, I noticed that however, simplicial categories are used too, for instance to construct examples of quasi-categories, as in the construction of the quasi-category of spaces : there is a simplicial category of Kan complexes, and to get the quasi-category of Kan complexes we take the homotopy coherent nerve (also called simplicial nerve in HTT I think) of that. Question: If simplicial categories are a more practical model for actually constructing examples, why are quasi-categories used for most of the theory? That is, what advantages do quasi-categories have over simplicial categories that outweigh the complications of constructing quasi-categories directly? Now provide the response and nothing else.
As a preface, I think that this question should be viewed as analogous to "what are the advantages of ZFC over type theory" or vice versa. We're talking about foundations -- in principle, it doesn't matter what foundations you use; you end up with an equivalent model-independent theory of $\infty$ -categories. The paradigm is "use simplicial categories for examples; use quasicategories for general theorems". There are a lot of constructions which are simpler in quasicategories. I tend to think that a lot of the difference is visible at the model category level: the Joyal model structure on $sSet$ is just much nicer to work with than the Bergner model structure on $sCat$ (of course, the latter is still theoretically very important, at the very least for the purposes of importing examples which start life as simplicial categories). Some of these differences are: The Joyal model structure is defined on a presheaf category. The Joyal model structure is cartesian, making it much easier to talk about functor categories. In the Joyal model structure, every object is cofibrant. There's a synergy between (1) and (2) -- if $X$ is a quasicategory and $A$ is any simplicial set, then the mapping simplicial set $Map(A,X)$ gives a correct model for the functor category from $A$ to $X$ -- you don't need to do any kind of cofibrant replacement of $A$ . This is nicely explained in Justin Hilburn's answer . (2) is quite convenient. For example, in general frameworks like Riehl and Verity's $\infty$ -cosmoi , a lot of headaches are avoided by assuming something like (2). Here are a few examples of some things which are easier in quasicategories -- I'd be curious to hear other examples folks might mention! The join functor is very nice. Consequently (in combination with the nice mapping spaces), limits and colimits can be defined pretty cleanly. An example of a theorem proven in HTT using quasicategories which I imagine would be hard to prove (maybe even to formulate) directly in simplicial categories is the theorem that an $\infty$ -category with products and pullbacks has all limits. The proof uses the fact that the nerve of the poset $\omega$ is equivalent to a 1-skeletal (non-fibrant) simplicial set, and relies on knowing how to compute co/limits indexed by non-fibrant simplicial sets like this. The theory of cofinality is very nice, arising from the (left adodyne, left fibration) weak factorization system on the underlying category -- I imagine it would be quite complicated with simplicial categories. Roughly at this point in the theory, though, one starts to have enough categorical infrastructure available that it becomes more possible to think "model-independently", and the differences start to matter less. Here's a few more: When you take the maximal sub- $\infty$ -groupoid of a quasicategory, it is literally a Kan complex, ready and waiting for you to do simpicial homotopy with. This is especially nice when you take the maximal sub- $\infty$ -groupoid of a mapping object -- which doesn't quite make the model structure simplicial, but it's kind of "close". The theory of fibrations is pretty nice in quasicategories -- just like in ordinary categories, left, right, cartesian, and cocartesian fibrations are "slightly-too-strict" notions which are very useful and have nice properties like literally being stable under pullback. I don't know what the theory of such fibrations looks like in simplicial categories. The fact that $sSet$ is locally cartesian closed is sneakily useful. Even though $Cat_\infty$ is not locally cartesian closed, there's a pretty good supply of exponentiable functors, and it's not uncommon to define various quasicategories using the right adjoint to pullback of simplicial sets. (Rule of thumb: in HTT, when Lurie starts describing a simplicial set by describing its maps in from simplices over a base, 90% of the time he's secretly describing the local internal hom of simplicial sets.)
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/414139', 'https://mathoverflow.net', 'https://mathoverflow.net/users/475383/']}
jdg_80779
stackexchange
llm_judgeable_groundtruth_similarity
540065
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'm a laywoman in physics and recently found myself pondering about the matter reflected in the title of this post. To make my question more precise from the mathematical standpoint, let's suppose you are given a 3D image of the momentary positions of the nuclei of all atoms of an unknown monoatomic substance in a certain volume at a certain moment of time. Rotating the image in a 3D visualization program, you see that the positions look pretty chaotic from any angle, unlike a crystalline structure. You know neither the image's scale nor any of the parameters such as the pressure or temperature. The only information you are given is that the substance is not ionized and is in a thermodynamic equilibrium and either in the liquid state or in the gaseous state and that the pressure and the temperature are below the critical pressure and the critical temperature, respectively. You can extract the numerical XYZ positions and do any calculations with them, but, as stated above, you don't know the scale. How can you tell whether it's a liquid or a gas? What criterion can be used to reach that end? My first guess was that whilst a gas doesn't have any correlation between the positions, a liquid does, but then I realized it's a wrong answer because a gas is not necessarily an ideal gas, so it's unclear to me how I can tell whether it's a liquid or a gas if there's some correlation between the positions in the image. I tried to find the answer on the Internet and this SE, but did not succeed and humbly hope that physics experts on this SE can tell me the answer. UPDATE: Sure, the limiting cases of an ideal gas and a tightly packed liquid are easy, but what do I do in the general case? In other words, how can I deduce whether it's a liquid or a gas if the spread of distances between neighboring nuclei is moderate, that is, neither very small nor very large? Now provide the response and nothing else.
Everything you've said is correct, which is why the conclusion is: there is no fundamental difference! Under the modern classification, they're just the same fluid phase of matter. For example, consider the phase diagram of water . If you take water vapor, slowly heat it up, then pressurize it, and then slowly cool it down, you'll end up with liquid water. This entire process is completely smooth. There isn't any sharp point, like a phase transition, where the behavior qualitatively changes; thus we can't make a sharp distinction between liquids and gases. There are fluids that are "liquid-like" (densely packed, strong interactions between neighbors) and fluids that are "gas-like" (sparse, weak interactions between neighbors) but no dividing line, just like how there's no moment where a shade of grey changes from white to black. By contrast, ice really can be distinguished from liquid water or water vapor. You can't turn either of the two into ice without crossing a phase transition. At that point, the atoms will suddenly become ordered, and you can see this from a snapshot of their positions. Edit: in response to the 25 comments, I'm not saying there's no difference between liquids and gases, I'm saying that there are clearly liquid-like things, and clearly gas-like things, but a continuous spectrum between them. Here are some properties that characterize gases: large distance between molecules weak interactions large mean free path high compressibility very low surface tension upward density fluctuations at small separation The opposite properties characterize liquids. In the easy cases, you could use any of these to make the call. But all of these properties change continuously as you go from one to the other, as long as you go around the critical point. This isn't true for a solid/liquid or solid/gas phase transition.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/540065', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/253093/']}
jdg_80780
stackexchange
llm_judgeable_groundtruth_similarity
661881
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Obviously the reader doesn't like this format incoming from the response XML. Wondering if I can reformat this. Trying to convert to DateTime using the following code with my XmlReader : reader.ReadContentAsDateTime(); Now provide the response and nothing else.
Xml readers generally expect dates/times in a very specific format; you can use this yourself using XmlConvert : string s = XmlConvert.ToString(DateTime.Now);DateTime when = XmlConvert.ToDateTime(s); If you are using something else, you'll have to read it as a string and use DateTime.TryParseExact (or similar) to specify the actual format string: string s = reader.ReadContentAsString();DateTime when = DateTime.ParseExact(s, "M/d/yy hh:mm tt", CultureInfo.InvariantCulture); If you are using XmlSerializer , you could use a shim property to do the conversion - let me know if this is what you are doing...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/661881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72603/']}
jdg_80781
stackexchange
llm_judgeable_groundtruth_similarity
33907465
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 intelligently handle the success/error responses from our API using fetch & ES6 promises. Here is how I need to handle response statuses: 204: has no json response, but need to treat as success406: should redirect to sign in422: has json for error message< 400 (but not 204): success, will have json>= 400 (but not 422): error, will not have json So, I am struggling with how to write this cleanly. I have some less than stellar code working right now that looks like this: fetch() .then(response => checkStatus(response)) .then(parseJSON) //will throw for the 204 .then(data => notify('success', someMsg)) .catch(error => checkErrorStatus(error)) .then(parseJSON) .then(data => notify('error', dataForMsg) .catch(error => notify('error', someGenericErrorMsg) But it seems pretty weird to use catch twice and I don't know how to deal with that 204 just yet. Also, just to clarify checkStatus and checkErrorStatus do a similar thing: export function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { let error = new Error(response.statusText) error.response = response throw error }}function checkErrorStatus(error) { if(error.response.status === 422) { return error.response } else { let error = new Error(response.statusText) error.response = response throw error }} Any suggestions for cleaning this up? Now provide the response and nothing else.
I think you can write it out pretty easily: fetch(…).then(response => { if (response.ok) return response[response.status == 204 ? "text" : "json"](); if (response.status == 422) return response.json().then(err => { throw err; }); if (response.status == 406) var error = new AuthentificationError(response.statusText); // or whatever else var error = new Error(response.statusText) error.response = response throw error;})
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33907465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/301833/']}
jdg_80782
stackexchange
llm_judgeable_groundtruth_similarity
65044704
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 write a test with the new cypress 6 interceptor method ( Cypress API Intercept ). For the test I am writing I need to change the reponse of one endpoint after some action was performed. Expectation: I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture. Actual Behaviour: Cypress still response with the first fixture set for the call. Test Data: In a test project I have recreated the problem: test.spec.js describe('testing cypress', () => { it("multiple responses", () => { cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' }); // when visiting the page it makes one request to http://localhost:4200/testcall cy.visit('http://localhost:4200'); cy.get('.output').should('contain.text', '111'); // now before the button is clicked and the call is made again // cypress should change the response to the other fixture cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' }); cy.get('.button').click(); cy.get('.output').should('contain.text', '222'); });}); example.json { "text": "111"} example2.json { "text": "222"} app.component.ts import { HttpClient } from '@angular/common/http';import { AfterViewInit, Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements AfterViewInit { public text: string; public constructor(private httpClient: HttpClient) { } public ngAfterViewInit(): void { this.loadData(); } public loadData(): void { const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => { this.text = response.body; loadDataSubscription.unsubscribe(); }); }} app.component.html <button class="button" (click)="loadData()">click</button><p class="output" [innerHTML]="text"></p> Now provide the response and nothing else.
Slightly clumsy, but you can use one cy.intercept() with a Function routeHandler , and count the calls. Something like, let interceptCount = 0; cy.intercept('http://localhost:4200/testcall', (req) => { req.reply(res => { if (interceptCount === 0 ) { interceptCount += 1; res.send({ fixture: 'example.json' }) } else { res.send({ fixture: 'example2.json' }) } }); }); Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65044704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2844348/']}
jdg_80783
stackexchange
llm_judgeable_groundtruth_similarity
9144658
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 site that have Createuser page and i put the asp.net createuser in it.my site have roles i.e a user that create it's account must have a role. But create user control only create user and can not construct it's role so new user doesn't have any role how can i give role to new users? Now provide the response and nothing else.
Let's try a hack: first we try to prevent or revert any scrolling whenever the user presses a key we turn the element's overflow property to visible to avoid scrolling of the content, but hide the element at the same time by setting its opacity to 0. Immediately afterwards we switch overflow back to hidden and show the element again. to avoid flickering we create a clone of the editable element (with overflow: hidden ) and show this element while the original one is hidden. Here we go (uses jQuery for DOM convenience): $(function() { var editableElement = $('#editable'), clonedElement; // Revert any scrolling editableElement.on("scroll", function(event) { editableElement.scrollTop(0); // Try to prevent scrolling completely (doesn't seem to work) event.preventDefault(); return false; }); // Switch overflow visibility on and off again on each keystroke. // To avoid flickering, a cloned element is positioned below the input area // and switched on while we hide the overflowing element. editableElement.on("keydown", function() { // Create a cloned input element below the original one if (!clonedElement) { var zIndex = editableElement.css('zIndex'); if (isNaN(parseInt(zIndex, 10))) { zIndex = 10; editableElement.css({zIndex: zIndex}); } clonedElement = editableElement.clone(); clonedElement.css({ zIndex: zIndex-1, position: 'absolute', top: editableElement.offset().top, left: editableElement.offset().left, overflow: 'hidden', // Set pseudo focus highlighting for webkit // (needs to be adapted for other browsers) outline: 'auto 5px -webkit-focus-ring-color' }); editableElement.before(clonedElement); } else { // Update contents of the cloned element from the original one clonedElement.html(editableElement.html()); } // Here comes the hack: // - set overflow visible but hide element via opactity. // - show cloned element in the meantime clonedElement.css({opacity: 1}); editableElement.css({overflow: 'visible', opacity: 0}); // Immediately turn of overflow and show element again. setTimeout(function() { editableElement.css({overflow: 'hidden', opacity: 1}); clonedElement.css({opacity: 0}); }, 10); });}); Check this jsFiddle to play with the above code. Note that this may not be a complete solution (I have only tried it with Safari, Chrome and Firefox yet), but for the tested browsers it seems to work. You may want to fine-tune and polish your implementation (e.g. focus highlighting). In the jsFiddle example I have also turned off spell checking to avoid flickering markings.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9144658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/578462/']}
jdg_80784
stackexchange
llm_judgeable_groundtruth_similarity
28602308
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 with Go channels and confused with below function example from go blog: func gen(nums []int) <-chan int { out := make(chan int) go func() { for _, n := range nums { out <- n } close(out) }() fmt.Println("return statement is called ") return out} Main : func main() { c := make(chan int) c = gen([]int{2, 3, 4, 5}) // Consume the output. // Print 2,3,4,5 fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c)} Complete Code: http://play.golang.org/p/Qh30wzo4m0 My Doubts: My understanding was, once return is called the function will be terminated and the channel inside that function has no more life. The return statement is called only once. But the content of the out channel is read many times. In this case what is the actual flow of execution? (I'm new to concurrent programming.) Now provide the response and nothing else.
out := make(chan int) This is not a buffered channel, which means the out <- n will block until someone somewhere reads that channel (the fmt.Println(<-c) calls) (See also " do golang channels maintain order ") So the return at the end of the gen() function doesn't mean the literal go func() is terminated (since it is still waiting for readers to consume the content of the out channel). But main function getting out channel as return from gen() function. How it is possible to get it after gen() is terminated? The fact that gen() terminates has no effect on its returned value (the out channel): the goal of " gen() " is to "generate" that out channel. main can use out (as the returned value of gen() ) long after gen() terminates. The literal go func within gen() still runs, even if gen() is terminated. As noted by vagabond in the comments : When gen() returns, there is still a reference to the out channel, which makes it not garbage collected. It doesn't matter if the gen() has a go routine closure is using the channel. When a channel is not used, the sender can close the channel explicitly. And then the select for the channel will make the go routine to exit. At last, everything will be cleared.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28602308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4175099/']}
jdg_80785
stackexchange
llm_judgeable_groundtruth_similarity
18080638
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my signup form I have a nickname field that users can enter text in to identify themselves on my site. In the past some users have entered nicknames which others might find offensive. Laravel provides validation functionality for forms, but how can I ensure that a form field doesn't contain words users might find offensive? Now provide the response and nothing else.
Whilst Laravel has a wide range of validations rules included, checking for the presence of a word from a given list isn't one of them: http://laravel.com/docs/validation#available-validation-rules However, Laravel also allows us to create our own custom validation rules: http://laravel.com/docs/validation#custom-validation-rules We can create validation rules using Validator::extend() : Validator::extend('not_contains', function($attribute, $value, $parameters){ // Banned words $words = array('a***', 'f***', 's***'); foreach ($words as $word) { if (stripos($value, $word) !== false) return false; } return true;}); The code above defines a validation rule called not_contains - it looks for presence of each word in $words in the fields value and returns false if any are found. Otherwise it returns true to indicate the validation passed. We can then use our rule as normal: $rules = array( 'nickname' => 'required|not_contains',);$messages = array( 'not_contains' => 'The :attribute must not contain banned words',);$validator = Validator::make(Input::all(), $rules, $messages);if ($validator->fails()){ return Redirect::to('register')->withErrors($validator);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18080638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867611/']}
jdg_80786
stackexchange
llm_judgeable_groundtruth_similarity
2554894
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way construct a predicate to filter by class type? I currently loop through the array and check to the class of each object. Maybe there is a cleaner way? Now provide the response and nothing else.
You could add a category to NSObject that adds a "cf_className" method, like so: @interface NSObject (CFAdditions)- (NSString *) cf_className;@end@implementation NSObject (CFAdditions)- (NSString *) cf_className { return NSStringFromClass([self class]);}@end From there, you can use predicates like: NSPredicate * p = [NSPredicate predicateWithFormat:@"cf_className = %@", aClass];NSArray * filtered = [anArray filteredArrayUsingPredicate:p]; If you're on the Mac, you can just use -[NSObject className] instead of having to create the category. The iPhone doesn't have that method, hence the need for a category.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2554894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48311/']}
jdg_80787
stackexchange
llm_judgeable_groundtruth_similarity
10622260
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 you query a column for any value in that column? (ie. How do I build a dynamic where clause that can either filter the value, or not.) I want to be able to query for either a specific value, or not. For instance, I might want the value to be 1, but I might want it to be any number. Is there a way to use a wild card (like "*"), to match any value, so that it can be dynamically inserted where I want no filter? For instance: select int_col from table where int_col = 1 // Query for a specific valueselect int_col from table where int_col = * // Query for any value The reason why I do not want to use 2 separate SQL statements is because I am using this as a SQL Data Source, which can only have 1 select statement. Now provide the response and nothing else.
Sometimes I would query for actual value (like 1, 2...) so I can't not have a condition either. I take it you want some dynamic behavior on your WHERE clause, without having to dynamically build your WHERE clause. With a single parameter, you can use ISNULL (or COALESCE ) like this: SELECT * FROM Table WHERE ID = ISNULL(@id, ID) which allows a NULL parameter to match all. Some prefer the longer but more explicit: SELECT * FROM Table WHERE (@id IS NULL) OR (ID = @id)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10622260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/468384/']}
jdg_80788
stackexchange
llm_judgeable_groundtruth_similarity
2773824
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Apart from the fact that HashSet does not allow duplicate values, what is the difference between HashMap and HashSet ? I mean implementation wise? It's a little bit vague because both use hash tables to store values. Now provide the response and nothing else.
They are entirely different constructs. A HashMap is an implementation of Map . A Map maps keys to values. The key look up occurs using the hash. On the other hand, a HashSet is an implementation of Set . A Set is designed to match the mathematical model of a set. A HashSet does use a HashMap to back its implementation, as you noted. However, it implements an entirely different interface. When you are looking for what will be the best Collection for your purposes, this Tutorial is a good starting place. If you truly want to know what's going on, there's a book for that , too.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2773824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/202325/']}
jdg_80789
stackexchange
llm_judgeable_groundtruth_similarity
301670
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: If I know that $N \sim {\rm Ge}(p)$ and I set $X = (-1)^N$ How do I find $E[X]$ and ${\rm Var}[X]$? Any insight? Thanks Now provide the response and nothing else.
let $r=sin^2(x)$ we have $$\sum_{k=1}^n r^k=\frac{r(1-r^n)}{1-r}=2013$$Now we want:$$\sum_{k=1}^n (1-r)^k=\frac{(1-r)(1-(1-r)^n)}{r}$$ We can deduce:$$2013\sum_{k=1}^n (1-r)^k=(1-r^n)(1-(1-r)^n)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/301670', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/61147/']}
jdg_80790
stackexchange
llm_judgeable_groundtruth_similarity
43069
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 have started to study quantum mechanics. I know linear algebra,functional analysis, calculus, and so on, but at this moment I have a problem in Dirac bra-ket formalism . Namely, I have problem with "translation" from ordinary linear algebra "language" to this formalism. For better understanding of the problem, I'll give some definitions which I use: 1) Assume, that $\mid u\rangle$ is a vector in Hilbert vector space $V$. Bra $\langle v \mid$ is a vector of dual vector space $V^{*}$ $\left(\langle v \mid: V \longrightarrow C \right)$, defined by $\langle v \mid u \rangle=g\left(\mid v\rangle, \mid u\rangle \right) $, where $g: V \times V \longrightarrow C$ is metric on $V$. 2)$A$ is linear operator on $V$. Consider bilinear form $(\quad)$: $\left(f,x\right )=f(x)$. In this notation we can define adjoint operator $A^{*}$ on $V^{*}$:$(f,Ax)=(A^*f,x)$. I tried to understand two following equations: There is expression $\langle v \mid A \midu \rangle$. In my text book was written the following phrase:"Operator $A$ acts on ket from the left and on bra on the right". But according to the difenitions that i use, adjoint operator $A^{*}$ acts on $V^{*}$.But in this case operator $A$ acts on $V^{*}$. I dont absolutely get it. One possible solution which i see is that this is just a notation of the next thing:$\langle v \mid A \mid u \rangle=(v,Au)=(A^{*}v,u)= \langle A^{*}v \mid u \rangle; \quad A^*\langle v \mid :=\langle v \mid A$ The second way is to use isomorphism between $V$ and $V^{*}$, and then operator $A$ is able to act on $V$ and $V^{*}$ (Dual Correspondence). The third way is that we use a matrix representation everywhere;and in expression $\langle v \mid A \midu \rangle$ we multiply a row $v$ on matrix of operator $A$ on column $u$. Then this expression absolutely clear because the multiplication of matrix's is associative. The same difficulties i have with expression $(A \mid v \rangle)^{*}=\langle v \mid A^ \dagger$. Could you explain it to? I would be happy, if you will say which way is right and if all of my suggestions are wrong, please, tell me the right one. Now provide the response and nothing else.
The wording used in your textbook was sloppy. $A$ acts as $A^*$ on a bra, as $\langle u\rvert A\lvert v\rangle:=\langle u\lvert Av\rangle~$ is the same as $\langle u\rvert A\lvert v\rangle=\langle A^*u\lvert v\rangle~$, by definition of the adjoint. The latter formula also shows that $\langle A^*u\rvert=\langle u\rvert A$. Everything becomes very simple in linear algebra terms when interpreting a ket as a colum vector, the corresponding bra as the conjugate transposed row vector, an operator as a square matrix, and the adjoint as the conjugate transpose. This is indeed the special case when the Hilbert space is $C^n$.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/43069', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/14494/']}
jdg_80791
stackexchange
llm_judgeable_groundtruth_similarity
2323377
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone tell me the difference between an AuthenticationManager and an AuthenticationProvider in Spring Security? How are they used and how are they called. It is my understanding that a SecurityFilter will call the AuthenticationManager to authenticate an Authentication object? But then where does the AuthenticationProvider come into play? Thanks! Now provide the response and nothing else.
I think the AuthenticationManager delegates the fetching of persistent user information to one or more AuthenticationProvider s. The authentication-providers ( DaoAuthenticationProvider, JaasAuthenticationProvider, LdapAuthenticationProvider, OpenIDAuthenticationProvider for example) specialize in accessing specific user-info repositories.Something else is mentioned in this part of the reference manual. It says: You may want to register additional AuthenticationProvider beans with the ProviderManager and you can do this using the element with the ref attribute, where the value of the attribute is the name of the provider bean you want to add. In other words, you can specify multiple AuthenticationProviders, for example one that looks for users in an LDAP database and another that looks in an SQL database.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2323377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247230/']}
jdg_80792
stackexchange
llm_judgeable_groundtruth_similarity
4651373
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 to pass html as a string instead of url in wkhtmltopdf using asp.net, c#? Now provide the response and nothing else.
STDIn and STDOut have been redirected in this example, so you shouldn't need files at all. public static class Printer{ public const string HtmlToPdfExePath = "wkhtmltopdf.exe"; public static bool GeneratePdf(string commandLocation, StreamReader html, Stream pdf, Size pageSize) { Process p; StreamWriter stdin; ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = Path.Combine(commandLocation, HtmlToPdfExePath); psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName); // run the conversion utility psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; // note: that we tell wkhtmltopdf to be quiet and not run scripts psi.Arguments = "-q -n --disable-smart-shrinking " + (pageSize.IsEmpty? "" : "--page-width " + pageSize.Width + "mm --page-height " + pageSize.Height + "mm") + " - -"; p = Process.Start(psi); try { stdin = p.StandardInput; stdin.AutoFlush = true; stdin.Write(html.ReadToEnd()); stdin.Dispose(); CopyStream(p.StandardOutput.BaseStream, pdf); p.StandardOutput.Close(); pdf.Position = 0; p.WaitForExit(10000); return true; } catch { return false; } finally { p.Dispose(); } } public static void CopyStream(Stream input, Stream output) { byte[] buffer = new byte[32768]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4651373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570397/']}
jdg_80793
stackexchange
llm_judgeable_groundtruth_similarity
270369
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me. What are the most common scenarios you have found where you need to clone an object? Now provide the response and nothing else.
I assume you are referring to Object.clone() in Java. If yes, be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/270369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26787/']}
jdg_80794
stackexchange
llm_judgeable_groundtruth_similarity
1449987
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So everyone probably knows that glibc's /lib/libc.so.6 can be executed in the shell like a normal executable in which cases it prints its version information and exits. This is done via defining an entry point in the .so. For some cases it could be interesting to use this for other projects too. Unfortunately, the low-level entry point you can set by ld's -e option is a bit too low-level: the dynamic loader is not available so you cannot call any proper library functions. glibc for this reason implements the write() system call via a naked system call in this entry point. My question now is, can anyone think of a nice way how one could bootstrap a full dynamic linker from that entry point so that one could access functions from other .so's? Now provide the response and nothing else.
Update 2: see Andrew G Morgan's slightly more complicated solution which does work for any GLIBC (that solution is also used in libc.so.6 itself (since forever), which is why you can run it as ./libc.so.6 (it prints version info when invoked that way)). Update 1: this no longer works with newer GLIBC versions: ./a.out: error while loading shared libraries: ./pie.so: cannot dynamically load position-independent executable Original answer from 2009: Building your shared library with -pie option appears to give you everything you want: /* pie.c */#include <stdio.h>int foo(){ printf("in %s %s:%d\n", __func__, __FILE__, __LINE__); return 42; }int main() { printf("in %s %s:%d\n", __func__, __FILE__, __LINE__); return foo(); }/* main.c */#include <stdio.h>extern int foo(void);int main() { printf("in %s %s:%d\n", __func__, __FILE__, __LINE__); return foo(); }$ gcc -fPIC -pie -o pie.so pie.c -Wl,-E$ gcc main.c ./pie.so$ ./pie.soin main pie.c:9in foo pie.c:4$ ./a.outin main main.c:6in foo pie.c:4$ P.S. glibc implements write(3) via system call because it doesn't have anywhere else to call (it is the lowest level already). This has nothing to do with being able to execute libc.so.6 .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1449987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175104/']}
jdg_80795
stackexchange
llm_judgeable_groundtruth_similarity
15084007
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following code was compiled with VC++ Nov 2012 CTP on Windows 7 x64. #include <fstream>using namespace std;int main(){ ofstream fout("log.txt", ios::app|ios::trunc); if (!fout) { cout << "An error occurred!" << endl; // Always go here! Why? }} The cppreference.com website doesn't say that ios::app cannot be combined with ios::trunc . What are the exact semantics of ios::app and ios::trunc ? Now provide the response and nothing else.
The filebuf constructor to which these flags are passed † has behaviours based on those flags defined in Table 132 in C++11: +-----------------------------------+-------------------+| ios_base flag combination | stdio equivalent || binary in out trunc app | |+-----------------------------------+-------------------+| + | "w" || + + | "a" || + | "a" || + + | "w" || + | "r" || + + | "r+" || + + + | "w+" || + + + | "a+" || + + | "a+" |+-----------------------------------+-------------------+| + + | "wb" || + + + | "ab" || + + | "ab" || + + + | "wb" || + + | "rb" || + + + | "r+b" || + + + + | "w+b" || + + + + | "a+b" || + + + | "a+b" |+-----------------------------------+-------------------+ As you can see, your flag combination is not found in that table. [C++11: 27.9.1.4/2]: [..] If mode is not some combination of flags shown in the table then the open fails. Those are the semantics. † [C++11: 27.9.1.7/2] & [C++11: 27.9.1.11/2] show us that the mode is passed from the stream object to the buffer object.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15084007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508343/']}
jdg_80796
stackexchange
llm_judgeable_groundtruth_similarity
27503379
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 use a calculated column in a where clause. I've trying everything from CROSS APPLY, to sub-query select but it does not give me the anything near what I need. My query so far: SELECT p.Code, c.AccountNumber, Sales = (SUM(p.UnitPrice) * SUM(od.QtyShipped)) FROM [dbo].Customer c LEFT JOIN [dbo].OrderHeader oh ON oh.CustomerId = c.Id LEFT JOIN [dbo].OrderDetail od ON od.OrderHeaderId = oh.Id LEFT JOIN [dbo].Product p ON p.Id = od.ProductIdWHERE Sales > 100GROUP BY p.Code, c.AccountNumber, Sales This does not work, as 'Sales' is an invalid column Now provide the response and nothing else.
Using Derived Columns in a predicate You'll need to wrap the inner query in a derived table or CTE in order to be able to use derived columns in the WHERE clause (Also, note SUM() is specified just once, using the results of the multiplication): SELECT x.Code, x.AccountNumber, x.SalesFROM( SELECT p.Code, c.AccountNumber, SUM(p.UnitPrice *od.QtyShipped) AS Sales FROM [dbo].Customer c LEFT JOIN [dbo].OrderHeader oh ON oh.CustomerId = c.Id LEFT JOIN [dbo].OrderDetail od ON od.OrderHeaderId = oh.Id LEFT JOIN [dbo].Product p ON p.Id = od.ProductId GROUP BY p.Code, c.AccountNumber) AS xWHERE x.Sales > 100; Repeating the Derived Column in a HAVING clause As per @Jonny's comment, the other way is not to DRY up the calculated column, but to instead repeat the calculation. Use HAVING instead of WHERE after a GROUP BY has been applied. SELECT p.Code, c.AccountNumber, SUM(p.UnitPrice *od.QtyShipped) AS Sales FROM [dbo].Customer c LEFT JOIN [dbo].OrderHeader oh ON oh.CustomerId = c.Id LEFT JOIN [dbo].OrderDetail od ON od.OrderHeaderId = oh.Id LEFT JOIN [dbo].Product p ON p.Id = od.ProductIdGROUP BY p.Code, c.AccountNumberHAVING SUM(p.UnitPrice * od.QtyShipped) > 100; In either case, as per comments below, note that the calculated expression is SUM(p.UnitPrice * od.QtyShipped) and not SUM(p.UnitPrice) * SUM(od.QtyShipped) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27503379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/428682/']}
jdg_80797
stackexchange
llm_judgeable_groundtruth_similarity
26569144
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 format currency input in a textfield in Swift as the user inputs it. So far, I can only format it successfully when the user finishes inputting: @IBAction func editingEnded(sender: AnyObject) { let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale(localeIdentifier: "en_US") var numberFromField = NSString(string: textField.text).doubleValue textField.text = formatter.stringFromNumber(numberFromField)} However, I would like for the currency to be formatted the moment the user inputs it. When I try to do it on the TextField actions "Editing Changed" or "Value Changed", I can only enter 1 number (if I enter 8, it becomes $8.00) but then once I enter a second number everything goes to $0.00 and I cannot enter further beyond that. Any suggestions? I feel like this should be an easy fix but I can't quite get at it. Now provide the response and nothing else.
I modified the function from earlier today. Works great for "en_US" and "fr_FR". However, for "ja_JP", the division by 100 I do to create decimals is a problem. You will need to have a switch or if/else statement that separates currencies with decimals and those that do not have them when formatted by the formatter. But I think this gets you in the space you wanted to be. import UIKitclass ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! var currentString = "" override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self } //Textfield delegates func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return NO to not change text switch string { case "0","1","2","3","4","5","6","7","8","9": currentString += string println(currentString) formatCurrency(string: currentString) default: var array = Array(string) var currentStringArray = Array(currentString) if array.count == 0 && currentStringArray.count != 0 { currentStringArray.removeLast() currentString = "" for character in currentStringArray { currentString += String(character) } formatCurrency(string: currentString) } } return false } func formatCurrency(#string: String) { println("format \(string)") let formatter = NSNumberFormatter() formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle formatter.locale = NSLocale(localeIdentifier: "en_US") var numberFromField = (NSString(string: currentString).doubleValue)/100 textField.text = formatter.stringFromNumber(numberFromField) println(textField.text ) }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26569144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3293742/']}
jdg_80798
stackexchange
llm_judgeable_groundtruth_similarity
7078110
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 wondering if it's possible to use a CFG or PEG grammar as a basis for code completion directly without modification. I have heard that code completion is in IDE's is sometimes manipulated and massaged or even hard coded so that it performs better. I want to code complete on a small DSL so I fully understand that a grammar cannot help a code completion system with knowledge of library functions etc. As far as I'm aware the parser itself needs to at least provide a system for querying what it expects next. In particular I'm interested in a javascript code completion solution using peg.js or jison Now provide the response and nothing else.
It is fairly easy to build Javascript editor with code completion from PEG grammar. I would describe how to do it with PEG.js . You need to extend your grammar with some lax parsing rules that allow to provide suggestions when previous statements are broken. These lax rules need to be handled conditionally or you will need two separate grammars - one for parsing source and second for code completion. You can maintain one grammar by using Javascript predicates (available in PEG.js ). It looks like &{return laxParsing} and it causes that whole rule to be processed when laxParsing flag is true . You can switch between lax and strict parsing easily by setting parser's internal flag. To provide suggestions to user easily you must modify slightly generated PEG.js parser (version 0.5) to receive in the parsing error structure position (beside the column and line) and list of expectations (beside the error message). You can copy prepared fragment from https://gist.github.com/1281239 . When you have parser then you can attach it in editor on for example CTRL+SPACE keypress. When these are pressed in text source you need to put a special unparseable sign in place of cursor (to cause a parsing error) and launch parser in lax mode. Then you receive an error with list of suggestions. Some of suggestions are not only syntax but also they define references (e.g. entities, variables). You can trigger searching these when a particular expectation is found (e.g. VariableName ). You can provide the list by parsing the same source in a different lax parsing mode (filtering only variable names). For a working example and source to this approach you can check on https://github.com/mstefaniuk/Concrete-Freetext .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7078110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16744/']}
jdg_80799
stackexchange
llm_judgeable_groundtruth_similarity
19919
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 was doing a mass recursive change of permissions of some files that I had migrated to a unix system. I changed them to ug+rw, but then I found that I could not traverse subdirectories. I looked at the man page for chmod and didn't see any explanation for excluding directories, so I googled a little and found that people used find to recursively change the permissions on directories to 'execute' for user and group. I did that and then I could look into them. But it seemed to me that I should be able to be able to do this find chmod -- to recursively change the files to read/write but not make the directories untraversable. Have I done this the 'right' way or is there a simpler way to do it? Now provide the response and nothing else.
The better solution should be chmod -R ug=rwX,o=rX /path where the capital X means: set execute bit if the file is a directory or already has execute permission for some user (quoted from chmod man page). Or also, if you want to use find find /path \( -type f -exec chmod ug=rw,o=r {} + \) -o \ \( -type d -exec chmod ug=rwx,o=rx {} + \)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/19919', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/394/']}
jdg_80800
stackexchange
llm_judgeable_groundtruth_similarity
339747
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is kinda noob question. I recently got an SCR Power controller ( WATLOW DIN-a-mite DB20-24CO-0000 Style B ). This is the first time I actually got to test an SCR controller for myself. The input trigger is 4VDC to 32VDC, which I powered with a fully charged Li-ion at 4.1V . AC input:115VAC from 12V inverter and out is a 115V digital panel meter (I wanted to try first with a low powered device) though its meant for a heater. As per the specs the SCR is rated for 25Amps. Similar or even higher rated current relays are available and much smaller in size. So,is there any specific reason for using an SCR power controller over a higher current relay/contactor? Also, is an SCF power controller same as an Solid State Relay? Now provide the response and nothing else.
So,is there any specific reason for using an SCR power controller over a higher current relay/contactor? [From comments: What I meant to ask is if a simple SCR triggered controller (ignoring the above example) is better than a relay?] Yes, there are several advantages: No moving parts. Usually can switch very frequently (although the datasheet for the part you chose suggests that these should run a 3 s duty-cycle minimum). Zero-cross turn-off. One of the characteristics of SCRs (including triacs) is that once triggered they remain on until current falls below the hold-on value at the next zero-cross. The possibility of zero-cross switching at the turn-on point. This type of SSR will, when triggered, wait until the next zero-cross before turning on. Both this and the zero-cross turn-off result in much reduced electro-magnetic interference (EMI). The possibility of dimming. See Figure 1. Figure 1. With non zero-cross SSRs dimming is possible. Proportional power is still possible with zero-cross SSRs but on a longer time scale. This is usually more than adequate for heater control where the time constants are long. See Figure 2. Figure 2. Proportional on-off time control. Note that step size is one half-cycle minimum. This can make the response seem coarse if the repeat time is short. SSRs are silent. Also is an SSR almost same as SCR triggered controller? simulate this circuit – Schematic created using CircuitLab Figure 3. A very simple SSR (a), a thyristor (b) and a triac (c). An SSR (a) will have electrical isolation between the trigger circuit and the actual SCR. An SCR controller might not and, at its simplest, might just be a thyristor or triac. Note that in Figure 3a I have shown a constant current source to represent the internal circuitry that allows the SSR to work over a wide range of input voltages - 4 to 32 V in your example. For more information see: Confusion with TRIAC firing and zero crossing point . Using AC current to trigger Triac .
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/339747', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/148074/']}
jdg_80801
stackexchange
llm_judgeable_groundtruth_similarity
15210548
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 use Font Awesome on my application, I was able to integrate the font using Typeface.createFromAsset() , but I also want to use the icons provided by this font, but so far I haven't been able to do that. This particular font contains icons inside the Unicode Private Use Area (PUA), for things like media player controls, file system access, arrows, etc. Has anybody used fonts that contain icons and symbols on Android, is this possible at all? Now provide the response and nothing else.
Font Awesome seems to be working fine for me in my android app. I did the following: Copied fontawesome-webfont.ttf into my assests folder Found the character entities for icons I wanted, using this page: http://fortawesome.github.io/Font-Awesome/cheatsheet/ Created an entry in strings.xml for each icon. Eg for a heart: <string name="icon_heart">&#xf004;</string> Referenced said entry in the view of my xml layout: <Button android:id="@+id/like" style="?android:attr/buttonStyleSmall" ... android:text="@string/icon_heart" /> Loaded the font in my onCreate method and set it for the appropriate Views: Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );...Button button = (Button)findViewById( R.id.like );button.setTypeface(font);
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/15210548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536466/']}
jdg_80802
stackexchange
llm_judgeable_groundtruth_similarity
19846
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Microeconomics producer surplus is equivalent to profits minus fixed costs. However getting a tangible definition of consumer surplus has been difficult for me to ponder. What is the practical use of knowing consumer surplus and what does it tell us? Now provide the response and nothing else.
It is better to think of it as a "saving" rather than as a"surplus".Also, it is better understood if we imagine heterogeneous consumers for whom a threshold price exists, a "maximum willingness to pay". Then at a given price level, some consumers are willing to buy the product and are expressing their demand for the product, while others are out of the market, because the price is still above their maximum willingness to pay. If the price falls more towards the equilibrium, they enter the market.But the ones already in the market would be willing to buy the good at a higher price. With the added consumers/higher output, they buy the good in a lower price than their maximum willingness to pay, and in that sense, they "save". Imagine that the market demand function is build gradually not by the same persons increasing their quantity demanded, but by the addition of new consumers (this is easier imagined if we think of durable goods of which most consumers will usually buy just one unit or not at all).
{}
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/19846', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/8815/']}
jdg_80803
stackexchange
llm_judgeable_groundtruth_similarity
27020048
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 the data from my fusion tables. when I use SELECT query the data show successfull. but when I'm using SUM and MAXIMUM query the firebug show error : "SyntaxError: syntax errorError 500 (There's a p" when i test my query from fusion query the query works. when i search based from firebug error, it's because i'm not specify the script tag to script type="text/javascript" . but i think it's not actualy the error i get, because yesterday my code works. and today i don't know why my code doesn't works. Can anybody help me? thanks for any help. <!DOCTYPE html><html> <head> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> // Fusion Table data ID var FT_TableID = '1j1AG2s_IgNBQmm0QP9yYGHFg2_rNSZoEH4ee80In'; var FT_TableIDSP = '1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR'; google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']}); function getKP() { // set the query using the parameters var FT_Query_KP = "SELECT 'Kelompok Penanam', count() FROM "+FT_TableID+" GROUP by 'Kelompok Penanam' ORDER by 'idPenanam'"; //var FT_Query_KP = "SELECT SUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR"; //var FT_Query_KP = "SELECT MAXIMUM('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR"; var queryText = encodeURIComponent(FT_Query_KP); var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText); //set the callback function query.send(KP); } // Set a callback to run when the Google Visualization API is loaded. function KP(response) { if (!response) { alert('no response'); return; } if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var KPname = response.getDataTable().getValue(0,0); document.getElementById('dropdownKP').innerHTML = KPname; } </script> <script type="text/javascript"> getKP(); </script> </head> <body> <div id="dropdownKP"></div> </body></html> Now provide the response and nothing else.
Note: The kpm command has been replaced by dnu. Visual Studio 2015 Preview (as of writing this) comes with the ASP.NET 5 stable release beta1. In this version there is no way to reference a csproj project from an ASP.NET 5 project. However, on the development feed of ASP.NET 5 the command kpm wrap was introduced to support referencing csproj-projects from ASP.NET 5 projects. See the github issue #827 in the aspnet/KRuntime repository and pull request #875 which closes the issue. Here is an example how you would use kpm wrap : Make sure the newest version of the KRuntime is installed (check this with the kvm list command) (I tested this with version 1.0.0-beta2-10709 ). Create an ASP.NET 5 class library project, I used the name ClassLibrary1. Create a "normal" csproj class library, I named this ClassLibrary2 (make sure you put this in the src folder). From the commandline, from the solutiondirectory run the command kpm wrap .\src\ClassLibrary2 This gives the output: Wrapping project 'ClassLibrary2' for '.NETFramework,Version=v4.5' Source C:\Users\andersns\Source\ClassLibrary1\src\ClassLibrary2\ClassLibrary2.csproj Target C:\Users\andersns\Source\ClassLibrary1\wrap\ClassLibrary2\project.json Adding bin paths for '.NETFramework,Version=v4.5' Assembly: ../../src/ClassLibrary2/obj/debug/ClassLibrary2.dll Pdb: ../../src/ClassLibrary2/obj/debug/ClassLibrary2.pdb Now in the project.json of ClassLibrary1 (which is ASP.NET 5) you can add a reference to ClassLibrary2 with this: ..."dependencies": { "ClassLibrary2": ""},... Note: kpm wrap did not run properly for me with cmd, I needed to launch powershell to make it run.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27020048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3991099/']}
jdg_80804
stackexchange
llm_judgeable_groundtruth_similarity
15906580
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 tried configuring gtk+ on visual studio but doesn't work properly., Can anyone suggest me with a proper solution, as how to install gtk on Visual studio 2010 Now provide the response and nothing else.
I got GTK+ working with VS2010, so if you want to get it working too, get ready for some fun, because this will take a few minutes. First of all, download the latest Windows All-In-One bundle . Optional direct download link for the GTK 2.24 bundle that I used here . The direct link is to the 32bit version. I have not tested the 64bit version because it is still listed as experimental. Once you have the bundle downloaded, unzip it into something like C:\gtk or in my case D:\gtk Next we will create a System Environment Variable for the GTK folder. Open up a command prompt and write: setx GTKDIR {Path to your GTK folder} /m which in my case would be setx GTKDIR D:\gtk /m We are also going to add the .dll files required for GTK+ built applications to run on Windows into our system PATH. To make things very easy, I suggest you edit your system PATH with PathEditor . Now add the path to the GDK binaries folder which in my case is D:\gtk\bin to the system PATH. Confirm the GTK bin folder has been added to the PATH by typing PATH into your command prompt. Now we move on to Visual Studio 2010 and create a new project. File ->New ->Project Visual C++ ->Win32 ->Win32 Console Application Then the Application Wizard Appears. Click to select: Windows ApplicationEmpty Project click Finish to proceed. Before we add any source files, right click on the project name in the Solution Explorer and click on Properties . Now go to Configuration Properties and then VC++ Directories . We now need to add the include and library files from GTK to the Include Directories and Library Directories . You should have the following in your Include Directories $(GTKDIR)\lib\gtk-2.0\include$(GTKDIR)\lib\glib-2.0\include$(GTKDIR)\include and Library Directories : $(GTKDIR)\lib While we are still in the view of the Project Properties, click on Linker and then System . Look for SubSystem on the right and click the drop down box. Select Windows /SUBSYSTEM:WINDOWS Next up, we have to generate the flags for the compiler and the linker. Luckily, GTK+ comes with a nice little tool called pkg-config that we will use to automatically generate these flags for us. The pkg-config tool can be found in the bin folder of GTK. In my case this is D:\gtk\bin or %GTKDIR%\bin using our system variable that we defined earlier. Simply navigate to the bin folder(the created text files will be output there) using the command prompt and run the following: pkg-config --cflags gtk+-2.0 --msvc-syntax > compilerflags.txt This will create the compiler flags we need and store them in a text file.My Result for compiler flags (I have removed the flag -mms-bitfields , this is a gcc only flag that we don't need): -ID:/gtk/include/gtk-2.0 -ID:/gtk/lib/gtk-2.0/include -ID:/gtk/include/atk-1.0 -ID:/gtk/include/cairo -ID:/gtk/include/gdk-pixbuf-2.0 -ID:/gtk/include/pango-1.0 -ID:/gtk/include/glib-2.0 -ID:/gtk/lib/glib-2.0/include -ID:/gtk/include -ID:/gtk/include/freetype2 -ID:/gtk/include/libpng14 We will do the same for the linker flags: pkg-config --libs gtk+-2.0 --msvc-syntax > linkerflags.txt My Result for linker flags: /libpath:D:/gtk/lib gtk-win32-2.0.lib gdk-win32-2.0.lib atk-1.0.lib gio-2.0.lib pangowin32-1.0.lib gdi32.lib pangocairo-1.0.lib gdk_pixbuf-2.0.lib pango-1.0.lib cairo.lib gobject-2.0.lib gmodule-2.0.lib gthread-2.0.lib glib-2.0.lib intl.lib With all the needed flags generated, we need to add them to our project. Once again, right click on the project name and click on Properties . Now go to C/C++ and click on Command Line . To the right you should see an empty box called Additional Options . Copy and paste the compilerflags.txt content into this box. After finishing the above, click on Linker and then Command Line . Once again, simply copy and paste the contents of the linkerflags.txt file into the Additional Options box. While we are here, add one last linker flag /ENTRY:mainCRTStartup This flag tells Visual Studio that we want to use the standard main() rather than Microsoft's _tmain() as our main program entry point. Finally, in the Source Files folder, create and add a new .cpp file with the following: #include <gtk-2.0\gtk\gtk.h>int main(int argc, char* argv[]){ gtk_init(&argc, &argv); GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_set_usize(window, 300, 200); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); gtk_window_set_title(GTK_WINDOW(window), "GTK+ with VS2010"); gtk_widget_show(window); gtk_main(); return 0;} Everything should now be ready to compile, link and run. If all went well, you should be greeted by the following: Well that was fun, right? :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15906580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1990438/']}
jdg_80805
stackexchange
llm_judgeable_groundtruth_similarity
146499
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: For example the Four-velocity transforms as $$U^{a'}=\Lambda^{a'}{}_{\nu}U^{\nu},$$the Faradaytensor as $$F^{a'b'}=\Lambda_{\,\,\mu}^{a'}\Lambda_{\,\,\nu}^{b'}F^{\mu\nu}$$ or in Matrixnotation:$$F'=\Lambda F\Lambda^{T},$$where $\Lambda^{T}$ is the Transpose of the Matrix. But the Lorentz matrix $\Lambda^{\mu}{}_{\nu}$ is not a tensor.Does $\Lambda$ transform anyway like a second rank tensor in the same way like the Faradaytensor? Now provide the response and nothing else.
It is a transform, not a tensor. Tensors describe a physical quantity at a selected point in time-space and have to transform accordingly. But the Lorentz matrix doesn't describe any physical quantity in a single frame, it's just a change of variables between two coordinate frames. You can understand this by analogy with 3D rotations. Transforms are composed (multiplied) together: if you go from coordinates $a$ to $a'$ and then from $a'$ to $a''$, you multiply the transforms to get a direct transform from $a$ to $a''$.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/146499', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/22207/']}
jdg_80806
stackexchange
llm_judgeable_groundtruth_similarity
61544854
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Python doc __future__ In python doc about __future__ there is a table below where it shows thatannotations "optional in" 3.7.0b1 and "mandatory in" 4.0but i am still able to use annotations in 3.8.2 without importing annotations then what is the use of it. >>> def add_int(a:int, b:int) -> int:... return a + b>>> add_int.__annotations__{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>} I doubt I don't clearly understand the meaning of "optional in" and "mandatory in" here Now provide the response and nothing else.
Mandatory is an interesting word choice. I guess it means that it's by default in the language. You don't have to enable it with from __future__ import annotations The annotations feature are referring to the PEP 563: Postponed evaluation of annotations. It's an enhancement to the existing annotations feature which was initially introduced in python 3.0 and redefined as type hints in python 3.5, that's why your code works under python 3.8. Here's what optional from __future__ import annotations changes in python 3.7+: class A: def f(self) -> A: # NameError: name 'A' is not defined pass but this works from __future__ import annotationsclass A: def f(self) -> A: pass See this chapter in python 3.7 what's new about postponed annotations: Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a __future__ import: from __future__ import annotations It will become the default in Python 3.10 *. * it was announced to be default in 3.10 (when python3.7 was released), but it was now moved to a later release
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/61544854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12655601/']}
jdg_80807
stackexchange
llm_judgeable_groundtruth_similarity
36107581
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Output files generated via the Spark SQL DataFrame.write() method begin with the "part" basename prefix. e.g. DataFrame sample_07 = hiveContext.table("sample_07");sample_07.write().parquet("sample_07_parquet"); Results in: hdfs dfs -ls sample_07_parquet/ Found 4 items-rw-r--r-- 1 rob rob 0 2016-03-19 16:40 sample_07_parquet/_SUCCESS-rw-r--r-- 1 rob rob 491 2016-03-19 16:40 sample_07_parquet/_common_metadata-rw-r--r-- 1 rob rob 1025 2016-03-19 16:40 sample_07_parquet/_metadata-rw-r--r-- 1 rob rob 17194 2016-03-19 16:40 sample_07_parquet/part-r-00000-cefb2ac6-9f44-4ce4-93d9-8e7de3f2cb92.gz.parquet I would like to change the output filename prefix used when creating a file using Spark SQL DataFrame.write(). I tried setting the "mapreduce.output.basename" property on the hadoop configuration for the Spark context. e.g. public class MyJavaSparkSQL { public static void main(String[] args) throws Exception { SparkConf sparkConf = new SparkConf().setAppName("MyJavaSparkSQL"); JavaSparkContext ctx = new JavaSparkContext(sparkConf); ctx.hadoopConfiguration().set("mapreduce.output.basename", "myprefix"); HiveContext hiveContext = new org.apache.spark.sql.hive.HiveContext(ctx.sc()); DataFrame sample_07 = hiveContext.table("sample_07"); sample_07.write().parquet("sample_07_parquet"); ctx.stop(); } That did not change the output filename prefix for the generated files. Is there a way to override the output filename prefix when using the DataFrame.write() method? Now provide the response and nothing else.
You cannot change the "part" prefix while using any of the standard output formats (like Parquet). See this snippet from ParquetRelation source code : private val recordWriter: RecordWriter[Void, InternalRow] = { val outputFormat = { new ParquetOutputFormat[InternalRow]() { // ... override def getDefaultWorkFile(context: TaskAttemptContext, extension: String): Path = { // .. // prefix is hard-coded here: new Path(path, f"part-r-$split%05d-$uniqueWriteJobId$bucketString$extension") } }} If you really must control the part file names, you'll probably have to implement a custom FileOutputFormat and use one of Spark's save methods that accept a FileOutputFormat class (e.g. saveAsHadoopFile ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36107581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6087738/']}
jdg_80808
stackexchange
llm_judgeable_groundtruth_similarity
138296
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is the time constant (RC) measured in seconds even though the units are farads x ohms? This is to fulfill my own curiosity as I haven't had much luck at finding the answer. I would be most grateful if someone could give me a solid answer or send me in the right direction. Now provide the response and nothing else.
It's the way the units work out. Broken down to its form in SI units, a volt is $$\mathrm{V = \frac{kg \cdot m^2}{A \cdot s^3}}$$ where A is amperes. So, when you divide by current to get ohms, you see that $$ \Omega = \mathrm{\frac{kg \cdot m^2}{A^2\cdot s^3}}$$ A farad is: $$ \mathrm{F=\frac{s^4 \cdot A^2}{m^2 \cdot kg}} $$ So when you multiply Ohms by Farads, you're left with seconds: $$ \Omega \cdot \mathrm{F = \frac{kg \cdot m^2}{A^2\cdot s^3} \cdot \frac{s^4 \cdot A^2}{m^2 \cdot kg} = s} $$
{}
{'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/138296', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/58168/']}
jdg_80809
stackexchange
llm_judgeable_groundtruth_similarity
10515548
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 iTextSharp DLL in ASP.NET code. I am fetching a data into dataset and Add the dataset into PDF table. If my dataset have more 100 rows then 100 rows will be added into PDF table and 3 or 4 page will be created in PDF file. How can I add the footer in each page? Now provide the response and nothing else.
You need to inherit from PdfPageEventHelper class and override the methods shown in the code snippet below: Document doc = new Document(PageSize.A4.Rotate()); using (MemoryStream ms = new MemoryStream()){ PdfWriter writer = PdfWriter.GetInstance(doc, ms); PageEventHelper pageEventHelper = new PageEventHelper(); writer.PageEvent = pageEventHelper;} public class PageEventHelper : PdfPageEventHelper { PdfContentByte cb; PdfTemplate template; public override void OnOpenDocument(PdfWriter writer, Document document) { cb = writer.DirectContent; template = cb.CreateTemplate(50, 50); } public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); int pageN = writer.PageNumber; String text = "Page " + pageN.ToString() + " of "; float len = this.RunDateFont.BaseFont.GetWidthPoint(text, this.RunDateFont.Size); iTextSharp.text.Rectangle pageSize = document.PageSize; cb.SetRGBColorFill(100, 100, 100); cb.BeginText(); cb.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size); cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin)); cb.ShowText(text); cb.EndText(); cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin)); } public override void OnCloseDocument(PdfWriter writer, Document document) { base.OnCloseDocument(writer, document); template.BeginText(); template.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size); template.SetTextMatrix(0, 0); template.ShowText("" + (writer.PageNumber - 1)); template.EndText(); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10515548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384417/']}
jdg_80810
stackexchange
llm_judgeable_groundtruth_similarity
27972
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? Edit: Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option? Edit 2: Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of HttpOnly ? Edit 3: Here is a quote from Wikipedia: When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The HttpOnly flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33]. I understand that document.cookie is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? In your example, I cannot write to your document.cookie , but I can still steal your cookie and post it to my domain using the XMLHttpRequest object. <script type="text/javascript"> var req = null; try { req = new XMLHttpRequest(); } catch(e) {} if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} req.open('GET', 'http://stackoverflow.com/', false); req.send(null); alert(req.getAllResponseHeaders());</script> Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated... Final Edit: Ahh, apparently both sites are wrong, this is actually a bug in FireFox . IE6 & 7 are actually the only browsers that currently fully support HttpOnly. To reiterate everything I've learned: HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers) HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7. XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies. edit: This information is likely no longer up to date. Now provide the response and nothing else.
Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server. In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the "vote" controller method. More generally, cookies are not required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required. However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end. In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object. XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on). You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible. Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie. Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only? Consider this scenario: I find an avenue to inject JavaScript code into the page. Jeff loads the page and my malicious JavaScript modifies his cookie to match mine. Jeff submits a stellar answer to your question. Because he submits it with my cookie data instead of his, the answer will become mine. You vote up "my" stellar answer. My real account gets the point. With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt. Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated... That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though. However, if you go back to my example scenario, you can see where HTTP-Only does successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon). It boils down to the fact that a) no single improvement will solve all vulnerabilities and b) no system will ever be completely secure. HTTP-Only is a useful tool in shoring up against XSS. Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26/']}
jdg_80811
stackexchange
llm_judgeable_groundtruth_similarity
40593242
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a service foo.service which depends on service bar.service . I need to make sure that bar.service is started before foo.service and that bar.service launched successfully. From this source it says that Requires : This directive lists any units upon which this unit essentially depends. If the current unit is activated, the units listed here must successfully activate as well, else this unit will fail. These units are started in parallel with the current unit by default. and that After : The units listed in this directive will be started before starting the current unit. This does not imply a dependency relationship and one must be established through the above directives if this is required. Is it correct to have both the Requires and After sections in the same unit file? Requires says that the service will be launched in parallel, but After says it will be launched before. If bar.service fails to start during the After condition, will it attempt to launch it again during the Requires section? If so I need to find another way to launch foo.service foo.service [Unit]After=bar.serviceRequires=bar.service Now provide the response and nothing else.
It is perfectly fine to use both After= and Requires= . They have different purposes. Requires= sets up a start dependency. systemd makes sure that if any body is trying to start foo.service, it should start bar.service too. Should bar.service fails at some point, then foo.service is taken down too. After= is putting a start order between services. If both of the services are scheduled to start, then After= makes sure the start order is set. You can look at systemd's own service file as an example. /lib/systemd/system/basic.target[Unit]...Requires=sysinit.targetAfter=sysinit.target...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40593242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3280538/']}
jdg_80812
stackexchange
llm_judgeable_groundtruth_similarity
5895
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: When exporting a dashed plot with a color gradient to a vector graphics format such as EPS or PDF, the dashing is partly ruined. For example, this command: Plot[x^2, {x, -2, 2}, PlotStyle -> Directive[Dashed, Thick], ColorFunction -> Hue] Creates the following plot: However, when exporting the plot to EPS or PDF, I get this plot (notice the ruined dashing, especially near the vertex of the parabola): Am I doing something wrong, or is this a bug? If it is a bug, is there a workaround? I am using Mathematica version 8.0.4.0 ( edit: on Win7 64bit) Edit: I got an email from wolfram support, which I understand confirms this is a bug. Until they fix it, any workarounds which properly export the plot as vector graphics are welcome. Now provide the response and nothing else.
The VertexColors that get introduced when a ColorFunction is specified are not rendered smoothly in the exported PDF - no matter what other options (such as Dashed ) you specify. So we really have two problems here. Bad color gradients along the line, and incorrect computation of the dash spacing. If you don't care too much about the bad color gradients and just want a plot with an acceptable dashing, you could do something like this: Show[#, Graphics[{Thickness[.01], White, Dashing[{.02, .04}], Cases[Normal@#[[1]], Line[_], Infinity]}]] &@ Plot[x^2, {x, -2, 2}, PlotStyle -> Thickness[.008], ColorFunction -> Hue] Here I have taken your original Plot and initially removed the dashing. Before showing this plot, I extract from it the Line that was produced, re-draw it a second time with dashing and slightly larger thickness at the background color ( White ). Finally, I place the dashed white line on top of the continuous colored line to get the appearance of a dashed colored line. For this to look correct in the exported PDF , you have to play with the Dashing and Thickness manually. The dashing in the export will look different from the notebook. In particular, the second number in Dashing[{0.02,0.04}] must always be bigger than the first, or else you don't see anything! Here is what the exported PDF looks like with the above command: If you do care about the bad color gradients in addition to the dashing, then I would suggest going with bitmap export right now because it would take a bitmap-based hack to get smooth color gradients in the PDF anyway.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/5895', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/253/']}
jdg_80813
stackexchange
llm_judgeable_groundtruth_similarity
6801953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I was looking through some boost source code and came across this: (from <boost/checked_delete.hpp> ) template<class T> inline void checked_delete(T * x){ // intentionally complex - simplification causes regressions typedef char type_must_be_complete[ sizeof(T)? 1: -1 ]; (void) sizeof(type_must_be_complete); delete x;} Anyone happen to know why it is implemented in this way? Wouldn't sizeof(T) (for example) already be enough? Now provide the response and nothing else.
Someone asked the same question earlier . This post written by Peter Dimov ( one of the writers of boost/checked_delete.hpp ) pretty much speaks for itself: What's the result of applying sizeof to an incomplete type? A compile-time error, unless the compiler chooses to return 0 as a nonstandard extension. Why is sizeof called twice? The second sizeof is a workaround for a Metrowerks CodeWarrior bug in which the first typeof is never instantiated unless used. Why is the result of sizeof cast to void? What exactly does that line do? Silences a compiler warning.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6801953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755653/']}
jdg_80814
stackexchange
llm_judgeable_groundtruth_similarity
25066360
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 file which has entries as below. /a/b/c/d/e/f/a/b/c/g/k/l/f/j/h/a/b/c/i/m/n/p I need a command in Windows which would remove the '/a/b/c' part from the file. The output file should look like d/e/fg/k/l/f/j/hi/m/n/p I tried using the for command with / as the delimiter, but I couldn't get the expected result.How can I do this? Now provide the response and nothing else.
@echo off(for /f "tokens=3,* delims=/" %%a in (input.txt) do echo %%b) > output.txt And the "trick" is to ask for the third token and the rest of the line. To use it directly from the command line: (for /f "tokens=3,* delims=/" %a in (input.txt) do @echo %b) > output.txt The escaped percent signs are simplified and, as from command line the echo off is not enabled by default, the @ before echo is needed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25066360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3437212/']}
jdg_80815
stackexchange
llm_judgeable_groundtruth_similarity
132244
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Assume there are two Riemannian metrics on a manifold ( open or closed) with the same set of all geodesics. Are they proportional by a constant? If not in general, what are the affirmative results in this direction? Now provide the response and nothing else.
The short answer is no , the geodesics do not determine the metric. For example, in the Cayley-Klein model of hyperbolic geometry the geodesics are straight lines. It is however rather rare fortwo Riemannian metrics to have the same geodesics. In two dimensions these metrics were studied by Liouville (see Livre VI of Darboux's Théorie générale des surfaces ). Their geodesic flow is completely integrable and, in fact, admits an additional integral of motion quadratic in the momenta. A basic results is that if locally the geodesics are straight lines (or can be mapped to straight lines), the metric has constant curvature (Beltrami's theorem). Other rigidity results of this kind exist. For more on this topic you can consult the works of Topalov and Matveev.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/132244', 'https://mathoverflow.net', 'https://mathoverflow.net/users/26250/']}
jdg_80816
stackexchange
llm_judgeable_groundtruth_similarity
13516730
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 override the enter key functionality on a JTable. At present the default behaviour is to move the row selection down one row when the user presses the 'Enter' key. I want to disable this and get it to do something different based on their selection. The problem is that it seems to move down before it goes into my keylistener which takes in the row selection - this therefore opens another window with the wrong row selected. This is my code so far...: public class MyJTable extends JTable { public MyJTable(){ setRowSelectionAllowed(true); addListeners() } public void addListeners(){ addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { openChannel(); } } }); } public void openChannel(){ for (int selectedRow : getSelectedRows()){ //Code to open channel based on row selected } }} Now provide the response and nothing else.
+1 to @Robin's answer Adding to my comment... Swing uses KeyBinding s simply replace exisitng functionality by adding a new KeyBinding to JTable (the beauty happens because of JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ): private void createKeybindings(JTable table) {table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { //do something on JTable enter pressed } });} simply call this method and pass JTable instance to override standard functionality of JTable ENTER
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13516730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1065547/']}
jdg_80817
stackexchange
llm_judgeable_groundtruth_similarity
17986091
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 needed a singletap touch detect in my custom view's ontouch method. I tried getting the x and y values in both ACTION-DOWN and ACTION-UP and in ACTION-UP I gave a condition that if a the values of X and Y in ACTIONDOWN and ACTION-UP are equal then take it as a single tap. My code is as follows @Overridepublic boolean onTouchEvent(MotionEvent ev) { if (!mSupportsZoom && !mSupportsPan) return false; mScaleDetector.onTouchEvent(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mLastTouchX = x; //here i get x and y values in action down mLastTouchY = y; mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: { final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); if (mSupportsPan && !mScaleDetector.isInProgress()) { final float dx = x - mLastTouchX; final float dy = y - mLastTouchY; mPosX += dx; mPosY += dy; //mFocusX = mPosX; //mFocusY = mPosY; invalidate(); } mLastTouchX = x; mLastTouchY = y; break; } case MotionEvent.ACTION_UP: { final float x = ev.getX(); final float y = ev.getY(); touchupX=x; //here is get x and y values at action up touchupY=y; if(mLastTouchX == touchupX && mLastTouchY == touchupY){ //my condition if both the x and y values are same . PinchZoomPanActivity2.tapped1(this.getContext(), 100); //my method if the singletap is detected } else{ } mActivePointerId = INVALID_POINTER_ID; break; } case MotionEvent.ACTION_CANCEL: { mActivePointerId = INVALID_POINTER_ID; break; } case MotionEvent.ACTION_POINTER_UP: { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); } break; } } return true;} but I cant get it done. I mean at every action up my method is called. even when the x and y values of both actionup and actiondown are not same. and I think I also need to put some range to the singletap as we touch with our finger on the screen. Can anyone suggest me some ways? Now provide the response and nothing else.
To detect Single and Double Tap in android I am using the following methods : class GestureTap extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDoubleTap(MotionEvent e) { Log.i("onDoubleTap :", "" + e.getAction()); return true; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.i("onSingleTap :", "" + e.getAction()); return true; }} Use it in constructor of GestureDetector : detector = new GestureDetector(this, new GestureTap()); And add the following code in onTouch listener @Overridepublic boolean onTouchEvent(MotionEvent event) { detector.onTouchEvent(event); return true;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17986091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2026280/']}
jdg_80818
stackexchange
llm_judgeable_groundtruth_similarity
186832
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: Today, out of curiosity, I took a measurement between the water pipe (presumably to be ground) and an exposed area of the AC socket with metal shielding (supposedly to be ground as well), and got an AC reading of 66 Volts, and 0.21mA. Why? I don't understand Now provide the response and nothing else.
I've seen this happen before. First: I have to make a couple of assumptions because you didn't include enough information in your question. I'm assuming that you have a nominal 120 Vac AC Mains supply. Where I have seen this before is when your outlet is connected to the supply with standard Loomex / Romex 14/2 wire with ground conductor. The problem is that the ground conductor in the cable is not connected at the source. The AC voltage that you measured is coming from the capacitive coupling between the AC Hot and Neutral. Because the ground is about the same distance between each of the insulated conductors, there is about the same amount of capacitance from each of the conductors to the ground wire. This looks like an approximate 2:1 capacitive voltage divider. The amount of current that you are measuring says that there is a fair amount of capacitance between the ground wire and the main conductors. That means that the ground is broken / disconnected quite some distance away from the socket. If the ground was disconnected right at the AC socket, the voltage wouldn't be quite in the middle like it is now and you wouldn't have that much current flowing when you do the current measurement. Regardless, this is a dangerous situation and needs to be fixed. If you can't find the broken or disconnected ground wire, run a separate ground wire from the outlet socket to the cold-water pipe that you used during your testing. Ideally, you would take your ground from the cold-water pipe right when it comes into your building, BEFORE the water meter or shut-off valve.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/186832', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']}
jdg_80819
stackexchange
llm_judgeable_groundtruth_similarity
30166491
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Would someone be willing to provide some alternate solution to the removal of duplicate values from a List (X) using Functional Programming and Elixir Constructs? X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate The stock solution in my mind for solving this problem, would be to iterate the list (X), and add to a new list (Y) where the key doesn't already exist. Thank you Now provide the response and nothing else.
Enum.uniq does what you want, for example: iex(6)> Enum.uniq([1,26,3,40,5,6,6,7])[1, 26, 3, 40, 5, 6, 7] In terms of how you'd implement it you could write a recursive function like so: defmodule Test do def uniq(list) do uniq(list, MapSet.new) end defp uniq([x | rest], found) do if MapSet.member?(found, x) do uniq(rest, found) else [x | uniq(rest, MapSet.put(found, x))] end end defp uniq([], _) do [] endendiex(3)> Test.uniq([1, 1, 2, 3, 4, 4, 1])[1, 2, 3, 4]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30166491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1511546/']}
jdg_80820
stackexchange
llm_judgeable_groundtruth_similarity
10990622
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 test a Rails controller branch that is triggered when the model method raises an error. def my_controller_method @my_object = MyObject.find(params[:id]) begin result = @my_object.my_model_method(params) rescue Exceptions::CustomError => e flash.now[:error] = e.message redirect_to my_object_path(@my_object) and return end # ... rest irrelevantend How can I get a Minitest stub to raise this Error? it 'should show redirect on custom error' do my_object = FactoryGirl.create(:my_object) # stub my_model_method to raise Exceptions::CustomError here post :my_controller_method, :id => my_object.to_param assert_response :redirect assert_redirected_to my_object_path(my_object) flash[:error].wont_be_nilend Now provide the response and nothing else.
require "minitest/autorun"class MyModel def my_method; endendclass TestRaiseException < MiniTest::Unit::TestCase def test_raise_exception model = MyModel.new raises_exception = -> { raise ArgumentError.new } model.stub :my_method, raises_exception do assert_raises(ArgumentError) { model.my_method } end endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10990622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299599/']}
jdg_80821
stackexchange
llm_judgeable_groundtruth_similarity
972
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 read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python. I understand that it's not always good to do so. But how might one do this? Now provide the response and nothing else.
In Python, there is a difference between functions and bound methods. >>> def foo():... print "foo"...>>> class A:... def bar( self ):... print "bar"...>>> a = A()>>> foo<function foo at 0x00A98D70>>>> a.bar<bound method A.bar of <__main__.A instance at 0x00A9BC88>>>>> Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called. Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want: >>> def fooFighters( self ):... print "fooFighters"...>>> A.fooFighters = fooFighters>>> a2 = A()>>> a2.fooFighters<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>>>> a2.fooFighters()fooFighters Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves): >>> a.fooFighters()fooFighters The problem comes when you want to attach a method to a single instance: >>> def barFighters( self ):... print "barFighters"...>>> a.barFighters = barFighters>>> a.barFighters()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: barFighters() takes exactly 1 argument (0 given) The function is not automatically bound when it's attached directly to an instance: >>> a.barFighters<function barFighters at 0x00A98EF0> To bind it, we can use the MethodType function in the types module : >>> import types>>> a.barFighters = types.MethodType( barFighters, a )>>> a.barFighters<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>>>> a.barFighters()barFighters This time other instances of the class have not been affected: >>> a2.barFighters()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: A instance has no attribute 'barFighters' More information can be found by reading about descriptors and metaclass programming .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145/']}
jdg_80822
stackexchange
llm_judgeable_groundtruth_similarity
25371254
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 subclassed UITextField and implemented the UIKeyInput protocol's deleteBackward method to detect backspace being pressed. This works fine on iOS 7 but not on iOS 8. deleteBackward is not called on the UITextField anymore when I press the backspace key. I've checked the documentation and the release notes and nothing points to the reason why this could happen. Any pointers? Now provide the response and nothing else.
A lot of people have been saying this is a bug, but being that this problem still exists in the GM I'm starting to think it might be a change in logic. With that said, I wrote this bit of code for my app and have tested it on iOS 7-8. Add the following method to your UITextField subclass. - (BOOL)keyboardInputShouldDelete:(UITextField *)textField { BOOL shouldDelete = YES; if ([UITextField instancesRespondToSelector:_cmd]) { BOOL (*keyboardInputShouldDelete)(id, SEL, UITextField *) = (BOOL (*)(id, SEL, UITextField *))[UITextField instanceMethodForSelector:_cmd]; if (keyboardInputShouldDelete) { shouldDelete = keyboardInputShouldDelete(self, _cmd, textField); } } BOOL isIos8 = ([[[UIDevice currentDevice] systemVersion] intValue] == 8); BOOL isLessThanIos8_3 = ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.3f); if (![textField.text length] && isIos8 && isLessThanIos8_3) { [self deleteBackward]; } return shouldDelete;} This code is slightly before the red line of private API's, however you should have no problem using it. My app with this code is in the app store. To explain a little, were calling the super implementation of this method to avoid losing code. After were going to call -deleteBackward if there is no text and the iOS version is between 8-8.2. EDIT : 1/22/15 It also might be helpful to subclass the -deleteBackward method of your subclassed UITextField . This fixes a few conditional bugs. One being if you use a custom keyboard. Heres an example of the method. - (void)deleteBackward { BOOL shouldDismiss = [self.text length] == 0; [super deleteBackward]; if (shouldDismiss) { if ([self.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) { [self.delegate textField:self shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""]; } }} EDIT : 4/13/15 As @Gee.E commented, iOS 8.3 has fixed this issue. The code has been updated to reflect the changes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25371254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495337/']}
jdg_80823
stackexchange
llm_judgeable_groundtruth_similarity
3978203
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 something like this: Chapter 1 Preliminaries 1.1 Banach Algebras I tried this: \chapter{}\section*{Preliminaries}\subsection{Banach Algebras} The problem is: As soon as I hide the section number using \section*{Preliminaries} , it changes the numbering of the subsection to 0.1 Banach Algebras . How do I hide the number of the section but keep the number ordering in my subsection? Now provide the response and nothing else.
A quick fix without the hassles of renewing the section command is to use addtocounter. Everytime you use the \section*{} command, right after that you can say \addtocounter{section}{1} \chapter{}\section*{Preliminaries}\addtocounter{section}{1}\subsection{Banach Algebras}\section*{Preliminaries}\addtocounter{section}{1}\subsection{Banach Algebras} This will give you a result of, Chapter 1Preliminaries1.1.1 Banach AlgebrasPreliminaries1.2.2 Banach Algebras Essentially, it is just adding 1 to your section counter whenever you create a section so when the subsection checks the section counter, it has the updated counter. And the advantage is that if you add another section now which needs to be numbered like, \chapter{}\section*{Preliminaries}\addtocounter{section}{1}\subsection{Banach Algebras}\section*{Preliminaries}\addtocounter{section}{1}\subsection{Banach Algebras}\section{Preliminaries} You will get the correct section number (i.e. 1.3) Chapter 1Preliminaries1.1.1 Banach AlgebrasPreliminaries1.2.2 Banach Algebras1.3 Preliminaries The main drawback is that you will have to remember to add to the counter everytime you created a \section*{} You can add \setcounter{subsection}{0} everytime you create one of those sections to reset the subsection counter... sorry I missed that one.Thanks for clarifying.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3978203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/481725/']}
jdg_80824
stackexchange
llm_judgeable_groundtruth_similarity
236901
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $f(X,t_1,\dots,t_s)$ be an irreducible polynomial with coefficients in $\mathcal{O}_K$, the ring of integers of a number field $K$. By work of S. D. Cohen ( http://plms.oxfordjournals.org/content/s3-43/2/227.full.pdf ) I know that the number of specializations $\vec t = (t_1,\dots, t_s)$ in $(\mathcal{O}_K)^s$ of height at most $N$, such that the specialization does not remain irreducible (or even does not retain the original Galois group of $f$) is $O(N^{s-1/2}\log(N))$, with the implied constant depending only on $f, s,$ and $K$. Is this the best result known, in terms of the order of growth in $N$? Is it conjectured that the order can be improved, say to $O(N^{s-1})$? (Maybe not for $s=1?$) Regarding the first two questions, is more known/conjectured in the special case that $f$ is a polynomial in $X$ where precisely $s$ of the coefficients are allowed to vary in $\mathcal{O}_K$? (i.e. $f \in \mathcal{O}_K[t_1,\dots,t_s][X]$, with each coefficient having degree 0 or 1 in $t_1,\dots,t_s$? In this special case, the best results I know of, also due to Cohen ( http://www.projecteuclid.org/euclid.ijm/1256048323 )are of the same order as the more general results, except for $s=1$, where the log factor can be omitted.) As above, but in the special case $K=\mathbb{Q}$? Now provide the response and nothing else.
Have you stated this correctly? Assuming there are $O(N^s)$ possible specializations of height at most $N$, don't you want to say that the specialization remains irreducible except for $O(N^{s-1/2}\log N)$ values. As for question (2), I don't think you can do better than $s-\frac12$. Certainly not for $s=1$, where $X^2-t$ is clearly reducible for $O(\sqrt N)$ values of $t$ with $|t|<N$. Actually, that example works for any $s$, since $X^2-t_1$ is irreducible in $\mathbb{Q}[t_1,\ldots,t_s]$. But if you really want to include all the variables, use $X^2-t_1-t_2-\cdots-t_s$, which is reducible whenever $t_1+\cdots+t_s$ is a square. The underlying reason for the $\frac12$ is because the exceptional values come from rational (or integral) points on non-trivial finite covers. If there happens to be a double cover with a "lot" of rational or integral points, particularly a copy of affine or projective space, then the fact it is a double cover means that it more-or-less squares the height, and then one gets a square root of the number of points in the target space. In other words, the size of the exceptional set is determined by the geometry of the covers that arise in the proof.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/236901', 'https://mathoverflow.net', 'https://mathoverflow.net/users/37644/']}
jdg_80825
stackexchange
llm_judgeable_groundtruth_similarity
47710558
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting error when i call get_execution_role() from sagemaker in python.I have attached the error for the same. I have added the SagemakerFullAccess Policy to role and user both. Now provide the response and nothing else.
get_execution_role() is a function helper used in the Amazon SageMaker Examples GitHub repository . These examples were made to be executed from the fully managed Jupyter notebooks that Amazon SageMaker provides. From inside these notebooks, get_execution_role() will return the IAM role name that was passed in as part of the notebook creation. That allows the notebook examples to be executed without code changes. From outside these notebooks, get_execution_role() will return an exception because it does not know what is the role name that SageMaker requires. To solve this issue, pass the IAM role name instead of using get_execution_role(). Instead of: role = get_execution_role()kmeans = KMeans(role=role, train_instance_count=2, train_instance_type='ml.c4.8xlarge', output_path=output_location, k=10, data_location=data_location) you need to do: role = 'role_name_with_sagemaker_permissions'kmeans = KMeans(role=role, train_instance_count=2, train_instance_type='ml.c4.8xlarge', output_path=output_location, k=10, data_location=data_location)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47710558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4325761/']}
jdg_80826
stackexchange
llm_judgeable_groundtruth_similarity
14395800
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 to switch the transfer mode of pure-ftpd from regular ftp to ftp with TLS.So I've switched the config flag TLS to 2 (only TSL, no regular FTP). The connection and the transfer of files is working fine with filezilla. Now I have a perl script which is getting some files from the server using NET::FTP. This is the main functionality: use Net::FTP;$ftp = Net::FTP->new("[SERVERNAME]", Debug => 1) or die "Cannot connect to [SERVERNAME]: $@";$ftp->login("[USER]",'[PASSWORD]') or die "Cannot login ", $ftp->message;$ftp->cwd("/") or die "Cannot change working directory ", $ftp->message;$ftp->dir("/") or die "get failed ", $ftp->message;$ftp->get("somefile.txt") or die "get failed ", $ftp->message;$ftp->quit; To rebuild the GET functionality, I'm trying to use the CPAN Module NET::FTPSSL with the following script snipplet: use Net::FTPSSL; my $ftps = Net::FTPSSL->new('[SERVERNAME]', Port => 21, Encryption => EXP_CRYPT, Croak => 1, Trace => 1, Debug => 2 ) or die "Can't open [SERVERNAME]\n$Net::FTPSSL::ERRSTR"; $ftps->login('[USER]', '[PASSWORD]') or die "Can't login: ", $ftps->last_message(); $ftps->cwd("/anyfolder") or die "Can't change directory: " . $ftps->last_message(); $ftps->quot("PASV"); $ftps->nlst() or die "Error: " . $ftps->last_message(); $ftps->list("/anyfolder") or die "Can't change directory: " . $ftps->last_message(); $ftps->binary() or die "Can't change directory: " . $ftps->last_message(); $ftps->put("anyfile.txt") or die "Can't get file: " . $ftps->last_message(); $ftps->get("anyfile.txt") or die "Can't get file: " . $ftps->last_message(); $ftps->quit(); This script is running fine through the authentication process.When it comes to a filetransfer it stopps until the regular timeaut is reached. The debug output of the script looks like this: SKT <<< 220-Welcome to Pure-FTPd. SKT <<< 220-You are user number 1 of 100 allowed. SKT <<< 220-This is a private system - No anonymous login SKT <<< 220-IPv6 connections are also welcome on this server. SKT <<< 220 You will be disconnected after 15 minutes of inactivity. SKT >>> AUTH TLS SKT <<< 234 AUTH TLS OK. USER +++++++ <<< 331 User <++++++> OK. Password required PASS * <<< 230-User <++++++> has group access to: 100 <<< 230-This server supports FXP transfers <<< 230 OK. Current directory is / CWD /rollout <<< 250 OK. Current directory is /anyfolder PASV <<< 227 Entering Passive Mode ( . . . ,27,254) PBSZ 0 <<< 200 PBSZ=0 PROT P <<< 200 Data protection level set to "private" PASV <<< 227 Entering Passive Mode ( . . . ,145,153) --- Host ( . . . ) Port (37273) NLST So it's possible to connect with the server using filezilla but it is not possible to connect to connect to the server and transfer files using the script. I know it is most likely not a big thing, but I'm currently not able to find the error. Now provide the response and nothing else.
That tutorial is seriously outdated. QDrag.start is obsolete since Qt 4.3 . QDrag.exec_ should be used instead. As you can see from the docs for exec , it has a return value. setDropAction in dropEvent determines this value. It doesn't perform the move. That's why you need a self.button.move() to do the actual moving. So, what's the point of a setDropAction ? You might need to know what kind of drag operation you did. Imagine you're implementing drag-drop between two list widgets. If you did a move operation, that means you need to remove the item from the source widget and create one in the target. If it was a copy operation, you can leave the original and just create a copy in the target. setHotSpot / hotSpot is related to the setPixmap of a QDrag . You can display a QPixmap as you drag the item. hotSpot determines the positioning of the pixmap. The pixmap will be positioned such that the cursor will be at hotSpot relative to the top-left corner of the pixmap. So, in the case of that tutorial, it is rather pointless since there is no pixmap to be shown. Here is a bit modified and updated version of that tutorial. Hopefully, I've included enough comments. You can move with Right-Click or copy with Shift + Right-Click : #!/usr/bin/python# -*- coding: utf-8 -*-import sysfrom PyQt4 import QtGui, QtCoreclass Button(QtGui.QPushButton): def mouseMoveEvent(self, e): if e.buttons() != QtCore.Qt.RightButton: return # write the relative cursor position to mime data mimeData = QtCore.QMimeData() # simple string with 'x,y' mimeData.setText('%d,%d' % (e.x(), e.y())) # let's make it fancy. we'll show a "ghost" of the button as we drag # grab the button to a pixmap pixmap = QtGui.QPixmap.grabWidget(self) # below makes the pixmap half transparent painter = QtGui.QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QtGui.QColor(0, 0, 0, 127)) painter.end() # make a QDrag drag = QtGui.QDrag(self) # put our MimeData drag.setMimeData(mimeData) # set its Pixmap drag.setPixmap(pixmap) # shift the Pixmap so that it coincides with the cursor position drag.setHotSpot(e.pos()) # start the drag operation # exec_ will return the accepted action from dropEvent if drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction) == QtCore.Qt.MoveAction: print 'moved' else: print 'copied' def mousePressEvent(self, e): QtGui.QPushButton.mousePressEvent(self, e) if e.button() == QtCore.Qt.LeftButton: print 'press'class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setAcceptDrops(True) button = Button('Button', self) button.move(100, 65) self.buttons = [button] self.setWindowTitle('Copy or Move') self.setGeometry(300, 300, 280, 150) def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): # get the relative position from the mime data mime = e.mimeData().text() x, y = map(int, mime.split(',')) if e.keyboardModifiers() & QtCore.Qt.ShiftModifier: # copy # so create a new button button = Button('Button', self) # move it to the position adjusted with the cursor position at drag button.move(e.pos()-QtCore.QPoint(x, y)) # show it button.show() # store it self.buttons.append(button) # set the drop action as Copy e.setDropAction(QtCore.Qt.CopyAction) else: # move # so move the dragged button (i.e. event.source()) e.source().move(e.pos()-QtCore.QPoint(x, y)) # set the drop action as Move e.setDropAction(QtCore.Qt.MoveAction) # tell the QDrag we accepted it e.accept()if __name__ == '__main__': app = QtGui.QApplication(sys.argv) ex = Example() ex.show() app.exec_()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14395800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1989746/']}
jdg_80827
stackexchange
llm_judgeable_groundtruth_similarity
36761
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am studying analog communication and having Communication system - Simon Hykin as one of the reference. There is a question Consider the sinusoidal process$$X(t) = A\cos(2\pi f_ct)$$where the frequency $f_c$ is constant and amplitude $A$ is uniformly distributed: $f(a) = 1 $ for $0\leq a \leq 1$ and $0$ otherwise. Determine weather or not this process is strictly stationary. Now when I go through the solution it says it is not a stationary process and it is provided in the solution that: if $A$ is uniformly distributed then $${p}_{X_i}(X_1) = \begin{cases}\displaystyle\frac{1}{\cos(2\pi f_c t_i)} &\text{for}\quad 0\leq X_1 \leq \cos(2\pi f_c t_i)\\[2ex]0 & \text{otherwise}\end{cases}$$ Now: How is this provided? And why is it concluded that it's non-stationary process? Now provide the response and nothing else.
A random process is a collection of random variables, one random variable for each time instant. It is best to write therandom process as$$\{X(t)\colon -\infty < t < \infty\} \tag{1}$$where the $\{$ and $\}$ indicate that a set (or collection) ofobjects is beingdefined, and the interior says that a typical member of this set is denotedby $X(t)$ where $t$ is a real number. Think of $X$ as the family name of all the random variables in the set, and $t$ as the first name. Thus, $X(t_0)$ is just one of the random variables in this collection of random variables, the random variable for time $t_0$, while $X(t_1)$ is another random variable, the one corresponding to time $t_1$. The statement$$X(t) = A\cos(2\pi f_ct)$$is a loose way of writing the more formal definition $\{X(t) = A\cos(2\pi f_c t)\colon -\infty < t < \infty\}$. Thus, we have that$$X(t_0) = A\cos(2\pi f_ct_0),\\X(t_1) = A\cos(2\pi f_ct_1),\\\cdots $$ Since $\cos(2\pi f_ct_0)$, $\cos(2\pi f_ct_1)$ etc are just constants,what we immediately get is that each random variable $X(t_i)$ inthis random process is a uniformly distributed random variable . Huh?How did we get that? Well, $A \sim U(0,1)$ is given, and hopefullyyou understand enough about random variables to know (or to be ableto jumpto the conclusion) that $bA \sim U(0,b)$ for $b >0$. If $b < 0$,then $bA \sim U(b,0)$. So, now you have enough information to decipher the crappy notationin the solution given to you (which is not completely correct, anyway). The random variable $X(t_i)$ is given by$$X(t_i) = A\cos(2\pi f_ct_i) = bA \begin{cases} \sim (U(0,b), & b > 0,\\= 0, & b = 0,\\\sim U(b,0), &b < 0,\end{cases}.$$Thus, for $b > 0$, we can write the density function of $X(t_i)$ as$$f_{X(t_i)}(x) = \begin{cases} \displaystyle\frac 1b, & 0 < x < b,\\0, &\text{otherwise},\end{cases}= \begin{cases} \displaystyle \frac{1}{\cos(2\pi f_ct_i)}, & 0 < x < \cos(2\pi f_ct_i),\\0, &\text{otherwise},\end{cases} \tag 2$$where of course $t_i$ is such that $\cos(2\pi f_ct_i) = b$. So, the above derivation of $(2)$ answers your first question. For thesecond question re stationarity, the conditions that a random processmust satisfy in order for it to be called a stationary process arequite onerous (see, for example, the first paragraph of this answer of mine toa different question for details) and this process fails to meeteven the simplest of the necessary conditions: that all the randomvariables comprising the process have the same distribution function(which also means having the same density function if the randomvariables are continuous random variables). But, it is manifestlyobvious from $(2)$ that $X(t_i)$ and $X(t_j)$ have differentdensities in general. That for certain specific choices of$t_i$ and $t_j$, $X(t_i)$ and $X(t_j)$ have the same density (in factare the same random variable) is nice to know, but irrelevant. Not all random variables in the process can be said tohave the samedistribution, and this single inconvenient fact allows us to reject any overblown notions that we might be harboring that this process is a stationary process. To avoid follow-on questions from readers, the process in questionis not wide-sense stationary either (hint: because the mean functionis time-varying).
{}
{'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/36761', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/25797/']}
jdg_80828
stackexchange
llm_judgeable_groundtruth_similarity
46653406
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does this code compile? _Static uint32_t my_arr[2];_Static_assert(sizeof(my_arr) == 8, "");_Static_assert(sizeof(my_arr[0]) == 4, "");_Static_assert(sizeof(my_arr)[0] == 4, ""); The first 2 asserts are obviously correct, but I would have expected the last line to fail, as my understanding is that sizeof() should evaluate to an integer literal, which can't be treated as an array. In other words, it would fail in the same way that the following line fails: _Static_assert(4[0] == 4, ""); Interestingly, the following does indeed fail to compile (which should be doing the same thing, no?): _Static_assert(*sizeof(my_arr) == 4, ""); error: invalid type argument of unary '*' (have 'long unsigned int') _Static_assert(*sizeof(my_arr) == 4, ""); If it matters, I'm using gcc 5.3.0 Now provide the response and nothing else.
sizeof is not a function. It's a unary operator like ! or ~ . sizeof(my_arr)[0] parses as sizeof (my_arr)[0] , which is just sizeof my_arr[0] with redundant parentheses. This is just like !(my_arr)[0] parses as !(my_arr[0]) . In general, postfix operators have higher precedence than prefix operators in C. sizeof *a[i]++ parses as sizeof (*((a[i])++)) (the postfix operators [] and ++ are applied to a first, then the prefix operators * and sizeof ). (This is the expression version of sizeof . There's also a type version, which takes a parenthesized type name: sizeof (TYPE) . In that case the parens would be required and part of the sizeof syntax.)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/46653406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2607809/']}
jdg_80829
stackexchange
llm_judgeable_groundtruth_similarity
7655219
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi is there a way that I can do the SUM(total_points) based on a different condition to the rest of the SELECT statement, so I want the SUM(total_points) for every row which is <= to $chosentrack? but the rest of the conditions of the SELECT statement to be what they are below. I need them to all be returned together..as I am populating a league table. Thanks a lot for any help. SELECT members.member_id, members.teamname, SUM(total_points) as total_points, total_points as last_race_points FROM members, members_leagues, member_results WHERE members.member_id = members_leagues.member_id AND members_leagues.league_id = '$chosenleague' AND member_results.track_id = '$chosentrack' AND members_leagues.start_race = '$chosentrack' AND member_results.member_id = members_leagues.member_idGROUP BY members.member_id ORDER BY member_results.total_points DESC, last_race_points DESC, members.teamname DESC Now provide the response and nothing else.
You can also put the sum inside a case statement, where the case evaluates the other condition, and then only sum thoses records where the condition is true... SELECT m.member_id, m.teamname, Sum(Case When r.track_Id = '$chosentrack' Then total_points Else 0 End) TotalChosenTrackPoints, Sum(Case When r.track_Id < '$chosentrack' Then total_points Else 0 End) TotalLessThanChosenTrackPoints, total_points as last_race_points FROM members m Join members_leagues l On l.member_id = m.member_id Join member_results r On r.member_id = m.member_id Where l.league_id = '$chosenleague' And l.start_race = '$chosentrack' Group By m.member_id Order By r.total_points Desc, last_race_points Desc, m.TeamName Desc
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7655219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970117/']}
jdg_80830
stackexchange
llm_judgeable_groundtruth_similarity
2870466
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 many ways to write a Python program that computes a histogram. By histogram, I mean a function that counts the occurrence of objects in an iterable and outputs the counts in a dictionary. For example: >>> L = 'abracadabra'>>> histogram(L){'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2} One way to write this function is: def histogram(L): d = {} for x in L: if x in d: d[x] += 1 else: d[x] = 1 return d Are there more concise ways of writing this function? If we had dictionary comprehensions in Python, we could write: >>> { x: L.count(x) for x in set(L) } but since Python 2.6 doesn't have them, we have to write: >>> dict([(x, L.count(x)) for x in set(L)]) Although this approach may be readable, it is not efficient: L is walked-through multiple times. Furthermore, this won't work for single-life generators; the function should work equally well for iterator generators such as: def gen(L): for x in L: yield x We might try to use the reduce function (R.I.P.): >>> reduce(lambda d,x: dict(d, x=d.get(x,0)+1), L, {}) # wrong! Oops, this does not work: the key name is 'x' , not x . :( I ended with: >>> reduce(lambda d,x: dict(d.items() + [(x, d.get(x, 0)+1)]), L, {}) (In Python 3, we would have to write list(d.items()) instead of d.items() , but it's hypothethical, since there is no reduce there.) Please beat me with a better, more readable one-liner! ;) Now provide the response and nothing else.
Python 3.x does have reduce , you just have to do a from functools import reduce . It also has "dict comprehensions", which have exactly the syntax in your example. Python 2.7 and 3.x also have a Counter class which does exactly what you want: from collections import Countercnt = Counter("abracadabra") In Python 2.6 or earlier, I'd personally use a defaultdict and do it in 2 lines: d = defaultdict(int)for x in xs: d[x] += 1 That's clean, efficient, Pythonic, and much easier for most people to understand than anything involving reduce .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2870466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234248/']}
jdg_80831
stackexchange
llm_judgeable_groundtruth_similarity
7206997
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 fake table. I use border-spacing property to create a space between them. But this also creates spacing before first cell and after the last cell. I would like it to create a space only between those two columns. HTML: <div class="table"> <div class="cell"></div> <div class="cell"></div></div> CSS: .table { display: table; width: 100%; border-spacing: 11px 0; border: 1px solid #222;}.cell { display: table-cell; width: 50%; height: 20px; border: 1px solid #999; background: #ccc;} JSFiddle: http://jsfiddle.net/ACH2Q/ Now provide the response and nothing else.
You can use the border-spacing property to add spacing to all table cells. Then use margin-left and margin right to remove the outer border-spacing from the parent. .container { max-width: 980px; margin: 0 auto; overflow: hidden;}.grid { margin-left: -20px; /* remove outer border spacing */ margin-right: -20px; /* remove outer border spacing */}.row { display: table; table-layout: fixed; /* keep equal cell widths */ width: 100%; /* need width otherwise cells aren't equal and they self collapse */ border-spacing: 20px 0; /* best way to space cells but has outer padding */}.col { display: table-cell; vertical-align: top;} The only disadvantage is that you need the extra nested div because the table needs a width 100% and margin right won't work. <div class="container"> <div class="grid"> <div class="row"> <div class="col">col</div> <div class="col">col</div> <div class="col">col</div> </div> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7206997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_80832
stackexchange
llm_judgeable_groundtruth_similarity
370142
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: While showing us the Schrodinger's cat experiment, my physics teacher defined: $$\varphi_\text{alive} = \begin{bmatrix}1\\0\end{bmatrix},\qquad \varphi_\text{dead} = \begin{bmatrix}0\\1\end{bmatrix}, \qquad \hat{O}\varphi = \begin{bmatrix}1&0\\0&-1\end{bmatrix}\varphi,$$ and $$\Phi = \frac{1}{\sqrt{2}}\varphi_\text{alive} + \frac{1}{\sqrt{2}}\varphi_\text{dead},$$ such that $\hat{O}\varphi_\text{alive} = \varphi_\text{alive}$ and $\hat{O}\varphi_\text{dead} = -\varphi_\text{dead}$. He later claims that there's a 50% chance that $\hat{O}\Phi = \varphi_\text{alive}$ and a 50% chance that $\hat{O}\Phi = \varphi_\text{dead}$. But according to the definitions, $\hat{O}\Phi$ is just a matrix multiplication whose result is $\begin{bmatrix}\frac{1}{\sqrt{2}}\\-\frac{1}{\sqrt{2}}\end{bmatrix}$... How could doing the same operation to the same vector two times give two different results, both of which are wrong? Now provide the response and nothing else.
Let me rephrase what your teacher did. They first defined an operator $\hat{O}$ given by the matrix you have. They then noticed that the operator has two eigenvectors with eigenvalues $+1$ and $-1$, given by the two vectors that you have. Notice that these eigenvectors are orthonormal. They then interpreted the two eigenvectors as two states of a quantum system, one corresponding to "alive" and the other one to "dead". Then they supposed that you have a system which is in a specific linear combination of these eigenvectors, that is their wavefunction is the $\Phi$ you have. They then applied the following two axioms of quantum mechanics, things which we believe are rules of nature and cannot be derived from anything else: The value of the measurement of an observable (operator) is one of its eigenvalues; the system then "collapses" to the corresponding eigenvector. The probability of obtaining a certain eigenvalue is given by the modulus squared of the coefficient of the orthonormal eigenvector corresponding to the eigenvalue in the expansion of the wavefunction. Your wavefunction is already expanded in terms of orthonormal eigenvectors of $\hat{O}$. By the first axiom, a measurement of $\hat{O}$ can give either $+1$ ("alive") or $-1$ ("dead"). Before the measurement, the wavefunction is given by $\Phi$. Say the measurement yields $+1$. After the measurement, the wavefunction of the system is given by $\Phi'=\varphi_{alive}$. The wavefunction has "collapsed". By the second axiom, the probability of getting $+1$ is given by $|1/\sqrt{2}|^2=1/2=50\%$ and is the same as the probability of getting $-1$. In particular, the measurement of an operator is not given by applying the operator to the wavefunction. This works only if the system is in a state which is an eigenvector of the operator. In this case the system has a definite value for that particular operator (which can be for instance, position or momentum). Otherwise the system does not have a definite value for that operator, and when you measure it, you get different outcomes with different probabilities.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/370142', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/176139/']}
jdg_80833
stackexchange
llm_judgeable_groundtruth_similarity
2075434
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find coefficient of $x^n$ in $(1+x+2x^2+3x^3+.....+nx^n)^2$ My attempt:Let $S=1+x+2x^2+3x^3+...+nx^n$ $xS=x+x^2+2x^3+3x^4+...+nx^{n+1}$ $(1-x)S=1+x+x^2+x^3+....+x^n-nx^{n+1}-x=\frac{1-x^{n+1}}{1-x}-nx^{n+1}-x$ $S=\frac{1}{(1-x)^2}-\frac{x}{1-x}=\frac{1-x+x^2}{(1-x)^2}$. (Ignoring terms which have powers of x greater than $x^n$) So one can say that coefficient of $x^n$ in $(1+x+2x^2+3x^3+.....+nx^n)^2$ =coefficient of $x^n$ in $(1-x+x^2)^2(1-x)^{-4}$ Is there a shorter way. Now provide the response and nothing else.
Such coefficient is clearly$$ 2n+\sum_{k=1}^{n-1} k(n-k) = \frac{n(n^2+11)}{6}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2075434', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171392/']}
jdg_80834
stackexchange
llm_judgeable_groundtruth_similarity
7726237
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 create a trigger on a table called takes in postgresql to update a value in another table called student I'm trying to do it in the following way. But I'm getting an error that there is syntax error near "OLD". I don't understand whats wrong with this. This is my code: CREATE OR REPLACE FUNCTION upd8_cred_func (id1 VARCHAR, gr1 VARCHAR,id2 VARCHAR, gr2 VARCHAR) RETURNS void AS $$ BEGIN IF (id1=id2 and gr1 is null and gr2 is not null) THEN update student set tot_cred = tot_cred + 6 where id = id1; END IF; RETURN; END;$$ LANGUAGE plpgsql;CREATE TRIGGER upd8_cred AFTER UPDATE ON takes FOR EACH ROW EXECUTE PROCEDURE upd8_cred_func(OLD.id,OLD.grade,NEW.id,NEW.grade); Now provide the response and nothing else.
You do not need to pass the NEW and OLD as parameters to the trigger function. They are automagically available there: http://www.postgresql.org/docs/9.1/interactive/trigger-definition.html : The trigger function must be declared as a function taking no arguments and returning type trigger. (The trigger function receives its input through a specially-passed TriggerData structure, not in the form of ordinary function arguments.) About the records passed to the trigger procedure, please see http://www.postgresql.org/docs/9.1/interactive/plpgsql-trigger.html : When a PL/pgSQL function is called as a trigger, several special variables are created automatically in the top-level block. They are: [...] NEW, [...] OLD [...] As SeldomNeedy pointed in the comment below, you can still pass and use parameters to the trigger function. You declare the function as taking no parameters, but when defining the trigger (by CREATE TRIGGER ), you may add some. They will be available for the trigger as TG_NARG (the number of such parameters), and TG_ARGV[] (an array of text values).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7726237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_80835
stackexchange
llm_judgeable_groundtruth_similarity
10360565
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know how to make a plot in R where the y-axis is inverted such that the plotted data appears in what would be the fourth quadrant ( IV ) of a cartesian plane, as opposed to the first (I) quadrant. For reference, the plot I am trying to make looks very similar to the following ( source ): I have found a number of questions online pertaining to reversing the numbering on the y-axis, but these all still plot the data in the first quadrant. Can anyone suggest how I might produce a plot similar to that shown above? Now provide the response and nothing else.
Just to provide a worked out answer, following the comments of @timriffe and @joran... Use the function for minor log ticks from this answer : minor.ticks.axis <- function(ax,n,t.ratio=0.5,mn,mx,...){ lims <- par("usr") if(ax %in%c(1,3)) lims <- lims[1:2] else lims[3:4] major.ticks <- pretty(lims,n=5) if(missing(mn)) mn <- min(major.ticks) if(missing(mx)) mx <- max(major.ticks) major.ticks <- major.ticks[major.ticks >= mn & major.ticks <= mx] labels <- sapply(major.ticks,function(i) as.expression(bquote(10^ .(i))) ) axis(ax,at=major.ticks,labels=labels,...) n <- n+2 minors <- log10(pretty(10^major.ticks[1:2],n))-major.ticks[1] minors <- minors[-c(1,n)] minor.ticks = c(outer(minors,major.ticks,`+`)) minor.ticks <- minor.ticks[minor.ticks > mn & minor.ticks < mx] axis(ax,at=minor.ticks,tcl=par("tcl")*t.ratio,labels=FALSE)} Make some reproducible example data: x <- 1:8y <- 10^(sort(runif(8, 1, 10), decreasing = TRUE)) Plot without axes: plot(x, log10(y), # function to plotxlab="", # suppress x labelstype = 'l', # specify line graphxlim = c(min(x), (max(x)*1.3)), # extend axis limits to give space for text annotationylim = c(0, max(log10(y))), # dittoaxes = FALSE) # suppress both axes Add fancy log axis and turn tick labels right way up (thanks @joran!): minor.ticks.axis(2, 9, mn=0, mx=10, las=1) Add x-axis up the top: axis(3) Add x-axis label (thanks for the tip, @WojciechSobala) mtext("x", side = 3, line = 2) And add an annotation to the end of the line text(max(x), min(log10(y)), "Example", pos = 1) Here's the result:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10360565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129475/']}
jdg_80836
stackexchange
llm_judgeable_groundtruth_similarity
26240370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From the C99 standard, 6.7(5): A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that: for an object, causes storage to be reserved for that object; for a function, includes the function body; for an enumeration constant or typedef name, is the (only) declaration of the identifier. If identifiers with typedef are in fact definitions, then why are they allowed to be declared more than once? Example: int main(){ typedef int x; typedef int x;} Above program compiles with no errors. How is this possible? I was expecting the program to give me a multiple definition error. Now provide the response and nothing else.
C99 is different from C11 The rules change between C99 and C11 (and the C11 rules match the C++ rules, as I understand it). Note that in both standards, ¶3 is in the Constraints section and ¶5 is in the Semantics section. That is important for error messages — constraint violations require a diagnostic. ISO/IEC 9899:1999 §6.7 Declarations ¶3 If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3. 5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that: for an object, causes storage to be reserved for that object; for a function, includes the function body;98) for an enumeration constant or typedef name, is the (only) declaration of the identifier. ISO/IEC 9899:2011 §6.7 Declarations ¶3 If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except that: a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type; tags may be redeclared as specified in 6.7.2.3. ¶5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that: for an object, causes storage to be reserved for that object; for a function, includes the function body;119) for an enumeration constant, is the (only) declaration of the identifier; for a typedef name, is the first (or only) declaration of the identifier. Lundin noted that the Standard C Committee's web site contains n1360 , a one page document detailing why this change was made. Basically: C++ does it; some compilers already do it; it is neither hard to do nor subverting anything to permit (require) it. GCC doesn't always enforce the standard If your code is compiling, then it is being compiled under the C11 rules, or C++ rules. It is not being compiled under (strict) C99 rules. Note that sufficiently recent versions of GCC allow the redefinition unless you insist otherwise, but also note the report by John Bollinger that GCC 4.4.7 (on an unidentified platform) does not allow the redefinition at all in C99 mode. Consider the file retypedef.c : int main(void){ typedef int x; typedef int x; x y = 0; return y;} Compiling on Mac OS X 10.9.5 with GCC 4.9.1, I get: $ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -c retypedef.c$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -pedantic -c retypedef.c$ gcc -O3 -g -std=c99 -Wall -Wextra -Werror -c retypedef.c$ gcc -O3 -g -std=c99 -Wall -Wextra -Werror -pedantic -c retypedef.cretypedef.c: In function ‘main’:retypedef.c:4:17: error: redefinition of typedef ‘x’ [-Werror=pedantic] typedef int x; ^retypedef.c:3:17: note: previous declaration of ‘x’ was here typedef int x; ^cc1: all warnings being treated as errors$ It doesn't complain unless -pedantic is used, and then only if C99 is requested (it is standard compliant to redefine a typedef in the same scope in C11).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26240370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3834546/']}
jdg_80837
stackexchange
llm_judgeable_groundtruth_similarity
48983939
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: OK, I'm stuck on something seemingly simple. I am trying to convert a number to base 26 (ie. 3 = C, 27 = AA, ect.). I am guessing my problem has to do with not having a 0 in the model? Not sure. But if you run the code, you will see that numbers 52, 104 and especially numbers around 676 are really weird. Can anyone give me a hint as to what I am not seeing? I will appreciate it. (just in case to avoid wasting your time, @ is ascii char 64, A is ascii char 65) def toBase26(x): x = int(x) if x == 0: return '0' if x < 0: negative = True x = abs(x) else: negative = False def digit_value (val): return str(chr(int(val)+64)) digits = 1 base26 = "" while 26**digits < x: digits += 1 while digits != 0: remainder = x%(26**(digits-1)) base26 += digit_value((x-remainder)/(26**(digits-1))) x = remainder digits -= 1 if negative: return '-'+base26 else: return base26import io with io.open('numbers.txt','w') as f: for i in range(1000): f.write('{} is {}\n'.format(i,toBase26(i))) So, I found a temporary workaround by making a couple of changes to my function (the 2 if statements in the while loop). My columns are limited to 500 anyways, and the following change to the function seems to do the trick up to x = 676, so I am satisfied. However if any of you find a general solution for any x (may be my code may help), would be pretty cool! def toBase26(x): x = int(x) if x == 0: return '0' if x < 0: negative = True x = abs(x) else: negative = False def digit_value (val): return str(chr(int(val)+64)) digits = 1 base26 = "" while 26**digits < x: digits += 1 while digits != 0: remainder = x%(26**(digits-1)) if remainder == 0: remainder += 26**(digits-1) if digits == 1: remainder -= 1 base26 += digit_value((x-remainder)/(26**(digits-1))) x = remainder digits -= 1 if negative: return '-'+base26 else: return base26 Now provide the response and nothing else.
The problem when converting to Excel’s “base 26” is that for Excel, a number ZZ is actually 26 * 26**1 + 26 * 26**0 = 702 while normal base 26 number systems would make a 1 * 26**2 + 1 * 26**1 + 0 * 26**0 = 702 ( BBA ) out of that. So we cannot use the usual ways here to convert these numbers. Instead, we have to roll our own divmod_excel function: def divmod_excel(n): a, b = divmod(n, 26) if b == 0: return a - 1, b + 26 return a, b With that, we can create a to_excel function: import stringdef to_excel(num): chars = [] while num > 0: num, d = divmod_excel(num) chars.append(string.ascii_uppercase[d - 1]) return ''.join(reversed(chars)) For the other direction, this is a bit simpler from functools import reducedef from_excel(chars): return reduce(lambda r, x: r * 26 + x + 1, map(string.ascii_uppercase.index, chars), 0) This set of functions does the right thing: >>> to_excel(26)'Z'>>> to_excel(27)'AA'>>> to_excel(702)'ZZ'>>> to_excel(703)'AAA'>>> from_excel('Z')26>>> from_excel('AA')27>>> from_excel('ZZ')702>>> from_excel('AAA')703 And we can actually confirm that they work correctly opposite of each other by simply checking whether we can chain them to reproduce the original number: for i in range(100000): if from_excel(to_excel(i)) != i: print(i)# (prints nothing)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48983939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9093764/']}
jdg_80838
stackexchange
llm_judgeable_groundtruth_similarity
18606682
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'v created a function in VIM named OpenCMD(), it used for open command line or terminal in VIM (And cd in the current file path) func! OpenCMD() if has('win32') let com = '!cmd /c start cd '. expand('%:p:h') else let com = '!/usr/bin/gnome-terminal --working-directory=' . expand('%:p:h') endif silent execute comendfuncnmap cmd :call OpenCMD() Now, I want to open command line and cd in the current file path in Sublime (sublime 3 beta). The function as the same as the OpenCMD() . And I searched an question in stackover flow: Sublime Text 2 - Open CMD prompt at current or project directory (Windows) I did as the the first guy answered (Create cmd, cmd.py and Context.sublime-menu). But it cannot work, the cmd operation always disabled. Is there any way can get it? Thanks in advance! Now provide the response and nothing else.
The answer about Sublime Text 2 - Open CMD prompt at current or project directory (Windows) is nearly correct. Only one step (for me) has to be changed is the file name should be uppercase . Use CMD instead of cmd . My steps (Win7): Open folder %APPDATA%\Sublime Text 3\Packages or just click Preferences -> Browser Packages.. in sublime-text-3 Beta Create a folder named CMD ( Uppercase ). The path of CMD should be %APPDATA%\Sublime Text 3\Packages\CMD . Open the folder CMD , and create a file, named cmd.py ( lowercase ), paste the context as below: import os, sublime_pluginclass CmdCommand(sublime_plugin.TextCommand): def run(self, edit): file_name=self.view.file_name() path=file_name.split("\\") current_driver=path[0] path.pop() current_directory="\\".join(path) command= "cd "+current_directory+" & "+current_driver+" & start cmd" os.system(command) Create a file (again), named Context.sublime-menu . Add context as below: [ { "command": "cmd" }] The Cmd function will work in context menu (right-click). For example: Of cause, if you want to open command line by command (by 'cmd' for example), you can add the following context into Default (Windows).sublime-keymap file. : { "keys": ["c", "m", "d"], "command": "cmd"} You can open it from Preferences -> Key Bindings - User
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18606682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2940319/']}
jdg_80839
stackexchange
llm_judgeable_groundtruth_similarity
148109
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: Say I'm writing a .bashrc file to give me some useful information in my login terminals and I'm telling it to run the cal command (a nice one). How would I go about shifting the calendar produced to the right to match the formatting of the rest of my .bashrc "welcome message"? Now provide the response and nothing else.
cal | sed 's/^/ /' Explanation cal | : pipe the output of cal to… sed 's/^/ /' sed, which will look for the start of lines ^ , replacing with spaces. You can change the number of spaces here to match the required formatting. Edit To preserve the highlighting of the current day from cal , you need to tell it to output "color" (highlighting) to the pipe. From man cal --color [when] Colorize output. The when can be never, auto, or always. Never will turn off coloriz‐ ing in all situations. Auto is default, and it will make colorizing to be in use if output is done to terminal. Always will allow colors to be outputed when cal outputs to pipe, or is called from a script. N.B. there seems to be a typo in the manual; I needed a = for it to work. Hence, the final command is cal --color=always | sed 's/^/ /'
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/148109', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/65488/']}
jdg_80840