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
532251
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 read that the blue column of light directly above the exploded reactor was actually the ionisation of air but I like to know where did the electric field came from to cause such phenomenon? I imagine thunder cloud where there is a built up of electric potential and then a lightning occurs so for the column of blue light there must also be a electric potential and why column that extends into the sky? Now provide the response and nothing else.
Air glows when molecules, that are brought to an excited state by a collision, go back to a less-excited state by emitting a photon. The question becomes : what generated a particle fast enough to generate such a collision? Acceleration of a charged particle by some electric field. That's the case for lightning or neon lights, for example. Emission of an energetic particle by some high-energy process (such as radioactive decay) ; this doesnt need any electric field. As far as I know, that was the case for Chernobyl : nuclear reactions in the core sent high energy particles in all directions ; those that went down or sideways were stopped by concrete in meters (or less) but those going upwards could travel through air (which is less dense) for a bit, eventually hit some air molecule and bring it to an excited state in the process. The fact that the light-column was kilometers high indicates that the mean-free-path of those high energy particles was kilometers (at least). That strongly suggests γ-ray photons. I have read several times that this glow was due to Cherenkov radiation (light emission by charged particles going through a medium faster than light propagation). I have some doubts about it because light speed in air is so close to that in vacuum (refractive index is very near 1) ; therefore the energy needed for a particle to be above the speed of light in air is positively huge, higher I think than energy of most nuclear processes. On the other hand, particle energy necessary to bring a molecule to an excited state would be mere eVs, much lower than that of any nuclear process. (obviously, blue glow of water in a nuclear reactor is an other matter, since speed of light in water is significantly slower than in vacuum, enabling Cherenkov radiation much more readily)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/532251', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/75502/']}
jdg_374341
stackexchange
llm_judgeable_groundtruth_similarity
49276487
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 change the state of a component every 5 seconds as below inside componentDidMount() hook import React, { Component } from 'react';export default class ToTest extends Component { constructor(props) { super(props); this.state = { test: false }; } componentDidMount() { setTimeout(() => { this.setState({ test: !this.state.test }) }, 5000); } renderDiv() { if(this.state.test) { return (<div>test is true</div>) } else { return (<div>test is false</div>) } } render() { return ( <div>{ this.renderDiv() }</div> ); }} But it executes only once. It changes from false to true once and then nothing.What am I missing? Now provide the response and nothing else.
componentDidMount() is only executed once when the component mounts and you only schedule it once. You have to use setInterval() to schedule it periodically. Also when you update the state based on the current state you should use a callback in setState() that takes the previous state as react may batch multiple calls to setState() . And don't forget to cancel the timer in componentWillUnmount() : import React, { Component } from 'react';export default class ToTest extends Component { state = { test: false, }; componentDidMount() { this.timer = setInterval( () => this.setState(prevState => ({ test: !prevState.test })), 5000, ); } componentWillUnmount() { clearInterval(this.timer); } // other methods ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49276487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5032858/']}
jdg_374342
stackexchange
llm_judgeable_groundtruth_similarity
48119378
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 read several tutorials how to place 3d objects in SceneKit/ARKit applications and all of them uses .scn format files for the objects. But I found there is no any issues if I use original .dae format and do not convert it to .scn format. I don't really see any difference between .dae and .scn formats. Actually result seems to me the same but can you explain what the difference between them and what I should use in what cases? Thank you! Now provide the response and nothing else.
DAE (Digital Asset Exchange, aka Collada) is a vendor-neutral format for 3D assets. It supports a wide range of features that exist in multiple 3D authoring and presentation tools, but not every possible feature in SceneKit. Historically, it was the only asset format for early versions of SceneKit. SCN format is a serialization of the SceneKit object graph. (There are convenience methods for reading/writing it on SCNScene , but really it's the same thing you get by passing an SCNScene to NSKeyedArchiver / NSKeyedUnarchiver .) Thus, it by definition supports all features of SceneKit, including physics, constraints, actions, physically based cameras, and shader modifiers. If you're using DAE assets, deploying to iOS (or tvOS or watchOS), and not seeing any difference vs using SCN assets, there are two possible reasons: Your assets use only those SceneKit features that are available in DAE format. When deploying to iOS/tvOS/watchOS, Xcode (via scntool ) automatically converts all 3D asset resources to SCN format. (And applies other transformations, like interleaving geometry buffers, for optimal rendering performance on iOS/tvOS/watchOS devices.) The filename in the built app's Resources directory still has a .dae extension, but the file contents are the same as SCN format. (SceneKit running in iOS/tvOS/watchOS actually can't read DAE, so it relies on this preprocessing by Xcode.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48119378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1645068/']}
jdg_374343
stackexchange
llm_judgeable_groundtruth_similarity
2752997
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 spherical ball of salt is dissolving in water in such a way that the rate of decrease in volume at any instant is proportional to the surface. Prove that the radius is decreasing at a constant rate. My Approach: $$\dfrac {dV}{dt}\propto Surface (S)$$$$\dfrac {dV}{dt}=k.S$$where $k$ is a proportionality constant. $$\dfrac {dV}{dt}=k.4\pi r^2$$ How do I proceed? Now provide the response and nothing else.
You have $V=\frac{4}{3} \pi r^3$ so:$$\frac{d V}{dt}=\frac{d}{dt}\left(\frac{4}{3} \pi r^3 \right)=\frac{4}{3} \pi \times 3 \frac{dr}{dt} r^2 $$so the equation is:$$4 \pi \frac{dr}{dt} r^2 = k 4 \pi r^2$$i.e (as long as $r\neq 0$):$$\frac{dr}{dt}=k$$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2752997', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/354073/']}
jdg_374344
stackexchange
llm_judgeable_groundtruth_similarity
1156601
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are you using to validate users' email addresses, and why? I had been using validates_email_veracity_of which actually queries the MX servers. But that is full of fail for various reasons, mostly related to network traffic and reliability. I looked around and I couldn't find anything obvious that a lot of people are using to perform a sanity check on an email address. Is there a maintained, reasonably accurate plugin or gem for this? P.S.: Please don't tell me to send an email with a link to see if the email works. I'm developing a "send to a friend" feature, so this isn't practical. Now provide the response and nothing else.
Don't make this harder than it needs to be. Your feature is non-critical; validation's just a basic sanity step to catch typos. I would do it with a simple regex, and not waste the CPU cycles on anything too complicated: /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/ That was adapted from http://www.regular-expressions.info/email.html -- which you should read if you really want to know all the tradeoffs. If you want a more correct and much more complicated fully RFC822-compliant regex, that's on that page too. But the thing is this: you don't have to get it totally right. If the address passes validation, you're going to send an email. If the email fails, you're going to get an error message. At which point you can tell the user "Sorry, your friend didn't receive that, would you like to try again?" or flag it for manual review, or just ignore it, or whatever. These are the same options you'd have to deal with if the address did pass validation. Because even if your validation is perfect and you acquire absolute proof that the address exists, sending could still fail. The cost of a false positive on validation is low. The benefit of better validation is also low. Validate generously, and worry about errors when they happen.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1156601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17965/']}
jdg_374345
stackexchange
llm_judgeable_groundtruth_similarity
17615272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For me below are the most probable definitions for asynchronous and non-blocking I/O: Asynchronous I/O: In asynchronous I/O applications return immediately and OS will let them know when the bytes are available for processing. NON-blocking I/O: Here application returns immediately what ever data available and application should have polling mechanism to find out when more data is ready. After knowing these definitions if we analyze java channels i.e. SocketChannel , ServerSocketChannel , DatagramSocketChannel then we can find that these channels can be used as blocking or non-blocking mode by the method configureBlocking(boolean block) . and assume that we are using them as non-blocking mode. So here comes the questions: if i will use Selector i.e. register channels to a selector whether it is Asynchronous I/O or NON-blocking I/O ? I feel this is Asynchronous I/O in java if and only if underlying operating system is informing the java application about readiness selection of a channel. Else it is non-blocking I/O and selector is just a mechanism which helps us polling the above mention channels as i mention in the definition. Which is correct? Thanks in advance. EDIT: I have answered one part of the question i.e. types of I/O and how java facilitates these functionality. But one question still remains whether all these functionalities are provides by java is simulated at java layer or it uses underlaying OS to facilitate? Assume the underlaying OS has all the support for these functionalities. Please refer to the answer. Now provide the response and nothing else.
I thought of answering my question by doing some more homework. This post will also help in understanding the I/O concepts w.r.t. underlying OS. This is blocking I/O: FileInputStream , FileOutputStream and even reading to or writing from Socket come under this category This is non-blocking I/O: this is used by Socket Channels like ServerSocketchannel , SocketChannel , DatagramChannel in Java This is multiplexed I/O: in Java it is used by Selector to handle multiple channels and these channels should be non-blocking by nature. So Socket channels can be registered to Selector and Selector can manage by I/O multiplexing facility of underlaying OS. Now comes Asynchronous I/O. In asynchronous I/O applications return immediately and OS will let them know when the bytes are available for processing. In java it is facilitated by AsynchronousSocketChannel , AsynchronousServerSocketChannel , AsynchronousFileChannel . For these above functionalities java uses underlying OS heavily. This is evident when i was going through the book . Here in chapter 4 the author mentions that True readiness selection must be done by the operating system. One of the most important functions performed by an operating system is to handle I/O requests and notify processes when their data is ready. So it only makes sense to delegate this function down to the operating system. The Selector class provides the abstraction by which Java code can request readiness selection service from the underlying operating system in a portable way. Hence it's clear that Java uses underlying OS heavily for these features.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17615272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2109070/']}
jdg_374346
stackexchange
llm_judgeable_groundtruth_similarity
50985087
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list of .JPG files on a Mac. I want to export them to a format taking less than 500 kilobytes per image.I know how to do that using the Preview application one image at a time; but I want to be able to do the same in batch, meaning on several files at once. Is there a command line way to do it so I could write a script and run it in the terminal?Or some other way that I could use? Now provide the response and nothing else.
This is an example from the command line using convert ( brew info imagemagick ) converting all *.jpg images in one directory to .png : $ for i in *.jpg; doconvert "$i" "${i%.jpg}.png"done To test before (dry-run) you could use echo instead of the <command> : $ for i in *.jpg; doecho "$i" "${i%.jpg}.png"done This will search for files within the directory having the extension .jpg then execute the command convert passing as arguments the file name $i and then using as an output the same file name removing the extension and adding the new one .png , this is done using: "${i%.jpg}.png" The use of double quotes " is for the case file could contain spaces, check this for more details: shell parameter expansion For example, to just change the quality of the file you could use: convert "$i" -quality 80% "${i%.jpg}-new.jpg" Or if no need to keep the original: mogrify -quality 80% *.jpg The main difference is that ‘convert‘ tends to be for working on individual images, whereas ‘mogrify‘ is for batch processing multiple files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50985087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611201/']}
jdg_374347
stackexchange
llm_judgeable_groundtruth_similarity
3772933
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's a fictional scenario with some populated data. For tax purposes, my fictional company must retain records of historical data. For this reason, I've included a version column to the table. TABLE EMPLOYEE: (with personal commentary)|ID | VERSION | NAME | Position | PAY |+---+---------+------------+----------+-----+| 1 | 1 | John Doe | Owner | 100 | Started company| 1 | 2 | John Doe | Owner | 80 | Pay cut to hire a coder| 2 | 1 | Mark May | Coder | 20 | Hire said coder| 2 | 2 | Mark May | Coder | 30 | Productive coder gets raise| 3 | 1 | Jane Field | Admn Asst| 15 | Need office staff| 2 | 3 | Mark May | Coder | 35 | Productive coder gets raise| 1 | 3 | John Doe | Owner | 120 | Sales = profit for owner!| 3 | 2 | Jane Field | Admn Asst| 20 | Raise for office staff| 4 | 1 | Cody Munn | Coder | 20 | Hire another coder| 4 | 2 | Cody Munn | Coder | 25 | Give that coder raise| 3 | 3 | Jane Munn | Admn Asst| 20 | Jane marries Cody <3| 2 | 4 | Mark May | Dev Lead | 40 | Promote mark to Dev Lead| 4 | 3 | Cody Munn | Coder | 30 | Give Cody a raise| 2 | 5 | Mark May | Retired | 0 | Mark retires| 5 | 1 | Joey Trib | Dev Lead | 40 | Bring outside help for Dev Lead| 6 | 1 | Hire Meplz | Coder | 10 | Hire a cheap coder| 3 | 4 | Jane Munn | Retired | 0 | Jane quits| 7 | 1 | Work Fofre | Admn Asst| 10 | Hire Janes replacement| 8 | 1 | Fran Hesky | Coder | 10 | Hire another coder| 9 | 1 | Deby Olav | Coder | 25 | Hire another coder| 4 | 4 | Cody Munn | VP Ops | 80 | Promote Cody| 9 | 2 | Deby Olav | VP Ops | 80 | Cody fails at VP Ops, promote Deby| 4 | 5 | Cody Munn | Retired | 0 | Cody retires in shame| 5 | 2 | Joey Trib | Dev Lead | 50 | Give Joey a raise+---+---------+------------+----------+-----+ Now, if I wanted to do something like "Get a list of the current coders" I couldn't just do SELECT * FROM EMPLOYEE WHERE Position = 'Coder' because that would return lots of historical data... which is bad. I'm looking for good ideas to handle this scenario. I see a few options that jump out at me, but I'm sure someone's going to say "Wow, that's a rookie mistake, glow... try this on for size:" which is what this place is all about, right? :-) Idea number 1: Keep a version table with the current version like this TABLE EMPLOYEE_VERSION:|ID |VERSION|+---+-------+| 1 | 3 || 2 | 5 || 3 | 4 || 4 | 6 || 5 | 2 || 6 | 1 || 7 | 1 || 8 | 1 || 9 | 2 | +---+-------+ Although I'm not sure how I'd do that with a single query, I'm sure it could be done, and I bet I could figure it out with a rather small amount of effort. Of course, I would have to update this table every time I insert into the EMPLOYEE table to increment the version for the given ID (or insert into the version table when a new id is made). The overhead of that seems undesireable. Idea number 2: Keep an archive table and a main table. Before updating the main table, insert the row I'm about to overwrite into archive table, and use the main table as I normally would as if I wasn't concerned about versioning. Idea number 3: Find a query that adds something along the lines of SELECT * FROM EMPLOYEE WHERE Position = 'Coder' and version=MaxVersionForId(EMPLOYEE.ID) ... Not entirely sure how I'd do this. This seems the best idea to me, but I'm really not sure at this point. Idea number 4: Make a column for "current" and add "WHERE current = true AND ..." It occurs to me that surely people have done this before, run into these same problems, and have insight on it to share, and so I come to collect that! :) I've tried to find examples of the problem on here already, but they seems specialized to a particular scenario. Thanks! EDIT 1: Firstly, I appreciate all answers, and you've all said the same thing - DATE is better than VERSION NUMBER . One reason I was going with VERSION NUMBER was to simplify the process of updating in the server to prevent the following scenario Person A loads employee record 3 in his session, and it has version 4.Person B loads employee record 3 in his session, and it has version 4.Person A makes changes and commits. This works because the most recent version in the database is 4. It is now 5.Person B makes changes and commits. This fails because the most recent version is 5, while his is 4. How would the EFFECTIVE DATE pattern address this issue? EDIT 2: I think I could do it by doing something like this:Person A loads employee record 3 in his session, and it's effective date is 1-1-2010, 1:00 pm, with no experation.Person B loads employee record 3 in his session, and it's effective date is 1-1-2010, 1:00 pm, with no experation.Person A makes changes and commits. The old copy goes to the archive table (basically idea 2) with an experation date of 9/22/2010 1:00 pm. The updated version of the main table has an effective date of 9/22/2010 1:00 pm.Person B makes changes and commits. The commit fails because the effective dates (in the database and session) don't match. Now provide the response and nothing else.
I think you've started down the wrong path. Typically, for versioning or storing historical data you do one of two (or both) things. You have a separate table that mimics the original table + a date/time column for the date it was changed. Whenever a record is updated, you insert the existing contents into the history table just prior to the update. You have a separate warehouse database. In this case you can either version it just like in #1 above OR you simply snapshot it once every so often (hourly, daily, weekly..) Keeping your version number in the same table as your normal one has several problems. First, the table size is going to grow like crazy. This will put constant pressure on normal production queries. Second, it's going to radically increase your query complexity for joins etc in order to make sure the latest version of each record is being used.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3772933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330057/']}
jdg_374348
stackexchange
llm_judgeable_groundtruth_similarity
11554006
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Maybe it's late, or maybe it's the sake, but I just read the docs for ArrayBuffer and can't think of a single thing it would be really useful for. Can someone enlighten me? Are there any uses anyone can think of that don't involve images? Now provide the response and nothing else.
Basically ArrayBuffer is used to keep binary data. It can be the binary data of an image for example. In other languages buffers are proved very useful. Yes, of-course it is little difficult to understand/use than other data types. ArrayBuffer can be used to get data of jpg image (RGB bytes) and produce a png out of it by adding alpha byte (i.e. RGBA). Mozilla site has given a small use of ArrayBuffer here Working with complex data structures By combining a single buffer with multiple views of different types, starting at different offsets into the buffer, you can interact with data objects containing multiple data types. This lets you, for example, interact with complex data structures from WebGL , data files, or C structures you need to use while using js-ctypes . Consider this C structure: struct someStruct { unsigned long id; char username[16]; float amountDue; }; You can access a buffer containing data in this format like this: var buffer = new ArrayBuffer(24); // ... read the data into the buffer ... var idView = new Uint32Array(buffer, 0, 1); var usernameView = new Uint8Array(buffer, 4, 16); var amountDueView = new Float32Array(buffer, 20, 1); Then you can access, for example, the amount due with amountDueView[0] . Note: The data structure alignment in a C structure is platform-dependent. Take precautions and considerations for these padding differences.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11554006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26188/']}
jdg_374349
stackexchange
llm_judgeable_groundtruth_similarity
112647
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the definition of this symbol $\mathbb{N}^{<\mathbb{N}}$? How is it related to the infinite product $\mathbb{N}^{\mathbb{N}}$? Now provide the response and nothing else.
We consider the set $X^n$ as the set of all sequences of length $n$ whose members are elements of $X$. For example, $\{0,1\}^n$ is the set of binary sequences of length $n$. We often want to consider instead of a fixed length, a variable length. For example, all sequences shorter than $5$, that would be: $X^0\cup X^1\cup\ldots\cup X^4$, this can be abbreviated as $X^{<5}$. In general, when $I$ has a nice [well-]ordering such that we can effectively know what lengths are shorter than $I$, we can write $X^{<I}$ as the set of all sequences of length shorter than $I$; and $X^I$ as the set of all sequences of length $I$. Indeed this is the set of all functions from $I$ into $X$, each of which defines a sequence. The natural numbers have a very nice order. In fact we know that a sequence has a finite length if and only if it is strictly shorter than the sequence $\langle 0,1,2,3,\ldots\rangle$. This means that by writing $<\mathbb N$ we mean "as long as you want, but finite". Therefore $X^{<\mathbb N}$ would mean all the finite sequences from $X$. If $X=\mathbb N$ as well this means all the finite sequences of natural numbers, whereas $\mathbb N^\mathbb N$ would be the set of all infinite sequences of natural numbers. Note that if $X$ is nonempty we can choose some fixed element to be added infinitely many times to a sequence in order to make a finite sequence infinite. That is, we think of the sequence $\langle 4,1,3\rangle$ as $\langle 4,1,3,0,0,0,0,0,0,\ldots\rangle$. The former is in $\mathbb N^3$ and thus in $\mathbb N^{<\mathbb N}$ while the latter is in $\mathbb N^\mathbb N$. If one wants an injection from $\mathbb N^{<\mathbb N}$ you need to remember that appending $0$ (for example) will not work, since $\langle 1\rangle$ and $\langle 1,0\rangle$ will both be sent to $\langle 1,0,0,0,\ldots\rangle$. This means that a slightly cleverer trick is in order.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/112647', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25610/']}
jdg_374350
stackexchange
llm_judgeable_groundtruth_similarity
173244
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: At my friend's work they have an accelerometer which measures the force with which certain objects hit the ground. He claims that from four feet high, cell phones hit a solid metal surface with a $g$ -force of over 2000. Is this right? It seems like that number is way too high. I understand that $g$ -force is calculated by (acceleration in m/s 2 )/9.8. I suppose if an object instantly decelerates it would have a very high $g$ -force. However, is 2000 a legitimate number? It just seems extremely high. Now provide the response and nothing else.
updated calculation As a rule of thumb the "g force" of an impact is the ratio of the distance of the fall, and the distance it took to stop falling. This is based on a simple work done argument - $F_1\Delta x_1=F_2\Delta x_2$, and of course $F=m\cdot a$. This approach is the same as used in this article describing a 'bubble wrap drop' Mythbusters experiment . There may be a factor 2 there depending on whether you assume a constant decelerating force (crushing bubble wrap) or an elastic deceleration (where force increases with displacement). I estimate that when a phone drops on a hard surface, it distorts by about 0.2 mm - based on observation of the small dent on the corner when my wife did in fact drop her phone. But see video below for a much larger distortion... Taking the ratio $\frac{1200 mm}{0.2 mm}\approx 6000 g$ - meaning that your 2000 g is a reasonable number. I found a slow motion video of an iPhone breaking - it shows that the distance over which it moves / distorts is significantly greater than I estimated so the g forces will be less: Source of image When you put your iPhone in a case that provides even a couple of mm of "give" during a drop, the g forces will be much lower and you will improve the chances of surviving a drop on a hard surface very significantly.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/173244', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/76600/']}
jdg_374351
stackexchange
llm_judgeable_groundtruth_similarity
2494501
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 added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ? Now provide the response and nothing else.
You can do this with a custom model manager and override the get_queryset function to always filter canceled=False. class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(canceled=False)class MyModel(models.Model): # Blah blah objects = CustomManager() Then when calling MyModel.objects.all() it will always exclude canceled objects. Here is a blog post I found helpful on the subject. http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/ EDIT:Perhaps a better approach with a custom manager would be to attach it to another property, other than objects, such as: class MyModel(models.Model): # Blah blah active = CustomManager() And in your views your queries would look like MyModel.active.all() . EDIT2:Updated method spelling from get_query_set to get_queryset for modern versions of django.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2494501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124503/']}
jdg_374352
stackexchange
llm_judgeable_groundtruth_similarity
4047833
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is a nested select with include: @items = Item.where("complete = ?", true).includes( :manufacturer, {:order=>[:supplier, :agent] }) This is a taxing query as it pulls 1000s of rows of data from all the above included tables. How can I get the query to only select specific fields? user.name, user.created_at order.created_at supplier.name agent.name manufacturer.name Now provide the response and nothing else.
There is a select method in ARel, but you must use the correct table names (i.e. plural and beware if you have polymorphic models or if you're using set_table_name or some other similar non-standard practice) @items = Item. select('users.name', 'users.created_at', 'orders.created_at', 'suppliers.name', 'agents.name', 'manufacturers.name'). where(:users => { :fulfilled => true }). includes(:orders => [:supplier, :agent], :manufacturer) "We can use select with joins not includes" - @Bhavesh_A_P Note: As @Bhavesh_A_P pointed out above, select with includes does not produce consistent behavior. It appears that if the included association returns no results, select will work properly, if it returns results, the select statement will have no effect. In fact, it will be completely ignored, such that your select statement could reference invalid table names and no error would be produced. select with joins will produce consistent behavior.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4047833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341583/']}
jdg_374353
stackexchange
llm_judgeable_groundtruth_similarity
449236
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a strange problem with a server I have sitting at my workplace (it's behind a NAT, if that's important). The issue is that at some times, it becomes unreachable and then comes back up again, usually within a few seconds, sometimes lasting up to 1 minute. It doesn't reboot, it doesn't crash. It simply becomes inaccessible. During this time, I cannot ssh into it, nor can I access any applications running on the machine (it's running a couple of Rails apps, so they become unreachable as well). I checked dmesg and saw these lines - [ 4.958074] ADDRCONF(NETDEV_UP): eth0: link is not ready[ 5.040476] ADDRCONF(NETDEV_UP): eth1: link is not ready[ 5.175624] igb: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: RX/TX[ 5.177207] ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready A couple of lines later, I see something similar concerning the network interfaces - [1195777.544167] igb: eth0 NIC Link is Down[1195780.962943] igb: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: RX/TX It does look like a network issue. /var/log/messages doesn't show anything interesting. I'm not sure how to debug this. Any clue as to what it could be? And what all things should I be checking here? Thanks! Now provide the response and nothing else.
This kind of problem usually doesn't generate a lot of log messages. You have discovered the important two messages which show the interfaces going down and up. These can be generated by unplugging the ethernet cable and plugging it back in. It could be a bad cable between the NIC and the router. My first steps (done one at a time) would be: Replace the cable connected to eth0 and see if that resolves the problem. Reconfigure the network interfaces so the traffic currently on eth0 is on eth1 and vise versa. (Requires a network restart and cable swap.) If the problem moves, then it is like a failing NIC. Verify the status of the upstream device and its power supply. If it looses power or is otherwise failing you can see this kind of behavior. Run netstat -i or ifconfig and examine the error counts. Normally, they should be 0 or single digits. High carrier or frame errors may indicate duplex mismatch. Duplex mismatch can be verified by uploading then downloading a large file. Large speed differences accompanied by increasing error counts indicate mismatch on the link. Cable modems usually have different upload and download bandwidths, so local transfers work better for this test. One tool I do use is mtr . I use a command like mtr -i 15 -n google.com to monitor connectivity. Consider using one of your ISP's servers instead of google.com. It can be run in report mode in batch. If the problem is upstream of the server, the output should help identify where the problem is occurring.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/449236', 'https://serverfault.com', 'https://serverfault.com/users/145743/']}
jdg_374354
stackexchange
llm_judgeable_groundtruth_similarity
3859940
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 $C$ be the category where objects are non-negative integers and $m \to n$ in $C$ exists (and uniquely) iff $m \mid n$ . It is a poset category, and $0$ is terminal with $1$ initial. The $\gcd$ , $(m,n)$ , is a categorical product of $m,n$ . Then addition $m+n$ has the property that it is the (hopefully unique, but it's not, see below) object $a$ existing for any two objects $m,n$ such that if $d$ is not the initial object and $d \to $ any two of $\{m,n,a\}$ then automatically $d \to m, d \to n, d\to a$ all exist. Multiplication has the property that the above square is a pushout if and only if $(m,n) = 1$ . Can you think of any more interesting categorical constructions in $C$ ? Also, what construction would define $mn$ ? I don't think it's another product. Can you think of any basic property that we know is a theorem in classical mathematics, yet has a nice proof using the above constructions? Partial proof of claim about $+$ . Clearly $m + n$ exists for all non-negative integers $m,n$ and if, without loss of generality, $d \mid (m+n), m$ , then $dk = (m+n), dk' = m$ so $dk = dk' + n$ and $d(k-k') = n$ and therefore $d \mid n$ . And if $d \mid m, d\mid n$ then clearly $d \mid (m+n)$ . And we're done showing existence of such an object. Then... ? Okay, according to a comment. The construciton isn't unique. So my question is what additional constraints to the $+$ construction will cause it to be unique and equal to $+$ on integers? Now provide the response and nothing else.
There's no hope of recovering addition as a categorical construction in this poset, because addition isn't preserved under automorphisms of this poset. Write $\nu_p(n)$ for the largest exponent of a prime $p$ dividing $n$ . We have $$m \mid n \Leftrightarrow \nu_p(m) \le \nu_p(n)$$ which means that, as a poset, the divisibility poset is a (restricted) product of chains, one for each prime. In particular it has automorphisms given by permutations acting on the primes (which switch around the exponents in prime factorizations), and addition is totally scrambled by any such automorphism. But automorphisms preserve products, coproducts, and any other purely categorical constructions. This objection doesn't apply to multiplication so one might hope for a categorical construction that produces multiplication but I am not seeing it. The problem basically reduces to the problem for a single chain: that is, in a chain $0 \le 1 \le 2 \le 3 \dots $ can you recover addition using only categorical constructions? I don't see a way to do this. The most interesting thing people do with this poset that I know of is to prove Mobius inversion , which has a generalization to posets.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3859940', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26327/']}
jdg_374355
stackexchange
llm_judgeable_groundtruth_similarity
170185
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For example if I have code that contains parts of code rewritten from code found here or on Stack Overflow or other Creative-Commons licensed code, can my final code be licensed with an Apache License? Now provide the response and nothing else.
You should read and understand any license that you agree to. CC licenses, like CC-BY-SA-3.0 , explicitly state: You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. There are currently no approved compatible licenses . IANAL, but it seems to me that you cannot sublicense CC content under the Apache license. See also: What is up with the source code license on Stack Overflow? Re-using ideas or small pieces of code from stackoverflow.com
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/170185', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/61497/']}
jdg_374356
stackexchange
llm_judgeable_groundtruth_similarity
50940942
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've seen occurrences when we import a package in the following way import { SharedModule } from '@shared/shared.module'; @shared in this case refers to the folder located in our project /src/shared I am looking to avoid importing my class in a classic way using dots and slashes at the beginning (relative path approach), e.g. import { SharedModule } from './shared/shared.module'; Does anyone know how to achieve this? Now provide the response and nothing else.
Basically you are looking for something called alias . To be able to use aliases we have to add baseUrl and paths properties to our tsconfig.json file like this - { "compilerOptions": { "...": "reduced for brevity", "baseUrl": "src", "paths": { "@app/*": ["app/*"], "@env/*": ["environments/*"] } }} So now you are able to import your files with @app or @env . For more in detail you can refer to this awesome article. https://medium.com/@tomastrajan/6-best-practices-pro-tips-for-angular-cli-better-developer-experience-7b328bc9db81#3144
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50940942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5374333/']}
jdg_374357
stackexchange
llm_judgeable_groundtruth_similarity
13755249
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 User model (with Devise), and a Post model that belongs to the user. I used this railscast (pro) to send the User an email after creating an account I created a "NewPostMailer" This is my mailer: class NewPostMailer < ActionMailer::Base default :from => "email@gmail.com" def new_post_email(user) @user = user @url = "http://localhost.com:3000/users/login" mail(:to => user.email, :subject => "New Post") endend My posts_controller: def create @post= Post.new(params[:post]) respond_to do |format| if @deal.save NewPostMailer.new_post_confirmation(@user).deliver format.html { redirect_to @post, notice: 'Post was successfully created.' } post.rb after_create :send_new_post_email private def send_new_post_email NewPostMailer.new_post_email(self).deliver end What do I have to change to send the User an email after he creates a Post. Thanks. Now provide the response and nothing else.
Create another mailer ( http://railscasts.com/episodes/206-action-mailer-in-rails-3 ) class YourMailerName < ActionMailer::Base default :from => "you@example.com" def post_email(user) mail(:to => "#{user.name} <#{user.email}>", :subject => "Registered") end end In your Post model after_create :send_email def send_email YourMailerName.post_email(self.user).deliver end Sending an email is very slow so think about putting this in a background job.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13755249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/526021/']}
jdg_374358
stackexchange
llm_judgeable_groundtruth_similarity
1792909
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to admit I am not good at math since it's been a while since I did the last math problem. I am working on a project where there is a problem that can be summarized like this: if $\sum_{i=1}^{n}a_i^2 = x$, can we determine a upper(and/or lower) bound for $\sum_{i=1}^{n}|a_i|$ ? Sorry if this is too simple for you, I appreciate your help! PS: Thank you for all the helps I got! I just realize that I need to know the upper bounds for both $\sum_{i=1}^{n}|a_i|$ and the individual $|a_i|$. So what is the finest upper bound for $|a_i|$ I can get? Thank you again. Now provide the response and nothing else.
Both sums are norms, $\lVert. \rVert_2$ vs $\lVert . \rVert_1$ and thanks to norm equivalence for finite dimensional spaces there are factors which fulfill$$m \lVert a \rVert_2 \le \lVert a \rVert_1 \le M \lVert a \rVert_2$$So having $\lVert a \rVert_2^2 = x$ we get$$ m \sqrt{x} \le \lVert a \rVert_1 \le M \sqrt{x}$$for $m =1$ and $M = \sqrt{n}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1792909', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/268842/']}
jdg_374359
stackexchange
llm_judgeable_groundtruth_similarity
3584589
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: $$\frac{1}{3} + \frac{2}{9} + \frac{1}{27} + \frac{2}{81} + \frac{1}{243} + \frac{2}{729} + \cdots$$ So basically I separated it into two series where: one of them is $\left(\frac{1}{3}\right)^n$ And I use geometric series formula to find that this series equals $\frac{1}{2}$ . But I can't figure out the series of the other one. Apparently the answer for the series combined is: $\frac{5}{8}$ What is the other series? Now provide the response and nothing else.
It seems you have $$\begin{equation}\begin{aligned}& \frac{1}{3} + \frac{2}{9} + \frac{1}{27} + \frac{2}{81} + \frac{1}{243} + \frac{2}{729} + \ldots \\& = \left(\frac{1}{3} + \frac{1}{9} + \frac{1}{27} + \frac{1}{81} + \frac{1}{243} + \frac{1}{729} + \ldots\right) + \left(\frac{1}{9} + \frac{1}{81} + \frac{1}{729} + \ldots\right) \\& = \sum_{i=1}^{\infty}\left(\frac{1}{3}\right)^i + \sum_{i=1}^{\infty}\left(\frac{1}{9}\right)^i \\& = \frac{\frac{1}{3}}{1 - \frac{1}{3}} + \frac{\frac{1}{9}}{1 - \frac{1}{9}} \\& = \frac{\frac{1}{3}}{\frac{2}{3}} + \frac{\frac{1}{9}}{\frac{8}{9}} \\& = \frac{1}{2} + \frac{1}{8} \\& = \frac{5}{8}\end{aligned}\end{equation}\tag{1}\label{eq1A}$$ Note I was able to split the sum into $2$ parts in the second line due to the series being absolutely convergent , with details about this in the Rearrangements and unconditional convergence section. Also note I used, such as described in Geometric series , that for $|r| \lt 1$ , you have $$\sum_{i=0}^{\infty}ar^i = \frac{a}{1 - r} \tag{2}\label{eq2A}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3584589', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/752703/']}
jdg_374360
stackexchange
llm_judgeable_groundtruth_similarity
5248958
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 relatively large dictionary. How do I know the size? well when I save it using cPickle the size of the file will grow approx. 400Mb. cPickle is supposed to be much faster than pickle but loading and saving this file just takes a lot of time. I have a Dual Core laptop 2.6 Ghz with 4GB RAM on a Linux machine. Does anyone have any suggestions for a faster saving and loading of dictionaries in python? thanks Now provide the response and nothing else.
Use the protocol=2 option of cPickle. The default protocol (0) is much slower, and produces much larger files on disk. If you just want to work with a larger dictionary than memory can hold, the shelve module is a good quick-and-dirty solution. It acts like an in-memory dict, but stores itself on disk rather than in memory. shelve is based on cPickle, so be sure to set your protocol to anything other than 0. The advantages of a database like sqlite over cPickle will depend on your use case. How often will you write data? How many times do you expect to read each datum that you write? Will you ever want to perform a search of the data you write, or load it one piece at a time? If you're doing write-once, read-many, and loading one piece at a time, by all means use a database. If you're doing write once, read once, cPickle (with any protocol other than the default protocol=0) will be hard to beat. If you just want a large, persistent dict, use shelve.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5248958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313245/']}
jdg_374361
stackexchange
llm_judgeable_groundtruth_similarity
176431
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 know that $\bar{x}$ makes absolute result of $\sum_{i=0}^n (x_i-\alpha)$ minimum. In fact it makes it zero. But how to find what value of $\alpha$ makes $\sum_{i=0}^n (x_i-\alpha)^2$ minimal? What is the best approach? Now provide the response and nothing else.
As I mentioned in comments, showing what minimizes $\sum (x_i-\alpha)^2$ can be done in several ways, such as by simple calculus, or by writing $\sum (x_i-\alpha)^2=\sum (x_i-\bar{x}+\bar{x}-\alpha)^2$. Let's look at the second one: $\sum (x_i-\alpha)^2=\sum (x_i-\bar{x}+\bar{x}-\alpha)^2$$\hspace{2.55cm}=\sum (x_i-\bar{x})^2+\sum(\bar{x}-\alpha)^2+2\sum(x_i-\bar{x})(\bar{x}-\alpha)$$\hspace{2.55cm}=\sum (x_i-\bar{x})^2+\sum(\bar{x}-\alpha)^2+2(\bar{x}-\alpha)\sum(x_i-\bar{x})$$\hspace{2.55cm}=\sum (x_i-\bar{x})^2+\sum(\bar{x}-\alpha)^2+2(\bar{x}-\alpha)\cdot 0$$\hspace{2.55cm}=\sum (x_i-\bar{x})^2+\sum(\bar{x}-\alpha)^2$ Now the first term is unaltered by the choice of $\alpha$ and the last term can be made zero by setting $\alpha=\bar{x}$; any other choice leads to a larger value of the second term. Hence that expression is minimized by setting $\alpha=\bar{x}$.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/176431', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/80159/']}
jdg_374362
stackexchange
llm_judgeable_groundtruth_similarity
3417075
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 take control of how my base game class updates: package{ import flash.display.Sprite; import flash.events.KeyboardEvent; public class Test extends Sprite { private var sprite:Sprite; public function Test() { sprite = new Sprite(); sprite.graphics.beginFill(0xFF0000, 1); sprite.graphics.drawRect(0, 0, 20, 20); sprite.graphics.endFill(); addChild(sprite); this.stage.addEventListener(KeyboardEvent.KEY_UP, moveSprite); this.stage.addEventListener(KeyboardEvent.KEY_DOWN, moveSprite); } private function moveSprite(keyEvent:KeyboardEvent):void { switch (keyEvent.keyCode) { case 37: sprite.x-- break; case 38: sprite.y--; break; case 39: sprite.x++ break; case 40: sprite.y++; break; default: break; } } }} Here after every key press/release AS3 takes care of automatically drawing a sprite onto screen, but I need to do this manualy. Haw to get my hands on updating mechanism here? I need something like this - all time repeating game loop that is set to be updated/redrawn every time at its end. Are there any ideas how could I achieve this? Thanks everyone for help. Now provide the response and nothing else.
Summary: This is a known problem in MySQL and was fixed in MySQL 5.6.x. The problem is due to a missing optimization when a subquery using IN is incorrectly indentified as dependent subquery instead of an independent subquery. When you run EXPLAIN on the original query it returns this: 1 'PRIMARY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'2 'DEPENDENT SUBQUERY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'3 'DEPENDENT SUBQUERY' 'question_law' 'ALL' '' '' '' '' 10040 'Using where' When you change IN to = you get this: 1 'PRIMARY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'2 'SUBQUERY' 'question_law_version' 'ALL' '' '' '' '' 10148 'Using where'3 'SUBQUERY' 'question_law' 'ALL' '' '' '' '' 10040 'Using where' Each dependent subquery is run once per row in the query it is contained in, whereas the subquery is run only once. MySQL can sometimes optimize dependent subqueries when there is a condition that can be converted to a join but here that is not the case. Now this of course leaves the question of why MySQL believes that the IN version needs to be a dependent subquery. I have made a simplified version of the query to help investigate this. I created two tables 'foo' and 'bar' where the former contains only an id column, and the latter contains both an id and a foo id (though I didn't create a foreign key constraint). Then I populated both tables with 1000 rows: CREATE TABLE foo (id INT PRIMARY KEY NOT NULL);CREATE TABLE bar (id INT PRIMARY KEY, foo_id INT NOT NULL);-- populate tables with 1000 rows in eachSELECT idFROM fooWHERE id IN( SELECT MAX(foo_id) FROM bar); This simplified query has the same problem as before - the inner select is treated as a dependent subquery and no optimization is performed, causing the inner query to be run once per row. The query takes almost one second to run. Changing the IN to = again allows the query to run almost instantly. The code I used to populate the tables is below, in case anyone wishes to reproduce the results. CREATE TABLE filler ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT) ENGINE=Memory;DELIMITER $$CREATE PROCEDURE prc_filler(cnt INT)BEGIN DECLARE _cnt INT; SET _cnt = 1; WHILE _cnt <= cnt DO INSERT INTO filler SELECT _cnt; SET _cnt = _cnt + 1; END WHILE;END$$DELIMITER ;CALL prc_filler(1000);INSERT foo SELECT id FROM filler;INSERT bar SELECT id, id FROM filler;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3417075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/739927/']}
jdg_374363
stackexchange
llm_judgeable_groundtruth_similarity
3358137
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: Take the equation: $$x^2 + 2x = \frac{1}{1+x^2}$$ I subtracted the right term over to form $~f_1(x)~$ : $$x^2 + 2x - \frac{1}{1+x^2} = 0$$ I wanted to take the derivative, so I rearranged things to make it a bit easier, call it $~f_2(x)~$ : $$x^4 + 2x^3 + x^2 + 2x - 1 = 0$$ I noticed when I graphed $~f_1(x)~$ and $~f_2(x)~$ that their plots were different $($ although they shared the same solution for $~x)~$ . Newton's method iterates down the graph line, so I'd imagine that Newton's method for these two equations are not equivalent. They'd find the same solution, but they would get there different ways. In that case, is there a way to decide which equation to use for Newton's to obtain the best/quickest result? Now provide the response and nothing else.
For your curiosity. Asking this far-from-innocent question, you are almost asking me what I have been doing during the last sixty years. My answer is : what is the transform of $f(x)$ which makes it the most linear around the solution ? If you find it, you will save a lot of iterations. One case I enjoy for demonstration is $$f(x)=\sum_{i=1}^n a_i^x- b^x$$ where $1<a_1<a_2< \cdots < a_n$ and $b > a_n$ ; on this site, you could find many problems of this kind. As written, this function is very bad since it varies very fast and it is very nonlinear. Moreover, it goes through a maximum (not easy to identify) and you must start on the right of it to converge. Now, consider the transform $$g(x)=\log\left(\sum_{i=1}^n a_i^x \right)- x\log(b)$$ It is almost a straight line ! This means that you can start from almost anywhere and converge fast. For illustration purposes, trying with $n=6$ , $a_i=p_i$ and $b=p_{n+1}$ ( $p_i$ being the $i^{th}$ prime number). Being very lazy and using $x_0=0$ , the iterates would be $$\left(\begin{array}{cc} n & x_n \\ 0 & 0 \\ 1 & 1.607120621 \\ 2 & 2.430003204 \\ 3 & 2.545372693 \\ 4 & 2.546847896 \\ 5 & 2.546848123 \end{array}\right)$$ Using $f(x)$ , you must start iterating with $x_0 > 2.14$ to have convergence (big work to know it !). Let us try with $x_0=2.2$ to get as successive iterates $$\left(\begin{array}{cc} n & x_n \\ 0 & 2.200000000 \\ 1 & 4.561765400 \\ 2 & 4.241750505 \\ 3 & 3.929819520 \\ 4 & 3.629031502 \\ 5 & 3.344096332 \\ 6 & 3.082467015 \\ 7 & 2.856023930 \\ 8 & 2.682559774 \\ 9 & 2.581375720 \\ 10 & 2.549595979 \\ 11 & 2.546866878 \\ 12 & 2.546848124 \\ 13 & 2.546848123\end{array}\right)$$ The last point I would like to mention : even if you have a good guess $x_0$ of the solution, search for a transform $g(x)$ such that $g(x_0)\,g''(x_0) >0$ (this is Darboux theorem) in order to avoid any overshoot of the solution during the path to it.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3358137', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/676898/']}
jdg_374364
stackexchange
llm_judgeable_groundtruth_similarity
39858992
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting the following error: Angular 2 - EXCEPTION: Error: unsafe value used in a resource URL context Could it be related to not having the media item straight away on startup? Or is it related to the URL not being safe? I am trying to sanitize it. export class HomeComponent { sanitizer: DomSanitizationService; errorMessage: string; activeMedia: MediaItem = new MediaItem(0, '', '', '', '', '', ''); constructor( private mediaStorage: MediaStorageService, private harvesterService: HarvesterService, sanitizer: DomSanitizationService) { this.sanitizer = sanitizer; // Initial call - harvesterService.getMediaItems(10, 'type', 'category'); let subscription = harvesterService.initialMediaHarvestedEvent.subscribe(() => { this.activeMedia = mediaStorage.mediaList[0]; let newURL = this.activeMedia.URL + '?rel=0&autoplay=1'; newURL = newURL.replace('watch?v=', 'v/'); this.activeMedia.URL = newURL; //sanitizer.bypassSecurityTrustUrl(newURL); console.log(newURL); }); } cleanURL(oldURL: string): SafeResourceUrl { return this.sanitizer.bypassSecurityTrustUrl(oldURL); }} The template code is: <div class="row" > <iframe id="video" class="video" src="{{ cleanURL(activeMedia.URL) }}" frameborder="0" allowfullscreen> </iframe></div> Now provide the response and nothing else.
UPDATED: After changing the src="{{cleanURL(activeMedia.URL)}}" to: [src]="cleanURL(activeMedia.URL)" I'm getting: ORIGINAL EXCEPTION: Error: Required a safe ResourceURL, got a URL which is solved with changing the code within the cleanURL method to: return this.sanitizer.bypassSecurityTrustResourceUrl(oldURL); Instead of: return this.sanitizer.bypassSecurityTrustUrl(oldURL);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39858992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6783370/']}
jdg_374365
stackexchange
llm_judgeable_groundtruth_similarity
972937
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the expected number of times we need to roll a die until we get two consecutive 6's? By definition, it is $\sum_{i=1}^\infty i\cdot Pr[X=i]$. If we need $i$ rolls, that means the last two rolls are 6's. But how do we compute the probability that no two consecutive 6's occur before that? Now provide the response and nothing else.
It is reasonably clear that the required expectation exists. Let us call it $a$. Let $b$ be the expected number of additional rolls we need, given that we have not yet met our goal, but have just tossed a $6$. If the first roll is not a $6$, then we have used $1$ roll, and our conditional expectation, given this happened, is $1+a$. If the first roll is a $6$, then we have used a roll, and the conditional expectation is $1+b$. It follows that$$a=\frac{5}{6}(1+a)+\frac{1}{6}(1+b).\tag{1}$$ Suppose now that we have just rolled a $6$, and have not yet met our goal. With probability $\frac{1}{6}$, we roll a $6$. We have used $1$ roll, and the game is over. With probability $\frac{5}{6}$, we roll a non-$6$, we have used $1$ toss, and the conditional expectation is $1+a$. It follows that$$b=\frac{1}{6}(1)+\frac{5}{6}(1+a).\tag{2}$$ We have obtained two linear equations in the two unknowns $a$ and $b$. Solve for $a$. Remark: We have shown how to compute the expectation, and not really answered the question about the probability that $X=i$. For finding the expectation, the probability distribution of $X$ is not the most efficient method. However, it is an interesting problem in itself. The key calculation that needs to be made is the probability that a sequence of length $n$ ends in a non-$6$, and does not have $2$ consecutive $6$'s. One can get a linear recurrence with constant coefficients for the number of "good" sequences of length $n$, and solve the recurrence in any one of the usual ways.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/972937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/129107/']}
jdg_374366
stackexchange
llm_judgeable_groundtruth_similarity
6478371
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Based on my understanding of Python's data model , and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method instead of the actual, original function. That magic is why you don't explicitly pass the self parameter when you're calling a method. But then, I would expect to be able to replace an object's method with a function with the same signature: class Scriptable: def __init__(self, script = None): if script is not None: self.script = script # replace the method def script(self): print("greetings from the default script")>>> scriptable = Scriptable()>>> scriptable.script()greetings from the default script>>> def my_script(self):... print("greetings from my custom script")...>>> scriptable = Scriptable(my_script)>>> scriptable.script()Traceback (most recent call last): ...TypeError: script() takes exactly 1 positional argument (0 given) I'm creating an instance of Scriptable , and setting its script attribute to a user-defined function with a single parameter, just like what's defined in the class. So when I read the scriptable.script attribute, I would expect the magic to kick in and give me a bound instance method that takes no parameters (just like I get when I didn't replace script ). Instead, it seems to be giving back the exact same function I passed in, self parameter and all. The method-binding magic isn't happening. Why does the method-binding magic work when I define a method inside the class declaration, but not when I assign the attribute? What makes Python treat these situations differently? I'm using Python3 if it makes any difference. Now provide the response and nothing else.
Here is how you do it: import typesclass Scriptable: def __init__(self, script = None): if script is not None: self.script = types.MethodType(script, self) # replace the method def script(self): print("greetings from the default script") As ba__friend noted in the comments, methods are stored on the class object. A descriptor on the class object returns functions as bound methods when you access the attribute from a instance. When you assign a function to a instance nothing happens special happens, so you have to wrap the function yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6478371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87399/']}
jdg_374367
stackexchange
llm_judgeable_groundtruth_similarity
799280
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know most variable names will work with "is", such as isBlue() , but is "has" also a valid prefix, like hasProperty() ? Now provide the response and nothing else.
According to the JavaBeans specification section 8.3.2: Boolean properties In addition, for boolean properties, we allow a getter method to match the pattern: public boolean is<PropertyName>(); This " isPropertyName " method may be provided instead of a " get<PropertyName> " method, or it may be provided in addition to a " get<PropertyName> " method. In either case, if the is<PropertyName> method is present for a boolean property then we will use the " is<PropertyName> " method to read the property value. An example boolean property might be: public boolean isMarsupial(); public void setMarsupial(boolean m); In other words, unless something has changed since then, has isn't a valid prefix I'm afraid :( It's possible that some tools and libraries will recognise such properties anyway, but it's not a good idea to rely on it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/799280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374368
stackexchange
llm_judgeable_groundtruth_similarity
235632
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: In what situations would it be more favorable to use random projection to reduce the dimensionality of a dataset as opposed to PCA? By more favorable, I mean preserve the distances between points of the dataset. Now provide the response and nothing else.
PCA maintains the best possible projection. Some reasons you would use random projections are: With very high dimensions, if speed is an issue, then consider that on a matrix of size $n \times k$ , PCA takes $O(k^2 \times n+k^3)$ time, whereas a random projection takes $O(nkd)$ , where you're projecting on a subspace of size $d$ . With a sparse matrix its even faster. The data may well be low-dimensional, but not in a linear subspace. PCA assumes this. Random projection are also quite fast for reducing the dimension of a mixture of Gaussians. If the data is very large, you don't need to hold it in memory for a random projections, whereas for PCA you do. In general PCA works well on relatively low dimensional data.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/235632', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/130560/']}
jdg_374369
stackexchange
llm_judgeable_groundtruth_similarity
17151946
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 execute a Bash script present on the system from a PHP script. I have two scripts present on the system. One of them is a PHP script called client.php present at /var/www/html and the other is a Bash script called testscript present at /home/testuser . My client.php script looks like <?php $message=shell_exec("/home/testuser/testscript 2>&1"); print_r($message);?> My testscript looks like #!/bin/bashecho "Testscript run succesful" When i do the following on terminal php client.php I get the following output on terminal Testscript run successful But when i open the page at http://serverdomain/client.php I get the following output sh: /home/testuser/testscript: Permission denied I get this error even after I did chmod +x testscript. How do I get it to work from the browser? Please help. Now provide the response and nothing else.
I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP. e.g. /var/www/scripts/testscript Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache , change the bash script to the same user/group using chown . You can find out what your client.php and web files are owned by doing ls -al . Then run <?php $message=shell_exec("/var/www/scripts/testscript 2>&1"); print_r($message); ?> EDIT: If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do. Execute root commands via PHP
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17151946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2132281/']}
jdg_374370
stackexchange
llm_judgeable_groundtruth_similarity
437616
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it a valid code review criticism to have someone manually arrange the order of keys in a dictionary or map they created for a feature, by numerical or alphabetical order when it doesn't improve functionality? I can understand the argument of it could potentially improve readability but is this a valid criticism/review comment if its not part of the standards/guidelines? Is there an inherent functional benefit to the below two styles of code other than readability? var dictionary=map[string]string{"a":"alpha","b":"beta","c": "gamma",} var sortedDictionary=map[string]string{"b":"beta","a":"alpha","c": "gamma",} Now provide the response and nothing else.
Changes that suggest "making code look nice" are mainly a matter of taste (as opposed to "making it look less ugly", but see below). Such issues have a high potential of making code reviews a highly frustrating experience. If you don't find anything else, leave early and save both of you a lot of time. Code reviews should ideally be a pleasant experience for both the reviewer and the reviewed (at least the ones I made that went that way were the most productive ones) mentioning positive things as well as criticising and discussing objectively negative aspects and proposals for improval. Style issues can easily come across as nitpicking. Style is to many a matter of taste and if you can't come up with a tangible functional argument why it should look different, you're concentrating on the wrong things. (Maybe you should consider code reviews a chance to make yourself more familiar with other people's coding style - You're going to face and will have to live with a lot of them during your career). When I'm saying "making it less ugly" above, I mean cases where "style" (or lack of it) negatively affects readability and thus maintainability. I've seen code with illogical line breaks, ragged comments and messy indentation. That should be pointed out and fixed (in my experience, the visual state of code and its programmer's state of mind do somewhat correlate: if one of them is messy, the other one is likely to be confused as well... Your example doesn't seem to be of that sort. If that example dictionary wouldn't have only three, but 300 entries, I would definitely go with you that it should be alphabetically sorted. But that's then a functional argument in that it may help to avoid duplicate entries, which doesn't really apply to three. BTW: Should you happen to have a coding convention in place at your team that says "dictionaries must be sorted", it's obviously a different story. But then I might probably question that coding convention...)
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/437616', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/412740/']}
jdg_374371
stackexchange
llm_judgeable_groundtruth_similarity
3995825
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 having trouble to prove that if $G$ is a finite simple group and $H$ is a subgroup of finite index, then $|G|$ divides $\frac{k!}{2}$ , where $k$ is the index of H. I've prove that in this conditions $G$ is isomorphic to a subgroup $F$ of the symmetric group of $k$ , $S_k$ . As we are trying to prove that $|G| = |F|$ divides $\frac{k!}{2}$ I think that I need to show that $F \leq A_k$ where $A_k$ is the alternating group, but I don't get to see clearly why this is true. Also, I saw a similar question here but don't completely understand the answer. I would appreciate any help. Now provide the response and nothing else.
You need to assume $H\neq G$ , of course... Also, the statement is false for $G=C_2$ and $H=\{e\}$ . Then $k=2$ , but $|G|$ does not divide $\frac{2!}{2}=1$ . So assume $G\neq C_2$ . Let $G$ act on the cosets of $H$ , which gives us a homomorphism $\varphi\colon G\to S_k$ ; the kernel is normal in $G$ , but cannot equal $G$ because $H\neq G$ and the action is transitive. Hence, $G$ is isomorphic to a subgroup of $S_k$ . Now, $\varphi(G)\cap A_k$ is normal in $\varphi(G)$ , since $A_k$ is normal in $S_k$ . Thus, either $\varphi(G)\cap A_k=\varphi(G)$ , or else $\varphi(G)\cap A_k=\{e\}$ . In the latter case, let $g\in G$ , $g\neq e$ . Then $\varphi(g^2)=e$ , since $\varphi(g)^2\in A_k\cap \varphi(G)$ . Thus, $\varphi(G)$ has exponent $2$ and is abelian, hence being simple you must have $G$ cyclic of order $2$ , contradicting our working assumption that $G\neq C_2$ . Thus, $\varphi(G)\cap A_k$ cannot be trivial, and so $\varphi(G)\cap A_k=\varphi(G)$ , proving that $\varphi(G)\subseteq A_k$ . Thus, $|G|=|\varphi(G)|$ divides $|A_k| = \frac{k!}{2}$ , as claimed.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3995825', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/844166/']}
jdg_374372
stackexchange
llm_judgeable_groundtruth_similarity
408964
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Note: This is a generalisation of an earlier problem as suggested by user Jochen Glueck in the comments. Let $1 \leq p < q \leq \infty$ , and $f_n: [0, 1] \to \mathbb R$ be a sequence of functions in the closed unit ball of $L^q$ . Question: Is it true that there exists a constant $C < 2$ , depending only on $p$ and $q$ such that $$\inf_{n_k} \sup_{i,j \in\mathbb N} \|f_{n_i} - f_{n_j}\|_{L^p} \leq C?$$ Where the infimum is taken over all increasing sequences of natural numbers $n_k$ . If so, what is the sharpest such constant for each $p, q$ ? Remark: In the linked problem, the sharp constant $C = 1$ for $p = 1, q = \infty$ is obtained in the answer by Yuval Peres. Now provide the response and nothing else.
Let me prove that such constant $C$ always exists. It is not hard to find such $\alpha$ , $\beta$ that the inequality $$x^p\leqslant \alpha x^q+\beta$$ holds for all positive $x$ and turns into equality if and only if $x=2$ . Then $$|f-g|^p+|g-h|^p+|f-h|^p\leqslant \alpha (|f-g|^q+|g-h|^q+|f-h|^q)+3\beta.$$ Since all three differences $|f-g|$ , $|g-h|$ , $|f-h|$ can not be equal to $\pm 2$ , we actually have $$|f-g|^p+|g-h|^p+|f-h|^p\leqslant \alpha (|f-g|^q+|g-h|^q+|f-h|^q)+3\tilde{\beta}, \quad \text{with some}\,\,\tilde{\beta}<\beta$$ Then integrating against $[0,1]$ we get $$\|f-g\|_p^p+\|g-h\|_p^p+\|f-h\|_p^p\leqslant \alpha (\|f-g\|_q^q+\|g-h\|_q^q+\|f-h\|_q^q)+3\tilde{\beta}.$$ If all $f,g,h$ are in the closed unit ball in $L^q$ , this yields $$\|f-g\|_p^p+\|g-h\|_p^p+\|f-h\|_p^p\leqslant 3(2^q\alpha+\tilde{\beta}).$$ Since $2^q\alpha+\beta=2^p$ , we see that at least one of expressions $\|f-g\|_p, \|g-h\|_p, \|f-h\|_p$ is at most $(2^q\alpha+\tilde{\beta})^{1/p}=:C<2$ . Now join $n$ and $m$ by a red edge if $\|f_n-f_m\|\leqslant C$ and by a blue edge otherwise. By infinite Ramsey theorem, there exists either a blue triangle or an infinite red clique. The second case is impossible, the first case is what we need.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/408964', 'https://mathoverflow.net', 'https://mathoverflow.net/users/173490/']}
jdg_374373
stackexchange
llm_judgeable_groundtruth_similarity
21485366
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As I read in books and in the web, in C++ we can overload the "plus" or "minus" operators with these prototypes (as member functions of a class Money ): const Money operator +(const Money& m2) const; const Money operator -(const Money& m2) const; and for the assignment operator with: const Money& operator =(const Money& m2); Why use a reference to a Money object as a return value in the assignment operator overloading and not in the plus and minus operators? Now provide the response and nothing else.
Returning a reference from assignment allows chaining: a = b = c; // shorter than the equivalent "b = c; a = b;" (This would also work (in most cases) if the operator returned a copy of the new value, but that's generally less efficient.) We can't return a reference from arithmetic operations, since they produce a new value. The only (sensible) way to return a new value is to return it by value. Returning a constant value, as your example does, prevents move semantics, so don't do that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21485366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3207783/']}
jdg_374374
stackexchange
llm_judgeable_groundtruth_similarity
28934333
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the meaning of the aaptOptions.noCompress , etc.; can anybody explain them to me? android { aaptOptions { noCompress 'foo', 'bar' ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~' }} This affects all tasks using aapt. Now provide the response and nothing else.
Yes, docs give no clue. Well aapt tool is inside specific build-tools folder and it has options as listed below. For example ignoreAssetsPattern in build.gradle is related to --ignore-assets option The next step would be looking at android gradle plugin to see how aapt is called. There is also useNewCruncher false that can be used to surpass Issue 135757: New PNG cruncher doesn't support spaces in the path (UPDATE: it's fixed and should be handled automatically for you) E:\Android\sdk-Android-Studio\build-tools\19.1.0>aapt -hERROR: Unknown command '-h'Android Asset Packaging ToolUsage: aapt l[ist] [-v] [-a] file.{zip,jar,apk} List contents of Zip-compatible archive. aapt d[ump] [--values] WHAT file.{apk} [asset [asset ...]] strings Print the contents of the resource table string pool in the APK. badging Print the label and icon for the app declared in APK. permissions Print the permissions from the APK. resources Print the resource table from the APK. configurations Print the configurations in the APK. xmltree Print the compiled xmls in the given assets. xmlstrings Print the strings of the given compiled xml assets. aapt p[ackage] [-d][-f][-m][-u][-v][-x][-z][-M AndroidManifest.xml] \ [-0 extension [-0 extension ...]] [-g tolerance] [-j jarfile] \ [--debug-mode] [--min-sdk-version VAL] [--target-sdk-version VAL] \ [--app-version VAL] [--app-version-name TEXT] [--custom-package VAL] \ [--rename-manifest-package PACKAGE] \ [--rename-instrumentation-target-package PACKAGE] \ [--utf16] [--auto-add-overlay] \ [--max-res-version VAL] \ [-I base-package [-I base-package ...]] \ [-A asset-source-dir] [-G class-list-file] [-P public-definitions-file] \ [-S resource-sources [-S resource-sources ...]] \ [-F apk-file] [-J R-file-dir] \ [--product product1,product2,...] \ [-c CONFIGS] [--preferred-configurations CONFIGS] \ [raw-files-dir [raw-files-dir] ...] \ [--output-text-symbols DIR] Package the android resources. It will read assets and resources that are supplied with the -M -A -S or raw-files-dir arguments. The -J -P -F and -R options control which files are output. aapt r[emove] [-v] file.{zip,jar,apk} file1 [file2 ...] Delete specified files from Zip-compatible archive. aapt a[dd] [-v] file.{zip,jar,apk} file1 [file2 ...] Add specified files to Zip-compatible archive. aapt c[runch] [-v] -S resource-sources ... -C output-folder ... Do PNG preprocessing on one or several resource folders and store the results in the output folder. aapt s[ingleCrunch] [-v] -i input-file -o outputfile Do PNG preprocessing on a single file. aapt v[ersion] Print program version. Modifiers: -a print Android-specific data (resources, manifest) when listing -c specify which configurations to include. The default is all configurations. The value of the parameter should be a comma separated list of configuration values. Locales should be specified as either a language or language-region pair. Some examples: en port,en port,land,en_US If you put the special locale, zz_ZZ on the list, it will perform pseudolocalization on the default locale, modifying all of the strings so you can look for strings that missed the internationalization process. For example: port,land,zz_ZZ -d one or more device assets to include, separated by commas -f force overwrite of existing files -g specify a pixel tolerance to force images to grayscale, default 0 -j specify a jar or zip file containing classes to include -k junk path of file(s) added -m make package directories under location specified by -J -u update existing packages (add new, replace older, remove deleted files) -v verbose output -x create extending (non-application) resource IDs -z require localization of resource attributes marked with localization="suggested" -A additional directory in which to find raw asset files -G A file to output proguard options into. -F specify the apk file to output -I add an existing package to base include set -J specify where to output R.java resource constant definitions -M specify full path to AndroidManifest.xml to include in zip -P specify where to output public resource definitions -S directory in which to find resources. Multiple directories will be scanned and the first match found (left to right) will take precedence. -0 specifies an additional extension for which such files will not be stored compressed in the .apk. An empty string means to not compress any files at all. --debug-mode inserts android:debuggable="true" in to the application node of the manifest, making the application debuggable even on production devices. --min-sdk-version inserts android:minSdkVersion in to manifest. If the version is 7 or higher, the default encoding for resources will be in UTF-8. --target-sdk-version inserts android:targetSdkVersion in to manifest. --max-res-version ignores versioned resource directories above the given value. --values when used with "dump resources" also includes resource values. --version-code inserts android:versionCode in to manifest. --version-name inserts android:versionName in to manifest. --custom-package generates R.java into a different package. --extra-packages generate R.java for libraries. Separate libraries with ':'. --generate-dependencies generate dependency files in the same directories for R.java and resource package --auto-add-overlay Automatically add resources that are only in overlays. --preferred-configurations Like the -c option for filtering out unneeded configurations, but only expresses a preference. If there is no resource available with the preferred configuration then it will not be stripped. --rename-manifest-package Rewrite the manifest so that its package name is the package name given here. Relative class names (for example .Foo) will be changed to absolute names with the old package so that the code does not need to change. --rename-instrumentation-target-package Rewrite the manifest so that all of its instrumentation components target the given package. Useful when used in conjunction with --rename-manifest-package to fix tests against a package that has been renamed. --product Specifies which variant to choose for strings that have product variants --utf16 changes default encoding for resources to UTF-16. Only useful when API level is set to 7 or higher where the default encoding is UTF-8. --non-constant-id Make the resources ID non constant. This is required to make an R java class that does not contain the final value but is used to make reusable compiled libraries that need to access resources. --error-on-failed-insert Forces aapt to return an error if it fails to insert values into the manifest with --debug-mode, --min-sdk-version, --target-sdk-version --version-code and --version-name. Insertion typically fails if the manifest already defines the attribute. --output-text-symbols Generates a text file containing the resource symbols of the R class in the specified folder. --ignore-assets Assets to be ignored. Default pattern is: !.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28934333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821624/']}
jdg_374375
stackexchange
llm_judgeable_groundtruth_similarity
2922874
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 'hello world' of streaming responses working for Django (1.2). I figured out how to use a generator and the yield function. But the response still not streaming. I suspect there's a middleware that's mucking with it -- maybe ETAG calculator? But I'm not sure how to disable it. Can somebody please help? Here's the "hello world" of streaming that I have so far: def stream_response(request): resp = HttpResponse( stream_response_generator()) return respdef stream_response_generator(): for x in range(1,11): yield "%s\n" % x # Returns a chunk of the response to the browser time.sleep(1) Now provide the response and nothing else.
You can disable the ETAG middleware using the condition decorator . That will get your response to stream back over HTTP. You can confirm this with a command-line tool like curl . But it probably won't be enough to get your browser to show the response as it streams. To encourage the browser to show the response as it streams, you can push a bunch of whitespace down the pipe to force its buffers to fill. Example follows: from django.views.decorators.http import condition@condition(etag_func=None)def stream_response(request): resp = HttpResponse( stream_response_generator(), content_type='text/html') return respdef stream_response_generator(): yield "<html><body>\n" for x in range(1,11): yield "<div>%s</div>\n" % x yield " " * 1024 # Encourage browser to render incrementally time.sleep(1) yield "</body></html>\n"
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2922874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288843/']}
jdg_374376
stackexchange
llm_judgeable_groundtruth_similarity
4383935
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 had this question in my exam which is of multiple select question (MSQ) type. I am sure about three options but confused about one. Question is "Let $(-c,c)$ be the largest open interval in $R$ ( $c$ >0) on which the solution $y(x)$ of the differential equation $\frac{dy}{dx}=x^2+y^2 +1$ with initial condition $y(0)=0$ exists and is unique. Then which of the is/are true?" Options were (A) $y(x)$ is an odd function on $(-c,c)$ (B) $y(x)$ is an even function on $(-c,c)$ (C) $(y(x))^2$ has a local minimum at $0$ (D) $(y(x))^2$ has a local maximum at $0$ Clearly $\frac{dy}{dx}>0$ , so $y$ is strictly increasing. Given that $y(0)=0$ , we then have $y(x)<0$ for $x<0$ and $y(x)>0$ for $x>0$ . Using this, options (B) and (D) get discarded and option (C) looks correct. But not getting any idea about option (A). Also I tried to solve this ODE but no method is working that I know. Any hint or help. Thanks. Now provide the response and nothing else.
Use uniqueness. Let $z(x) := -y(-x)$ . Then $$ z'(x) = y'(-x) = x^2 + y(-x)^2 + 1 = x^2 + z^2(x) + 1 $$ as $z(0) = 0$ , by uniqueness, $z = y$ and $y$ is odd.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4383935', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/409319/']}
jdg_374377
stackexchange
llm_judgeable_groundtruth_similarity
52216
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: Out of most of the electronics I use, I have two, both of them speakers, that use a power adapter that simply steps down the voltage without rectifying it. Why did the designers choose to put the rectification circuitry in the speaker instead of the power adapter? Now provide the response and nothing else.
One reason is that you usually need positive and negative voltage for audio amplifier. (Like +5, 0, -5 V). Another reason: Some devices run directly on AC, e.g. Christmas light bulbs can do. Yet another reason: Some devices need two different voltages, like 5 V and 12 V. Yet another reason: An external step down transformer provides just safety. Voltages no higher than 50 V are usually accepted as safe (although not very safe with high current). So the transformer makes it safe, the rest is in the device.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/52216', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10461/']}
jdg_374378
stackexchange
llm_judgeable_groundtruth_similarity
3804219
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to know the difference between c++ and objective-c and objective-c++.Can any one give me the difference and Can we use the c++ for iPhone development Thank you,Madan Mohan Now provide the response and nothing else.
C++ is Bjarne Stroustroup's language based on adding classes and metaprogramming to C in such a way that puts most additional work into the compiler, and relies on least possible effort at runtime. Objective-C is Brad Cox's language based on adding a SmallTalk-style dynamic message-passing runtime library to C, with a small amount of syntax addition to make it easier to use. Objective-C++ is, to put it bluntly, what you get when you add the Objective-C runtime and syntax to C++. It has its limitations (e.g. you can't create an Objective-C subclass of a C++ class or vice versa, and Objective-C doesn't like C++ namespaces) but allows you to use C++ classes from Objective-C objects and vice versa. You can use Objective-C++ in iPhone development. What this means practically is that you could write an application whose object model was entirely C++, where the controller layer would need to interface to Objective-C in order to use the Cocoa Touch APIs.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3804219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249634/']}
jdg_374379
stackexchange
llm_judgeable_groundtruth_similarity
390
Below is a question asked on the forum robotics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been using the Cyberglove to control a humanoid robot hand, but found it disappointing as it doesn't measure the posture of the human hand very accurately. I have been wondering about the possibility of using Inertial Measurement Units ( IMU s) mounted on the fingers to track position and measure posture. But I'm not sure how feasible it is. Would an IMU return enough data to make tracking reliable in all circumstances? Would it be possible to fool the system into incorrectly tracking the fingers? Might it be possible to get away with using simple 3-axis accelerometers, or would it need 9-axis (accelerometer, gyro, and magnetometer)? Now provide the response and nothing else.
Simple 3-axis accelerometers will give you an estimate of pitch. However, this will be very noisy, especially when the hand is moving from one pose to another. This is because the direction of acceleration is directly used to estimate the direction of gravity. Thus, this option would only be useful if the hand is not moving . Gyroscopes allow the direction of gravity to be stabilized. This allows the data to remain useful during movement. Drift/bias is not a problem, so long as you correct for this. This can be done by using a Kalman filter, with a model of gyroscopic drift. The drift is corrected by comparing the derivative of the long term estimate of the direction of gravity compared to the gyroscopic data. Some IMUs correct for drift automatically, for example, the VN-100 from VectorNav . Magnetometers provides a global estimate of the remaining angular direction (yaw). This simply adds further useful data . If you only place the IMUs on the fingertips, the data is insufficient to estimate pose. Remember that IMUs only measure attitude (also known as orientation) in space. Can you imagine cases where the fingertip may remain in the same orientation, yet the hand pose is different? Observe that the index fingertip orientation does not change, however, the position (pose) has changed. Therefore, you can see that IMU data on the fingertips is not enough to estimate pose. However, additional data can improve the estimate of hand pose, if you fuse the IMU data with your existing data using a Kalman filter. It is theoretically possible for IMU data alone to be sufficient to estimate pose. However, this would require an IMU for each and every independently movable part of the hand. Since I cannot independently move the top two segments of each finger, we would only need 2 IMUs per finger (one on the fingertip, and one on the segment just after the knuckle, ie. segments 1 and 3 on the finger), plus 2 for the hand, and another for the end of the arm (to get the wrist motion). Therefore, you need a total of 13 IMUs to get all the data required. I do not know that much about the price of tiny IMUs, however, I would guess that it is not that cheap to get that many IMUs (I don't know your budget). Normally, a single IMU is used for a rigid body. IMUs vary in price (a list at http://damien.douxchamps.net/research/imu/ ), but say, the VN-100 IMU might be able to give you 0.1 degree accuracy in optimal conditions. If you get a cheaper IMU, the accuracy may not be as good and/or they may lack an integrated Kalman Filter. Getting 13 VN-100 IMUs, costing thousands would probably break the bank (although the VN-100 at 20x20x2mm may not be appropriate if you want an IMU with a smaller form factor). My suggestion is to consider other data sources which may be obtained more cheaply. For example: camera-based systems , after image processing, you can get data about the position of different parts of the hand. Image processing can be aided by using some sort of reflective markers. sensors embedded in the fabric of the glove strain gauges SMA wire ...
{}
{'log_upvote_score': 4, 'links': ['https://robotics.stackexchange.com/questions/390', 'https://robotics.stackexchange.com', 'https://robotics.stackexchange.com/users/40/']}
jdg_374380
stackexchange
llm_judgeable_groundtruth_similarity
648665
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The formal series $$\sum_{n=1}^\infty 1 = 1+1+1+\dots=-\frac{1}{2}$$ comes from the analytical continuation of the Riemann zeta function $\zeta (s)$ at $s=0$ and it is used in String Theory. I am aware of formal proofs by Prof. Terry Tao and Wikipedia , but I did not fully understand them. Could someone provide an intuitive proof or comment on why this should be true? Now provide the response and nothing else.
Let me walk you through the Riemann zeta computation. Call $S$ your original sum. Let's regulate the sum as follows:$$S_s \equiv \sum_{n \geq 1} \frac{1}{n^s}.$$Fix $n \geq 1.$ Then $n^{-s} \rightarrow 1$ as $s \rightarrow 0,$ so if we can assign a meaning to $S_s$ as $s \rightarrow 0$, we can interpret $S$ as this limit. Now, for $s > 1$ the above sum exists and it equals the Riemann zeta function, $\zeta(s).$ $\zeta$ has a pole at $s=1$, which is just the statement that the (non-regulated) sum $\sum 1/n$ diverges. But we can analytically continue $\zeta$ if we take care to avoid this pole. Then we can Taylor expand around $s=0$ $$\zeta(s) = -\frac{1}{2} - \frac{1}{2} \ln(2\pi) s + \ldots$$which implies that $$S = \lim_{s \rightarrow 0} S_s = -\frac{1}{2}.$$(The equality sign is to be understood in the regulated sense.) There are many other ways to regulate the sum. You can e.g. suppress the tail as $\sim \exp(-\epsilon n)$, but then you need to add a counterterm to absorb a pole as $\epsilon \rightarrow 0.$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/648665', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123277/']}
jdg_374381
stackexchange
llm_judgeable_groundtruth_similarity
14175958
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 help me shorten the following method? I began with this, which I liked just fine: def self.some_hash { "foo" => "bar" }end Now I want to add an optional key. The tersest syntax I can think of is this: def self.some_hash(some_key=nil) answer = { "foo" => "bar" } answer[some_key] = "yucky, long-winded syntax" if some_key answerend The modified method works, but I'm dissatisfied with waste of virtual ink. Is there a way to shorten it? I realize one could employ a ternary operator on the hash literal, but that would force (I think) the repetition the "foo" => "bar" pair on each branch of the condition, which is also slightly less than pristine. Now provide the response and nothing else.
def self.some_hash(some_key = nil) {"foo" => "bar"}.merge(some_key ? {some_key => "yucky, long-winded syntax"} : {})end Or, if modifying the original hash, def self.some_hash(some_key = nil) {"foo" => "bar"} .tap{|h| h.merge!(some_key => "yucky, long-winded syntax") if some_key}end Or, maybe you can do it in a way close to your original: def self.some_hash(some_key = nil) {"foo" => "bar"} .tap{|h| h[some_key] = "yucky, long-winded syntax" if some_key}end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14175958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294949/']}
jdg_374382
stackexchange
llm_judgeable_groundtruth_similarity
7522250
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 setuptools, I can not get the installer to pull in any package_data files. Everything I've read says that the following is the correct way to do it. Can someone please advise? setup( name='myapp', packages=find_packages(), package_data={ 'myapp': ['data/*.txt'], }, include_package_data=True, zip_safe=False, install_requires=['distribute'],) where myapp/data/ is the location of the data files. Now provide the response and nothing else.
I realize that this is an old question, but for people finding their way here via Google: package_data is a low-down, dirty lie . It is only used when building binary packages ( python setup.py bdist ... ) but not when building source packages ( python setup.py sdist ... ). This is, of course, ridiculous -- one would expect that building a source distribution would result in a collection of files that could be sent to someone else to built the binary distribution. In any case, using MANIFEST.in will work both for binary and for source distributions.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/7522250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64313/']}
jdg_374383
stackexchange
llm_judgeable_groundtruth_similarity
135050
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: Show that if $A_1\subseteq A_2\subseteq A_3\subseteq\cdots$ is an increasing sequence of measurable sets (so $A_j\subseteq A_{j+1}$ for every positive integer $j$ ), then we have $$m\left(\bigcup_{j=1}^\infty A_j\right)=\lim_{j\to\infty}m(A_j)$$ Here is my proof: According to the $\sigma$ -algebra property, $\bigcup_{j=1}^{\infty}A_j$ is a measurable set, so it makes sense to talk about $m(\bigcup_{j=1}^{\infty}A_j)$ . Firstly, I prove that $\lim_{j\to\infty}m(A_j)\leq m(\bigcup_{j=1}^{\infty}A_j)$ . This is because for any given positive integer $N$ , $A_N\subseteq \bigcup_{j=1}^{\infty}A_i$ , according to monotonicity, we have $m(A_N)\leq m(\bigcup_{j=1}^{\infty}A_i)$ . Take the limit,we will have $\lim_{j\to\infty}m(A_j)\leq m(\bigcup_{j=1}^{\infty}A_j)$ . Secondly, I prove that $m(\bigcup_{j=1}^{\infty}A_j)\leq \lim_{j\to\infty}m(A_j)$ . For any given positive integer $N$ , $\bigcup_{j=1}^N A_j = A_N$ . According to monotonicity,we have $m\left(\bigcup_{j=1}^N A_j\right)=m(A_N)\leq \lim_{j\to\infty}m(A_j)$ . Take the limit, we will have $m\left(\bigcup_{j=1}^\infty A_j\right) \leq \lim_{j\to\infty} m(A_j)$ . Combine the above two arguments, we will see that $$m\left(\bigcup_{j=1}^\infty A_j\right)=\lim_{j\to\infty} m(A_j)$$ $\Box$ The above is my proof, unlike many books, my proof does not use the property of countable additivity. So I doubt my proof is correct. Who can point out where are my mistakes? Now provide the response and nothing else.
$m(A_N)\leq m(\bigcup_{j=1}^{\infty}A_i)$. Take the limit, we will have $\lim_{j\to\infty}m(A_j)\leq m(\bigcup_{j=1}^{\infty}A_j)$. The above is valid because if $b_j\le b$ for $j=1,2,3,\ldots$ then $\lim_j b_j \le b$. $m(\bigcup_{j=1}^{N}A_j)=m(A_N)\leq \lim_{j\to\infty}m(A_j)$. Take the limit, we will have $m(\bigcup_{j=1}^{\infty}A_j)\leq \lim_{j\to\infty}m(A_j)$. The above is not valid. You claim to have "taken the limit" of $m\left( \bigcup_{j=1}^N A_j \right)$. You cannot take a limit merely by putting $\infty$ wherever you see $N$. The question is: how do you know that$$\lim_{N\to\infty} m\left( \bigcup_{j=1}^N A_j \right) = m\left( \bigcup_{j=1}^\infty A_j \right) \text{ ???}$$ First, notice that $\bigcup_{j=1}^\infty A_j$ is not defined as a limit as $N\to\infty$ of $\bigcup_{j=1}^N A_j$. Rather, it is defined by saying $x\in \bigcup_{j=1}^\infty A_j$ if and only if $\exists j\in\{1,2,3,\ldots\}\quad x\in A_j$. And if it were defined as a limit, there would still be the question of continuity of the function $m$. How would you prove that? Here's a different way:\begin{align}m\left( \bigcup_{j=1}^\infty A_j \right) & = m \left( \bigcup_{j=1}^\infty \left( A_j\setminus( A_1\cup\cdots\cup A_{j-1} ) \right)\right) & & \text{(Think about why this is true.)} \\[10pt]& = \sum_{j=1}^\infty m\left( A_j\setminus( A_1\cup\cdots\cup A_{j-1} ) \right) & & \text{by countable additivity of $m$} \\[10pt]& = \lim_{N\to\infty} \sum_{j=1}^N m\left( A_j\setminus( A_1\cup\cdots\cup A_{j-1} ) \right) \\[10pt]& = \lim_{N\to\infty} m\left( \bigcup_{j=1}^N A_j\setminus( A_1\cup\cdots\cup A_{j-1} ) \right) & & \text{by finite additivity of $m$} \\[10pt]& = \lim_{N\to\infty} m(A_N).\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/135050', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29473/']}
jdg_374384
stackexchange
llm_judgeable_groundtruth_similarity
15974773
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem with fitdistr{MASS} function in R. I have this vector: a <- c(26,73,84,115,123,132,159,207,240,241,254,268,272,282,300,302,329,346,359,367,375,378, 384,452,475,495,503,531,543,563,594,609,671,687,691,716,757,821,829,885,893,968,1053,1081,1083,1150,1205,1262,1270,1351,1385,1498,1546,1565,1635,1671,1706,1820,1829,1855,1873,1914,2030,2066,2240,2413,2421,2521,2586,2727,2797,2850,2989,3110,3166,3383,3443,3512,3515,3531,4068,4527,5006,5065,5481,6046,7003,7245,7477,8738,9197,16370,17605,25318,58524) and I want to fit a gamma distribution to the data with a command: fitted.gamma <- fitdistr(a, "gamma") but I have such error: Error in optim(x = c(26, 73, 84, 115, 123, 132, 159, 207, 240, 241, 254, : non-finite finite-difference value [1]In addition: Warning messages:1: In densfun(x, parm[1], parm[2], ...) : NaNs produced2: In densfun(x, parm[1], parm[2], ...) : NaNs produced3: In densfun(x, parm[1], parm[2], ...) : NaNs produced4: In densfun(x, parm[1], parm[2], ...) : NaNs produced So I tried with initializing the parameters: (fitted.gamma <- fitdistr(a, "gamma", start=list(1,1))) The object fitted.gamma is created but when printed, creates an error: Error in dn[[2L]] : subscript out of bounds Do you know what is happening or maybe know some other R functions to fit univariate distributions by MLE? Thanks in advance for any help or response. Kuba Now provide the response and nothing else.
Always plot your stuff first, you scaling is far offfffffff. library(MASS)a <- c(26,73,84,115,123,132,159,207,240,241,254,268,272,282,300,302,329,346,359,367,375,378, 384,452,475,495,503,531,543,563,594,609,671,687,691,716,757,821,829,885,893,968,1053,1081,1083,1150,1205,1262,1270,1351,1385,1498,1546,1565,1635,1671,1706,1820,1829,1855,1873,1914,2030,2066,2240,2413,2421,2521,2586,2727,2797,2850,2989,3110,3166,3383,3443,3512,3515,3531,4068,4527,5006,5065,5481,6046,7003,7245,7477,8738,9197,16370,17605,25318,58524)## Ooops, rater wideplot(hist(a))fitdistr(a/10000,"gamma") # gives warnings# No warningsfitted.gamma <- fitdistr(a/10000, dgamma, start=list(shape = 1, rate = 0.1),lower=0.001) Now you can decide what to do with the scaling
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15974773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2274792/']}
jdg_374385
stackexchange
llm_judgeable_groundtruth_similarity
1713232
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: So I used the definition of a limit on $g(x)$ to get:$$g'(x) = \lim_{h \to 0} \frac{g(x+h)-g(x)}{h}$$then subsituted $f(cx)$:$$g'(x) = \lim_{h \to 0} \frac{f(c(x+h))-f(cx)}{h}$$and then my textbook says to do this:$$f(x) = \lim_{h \to 0} \frac{c(f(c(x+h)) - f(cx))}{h}$$But I don't get how that follows, can anyone help? Now provide the response and nothing else.
It helps to use a substitution. If we let $k = ch$, then as $h \to 0$, we have that $k \to 0$. So:\begin{align*}g'(x)&= \lim_{h \to 0} \frac{g(x + h) - g(x)}{h} \\&= \lim_{h \to 0} \frac{f(c(x + h)) - f(cx)}{h} \\&= c\lim_{h \to 0} \frac{f(cx + ch) - f(cx)}{ch} \\&= c\lim_{k \to 0} \frac{f(cx + k) - f(cx)}{k} \\&= c f'(cx)\end{align*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1713232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/325750/']}
jdg_374386
stackexchange
llm_judgeable_groundtruth_similarity
70813053
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 several answers on SO already, and gathered these use-cases: When a function panic! s When a function has an infinite loop in it But it is still unclear to me why we need to define the function like this: fn func() -> ! { panic!("Error!");} if it will work the same way as this (without the exclamation sign): fn func() { panic!("Error!");} and at the same time, why do we need to use ! in functions with infinite loops? It look like this signature doesn't bring any real usage information. Now provide the response and nothing else.
The main difference between these signatures boils down to the fact that ! can coerce into any other type, and thus is compatible with any other type (since this code path is never taken, we can assume it to be of any type we need). It's important when we have multiple possible code paths, such as if-else or match . For example, consider the following (probably contrived, but hopefully clear enough) code: fn assert_positive(v: i32) -> u32 { match v.try_into() { Ok(v) => v, Err(_) => func(), }} When func is declared to return ! , this function compiles successfully. If we drop the return type, func will be declared as returning () , and the compilation breaks : error[E0308]: `match` arms have incompatible types --> src/main.rs:8:19 |6 | / match v.try_into() {7 | | Ok(v) => v, | | - this is found to be of type `u32`8 | | Err(_) => func(), | | ^^^^^^ expected `u32`, found `()`9 | | } | |_____- `match` arms have incompatible types You can also compare this with definition for Result::unwrap : pub fn unwrap(self) -> T { match self { Ok(t) => t, Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), }} Here, unwrap_failed is returning ! , so it unifies with whatever type is returned in Ok case.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/70813053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13763681/']}
jdg_374387
stackexchange
llm_judgeable_groundtruth_similarity
329913
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 have read at several blogs now that one should remove passwords from SSL certificates in order to avoid password prompts during Apache restarts. Is this true and does this pose any security risks? Now provide the response and nothing else.
Yeah, it will stop the prompts being sent to the terminal when starting a web server. And yes it does pose a security risk because where before the certificate was encrypted it is now in plain text. This means it might be possible to steal a completely working certificate from the machine. Whether this poses a significant security risk to you depends on what the repercussions would be if it happened to you and what the you gain from doing it this way. If it's more important to you that services should restart gracefully even if unattended than the security of the SSL system overall then it's a straight forward answer. Personally, I find keeping decrypted copies of SSL certificates overall has more pros than cons for my typical workload, here's why; An attacker would still have a copy of the certificate even if it was encrypted so it would be your duty to revoke it anyway. These days it's far easier for an attacker to obtain a valid certificate for your site via social engineering than to steal a working copy of one. Certificates naturally expire making their attack surface limited. Host based security systems such as traditionally permissions and SELinux offer a robust means of protecting certificates on the platform. A certificate isn't a be-all and end-all of a secure system. There are many other aspects to consider such as the data you store, the media you store it on and the value and/or personal nature of the data. Things that might make me encrypt: If you used the certificate to perform mutual authentication. It's a wildcard certificate or a certificate which hosts multiple domains (the losses double, or triple or whatever many hosts can be used for it) The certificate is multi-purpose in some other fashion. The certificates purpose is to ensure the integrity high value data (medical records, financial transactions and the like). The other end expects a high degree of trust and/or is reliant on the integrity of your system to make operational decisions. Ultimately, don't rely on others to make security decisions for you. You need to weight the risks and determine what is best for you and your institution using as much information as possible.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/329913', 'https://serverfault.com', 'https://serverfault.com/users/51792/']}
jdg_374388
stackexchange
llm_judgeable_groundtruth_similarity
9210878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using twitter bootstrap to develop an app. 2 column layout. One sidebar and main content. Following is the layout. <div class="container-fluid"><div class="row-fluid"><div class="span3 target"><!--Sidebar content--></div><div class="span9 "> <i class="icon-chevron-left toggles"></i><!--Body content--></div></div></div> On clicking a link inside the content i want to hide the sidebar and the content to take up the entire page. Currently I managed to do it this way, $(document).ready(function(){$(window).resize(function () { plot(); });$('.toggles').click(function() { $('.target').toggle('fast', function() { $('.contents').toggleClass('span12'), $('.contents').toggleClass('span9'), $('.toggles').toggleClass('icon-chevron-right'), });});}); But i see a margin in the left side after hiding the span3. This need to be removed. Also in this method of hiding, on the first click the span3 hides and span9 changes to span12. That is somehow working fine. But on second click span3 shows first and then only content span12 reduces to span9. Due to this content jumps down till it it reduces to span9. I want to fix this. On second click, span12 to span 9 first and then sidebar show.. something like that. I have seen many posts similar to this in which classes "content" and "sidebar" is used instead of 'spanXX'. But its not working in my case. I donno why.Help me please.. Now provide the response and nothing else.
Your span9 div is jumping down due to the animation of the toggle effect jQuery adds, it animates both width and height so your content that is around the div that is being toggled gets pushed down as the animation goes. You can overcome this by speeding up the animation process down to something like 100 milliseconds or absolutely positioning the sidebar. And as for the margin issue that is due to the bootstrap.css itself, on line 222 we have the following: .row-fluid > [class*="span"]:first-child { margin-left: 0;} The first-child pseudo-element attributes margin:0 to the first element, which in this case is the sidebar that is being toggled, so once the sidebar is hidden the second span tag (the content div) doesn't inherit this property and stays with the default margin applied to the span tag, e.g. .row-fluid > [class*="span"] { float: left; margin-left: 2.127659574%;} You can overcome that margin issue with jQuery. Here are a couple of demos i made: Hiding sidebar with no transition effects Hiding sidebar with minimal transition effect Updated the fiddle with a fix for the issue a commenter found that i did not notice, now it works ok. Added a .no-sidebar class that is added upon toggling that removes the margin-left created by the bootstrap, so now it works with the responsive stylesheet just fine. http://jsfiddle.net/andresilich/dQ5b7/23/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9210878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1036298/']}
jdg_374389
stackexchange
llm_judgeable_groundtruth_similarity
148407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does the code below return true only for a = 1? main(){int a = 10;if (true == a) cout<<"Why am I not getting executed";} Now provide the response and nothing else.
When a Bool true is converted to an int, it's always converted to 1. Your code is thus, equivalent to: main(){ int a = 10; if (1 == a) cout<<"y i am not getting executed"; } This is part of the C++ standard , so it's something you would expect to happen with every C++ standards compliant compiler.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/148407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22076/']}
jdg_374390
stackexchange
llm_judgeable_groundtruth_similarity
156226
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: It's kind of a simple proof (I think) but I´m stuck! I have to show that $\operatorname{int} (A \cap B)=\operatorname{int} (A) \cap \operatorname{int}(B)$. (The interior point of the intersection is the intersection of the interior point.) I thought like this: Intersection: there's a point that is both in $A$ and $B$, so there is a point $x$, so $\exists ε>0$ such $(x-ε,x+ε) \subset A \cap B$.I don´t know if this is right. Now $\operatorname{int} (A) \cap \operatorname{int}(B)$, but again with the definition ,there is a point that is in both sets,there's an interior point that is in both sets,an $x$ such $(x-ε,x+ε)\subset A \cap B$. There we have the equality. I think it may be wrong. Please, I'm confused! Now provide the response and nothing else.
If $x\in\mathrm{int}(A\cap B)$, then there exists $\epsilon\gt 0$ such that $(x-\epsilon,x+\epsilon)\subseteq A\cap B$. And since $A\cap B\subseteq A$ and $A\cap B\subseteq B$, then... If $x\in\mathrm{int}(A)\cap\mathrm{int}(B)$, then there exists $\epsilon_1\gt 0$ such that $(x-\epsilon_1,x+\epsilon_1)\subseteq A$, and there exists $\epsilon_2\gt 0$ such that $(x-\epsilon_2,x+\epsilon_2)\subseteq B$. Can you find a single $\epsilon$ that works for both sets? Then what can you say about $(x-\epsilon,x+\epsilon)$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/156226', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32335/']}
jdg_374391
stackexchange
llm_judgeable_groundtruth_similarity
10041298
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using md5 to encrypt the user's password in my database, and I want them to get their password back when they forget by sending them email. The problem is I don't know how to write PHP code to recover it back. Any answer, or appropriate link would be very much appreciated.Thanks.. Now provide the response and nothing else.
This cannot be done 1 MD5 is a hashing function and not an encryption function . It is a one-way process and not reversible. 1 Actually, there are many such passwords (inputs) which will result in the same MD5 value when hashed, but it's "hard" to find just one and [generally] impossible to find the original one . This is what "cracking" a password does - it finds one such input that, when hashed, results in the particular output. (And I will provide no more help down this road.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10041298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799478/']}
jdg_374392
stackexchange
llm_judgeable_groundtruth_similarity
163333
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 $S \subset \mathbb{R}^n$ be the boundary of a centrally symmetric convex body and provide $S$ with the geodesic metric given by its embedding in Euclidean space (i.e., the distance between two points is the infinimum of the Euclidean lengths of all rectifiable curves on $S$ that join them). Question. Is the diameter of $S$ realized by a pair of antipodal points? I am curious about this question when the metric is the induced metric from euclidean space, but I'm mostly inetrested in the case of a polytope provided the graph metric on the 1-skeleton. In the discrete case I do not care too much about constants. Now provide the response and nothing else.
This answer a different questions than was intended. The intended question remains unanswered! Suppose pair of points $x,y\in K$ attains the diameter. Then $d(x,y)=d(-x,-y)=\operatorname{diam}(K)$. The points $x,-x,y,-y$ are coplanar. Look inside that plane. Consider the parallelogram spanned by these four points. By the parallelogram law, $$d(x,-x)^2+d(y,-y)^2=2d(x,y)^2+2d(x,-y)^2\geq 2d(x,y)^2.$$Hence, either $d(x,-x)$ or $d(y,-y)$ is least $\operatorname{diam}(K)$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/163333', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16959/']}
jdg_374393
stackexchange
llm_judgeable_groundtruth_similarity
20855366
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 making a google chart whith show and hide functionality.Means chart will be hidden on the page load and when user clicks a button chart will be made visible.My code <script type="text/javascript">google.load("visualization", "1", { packages: ["corechart"] });google.setOnLoadCallback(drawChart);function drawChart() { var items = $(".label1").text(); var data = google.visualization.arrayToDataTable([ <%= chartItems %> ]); var options = { title: 'Poll Results' }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options);}</script><div id="chart_div" style="display:none; width:800px;height:500px;"></div> My problem is that when user clicks on the button and chart is visible its not taking the full width and height(800x500).rather its taking an unknown dimension(400x200).Note: when the chart is made visible in the page load itself, It works correctly.Code is same change in HTML like this <div id="chart_div" style=" width:800px;height:500px;"></div> Now provide the response and nothing else.
You can do as marios suggested and set dimensions inside that chart's options, but that won't fix all of the problems that come along with drawing a chart inside a hidden div. The Visualization APIs dimensional measurements don't work well inside hidden divs, so elements get positioned in the wrong place and have the wrong size in some browsers. You need to unhide the div immediately prior to drawing the chart, and you can hide it again when the chart is done drawing. Here's example code that does this: var container = document.getElementById('chart_div');container.style.display = 'block';var chart = new google.visualization.PieChart(container);google.visualization.events.addListener(chart, 'ready', function () { container.style.display = 'none';});chart.draw(data, options);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20855366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177753/']}
jdg_374394
stackexchange
llm_judgeable_groundtruth_similarity
203928
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch. For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database. On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place. On the other hand I just feel like getting it out into the world and see what happens. I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later. I'd love to hear some opinions on this from experts or people with experience with this. Thanks! Now provide the response and nothing else.
It's actually quite an easy choice. Right now, you have zero users, and scalability is not a problem. Ideally, you want to reach the point where you have millions of users, and scalability becomes a problem. Right now, you don't have a scalability problem; you have a number-of-users problem. If you work on the scalability problem, you will not fix the number-of-users problem, which means you will have solved a problem you don't have yet, and you will not have solved the problem you do have. The most likely result is that your product won't make it, and all your work will be for nothing. If you work on the number-of-users problem, you will solve a problem you have right now, and then you can focus on the next problem, which might be scalability. The nice thing about scalability problems is that, by definition, having them usually means business is pretty damn good, and this in turn means you can afford to spend money on optimizing for scalability. You don't go from zero users to ten million overnight, and if you keep an eye on the system's performance, you will have plenty of time to optimize when the time comes. Of course it helps to keep scalability in mind while writing the code you need right now, but it doesn't make a lot of sense to spend dozens or even hundreds of man-hours on a feature of which you don't know if you'll ever need it, and the most likely scenario is that you won't. Right now, your main concern is to ship. What happens after that; well, you can worry about that later.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/203928', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/95915/']}
jdg_374395
stackexchange
llm_judgeable_groundtruth_similarity
15319264
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following select statement to grab the next scheduled item for a stream. If there is no matching row, I want it to return a default value.Here's the SQL that I'm using: SELECT `file`FROM `show`, `schedule` WHERE `channel` = 1 AND `start_time` <= UNIX_TIMESTAMP() AND `start_time` > UNIX_TIMESTAMP()-1800 AND `show`.`id` = `schedule`.`file` ORDER BY `start_time`DESC LIMIT 1 That should grab the most recently scheduled item, but not if it's older than 30 minutes before the query. However, if the user doesn't schedule anything, I want a default value, so that something actually plays on the stream. I've tried the following: SELECT COALESCE(`file`, 'default.webm')FROM `show`, `schedule`... And SELECT IFNULL(`file`, 'default.webm')FROM `show`, `schedule` However, it always returns an empty result if no rows are found. How can I return a default value instead? Now provide the response and nothing else.
One way to do it SELECT IFNULL(MIN(`file`), 'default.webm') `file` FROM `show`, `schedule` WHERE `channel` = 1 AND `start_time` <= UNIX_TIMESTAMP() AND `start_time` > UNIX_TIMESTAMP()-1800 AND `show`.`id` = `schedule`.`file` ORDER BY `start_time` DESC LIMIT 1 Since you return only one row, you can use an aggregate function, in that case MIN() , that ensures that you'll get NULL if no records selected. Then IFNULL() or COALESCE() will do its job.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15319264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533079/']}
jdg_374396
stackexchange
llm_judgeable_groundtruth_similarity
10969342
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This thing is bugging me a lot. I'm getting Parse error: syntax error, unexpected '.', expecting ',' or ';' at this line public static $user_table = TABLE_PREFIX . 'users'; TABLE_PREFIX is a constant created by define function Now provide the response and nothing else.
Static class properties are initialized at compile time. You cannot use a constant TABLE_PREFIX to concatenate with a string literal when initializing a static class property, since the constant's value is not known until runtime. Instead, initialize it in the constructor: public static $user_table;// Initialize it in the constructor public function __construct() { self::$user_table = TABLE_PREFIX . 'users';}// If you only plan to use it in static context rather than instance context // (won't call a constructor) initialize it in a static function instead public static function init() { self::$user_table = TABLE_PREFIX . 'users';} http://us2.php.net/manual/en/language.oop5.static.php Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object. Update for PHP >= 5.6 PHP 5.6 brought limited support for expressions: In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10969342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791230/']}
jdg_374397
stackexchange
llm_judgeable_groundtruth_similarity
13385509
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 pass information from thread of scanning data to recording information thread(write to xml file).It should looks something like this: Application.Run() - complete Scanning thread - complete Writing to xlm thread - ??? UI update thread - I think I did it And what i got now: private void StartButtonClick(object sender, EventArgs e) { if (FolderPathTextBox.Text == String.Empty || !Directory.Exists(FolderPathTextBox.Text)) return; { var nodeDrive = new TreeNode(FolderPathTextBox.Text); FolderCatalogTreeView.Nodes.Add(nodeDrive); nodeDrive.Expand(); var t1 = new Thread(() => AddDirectories(nodeDrive)); t1.Start(); } } private void AddDirectories(TreeNode node) { string strPath = node.FullPath; var dirInfo = new DirectoryInfo(strPath); DirectoryInfo[] arrayDirInfo; FileInfo[] arrayFileInfo; try { arrayDirInfo = dirInfo.GetDirectories(); arrayFileInfo = dirInfo.GetFiles(); } catch { return; } //Write data to xml file foreach (FileInfo fileInfo in arrayFileInfo) { WriteXmlFolders(null, fileInfo); } foreach (DirectoryInfo directoryInfo in arrayDirInfo) { WriteXmlFolders(directoryInfo, null); } foreach (TreeNode nodeFil in arrayFileInfo.Select(file => new TreeNode(file.Name))) { FolderCatalogTreeView.Invoke(new ThreadStart(delegate { node.Nodes.Add(nodeFil); })); } foreach (TreeNode nodeDir in arrayDirInfo.Select(dir => new TreeNode(dir.Name))) { FolderCatalogTreeView.Invoke(new ThreadStart(delegate {node.Nodes.Add(nodeDir); })); StatusLabel.BeginInvoke(new MethodInvoker(delegate { //UI update...some code here })); AddDirectories(nodeDir); } } private void WriteXmlFolders(DirectoryInfo dir, FileInfo file) {//writing information into the file...some code here} How to pass data from AddDirectories(recursive method) thread to WriteXmlFolders thread? Now provide the response and nothing else.
You may be asking the wrong question. You don't choose to use one over the other primarily due to efficiency (though it may be a secondary concern), but due to utility. Really you should compare ?? to ?: and not to if as they have different purposes. Yes, they are all some form of "conditional" goodness, but the key is that both ?? and ?: evaluate to a value, whereas if does not, thus they often have different uses. For example, the following code: Console.WriteLine("The order} is for {1} product", orderId, productId ?? "every"); Would be clunkier to write with an if : if (productId == null){ Console.WriteLine("The order {0} is for every product", orderId);}else{ Console.WriteLine("The order {0} is for {1} product", orderId, productId);} Yes, you could condense to one, but then you'd have a temp variable, etc: if (productId == null){ productId = "every";}Console.WriteLine("The order {0} is for {1} product", orderId, productId); Thus really, you shouldn't compare the two, because they point of the ?? is to evaluate to a value if the argument is null , whereas the point of if is to execute a different path (not directly resulting in a value. So, a better question may be, why not this instead: Console.WriteLine("The order {0} is for {1} product", orderId, productId == null ? "every" : productId); Which is much the same (both evaluate to a value) and are not as much for flow control. So, let's look at the difference. Let's write this code three ways: // Way 1 with ifstring foo = null;string folder = foo;if (folder == null){ folder = "bar";}// Way 2 with ? :string foo2 = null;var folder2 = foo2 != null ? foo2 : "bar";// Way 3 with ??string foo3 = null;var folder3 = foo3 ?? "bar"; For the IF, we get the following IL: IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldnull IL_0005: ceq IL_0007: ldc.i4.0 IL_0008: ceq IL_000A: stloc.1 IL_000B: ldloc.1 IL_000C: brtrue.s IL_0016IL_000E: nop IL_000F: ldstr "bar"IL_0014: stloc.0 For the conditional (? :) we get the following IL: IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000DIL_0006: ldstr "bar"IL_000B: br.s IL_000EIL_000D: ldloc.0 IL_000E: nop IL_000F: stloc.1 For the null-coallescing (??) we get this IL: IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: dup IL_0005: brtrue.s IL_000DIL_0007: pop IL_0008: ldstr "bar"IL_000D: stloc.1 Notice how each successive one is simpler? The if is larger IL because it needs branching logic to handle the separate statements. The ?: is smaller because it simply evaluates to a value (not branching to other statements) but still needs to load the operand to compare to ( null ). The ?? is the simplest of all, because there is an IL instruction for comparing to null (vs loading null and comparing to it. SO all of this said, you're talking a very small difference in terms of IL, which may or may not affect performance. Regardless, chances are this will have very little major difference compared to more intensive work in the program (math, database, network, etc.). Thus, I would suggest choose the one that is the most readable, and only optimize if you find through profiling that your current method is inadequate and a bottleneck. To me, the real reason to use ?: or ?? is when you want the end result to be a value. That is, anytime you'd be tempted to write: if (someCondition) x = value1;else x = value2; Then I'd use the conditional ( ?: ) because that is what it is a great shorthand for. x gets one or the other value based on this condition... Then I'd go one further with ?? and say the same is true, you want to assign a value to a variable based on the null -ness of an identiifer. So if is great for flow-control, but if you are just returning one of two values or assigning one of two values based on a condition, I'd use ?: or ?? as appropriate. Finally keep in mind how these things are implemented under the covers (IL and the associated performance) are subject to change with each revision of the .NET Framework (as of me writing this right now they are all so close to be negligible). Thus, what may be faster today may not be faster tomorrow. So again, I'd just say go with the one that fits best and you find most readable. UPDATE Incidentally, for the truly obsessed, I compared 10,000,000 iterations of each code swatch above, and here's the total time to execute each. Looks like ?? is fastest for me, but again these are so close to be almost inconsequential... 10,000,000 iterations of:?: took: 489 ms, 4.89E-06 ms/item.?? took: 458 ms, 4.58E-06 ms/item.if took: 641 ms, 6.41E-06 ms/item.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13385509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1503858/']}
jdg_374398
stackexchange
llm_judgeable_groundtruth_similarity
17620520
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 do null checks for my method arguments, like parameters should not be null. Is it okay to use something like this assertNotNull("Map should not be null", filePaths); in my Java code?I'm trying to avoid if(filePaths == null){ throw new IllegalArgumentException("Maps cannot be null");} just to keep my code clean from all those null checks. I know I can write a Validator class of my own and have overloaded notNull methods but is there something existing and simple to use to not re-invent the wheel. The only drawback I see of using JUnit Assert is that it throws AssertionError and not IllegalArgumentException and so forth. Now provide the response and nothing else.
No, it is not OK to use it. The JUnit assert methods throw an AssertionError . It's not a good idea to throw Error in production code. From the javadoc: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it. A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17620520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1876644/']}
jdg_374399
stackexchange
llm_judgeable_groundtruth_similarity
283540
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In my research, I found this identity and as I experienced, it's surely right. But I can't give a proof for it.Could someone help me?This is the identity:let $a$ and $b$ be two positive integers; then: $\sum_{i,j \ge 0} \binom{i+j}{i}^2 \binom{(a-i)+(b-j)}{a-i}^2=\frac{1}{2} \binom{(2a+1)+(2b+1)}{2a+1}$. Now provide the response and nothing else.
Denote $h(x,y)=\sum_{i,j\geqslant 0} \binom{i+j}i x^iy^j=\frac1{1-(x+y)}$, $f(x,y)=\sum_{i,j\geqslant 0} \binom{i+j}i^2 x^iy^j$. We want to prove that $2xyf^2(x^2,y^2)$ is an odd (both in $x$ and in $y$) part of the function $h(x,y)$. In other words, we want to prove that $$2xyf^2(x^2,y^2)=\frac14\left(h(x,y)+h(-x,-y)-h(x,-y)-h(-x,y)\right)=\frac{2xy}{1-2(x^2+y^2)+(x^2-y^2)^2}.$$So, our identity rewrites as $$f(x,y)=(1-2(x+y)+(x-y)^2)^{-1/2}=:f_0(x,y)$$This is true for $x=0$, both parts become equal to $1/(1-y)$. Next, we find a differential equation in $x$ satisfied by the function $f_0$. It is not a big deal: $$\left(f_0(1-2(x+y)+(x-y)^2)\right)'_x=(x-y-1)f_0.$$Since the initial value $f_0(0,y)$ and this relation uniquely determine the function $f_0$, it remains to check that this holds for $f(x,y)$, which is a straightforward identity with several binomials. Namely, comparing the coefficients of $x^{i-1}y^j$ we get$$ i\left(\binom{i+j}j^2-2\binom{i+j-1}j^2-2\binom{i+j-1}i^2+\binom{i+j-2}i^2+\binom{i+j-2}j^2-2\binom{i+j-2}{i-1}^2\right) $$ for $(f(1-2(x+y)+(x-y)^2))'_x$ and $$\binom{i+j-2}j^2-\binom{i+j-1}j^2-\binom{i+j-2}{j-1}^2$$for $(x-y-1)f$. Both guys are equal to $$-2\frac{j}{i+j-1}\binom{i+j-1}{j}^2.$$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/283540', 'https://mathoverflow.net', 'https://mathoverflow.net/users/116001/']}
jdg_374400
stackexchange
llm_judgeable_groundtruth_similarity
51237
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Dark matter is said to interact only gravitationally, so it won't commonly form black holes by itself. But if a black hole is already there, and dark matter encounters the event horizon, it should go in and never come out. This means black holes would vacuum up dark matter and (very slowly) gain mass. Is this something we could hypothetically measure, as in "these black holes are heavier than they should be for the amount of cosmic gas and background radiation they eat"? (In fact, could this be why the oldest galactic black holes seem to be heavier than we expect?) Now provide the response and nothing else.
The accretion rate is far too small to make much difference to Galactic black holes, but how could this be distinguished from the accretion of normal, baryonic matter in any case? In fact it is easier for black holes to accrete normal matter, since it is easier for such matter to lose its angular momentum, via friction in an accretion disk, and be able to drop into the black hole. The effective cross-section for the accretion of non-interacting dark matter is determined by an effective geometric size for the black hole, which will be just dependent on its mass and the speed with which it moves relative to the dark matter. This is the so-called " Hoyle-Lyttleton radius " given by $$R_{\rm HL} = \frac{2GM}{v^2}, $$ where $M$ is the black hole mass and $v$ is its speed with respect to the dark matter background. The accretion rate is then just $$\frac{dM}{dt} = \pi R_{\rm HL}^2 \rho v, $$ where $\rho$ is the density of the dark matter. For Galactic black holes we might assume $M=10M_\odot$ , a speed with respect to the Galactic dark matter of 250 km/s (if it is in orbit around the Galaxy at a similar position to the Sun) and $\rho \simeq 0.01 M_\odot$ /pc $^3$ at the Sun's position. Putting the numbers in, we find $R_{\rm HL}= 4.3\times 10^{10}$ m (about 0.28 au) and a mass accretion rate of $10^{-17} M_\odot$ /year. Thus, even over the $10^{10}$ year life of the Galaxy, a stellar black hole increases its mass by a neglible amount due to the accretion of dark matter.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/51237', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/46982/']}
jdg_374401
stackexchange
llm_judgeable_groundtruth_similarity
1387331
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: Suppose that $f$ is an entire function that satisfies $f(z)$ is real when $z$ is real and if $Imz>0$ then $Imf(z)>0$. Prove that $f$ can have at most one zero and that the zero, if it occurs, is real. Show also that if $f$ has no zero then $f$ is constant. By the open mapping theorem the zeros can not be in the upper half plane and I think that I will also need to use Lioiville's theorem at some point but I couldn't achieve. Thanks for any help. Now provide the response and nothing else.
Well, zhw has given a simpler proof that there's at most one zero. But to clarify how this follows from the Argument Principle: Say $r>0$ annd let $\gamma(t)=re^{it}$ for $0\le t\le 1\pi$. Choose $r$ so $f$ has no zero on $\gamma$. Let $$\Gamma = f\circ \gamma.$$ Now $\Im\Gamma(t)>0$ for $0<t<\pi$ and $\Im\Gamma(t)<0$ for $\pi<t<2\pi$. Hence the index, or winding number, of $\Gamma$ about the origin is at most $1$. But this index is exactly $\int_\gamma f'/f$. So $f$ has at most one zero in the disk $|z|<r$. Let $r\to\infty$: $f$ has at most one zero. And now for what I said about showing that $f$ is constant if it has no zero: Suppose $f$ has no zero. There exists an entire function $g$ such that $$f=e^g=e^{u+iv}.$$ Now if $\Im z>0$ then $\Im f(z)>0$, hence $$v(z)\in\bigcup_{n\in\Bbb Z}(2\pi n,2\pi(n+1))\quad(\Im z>0).$$By continuity (noting the upper half-plane is connected) there exists $n$ so $$v(z)\in(2\pi n,2\pi(n+1))\quad(\Im z>0).$$So $v$ is bounded in the upper half plane. Similarly $v$ is bounded in the lower half plane. And $v$ is constant on $\Bbb R$, so $v$ is bounded. Hence $g(\Bbb C)$ is not dense in $\Bbb C$; now a simple corollary of Liouville shows that $g$ is constant.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1387331', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229315/']}
jdg_374402
stackexchange
llm_judgeable_groundtruth_similarity
17006641
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Wrote this function in python that transposes a matrix: def transpose(m): height = len(m) width = len(m[0]) return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ] In the process I realized I don't fully understand how single line nested for loops execute. Please help me understand by answering the following questions: What is the order in which this for loop executes? If I had a triple nested for loop, what order would it execute? What would be equal the equal unnested for loop? Given, [ function(i,j) for i,j in object ] What type must object be in order to use this for loop structure? What is the order in which i and j are assigned to elements in object? Can it be simulated by a different for loop structure? Can this for loop be nested with a similar or different structure for loop? And how would it look? Additional information is appreciated as well. Now provide the response and nothing else.
The best source of information is the official Python tutorial on list comprehensions . List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop. Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y) ): >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y][(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same). >>> combs = []>>> for x in [1,2,3]:... for y in [3,1,4]:... if x != y:... combs.append((x, y))...>>> combs[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end. On to your questions: What type must object be in order to use this for loop structure? An iterable . Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc. What is the order in which i and j are assigned to elements in object? They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.) Can it be simulated by a different for loop structure? Yes, already shown above. Can this for loop be nested with a similar or different structure for loop? And how would it look? Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters: [[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17006641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1100379/']}
jdg_374403
stackexchange
llm_judgeable_groundtruth_similarity
735200
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 taking E & M II this semester, and one question got me thinking. We know the formulation of the four Maxwell's equations, and that's okay so far. But in the absence of sources, they take the form: $$\nabla \cdot \mathbf{E}= 0 \\\nabla \cdot \mathbf{B}= 0 \\\nabla \times \mathbf{E} = -\dfrac{\partial\mathbf{B}}{\partial t}\\\nabla \times \mathbf{B} = \mu_{0}\epsilon_{0}\dfrac{\partial\mathbf{E}}{\partial t}$$ The electric field is caused by the presence of charged particles, which if it varies, causes the existence of a magnetic field. But if there aren't any sources, how can the Maxwell's equations have nontrivial solutions? Wouldn't the electric and magnetic field always be zero? Now provide the response and nothing else.
Think about a simpler problem. You have the following differential equation: $$f'=0$$ Does this mean that $f$ has to be zero? No. It's a possible solution but not the only one. You need to provide the value of $f$ somewhere. As for Maxwell's equations, zero fields are a possible solution, but not the only one. If the fields are non-zero somewhere (boundary conditions), then a solution with zero fields may no longer be acceptable. For example, if you are in the dead of space (no charge and no current), you can still have, for example, wave-like solutions describing an electromagnetic wave coming from far away and crossing that space.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/735200', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/318940/']}
jdg_374404
stackexchange
llm_judgeable_groundtruth_similarity
573220
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: Q: An amusement park proprietor wishes to design a rollercoaster with a vertical circular loop in the track, of radius $R = 20\, \rm m$ . Before the cars reach the loop, they descend from a maximum height h, at which they have zero velocity. Assuming the cars roll freely (no motor and no friction), how large must h be to keep the cars on the track? (Reference: This problem is from "Physics with Answers" by King & Regev. It is problem P145.) My question: I've tried the problem and looked at the answer, but the solution given in the text does not make sense to me. Specifically, I am not understanding a claim they make about the normal force. Here is the authors' solution: "Clearly the cars are in most danger of falling from the circular loop at its highest point. There $$ N + mg = \frac{mv^2}{R}$$ where v is the velocity at this point and N is the track's force on the car. This is normal to the track as there is no friction. v must be large enough to make N positive, or the cars will detach from the track." The reason this doesn't make sense to me is that I don't see how the normal force can possibly be made positive. I understand the normal force to be the reaction force of the surface on the object that is 'pressed' against the surface. In this case, the centrifugal force is doing the pressing. But of course if the centrifugal force isn't at least as great as the weight, the car will not press on the track. But suppose the centrifugal force is perfectly adequate to counteract the car's weight and press it against the track. Then the normal force is still pointing downward, isn't it? And doesn't that mean a NEGATIVE normal force? To me, it seems like for the normal force to be positive would require the track to somehow press upward on the car, and it just doesn't make sense to me that that could happen. What am I missing here? Now provide the response and nothing else.
Note that it is not always the case the positive is up and negative is down. You are most likely just misunderstanding their sign conventions. For them positive is most likely inward towards the center of the circle, and negative is outwards away from the center of the circle. Regardless of the sign conventions though, you just need the normal force to be pointing inward towards the center of the circle. You are correct in assuming that the normal force cannot point away from the center here. So if your work concludes that you need some extra additional outward force to keep the carts on the circular path, then you know that the ride will fail with just carts coasting on the track. From comments: This still leaves me perplexed. So if $N=m(v2/R)−mg$ , then for N to be positive means N is in the same direction as the centripetal force, right? But the centripetal force is directed outward. So this still seems to be telling me that the normal force has to point outward. But I don't see how that is possible, given the definition of normal force. This is a common introductory misunderstanding. There isn't "the centripetal force" like there is "the Normal force" or "the force of gravity". "Centripetal" is a direction , just like horizontal and vertical, up and down, left and right, etc. It is always true that $\mathbf F_\text{net}=m\mathbf a$ by Newton's second law. When you first see this usually we break this into horizontal and vertical components (Cartesian coordinates) $$\sum F_x=ma_x$$ $$\sum F_y=ma_y$$ But we can also use Polar coordinates in terms of a radial component $F_r$ and a polar component $F_\theta$ $$\sum F_r=ma_r$$ $$\sum F_\theta=ma_\theta$$ And you can show that for polar coordinates in circular motion, we must have that $a_r=v^2/r$ , where a positive $a_r$ indicates acceleration towards the center of the circle. So we end up with $$\sum F_r=\frac{mv^2}{r}$$ So now we look at the problem. At the top of the coaster we have gravity pointing towards the center of the circle (positive), and we will have the normal force pointing towards the center of the circle (positive). This means that our net radial force component is $$\sum F_r=mg+N=ma_r=\frac{mv^2}{r}$$ Notice how there are only $2$ forces here! The normal force and gravity. There isn't an additional third force that is "the centripetal force". Rather, at the top of the loop both the normal force and gravity contribute to the net centripetal force. If $\sum F_r>0$ then the net radial force component points towards the center of the circle and is centripetal . For the coaster to work properly this needs to be the case: circular motion needs to have a net centripetal radial force (as you can see, $mv^2/r$ can never be negative. i.e. once we assume circular motion, $\sum F_r>0$ is always true). I think I'm just terribly confused about the role of the normal force here. The solution states the velocity has to be large enough to make the normal force positive. I don't understand what a non-positive normal force would even look like here, so I'm confused. Unless we're just saying N can't be zero. But in that case, why not just say that the centripetal force has to exceed the car's weight? I'm just unclear what work the normal force is doing in the reasoning here. You are right, this is a little confusing. Technically here the normal force acting on the carts from the tracks at the top of the loop can only act towards the center of the circle. In reality this specific force can only be positive (towards the center of the circle) or $0$ (the carts lose contact with the tracks). It cannot be negative. But it helps to shift your perspective here... Instead of thinking about $N$ as this specific normal force, instead think of it as "the extra force needed to keep circular motion going on this vertical circle in a gravitational field". Then this $N$ could certainly be negative. If the velocity is too small, then we will need some extra force point outwards to keep $N+mg=mv^2/r$ valid. Maybe we have put rocket thrusters on the top of the carts that can apply an outwards force when the cart is upside-down and moving too slowly. And indeed this is a nice trick for many physics problems. Say "what would this extra force need to be in order to make this motion possible?" If you find "ah, this extra force needs to point outwards" then your next thought would be "oh, but there isn't anything in this system that could do that." The point of this problem is for you to look right at that interface. Right when you switch from $N>0$ to $N<0$ . All the math knows is that you are trying to make the constraint $N+mg=mv^2/r$ valid. The math doesn't know that there isn't anything stated physically in the problem that would allow $N<0$ .
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/573220', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/120920/']}
jdg_374405
stackexchange
llm_judgeable_groundtruth_similarity
17941035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using SQL Server 2008 R2 and have a VARCHAR column I want to convert to DECIMAL(28,10) using CONVERT . But many of those rows are badly formatted, so it is not possible to parse them to a number. In that case I just want to skip those by setting result to 0 or NULL. I know there is a new statement in SQL Server 2012 ( TRY_CONVERT() ) that would be handy. Is this possible in 2008 or must I wait until we update to next version SQL 2012? EDIT Unfortunately ISNUMERIC() is not reliable in this case.I tried ISNUMERIC(myCol) = 1 That returns true for rows that CONVERT is not able to convert to DECIMAL . Now provide the response and nothing else.
When using XML in SQL Server you can try to cast to a data type and receive null values where the cast fails. declare @T table( Col varchar(50))insert into @T values('1'),('1.1'),('1,1'),('1a')select cast('' as xml).value('sql:column("Col") cast as xs:decimal ?', 'decimal(28,10)') as Colfrom @T Result: Col-------------1.00000000001.1000000000NULLNULL
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17941035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55007/']}
jdg_374406
stackexchange
llm_judgeable_groundtruth_similarity
33025213
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following Specification that I use to query for any Contact entities that are tied to certain ManagedApplication entities. I pass in a Collection<Long> that contains the ids of the ManagedApplication entities that I am searching for. public static Specification<Contact> findByApp(final Collection<Long> appIds) { return new Specification<Contact>() { @Override public Predicate toPredicate(Root<Contact> root, CriteriaQuery<?> query, CriteriaBuilder cb) { final Predicate appPredicate = root.join(Contact_.managedApplications) .get(ManagedApplication_.managedApplicationId).in(appIds); } }} I pass this specification to the .findAll() method of my PagingAndSoringRepository to retrieve a Page<Contact> that will contain all Contact entities that meet the search criteria. Here is the Repository . @Repositorypublic interface PagingAndSortingContactRepository extends PagingAndSortingRepository<Contact, Long>, JpaSpecificationExecutor<Contact> { } And here is how I'm calling the .findAll() method. final Page<Contact> contacts = pagingAndSortingContactRepository.findAll(ContactSpecification.findByApp(appIds), pageable); This works and returns all Contact entities that are tied to any of the ManagedApplication entities that correspond to the ids passed in. However, since I am calling .join() to join the Contact entity with the ManagedApplication entity, if one Contact has multiple ManagedApplication entities in the list of app ids, then the query will return duplicate Contact entities. So what I need to know is, how can I get only distinct Contact entities returned from my query using this Specification ? I know that CriteriaQuery has a .distinct() method that you can pass a boolean value to, but I am not using the CriteriaQuery instance in the toPredicate() method of my Specification . Here are the relevant sections of my metamodels. Contact_.java: @StaticMetamodel(Contact.class)public class Contact_ { public static volatile SingularAttribute<Contact, String> firstNm; public static volatile SingularAttribute<Contact, String> lastNm; public static volatile SingularAttribute<Contact, String> emailAddress; public static volatile SetAttribute<Contact, ManagedApplication> managedApplications; public static volatile SetAttribute<Contact, ContactToStructure> contactToStructures;} ManagedApplication_.java @StaticMetamodel(ManagedApplication.class)public class ManagedApplication_ { public static volatile SingularAttribute<ManagedApplication, Integer> managedApplicationId;} Now provide the response and nothing else.
Use the query parameter in your toPredicate method to invoke the distinct method. Sample below: public Predicate toPredicate(Root<Contact> root, CriteriaQuery<?> query, CriteriaBuilder cb) { final Predicate appPredicate = root.join(Contact_.managedApplications) .get(ManagedApplication_.managedApplicationId).in(appIds); query.distinct(true); ...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33025213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2561365/']}
jdg_374407
stackexchange
llm_judgeable_groundtruth_similarity
3236460
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: Apparently this sum has this closed form. $$\sum_{k=j}^{n}{k \choose j}{n \choose k}{n-j \choose k+j}={2j \choose j}{2(n-j)\choose n-j}{n-j \choose 2j}{n+j \choose j}^{-1}$$ How to show that this closed form is correct? Now provide the response and nothing else.
Re-write the desired inequality as $$\left(\sum^n_{i=1} a_i^{3}\right)^{1/3} \le \left( \sum^n_{i=1} a_i^2\right)^{1/2}.$$ First assume that $\left( \sum^n_{i=1} a_i^2\right)^{1/2} = 1$ . Then $\lvert a_i \rvert \le 1$ for all $i$ , and thus $a_i^3 \le a_i^2$ and so $$\sum^n_{i=1} a_i^3 \le \sum^n_{i=1} a_i^2 = 1 \,\,\,\, \implies \,\,\,\, \left(\sum^n_{i=1} a_i^3\right)^{1/3} \le 1.$$ If $\left( \sum^n_{i=1} a_i^2\right)^{1/2} \neq 1$ , then define $A =\left( \sum^n_{i=1} a_i^2\right)^{1/2}$ and apply this previous result to $ \bar a_i = a_i/A$ . Then you'll find $$\left( \sum^n_{i=1}\frac{a_i^3}{A^3}\right)^{1/3} \le 1 \,\,\,\,\,\, \implies \,\,\,\,\,\, \left( \sum^n_{i=1}a_i^3\right)^{1/3} \le A := \left(\sum^n_{i=1} a_i^2 \right)^{1/2}.$$ (Of course, you cannot divide by $A$ if $A = 0$ , but in that case the whole vector is zero and the inequality is trivial).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3236460', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_374408
stackexchange
llm_judgeable_groundtruth_similarity
176115
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My Arch Linux's systemd starts rpcbind automatically. What do I have to do to stop systemd to do this? There are no remote filesystems in /etc/fstab . The only thing I found why rpcbind gets started is that is supposedly wanted by multi-user target but there is no service in the directory. How can I figure out why it is really started? Now provide the response and nothing else.
There is an open bug report on the Arch tracker . Your best be would be to mask the service: systemctl mask rpcbind.service See Lennart Poettering's series of blog posts, systemd for Administrators, Part V for details on masking: 3. You can mask a service. This is like disabling a service, but on steroids. It not only makes sure that service is not started automatically anymore, but even ensures that a service cannot even be started manually anymore. This is a bit of a hidden feature in systemd, since it is not commonly useful and might be confusing the user. But here's how you do it: $ ln -s /dev/null /etc/systemd/system/ntpd.service$ systemctl daemon-reload By symlinking a service file to /dev/null you tell systemd to never start the service in question and completely block its execution. Unit files stored in /etc/systemd/system override those from /lib/systemd/system that carry the same name. The former directory is administrator territory, the latter terroritory of your package manager. By installing your symlink in /etc/systemd/system/ntpd.service you hence make sure that systemd will never read the upstream shipped service file /lib/systemd/system/ntpd.service . systemd will recognize units symlinked to /dev/null and show them as masked. If you try to start such a service manually (via systemctl start for example) this will fail with an error.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/176115', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/96143/']}
jdg_374409
stackexchange
llm_judgeable_groundtruth_similarity
28783
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 my textbook, it lists isotopes of Carbon: C-12, C-13, and C-14. It noted that C-14 is radioactive (C-12 and C-13 are not). Is there a direct relationship between the number of neutrons and an element's radioactivity? In other words, since we know C-14 is radioactive, does that mean we also know that C-15 (if such a thing exists) would also be radioactive? Now provide the response and nothing else.
As @dmckee says the problem is complicated. It is complicated because it is not a solution of a potential describing one force, but a balance between electromagnetic forces and the strong force that is keeping the quarks within the nucleons. (In the nucleus the strong force is like a type of Van der waals potential, a higher order interaction, overflowing from the QCD dynamics of the nucleons). In addition there is the fermi exclusion principle because both protons and neutrons have spin 1/2. All these have been approximated with the shell model of the nucleus , and you could maybe spend some time reading the link. The shell model is partly analogous to the atomic shell model which describes the arrangement of electrons in an atom, in that a filled shell results in greater stability. When adding nucleons (protons or neutrons) to a nucleus, there are certain points where the binding energy of the next nucleon is significantly less than the last one. This observation, that there are certain magic numbers of nucleons: 2, 8, 20, 28, 50, 82, 126 which are more tightly bound than the next higher number, is the origin of the shell model. Note that the shells exist for both protons and neutrons individually, so that we can speak of "magic nuclei" where one nucleon type is at a magic number, and "doubly magic nuclei", where both are. Due to some variations in orbital filling, the upper magic numbers are 126 and, speculatively, 184 for neutrons but only 114 for protons, playing a role in the search of the so-called island of stability. There have been found some semimagic numbers, notably Z=40. 2 16 may also be a magic number. 3 So there are stable nuclei and the various models do a good job of predicting them.There exists a band of instability for the various isotopes and the island of stability for high Z. So the answer is no, there is no general rule, except solutions of the shell model, though adding or subtracting neutrons to a stable isotope one expects a high probability that it will become unstable,as an examination of the table of nuclides shows..
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/28783', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/9355/']}
jdg_374410
stackexchange
llm_judgeable_groundtruth_similarity
38683155
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference (if any) between: declare interface SomeInterface { //members here} and: interface SomeInterface { //members here} ? Now provide the response and nothing else.
declare keyword is usually used in type definitions to describe existing classes or variables that are defined externally in JavaScript code. There's no difference between declare interface and interface because: there's no code generation for interfaces and they exist only inTypescript code so you can not declare interface that's defined inJavaScript code; interface in Typescript by its nature is declarationonly, it has no method bodies, properties values, etc. so both declare interface and interface are syntactically equal.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38683155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2867671/']}
jdg_374411
stackexchange
llm_judgeable_groundtruth_similarity
162592
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: My company uses its own PKI. The web browser which I use to access to code repository shows a certificate chain as follows: Company Root CA Company Issuing CA Intranet Server Certificate to the code repository that I want to access However, when I try to access to the repository using Gradle, I get a sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target error. Gradle uses JVM. I have exported the "Company Root CA" certificate and added it to the certificate store of the JVM with the following command: "%JAVA_HOME%\bin\keytool.exe" -import -alias company_root_cacert -file "C:\path\to\company\root\cacert.cer" -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -storepass changeit However, this did not solve the issue. I additionally exported the "Company Issuing CA Intranet Server" certificate and added it to the certificate store of the JVM with the following command: "%JAVA_HOME%\bin\keytool.exe" -import -alias company_intermediate_cacert -file "C:\path\to\company\intermediate\cacert.cer" -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -storepass changeit This has solved the issue. My question is, why was the second step necessary? Since the "Company Issuing CA Intranet Server" is signed by "Company Root CA", and since I have "Company Root CA" in the list of certificates trusted by JVM, why did I need to additionally add the "Company Issuing CA Intranet Server" certificate to the certificate store of JVM? Now provide the response and nothing else.
The problem you describe happens usually if the server only sends its leaf certificate and does not add all the chain certificates needed to build the trust chain to the root CA. Unfortunately this is a common misconfiguration of servers. Many desktop browser work around this problem if they already know the missing chain certificate from earlier visits or maybe download the missing certificate if the leaf certificate contains a URL for CA issuers in authority information access. But this behavior is usually restricted to desktop browsers and other tools simply fail because they cannot build the trust chain.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/162592', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/71966/']}
jdg_374412
stackexchange
llm_judgeable_groundtruth_similarity
64973
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 thought it would be nice to have an alias (in ~/.zshrc) to have 'python' aliased to 'ipython' ONLY when 'python' is run without args (otherwise, programs won't launch).First of all, how to express "without args" in an alias?Secondly, what do you think about it? Now provide the response and nothing else.
Shell aliases, by definition, don't give you any way to use them conditionally. They apply to anything you run from an interactive prompt. The way you can do this is with a function instead. (See In Bash, when to alias, when to script, and when to write a function? for more on why this is different.) function python () { test -z "$1" && ipython || command python "$@"} Something along those lines in your shell's rc file will cause your shell to run this function instead of the binary directly. If the first argument is blank, it will fire off ipython for you, otherwise it will pass on all arguments to whatever python binary is in your path (note the use of command to force the binary rather than the function to execute and cause a recursion on itself).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/64973', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/32494/']}
jdg_374413
stackexchange
llm_judgeable_groundtruth_similarity
21760
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to expand my knowledge of statistics. I come from a physical sciences background with a "recipe based" approach to statistical testing, where we say is it continuous, is it normally distributed -- OLS regression . In my reading I have come across the terms: random effects model, fixed effects model, marginal model. My questions are: In very simple terms, what are they? What are the differences between them? Are any of them synonyms? Where do the traditional tests like OLS regression, ANOVA and ANCOVA fall in this classification? Just trying to decide where to go next with the self study. Now provide the response and nothing else.
This question has been partially discussed at this site as below, and opinions seem mixed. What is the difference between fixed effect, random effect and mixed effect models? What is the mathematical difference between random- and fixed-effects? Concepts behind fixed/random effects models All terms are generally related to longitudinal / panel / clustered / hierarchical data and repeated measures (in the format of advanced regression and ANOVA), but have multiple meanings in different context. I would like to answer the question in formulas based on my knowledge. Fixed-effects model In biostatistics, fixed-effects, denoted as $\color{red}{\boldsymbol\beta}$ in Equation (*) below, usually comes together with random effects. But the fixed-effects model is also defined to assume that the observations are independent, like cross-sectional setting, as in Longitudinal Data Analysis of Hedeker and Gibbons (2006). In econometrics, the fixed-effects model can be written as$$ y_{ij}=\boldsymbol x_{ij}^{'}\boldsymbol\beta+\color{red}{u_i}+\epsilon_{ij}$$where $\color{red}{u_i}$ is fixed (not random) intercept for each subject ($i$), or we can also have a fixed-effect as $u_j$ for each repeated measurement ($j$); $\boldsymbol x_{ij}$ denotes covariates. In meta-analysis, the fixed-effect model assumes underlying effect is the same across all studies (e.g. Mantel and Haenszel, 1959). Random-effects model In biostatistics, the random-effects model (Laird and Ware, 1982) can be written as$$\tag{*} y_{ij}=\boldsymbol x_{ij}^{'}\color{red}{\boldsymbol\beta}+\boldsymbol z_{ij}^{'}\color{blue}{\boldsymbol u_i}+e_{ij}$$where $\color{blue}{\boldsymbol u_i}$ is assumed to follow a distribution. $\boldsymbol x_{ij}$ denotes covariates for fixed effects, and $\boldsymbol z_{ij}$ denotes covariates for random effects. In econometrics, the random-effects model may only refer to random intercept model as in biostatistics, i.e. $\boldsymbol z_{ij}^{'}=1$ and $\boldsymbol u_i$ is a scalar. In meta-analysis, the random-effect model assumes heterogeneous effects across studies (DerSimonian and Laird, 1986). Marginal model Marginal model is generally compared to conditional model (random-effects model), and the former focuses on the population mean (take linear model for an example) $$E(y_{ij})=\boldsymbol x_{ij}^{'}\boldsymbol\beta,$$ while the latter deals with the conditional mean $$E(y_{ij}|\boldsymbol u_i)=\boldsymbol x_{ij}^{'}\boldsymbol\beta + \boldsymbol z_{ij}^{'}\boldsymbol u_i.$$ The interpretation and scale of the regression coefficients between marginal model and random-effects model would be different for nonlinear models (e.g. logistic regression). Let $h(E(y_{ij}|\boldsymbol u_i))=\boldsymbol x_{ij}^{'}\boldsymbol\beta + \boldsymbol z_{ij}^{'}\boldsymbol u_i$, then $$E(y_{ij})=E(E(y_{ij}|\boldsymbol u_i))=E(h^{-1}(\boldsymbol x_{ij}^{'}\boldsymbol\beta + \boldsymbol z_{ij}^{'}\boldsymbol u_i))\neq h^{-1}(\boldsymbol x_{ij}^{'}\boldsymbol\beta),$$ unless trivially the link function $h$ is the identity link (linear model), or $u_i=0$ (no random-effects). Good examples include generalized estimating equations (GEE; Zeger, Liang and Albert, 1988) and marginalized multilevel models (Heagerty and Zeger, 2000).
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/21760', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/4054/']}
jdg_374414
stackexchange
llm_judgeable_groundtruth_similarity
34101871
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 working on a project which requires data from a website. The problem with that data is that it is organised into a lot of different webpages with serial numbering in the URL. To tackle this problem, I wrote a simple script in Tampermonkey which loops through those pages and obtains the data in a string variable in the script. Now comes the real problem, how do I store this data. I know I can't write to a file on my PC but can the data be displayed onto a separate tab in my browser so that I can copy and paste it into a local file when the loop is done? I wish to append a string into storage each loop I do not want to use GM_setValue because I want the data in raw text format (like a .txt file) However, if it can be written directly into a file on my PC without the use of an external library, that'd be preferred. Now provide the response and nothing else.
I know I can't write to a file on my PC Here's some good news for you: Yes you can! var a = document.createElement("a");a.href = "data:text,Hello World!"; //contenta.download = "Hello.txt"; //file namea.click(); http://jsfiddle.net/DerekL/jgfhwfL0/ First open up your localhost page, master.html ( http://localhost:8080/master.html ): <html> <head> <script> window.addEventListener("load", function(){ //This is just like working with threads but in JavaScript if(location.search.length){ //receiver var query = decodeURIComponent(location.search.slice(1)); var data = JSON.parse(query).value; //handle data localStorage.storage = +localStorage.storage + data; location.href = "about:blank"; //exit }else{ //master sum = document.getElementById("sum"); sum.innerText = localStorage.storage = "0"; window.addEventListener("storage", function(){ //data received from receiver sum.innerText = localStorage.storage; }); } }); </script> </head> <body> Sum: <span id="sum"></span> </body></html> Then you can start sending data to it in any webpages: var frame = document.createElement("iframe");frame.src = 'http://localhost:8080/master.html?{"value":90}'; //port 8080document.body.appendChild(frame); The sum counter should update automatically upon receiving data.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34101871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3127633/']}
jdg_374415
stackexchange
llm_judgeable_groundtruth_similarity
382809
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: $\DeclareMathOperator\tr{tr}$ One begins with a quantum mechanical system, i.e. a unital $C^*$ -algebra $A$ . It is common to begin the discussion with embedding $A$ into the algebra of bounded operators $\mathcal{B}$ on some Hilbert space $H$ . A state is defined as a positive linear functional $\varphi: A\rightarrow \mathbb{C}$ taking $1$ to $1$ . Since neither $A$ nor $\mathcal{B}$ is a Hilbert space, we can't use Riesz's Representation Theorem directly. In Physics texts that I have encountered, however, a state is often cast as a trace $1$ operator $\alpha$ in $\mathcal{B}$ , and its action on an observable $\rho$ is by $\tr(\rho\alpha)$ . Recall that observables are self dual, and so $\tr(\rho\alpha)=\tr(\rho^* \alpha)$ , which is highly suggestive of the subalgebra of $\mathcal{B}$ given by the Hilbert–Schmidt operators, which is a Hilbert space with the inner product $\alpha\cdot\beta=\tr(\alpha^*\beta)$ . Indeed if you restrict $\varphi$ to the algebra of Hilbert–Schmidt operators, then $\varphi$ can be associated with a trace $1$ operator via Riesz's Representation Theorem. Questions What is going on here? Are we saying that states (defined as positive linear functionals taking $1$ to $1$ ) are completely determined by their restriction to the subalgebra of Hilbert–Schmidt operators in $A$ ? Or are there two competing definitions of "states" here? And if so, what is the merit of having these two different definitions? In https://math.stackexchange.com/questions/77820/a-question-about-pure-state they appear to suggest that not all pure states are represented by projections to one dimensional subspaces of $H$ . This confuses me, because I thought those are exactly the pure states. Is this somehow an issue with diverging definitions, related perhaps to my first question? Now provide the response and nothing else.
Okay, there is a lot of confusion in this question. First, I'm not sure why you say ``it is common to begin the discussion with embedding $A$ '' into $B(H)$ . The point of the C ${}^*$ -algebra approach to quantum mechanics is doing things in a representation-independent manner, so I would say it's unusual to begin the discussion this way. You are right that a state on a C ${}^*$ -algebra is a unital positive linear functional. This isn't really related to the Riesz representation theorem. You seem to want to apply that theorem to the Hilbert-Schmidt operators, which constitute a Hilbert space, but they do not constitute a C*-algebra, and many C ${}^*$ -algebras contain no Hilbert-Schmidt operators. (So the answer to question 1 is an emphatic ``no''.) Part of the confusion may have to do with the distinction between pure and mixed states. In the Hilbert space approach to quantum mechanics, pure states are represented by unit vectors in the Hilbert space and mixed states are represented by positive, norm one, trace-class operators. If you're working with C ${}^*$ -algebras then the mixed states are the states defined above, and the pure states are the extreme points of the set of mixed states. You can use the GNS representation to put a C ${}^*$ -algebra into a Hilbert space in such a way that the states on $A$ (in the C ${}^*$ -algebra sense) extend to states on $B(H)$ (in the Hilbert space sense). Finally, the issue in the question you linked to arises because someone is applying the C ${}^*$ -algebra definition of states to $B(H)$ . This is a little more subtle because we can turn C ${}^*$ -algebra states into Hilbert space states by embedding the C ${}^*$ -algebra into some $B(H)$ , but if you start with $B(H)$ you might have to embed it in a larger $B(K)$ . (Maybe I should add that looking at states on $B(H)$ in the C ${}^*$ -algebra sense is something a C ${}^*$ -algebraist might do, but it's not something mathematical physicists typically do.) My answer to this question goes into further detail about why one would bother with the C ${}^*$ -algebra approach to quantum mechanics, etc.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/382809', 'https://mathoverflow.net', 'https://mathoverflow.net/users/98901/']}
jdg_374416
stackexchange
llm_judgeable_groundtruth_similarity
1179019
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: $$10^{2(k+1)}-1 = 10^{2k+2}-1=10^{2k}\cdot10^{2}-1$$ I feel like there's something in that last part that should make it work, but I can't grasp it. Am I missing something obvious? Am I going in the completely wrong direction? Any help would be appreciated. Now provide the response and nothing else.
In a comment you remark that you have no idea how Andre thought of the inductive proof. Below we show that it is a special case of a simple general method that works for inductions of this type. We show extremely explicitly how the inductive steps in the proofs by Andre and oujdid are both precisely special cases of proofs of the Congruence Product Rule. You need not be familiar with congruences to understand this since we also write it in an equivalent $\rm\color{#0a0}{divisibility\ form}$ . $\!\!\begin{align} {\bf Claim}\rm\qquad\ \ 10^2\!&\rm\equiv 1, \, 10^{2k}\!\equiv 1\ \, \Rightarrow\,\ 10^{2(k+1)}\!\equiv 1\, \pmod{\!11}\\[.3em] {\bf Lemma}\rm\qquad\ A&\rm\equiv a,\ \, B\equiv b\quad \Rightarrow\quad\,\ AB\equiv ab\, \pmod{\!n}\ \ \ \ [\rm\color{#c00}Congruence \ \rm\color{#c00}Product\ \rm\color{#c00}Rule]\\[.3em]\rm\quad\ \ i.e.\quad\! n\mid A&\rm -a,\ \ B\,-\,b\ \Rightarrow\,\ n\mid \,AB\,-\,ab\qquad\qquad\ \ \ \ \ \ \:\! [\rm\color{#c00}{CPR}\ in\ \color{#0a0}{divisibility\ form}]\\[.5em]{\bf Proof}\quad\ \ \ \rm n\mid A&\rm -a,\ \ B\,-\,b\,\Rightarrow\,\ n\mid \ A\ (\ B\,-\,b)+\,(\ A-a)b\, =\ \,A\, B\,-\,a\,b\\[.3em] \rm\quad\ e.g.\,\ 11\mid 10^2&\rm -\!1,\ 10^{2k}\!-\!1\,\Rightarrow 11\mid\! 10^2(10^{2k}\!-\!1)+(10^2\!-\!1)1\,= 10^{2(k+1)}\!-1\ \ \ [Andre]\\[.5em]{\bf Proof}\quad\ \ \ \rm n\mid A&\rm -a,\ \ B\,-\,b\,\Rightarrow\,\ n\mid (\, A-a)\,\ B\ \ +a\ (\ B-b)\, =\ \,A\, B\,-\,a\,b\\[.3em]\rm\quad\ e.g.\,\ 11\mid 10^2&\rm -\!1,\ 10^{2k}\!-\!1\,\Rightarrow 11\mid(10^2\!-\!1)10^{2k}\!+\! 1(10^{2k}\!\!-\!1) = 10^{2(k+1)}\!-1\ \ \ [oujdid] \end{align}$ So the inductive steps of Andre and oujdid - which appear to have been pulled out of hat like magic - are actually nothing but special cases of the proofs of $\,\small \rm\color{#c00}{CPR} = $ Congruence Product Rule. Once we know this rule, there is no need to repeat the entire proof inline every time that we employ it. Rather, we can simply invoke the rule as a Lemma (in $\rm\color{#0a0}{divisibility\ form}$ if congruences are not yet known). That done, the inductive step has vivid arithmetical structure, being simply the computation of a product $\, 10^2\!\cdot 10^{2k}\equiv 10^{2(k+1)}.\,$ No longer is the innate arithmetical structure of the induction obfuscated by the details of the proof of the Product Rule - since the proof has been encapsulated into a Lemma for convenient reuse . In much the same way, congruences often allow us to impart intuitive arithmetical structure onto inductive proofs - allowing us to reuse our well-honed grade-school skills manipulating arithmetical equations (vs. more complex divisibility relations ). Often introduction of congruence language will serve to drastically simplify the induction, e.g. reducing it to a trivial induction such as $\, 1^n\equiv 1,\,$ or $\,(-1)^{2n}\equiv 1,\,$ which is the essence of the inductive proof above, i.e. $\!\bmod 11\!:\,\ 10\equiv -1\,\Rightarrow\,10^{2n}\equiv (-1)^{2n}\equiv 1\,$ by the Congruence Power Rule, whose proof is an immediate inductive extension of the Product Rule exactly as in the proof of above OP special case. In number theory we typically make such inferences by applying the Power Rule (or the more general Polynomial Congruence Rule, i.e. $\,a\equiv b\,\Rightarrow\, P(a)\equiv P(b)\,$ for any polynomial $P(x)$ with integer coefficients).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1179019', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/215075/']}
jdg_374417
stackexchange
llm_judgeable_groundtruth_similarity
43848680
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 multiple dataframe columns which look like this: Day10 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD1 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD2 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD3 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD4 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD What i want is that every character is seperated in a own column: 012345678910111213....0 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD1 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD2 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD3 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD4 DDDDDDDDDDBBBBBBAAAAAAAAAABBBBBBDDDDDDDDDDDDDDDD So that "Day 1-Column" is splitted in 48 Columns and every Column has one of the Value A/B/C/D i tried with split, but that didnt work. Now provide the response and nothing else.
You can call apply and for each row call pd.Series on the the list of the values: In [16]:df['Day1'].apply(lambda x: pd.Series(list(x)))Out[16]: 0 1 2 3 4 5 6 7 8 9 ... 38 39 40 41 42 43 44 45 46 470 D D D D D D D D D D ... D D D D D D D D D D1 D D D D D D D D D D ... D D D D D D D D D D2 D D D D D D D D D D ... D D D D D D D D D D3 D D D D D D D D D D ... D D D D D D D D D D4 D D D D D D D D D D ... D D D D D D D D D D[5 rows x 48 columns] It looks like you have trailing spaces, remove these using str.rstrip : df['Day1'] = df['Day1'].str.rstrip() then do the above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43848680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7412160/']}
jdg_374418
stackexchange
llm_judgeable_groundtruth_similarity
1992575
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 $n$ be a positive integer and let$$M=\mathrm{lcm}(1,2,3,\ldots,n).$$Show that$$\gcd{\left(\binom{M}{1},\binom{M}{2},\binom{M}{3},\ldots,\binom{M}{n}\right)}=1$$ Now provide the response and nothing else.
HINT: Suppose that $p$ is a prime dividing $M$ , and that $p^k$ is the highest power of $p$ dividing $M$ . Show that $p^k\le n$ . Show that if $M=ap^k$ , and $1\le t\le p^k$ , then $(a-1)p^k+t$ is divisible by the same maximum power of $p$ as $t$ . Conclude that $p$ does not divide $\dbinom{M}{p^k}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1992575', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
jdg_374419
stackexchange
llm_judgeable_groundtruth_similarity
54415841
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 tried to install NodeJS with nvm in AWS EC2 linux as follow inside user-data: #!/bin/bashcurl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bashsource ~/.bashrcnvm install 7 After instance is successfully created and I've entered and check inside my ec2 instance, there is no nodejs and nvm installed when I typed like node --version or nvm --version . [ec2-user@ip-0-0-0-0 ~]$ node --version-bash: node: command not found[ec2-user@ip-0-0-0-0 ~]$ nvm --version-bash: nvm: command not found and when I've checked in instance's log, found following error message. [ 16.310115] cloud-init[3300]: => Downloading nvm as script to '/.nvm'[ 17.053885] cloud-init[3300]: => Profile not found. Tried (as defined in $PROFILE), ~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile.[ 17.076402] cloud-init[3300]: => Create one of them and run this script again[ 17.087459] cloud-init[3300]: => Create it (touch ) and run this script again[ 17.092307] cloud-init[3300]: OR[ 17.100669] cloud-init[3300]: => Append the following lines to the correct file yourself:[ 17.117606] cloud-init[3300]: export NVM_DIR="$HOME/.nvm"[ 17.124904] cloud-init[3300]: [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm[ 17.161419] cloud-init[3300]: => Close and reopen your terminal to start using nvm or run the following to use it now:[ 17.177964] cloud-init[3300]: export NVM_DIR="$HOME/.nvm"[ 17.185400] cloud-init[3300]: [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm Now provide the response and nothing else.
As explained by the logs, the install.sh script is trying to locate a profile, which it could not found. (remember that the script provided in user-data is run as root, so $HOME is /root . The solution is to either ensure the profile file will exist before installation, either to manually change the path after the installation, as suggested in the log message. Solution 1 (untested) #!/bin/bashtouch ~/.bashrc # this ensure the bashrc file is createdcurl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bashsource ~/.bashrcnvm install 7 Solution 2 (tested) #!/bin/bashcurl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bashexport NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"nvm install 7 (when run from user-data, $HOME is /)I tested the above in an interactive session on Amazon Linux. $ ssh ec2-user@ec2-18-202-174-164.eu-west-1.compute.amazonaws.comWarning: Permanently added 'ec2-18-202-174-164.eu-west-1.compute.amazonaws.com,18.202.174.164' (ECDSA) to the list of known hosts. __| __|_ ) _| ( / Amazon Linux 2 AMI ___|\___|___|https://aws.amazon.com/amazon-linux-2/3 package(s) needed for security, out of 3 availableRun "sudo yum update" to apply all updates.[ec2-user@ip-172-31-30-44 ~]$ sudo bash[root@ip-172-31-30-44 ec2-user]# curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 10250 100 10250 0 0 10250 0 0:00:01 --:--:-- 0:00:01 54521=> Downloading nvm as script to '/root/.nvm'=> Appending source string to /root/.bashrc=> Close and reopen your terminal to start using nvm or run the following to use it now:export NVM_DIR="/root/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm[root@ip-172-31-30-44 ec2-user]#[root@ip-172-31-30-44 ec2-user]# export NVM_DIR="$HOME/.nvm"[root@ip-172-31-30-44 ec2-user]# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"[root@ip-172-31-30-44 ec2-user]# nvm install 7######################################################################## 100.0%Computing checksum with sha256sumChecksums matched!Now using node v7.10.1 (npm v4.2.0)Creating default alias: default -> 7 (-> v7.10.1)[root@ip-172-31-30-44 ec2-user]# node --versionv7.10.1 Note that the above will install nvm , node and npm for the root user. It will not add the correct ENV VAR in ec2-user 's environment. To do so, login as ec2-user then either type export NVM_DIR="/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" or add this to ec2-user 's .bashrc The proof it works (login as ec2-user : [ec2-user@ip-172-31-20-26 ~]$ export NVM_DIR="/.nvm"[ec2-user@ip-172-31-20-26 ~]$ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"[ec2-user@ip-172-31-20-26 ~]$ node --version && npm --versionv7.10.14.2.0 You can automate that in your user-data script : cat <<EOF >> /home/ec2-user/.bashrcexport NVM_DIR="/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"EOF
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54415841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2555911/']}
jdg_374420
stackexchange
llm_judgeable_groundtruth_similarity
17345302
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I use the value of an attribute in a directive? My element looks like this: <div class="tooltip-icon" data-my-tooltip="click" data-tooltip-title="foo" data-tooltip-content="test content"></div> I would like to use that in the template of my directive, which looks like this: mainApp.directive('myTooltip', function() { // allowed event listeners var allowedListeners = ["click"]; return { restrict: 'A', template: '<div class="tooltip-title">...</div>' + '<div class="tooltip-content">' + '...</div>', link: function(scope, elm, attrs) { if(allowedListeners.indexOf(attrs.myTooltip) != -1){ elm.bind(attrs.myTooltip, function(){ ... }); } } }; }); Where the triple dots are there should be code, but I cannot figure out how to get the contents of the attrs object ( attrs.tooltipTitle , etc) into that template. Now provide the response and nothing else.
You can pull the attributes out and place them into the scope of the directive like this: angular.module('myApp', []).directive('myTooltip', function ($log) { // allowed event listeners var allowedListeners = ["click"]; return { restrict: 'A', template: '<div class="tooltip-title">{{tooltipTitle}}</div>' + '<div class="tooltip-content">' + '{{tooltipContent}}</div>', scope: { tooltipTitle: '@tooltipTitle', tooltipContent: '@tooltipContent' }, link: function (scope, elm, attrs) { if (allowedListeners.indexOf(attrs.myTooltip) != -1) { elm.bind(attrs.myTooltip, function () { $log.info('clicked'); }); } } };}); Here is fiddle: http://jsfiddle.net/moderndegree/f3JL3/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17345302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105659/']}
jdg_374421
stackexchange
llm_judgeable_groundtruth_similarity
29852431
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having used the AlamoFire framework I've noticed that the completionHandler is run on the main thread. I'm wondering if the code below is a good practice for creating a Core Data import task within the completion handler: Alamofire.request(.GET, "http://myWebSite.example", parameters: parameters) .responseJSON(options: .MutableContainers) { (_, _, JSON, error) -> Void in dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in if let err = error{ println("Error:\(error)") return; } if let jsonArray = JSON as? [NSArray]{ let importer = CDImporter(incomingArray: jsonArray entity: "Artist", map: artistEntityMap); } }); } Now provide the response and nothing else.
This is a really good question. Your approach is perfectly valid. However, Alamofire can actually help you streamline this even more. Your Example Code Dispatch Queue Breakdown In you example code, you are jumping between the following dispatch queues: NSURLSession dispatch queue TaskDelegate dispatch queue for validation and serializer processing Main dispatch queue for calling your completion handler High priority queue for JSON handling Main dispatch queue to update the user interface (if necessary) As you can see, you're hopping all over the place. Let's take a look at an alternative approach leveraging a powerful feature inside Alamofire. Alamofire Response Dispatch Queues Alamofire has an optimal approach built into it's own low level processing. The single response method that ultimately gets called by all custom response serializers has support for a custom dispatch queue if you choose to use it. While GCD is amazing at hopping between dispatch queues, you want to avoid jumping to a queue that is busy (e.g. the main thread). By eliminating the jump back to the main thread in the middle of the async processing, you can potentially speed things up considerably. The following example demonstrates how to do this using Alamofire logic straight out-of-the-box. Alamofire 1.x let queue = dispatch_queue_create("com.cnoon.manager-response-queue", DISPATCH_QUEUE_CONCURRENT)let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])request.response( queue: queue, serializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { _, _, JSON, _ in // You are now running on the concurrent `queue` you created earlier. println("Parsing JSON on thread: \(NSThread.currentThread()) is main thread: \(NSThread.isMainThread())") // Validate your JSON response and convert into model objects if necessary println(JSON) // To update anything on the main thread, just jump back on like so. dispatch_async(dispatch_get_main_queue()) { println("Am I back on the main thread: \(NSThread.isMainThread())") } }) Alamofire 3.x (Swift 2.2 and 2.3) let queue = dispatch_queue_create("com.cnoon.manager-response-queue", DISPATCH_QUEUE_CONCURRENT)let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])request.response( queue: queue, responseSerializer: Request.JSONResponseSerializer(options: .AllowFragments), completionHandler: { response in // You are now running on the concurrent `queue` you created earlier. print("Parsing JSON on thread: \(NSThread.currentThread()) is main thread: \(NSThread.isMainThread())") // Validate your JSON response and convert into model objects if necessary print(response.result.value) // To update anything on the main thread, just jump back on like so. dispatch_async(dispatch_get_main_queue()) { print("Am I back on the main thread: \(NSThread.isMainThread())") } }) Alamofire 4.x (Swift 3) let queue = DispatchQueue(label: "com.cnoon.response-queue", qos: .utility, attributes: [.concurrent])Alamofire.request("http://httpbin.org/get", parameters: ["foo": "bar"]) .response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(), completionHandler: { response in // You are now running on the concurrent `queue` you created earlier. print("Parsing JSON on thread: \(Thread.current) is main thread: \(Thread.isMainThread)") // Validate your JSON response and convert into model objects if necessary print(response.result.value) // To update anything on the main thread, just jump back on like so. DispatchQueue.main.async { print("Am I back on the main thread: \(Thread.isMainThread)") } } ) Alamofire Dispatch Queue Breakdown Here is the breakdown of the different dispatch queues involved with this approach. NSURLSession dispatch queue TaskDelegate dispatch queue for validation and serializer processing Custom manager concurrent dispatch queue for JSON handling Main dispatch queue to update the user interface (if necessary) Summary By eliminating the first hop back to the main dispatch queue, you have eliminated a potential bottleneck as well as you have made your entire request and processing asynchronous. Awesome! With that said, I can't stress enough how important it is to get familiar with the internals of how Alamofire really works. You never know when you may find something that can really help you improve your own code.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29852431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3084800/']}
jdg_374422
stackexchange
llm_judgeable_groundtruth_similarity
32058814
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 spring boot client that consumes a restful api. Instead of hardcoding the IP address of the REST API in the java class, is there any key entry in the application.properties I can use? And if not, can I create a custom entry? Thanks Now provide the response and nothing else.
The infrastructure that Spring Boot uses can be used in your own project in the exact same way. You commented in @zmitrok answer about a "unknown property" warning. That is because your property has no meta-data so the IDE does not know about it. I would strongly advice you not to use @Value if you can as it is rather limited compared to what Spring Boot offers ( @Value is a Spring Framework feature). Start by creating some POJO for your IP: @ConfigurationProperties("app.foo")public class FooProperties { /** * IP of foo service used to blah. */ private String ip = 127.0.0.1; // getter & setter} Then you have two choices Put @Component on FooProperties and enable the processing of configuration properties by adding @EnableConfigurationProperties on any of your @Configuration class (this last step is no longer necessary as of Spring Boot 1.3.0.M3 ) Leave FooProperties as is and add @EnableConfigurationProperties(FooProperties.class) to any of your @Configuration class which will create a Spring Bean automatically for you. Once you've done that app.foo.ip can be used in application.properties and you can @Autowired FooProperties in your code to look for the value of the property @Componentpublic MyRestClient { private final FooProperties fooProperties; @Autowired public MyRestClient(FooProperties fooProperties) { ... } public callFoo() { String ip = this.fooProperties.getIp(); ... }} Okay so your key is still yellow in your IDE. The last step is to add an extra dependency that will look your code and generate the relevant meta-data at build time . Add the following to your pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional></dependency> And voilà, your key is recognized, you have javadoc and the IDE gives you the default value (the value you initialized on the field). Once you've that you can use any type the conversion service handles (i.e. URL ) and the javadoc on the field is used to generate documentation for your keys. You can also add any JSR-303 constraint validation on your field (for instance a regex to check it's a valid ip). Check this sample project and the documentation for more details.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32058814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5100278/']}
jdg_374423
stackexchange
llm_judgeable_groundtruth_similarity
3119840
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This seems very basic but I can't figure it out. I've got a table "item_tags", and I want to select all of the items that match tags 1 and 2 (as in, each item has to have both tags). How would I do this in mysql? Create table is: CREATE TABLE `item_tags` ( `uid_local` int(11) NOT NULL DEFAULT '0', `uid_foreign` int(11) NOT NULL DEFAULT '0', `sorting` int(11) NOT NULL DEFAULT '0', KEY `uid_local` (`uid_local`), KEY `uid_foreign` (`uid_foreign`)) ENGINE=MyISAM DEFAULT CHARSET=utf8; Thanks! Now provide the response and nothing else.
Use: SELECT i.uid FROM ITEMS i JOIN ITEM_TAGS it ON it.uid_local = i.uid AND it.uid_foreign IN (1, 2)GROUP BY i.uid HAVING COUNT(DISTINCT it.uid_foreign) = 2 You need to have a GROUP BY and HAVING clause defined, and the count of distinct tag ids must equal the number of tags you specify in the IN clause.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3119840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78949/']}
jdg_374424
stackexchange
llm_judgeable_groundtruth_similarity
40785715
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Occasionally I have to work with mixed Unix/DOS files in Vim. That file will show ^M on the end on most of the lines. I can't convert the whole file to just Unix format. Fix for that is :e ++ff=dos I have tried to incorporate that in my vimrc at least as a shorcut (if not autocmd) but without success. ga for ^M will show: <^M> 13, Hex 0d, Octal 15 This won't work from vimrc: function! Fix_dos() execute "normal :e ++ff=dos<cr>"endfunction I have tried something with conceal feature, but that won't conceal all ^M chars. :set conceallevel=2:syntax match Todo /\r/ conceal Also, is there a way to detect if file will show ^M chars? Thanks for your help. Now provide the response and nothing else.
You can use try(Connection conn = DAOUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(addSubscriptionSql); AutoCloseable finish = conn::rollback) { conn.setAutoCommit(false); //do work conn.commit();} This will always call rollback() , but after a successful completion of commit() , the rollback will become a no-op as it resets the state to that after the last successful completion of commit() … Since AutoCloseable declares to throw Exception that will require to handle this broad exception type. It can be fixed with a custom type that might be useful in other cases as well: interface SQLCloseable extends AutoCloseable { @Override public void close() throws SQLException;} … try(Connection conn = DAOUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(addSubscriptionSql); SQLCloseable finish = conn::rollback) { conn.setAutoCommit(false); //do work conn.commit();} Now, only the handling of the exception type SQLException is enforced. If you don’t like the idea of rollback() being called unconditionally, the solution becomes less elegant: boolean[] success = { false };try(Connection conn = DAOUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(addSubscriptionSql); SQLCloseable finish = () -> { if(!success[0]) conn.rollback(); }) { conn.setAutoCommit(false); //do work conn.commit(); success[0] = true;} If you reset the auto-commit state at the end, you could use that as an indicator for the necessity of a roll-back: try(Connection conn = DAOUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(addSubscriptionSql); SQLCloseable finish = () -> { if(!conn.getAutoCommit()) conn.rollback(); }) { conn.setAutoCommit(false); //do work conn.commit(); conn.setAutoCommit(true);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40785715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5151913/']}
jdg_374425
stackexchange
llm_judgeable_groundtruth_similarity
44294169
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two buttons with hidden inputs, what i want to do is to make them active onclick, when they become active i want the background color of the button to change and add the class active to button and change the hidden input value from 0 to 1, here what i have tried so far: $(".btn-default").click(function () { $(this).css('background-color', 'blue'); $(this).toggleClass("active"); }); input{display: none;}.btn-default{background-color: red} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><button type="button" class="btn btn-default">Button 1</button> <input type="text" class="form-control" id="input1" value="0"><button type="button" class="btn btn-default">Button 2</button> <input type="text" class="form-control" id="input2" value="0"> Now provide the response and nothing else.
Firebase Cloud Messaging is quite complex to get set up correctly on iOS, because you have to ensure that your APNs configuration is working, and then add FCM on top of that. APNs Setup APNs Authentication Keys are also really nice by apple because they don't expire, works in both sandbox and production environments, and the same key (as a .p8 file) can be used to send push notifications to all apps under that Apple Developer account. It also introduces a new area for a potential failure: typos . You can type in a random bundle id, and as long as the right "team" is configured in Xcode, your app will happily get an APNs device token. Sending a notification to that device token via APNs (I used this script to send test notifications over HTTP/2 + Auth Keys) will yield a DeviceTokenNotForTopic error, so that should help you figure out what went wrong. Checklist Ensure your app bundle id matches the bundle id you're sending to Ensure you have an entitlements file, with at least an aps-environment key set to development (this is automatically updated for you in release builds, by Xcode) If using "automatic" configuration (i.e. swizzling) in other SDKs like Firebase, make sure you're getting an APNs token in application:didRegisterForRemoteNotificationsWithDeviceToken: . That at least confirms that your APNs set up is okay (but still you might have a typo) FCM Setup Be sure that the GoogleService-Info.plist file you're using is for the same app as the BUNDLE_ID key in the plist. I've seen developers think that because APNs Keys should work just fine across all of their apps, that the same GoogleService-Info.plist is fine across apps, but that's not the case. Testing I'd also recommend sending yourself test notifications using FCM's HTTP API from Terminal, to help debug the issue. Unlike the Firebase Notifications Console, it will give you any raw errors it encounters. Here's an example: curl -X "POST" "https://fcm.googleapis.com/fcm/send" \ -H "Authorization: key=SERVER_KEY" \ -H "Content-Type: application/json" \ -d $'{ "notification": { "body": "Testing with direct FCM API", "title": "Test Message", "badge": "0", "sound": "default" }, "registration_ids": [ "FCM_TOKEN" ]}' Fill in your SERVER_KEY with the value in your Firebase Console > Project Settings > Cloud Messaging > Server Key. Replace FCM_TOKEN with your FCM token. I use Paw to send test notifications to my apps when I'm working on the FCM SDK.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44294169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5700753/']}
jdg_374426
stackexchange
llm_judgeable_groundtruth_similarity
564224
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: As tide approaches in lower part of some rivers (e.g. Ganges), a several feet high tidal wave enters from the sea against the flow of the river (making a great noise), and the water level suddenly rises as the wave proceeds. I would expect the water level to rise slowly and gradually, as the angle between the moon and the zenith continuously changes from $90^{\circ}$ to $0^{\circ}$ (or $180^{\circ}$ ). Why does the tidal wave appear so suddenly? I am unsure if this occurs in seas as well, but I have seen this phenomenon in rivers near the sea. Now provide the response and nothing else.
What you are describing is called a tidal bore. Quoted from Wikipedia - Tidal bore - Description : Bores occur in relatively few locations worldwide, usually in areaswith a large tidal range (typically more than 6 meters (20 ft) betweenhigh and low tide) and where incoming tides are funneled into a shallow,narrowing river or lake via a broad bay. The funnel-like shape not onlyincreases the tidal range, but it can also decrease the duration of theflood tide, down to a point where the flood appears as a sudden increasein the water level. A tidal bore takes place during the flood tide andnever during the ebb tide. In the ocean the sea level rises quite slowly (only a few feet per hour).But in the shallow water of rivers (and also in funnel-like bays)this will result in a sudden wave-like rise of the water-level.Due to the small slope of the river the slow vertical rise (a few feet per hour)is converted to high horizontal speed (several kilometers per hour) of the wave-front.And due to the funnel-like shape (from a wide sea bay to a narrow river)the height of the wave front piles up on the way. (image from Fisheries and Oceans Canada - Phenomena - Tidal bores ) Here is a real image of the phenomenon. (image from Spectacular tidal bore surges up China river )
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/564224', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/60646/']}
jdg_374427
stackexchange
llm_judgeable_groundtruth_similarity
7639141
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 quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges. At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I would have to set the setuid bit on Python itself, which I assume is big no no. From what I can tell, this would also be the case if using sudo, which I really would like to avoid. At this point, I'm considering just writing a C wrapper the uses seteuid and calls my python script as root, passing the necessary arguments to it. Is this the correct thing to do or should I be looking at something else? Now provide the response and nothing else.
sudo does not require setuid bit on Python. You can enable sudo for one command only, no arguments: www ALL=(ALL) NOPASSWD: /root/bin/reload-stuff.py "" This would be secure if your script does not take any arguments, cannot be overridden by www user, and sudo does "env_reset" (the default in most distros). You can accept arguments, but be very careful with them -- do not take output filenames, make sure you verify all inputs. In this case, remove "" from the end of sudo line.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7639141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975643/']}
jdg_374428
stackexchange
llm_judgeable_groundtruth_similarity
1116
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How many ways can a rectangle be partitioned by either vertical or horizontal lines into n sub-rectangles? At first I thought it would be: f(n) = 4f(n-1) - 2f(n-2) where f(0) = 1 and f(1) = 1 but the recurrence relation only counts the cases in which at least one side (either top, bottom, left or right of the original rectangle) is not split into sub-rectangles. There are many other partitions that don't belong to those simple cases like [EDIT ImageShack has removed the picture. One of the cases is the sixth partition when n = 4 in the picture in the accepted answer below.] Any other related problem suggestions are welcome. Also it is nice to know how to traverse this partition efficiently. Now provide the response and nothing else.
I had my student, Tim Michaels, work on this. We came up with a complicated recurrence relation, indicated below. The first few answers are 1, 2, 6, 25, 128, 758, 5014, 36194, 280433, 2303918, 19885534, 179028087, 1671644720, 16114138846, 159761516110, 1623972412726, 16880442523007, 179026930243822, 1933537655138482, 21231023519199575, 236674460790503286, 2675162663681345170, 30625903703241927542, 354767977792683552908, 4154708768196322925749, 49152046198035152483150, 587011110939295781585102, 7072674305834582713614923. Note that we are counting rotations and reflections as distinct tilings. An interesting pattern is that mod 2, there is an 8-fold periodicity which we don't understand and can't prove in general. Here's a picture of the cases n=1,2,3,4, with 1,2,6,25 tilings in each case.The way to systematically generate these is to "push in" a vertical line from the right to all previously constructed tilings in all possible ways. That's how the recurrence relation is defined. Okay, here is the recurrence:Let $a_{\ell,j,m}$ be the number of distinct tilings with $\ell$ tiles, $j$ edges that meet the right-hand side of the square and $m$ 4-valent vertices.$$a_{\ell,j,m}=\sum_{p=1}^\ell(-1)^{p+1}\sum_{i=0}^m\sum_{n=1}^{\ell-1}\sum_{k=0}^{n-1}\alpha_{n,k,i,\ell,j,m,p} a_{n,k,i}$$where, letting $t=m-i, s=\ell-n-p-t$ and $r=k+s+t+p-j$,$$\alpha_{n,k,i,l,j,m,p}=\binom{r-1}{p-1}\binom{k-r+2}{p}\binom{s+r-1}{r-1}\binom{r-p}{t}.$$ Edit: I have posted a preprint describing the recurrence relation here. Comments are welcome. Is this sort of thing publishable anywhere to anyone's knowledge? Edit 2: Nathan Reading has just posted a relevant preprint. He finds a bijection between generic tilings (no 4-valent vertices) and a set of permutations that avoid a certain pattern. Edit 3: The paper has been published in the Annals of Combinatorics .
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/333/']}
jdg_374429
stackexchange
llm_judgeable_groundtruth_similarity
47526
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: Let's say I have an encrypted message. I want to make it so that someone is able to decrypt it. The only way of giving it to them is online. For the purposes of this question, I can't call, mail or meet them in person. I want to ensure that only they are able to decrypt it. I know that the method of communication (whatever you want it to be) isn't monitored yet , but the message could be read at any time. How would I do this? Now provide the response and nothing else.
The answer to your situation, presented as it is, is that it is impossible unless you make certain assumptions. You have two problems you need to resolve for this to work. For this example, I will use Alice and Bob as examples. You need to have Alice and Bob exchange keys in a secure fashion. This is the easy problem. Any key exchange method like Diffie-Hellman or RSA will do. Alice needs to know that she is performing the key exchange with Bob. This is the difficult problem which is impossible to achieve under your scenario without making some assumptions. Let's explore some of the options we have. Bob publishes a public key that Alice will use to encrypt the encryption key with. However, how would Alice know that this public key belongs to Bob? Historically, there are two ways to accomplish this. X.509 certificates. The X.590 standard is a centralized trust model where you have to rely on a Certificate Authority to verify Bob's identity. Alice has to trust the Certificate Authority that this particular public key belongs to Bob and not a malicious attacker. This is the model used in TLS/SSL . PGP/GnuPU . PGP uses a decentralized trust model commonly referred to as the Web of Trust. This works by having many different users sign Bob's public key, essentially endorsing that the particular public key belongs to Bob. In this model, Alice has to trust that only the real Bob is able to garner enough endorsements from users. I know that your question assumes that there isn't an out-of-band means for Alice to verify Bob's identity. In the hopes of making this answer more comprehensive though, I'll cover this situation a little bit as well. If Alice can meet Bob even once, the situation gets a lot easier. Alice and Bob can simply exchange public keys through a medium like USB drives and use the public keys to encrypt further communications. Essentially, what you are asking after is a Public-key Infrastructure . As usual, do not reinvent the wheel outside of academic purposes. Use either TLS/SSL or PGP/GnuPG in practice.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/47526', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/12119/']}
jdg_374430
stackexchange
llm_judgeable_groundtruth_similarity
17989
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: SNR is defined as: $$SNR=10 \log_{10}\left(\frac{\sigma_s^2}{\sigma_n^2}\right)$$ For instance, when we say the SNR of 10 dB is 10 times higher than that of 20 dB, it is higher in what unit? Amplitude, power or what? Also, could you relate as to why it's 10 times higher for the above example. Now provide the response and nothing else.
SNR stands for Signal to Noise Ratio. It is a ratio and as such does not have any units, it describes the proportion of signal to undesired noise. There is no single correct measure of SNR, it differs depending on the application. In the equation you have given, the SNR is broken down in the following way: 1) Calculate the power ratio $$\frac{\sigma_s^2}{\sigma_n^2}$$ Your equation requires us to know the variance of the signal and the noise, dividing one by the other gives the power ratio. To answer one of your questions, this is the ratio of power, not amplitude, we could achieve the same result by taking a ratio of the root mean square of the signal and noise - another measure of power. 2) Express the ratio in decibels $$10\log_{10}$$ This is simply a convenience, the SNR may be a very large number so expressing the value on a logarithmic scale can make the information more manageable. Converting a unit to decibels simply involves taking the log10 of the value and multiplying by 10.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/17989', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/5132/']}
jdg_374431
stackexchange
llm_judgeable_groundtruth_similarity
5776660
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 making a shell script to export a sqlite query to a csv file, just like this: #!/bin/bash./bin/sqlite3 ./sys/xserve_sqlite.db ".headers on"./bin/sqlite3 ./sys/xserve_sqlite.db ".mode csv"./bin/sqlite3 ./sys/xserve_sqlite.db ".output out.csv"./bin/sqlite3 ./sys/xserve_sqlite.db "select * from eS1100_sensor_results;"./bin/sqlite3 ./sys/xserve_sqlite.db ".exit" When executing the script, the output apears on the screen, instead of being saved to "out.csv". It's working doing the same method with the command line, but I don't know why the shell script fails to export data to the file. What am I doing wrong? Now provide the response and nothing else.
sqlite3 You have a separate call to sqlite3 for each line; by the time your select runs, your .out out.csv has been forgotten. Try: #!/bin/bash./bin/sqlite3 ./sys/xserve_sqlite.db <<!.headers on.mode csv.output out.csvselect * from eS1100_sensor_results;! instead. sh/bash methods You can either call your script with a redirection: $ your_script >out.csv or you can insert the following as a first line in your script: exec >out.csv The former method allows you to specify different filenames, while the latter outputs to a specific filename. In both cases the line .output out.csv can be ignored.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5776660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704178/']}
jdg_374432
stackexchange
llm_judgeable_groundtruth_similarity
466844
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that there exists a prime between $n$ and $2n$ for all $2\leq n \in \mathbb{N}$ . Which number is the fourth number that has just one prime in its gap? First three numbers are $2$ , $3$ and $5$ . I checked with computer until $15000$ and couldn't find next one. Maybe, you can prove that there is no other number with this condition? Also, when I say, a number $n$ has one prime in its gap it means the set $X = \{x: x$ is prime and $n<x<2n\}$ has only one element. Thanks for any help. Now provide the response and nothing else.
There is no other such $n$ . For instance , In 1952, Jitsuro Nagura proved that for $n ≥ 25$ , there is always a prime between $n$ and $(1 + 1/5)n$ . This immediately means that for $n \ge 25$ , we have one prime between $n$ and $\frac{6}{5}n$ , and another prime between $\frac{6}{5}n$ and $\frac65\frac65n = \frac{36}{25}n < 2n$ . In fact, $\left(\frac{6}{5}\right)^3 < 2$ as well, so we can be sure that for $n \ge 25$ , there are at least three primes between $n$ and $2n$ . As you have already checked all $n$ up to $25$ (and more) and found only $2$ , $3$ , $5$ , we can be sure that these are the only ones. The number of primes between $n$ and $2n$ only gets larger as $n$ increases: it follows from the prime-number theorem that $$ \lim_{n \to \infty} \frac{\pi(2n) - \pi(n)}{n/\log n} = 2 - 1 = 1,$$ so the number of primes between $n$ and $2n$ , which is $\pi(2n) - \pi(n)$ , is actually asymptotic to $\frac{n}{\log n}$ which gets arbitrarily large.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/466844', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87855/']}
jdg_374433
stackexchange
llm_judgeable_groundtruth_similarity
7341853
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 to use fetched properties a couple of times, and although it seems to be the right approach, it never works. In my latest attempt I added the fetched-property to my entity, selected the other entity in the model as the 'destination', and set the predicate to a condition that I know is valid. Problem 1: When the NSManagedObject-class for the entity is generated it does not include anything for the fetched-property. After some searching I added the declaration for it in the .h file and the @dynamic statement for it in the .m file (yes, I know it's an NSArray * type). Problem 2: Even after that, when I access this property in code I get an exception being thrown that states something to the effect that the fetch-request does not have an entity. I am assuming that the 'entity' would be the one specified as the 'destination' and it is, in fact, there. So, I'd like someone to provide a concrete working example (iOS platform) where a fetched-property is defined in the model, declared in a NSManagedObject-derived class, and actually used from code. At this point I am giving up on this time-waster and simply implementing the fetch-request code myself. Now provide the response and nothing else.
Here's my relevant bits of code (including bits you've already mentioned): My example has a 'Card' object that has a 1->many relationship with a 'Stats' object. Each 'Stats' object has an 'outcome' that can be 1-4. My fetched property is a simple one to give my 'Card' object an array of 'Stats' objects that are of 'outcome'=1 only. I wanted to use the fetched property so that I could easily get hold of 'Card' objects that had more than a certain number and kind of 'Stats' objects. So, in the 'Card' object I put the Fetched Property 'statsOfTypeOne', with Destination set to 'Stats'. In the predicate for this fetched property I put (SELF.outcome=1) AND (SELF.card=$FETCH_SOURCE) 'SELF' is the 'stats' record, and $FETCH_SOURCE magically becomes the 'Card' object when executed. As you did, I put the following in the .h and .m files for the 'Card' object: @property (nonatomic, retain) NSArray *statsOfTypeOne;@dynamic statsOfTypeOne; Then in my code I used: [self.managedObjectContext refreshObject:cardInstance mergeChanges:YES];[cardInstance valueForKey:@"statsOfTypeOne"] to get at the array (although cardInstance.statsOfTypeOne should be fine). Without the refresh object it wasn't updating the Fetched property (as per the manual). I think that's everything that I did to make it work. Let me know if it works for you. Peter
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7341853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374434
stackexchange
llm_judgeable_groundtruth_similarity
30802322
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: app.use(session( { ... proxy: true, resave: true, saveUninitialized: true })); I found a tutorial on express-session and they have an proxy: true option. Can I leave it on true? What does this do? Is it better to include it? I know what a proxy is however I don't really get why this is an option? Now provide the response and nothing else.
The fine manual states: Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header). This refers to situations where clients don't connect directly to your Node server, but through a reverse proxy. For instance, clients connect to an NGINX webserver, which forwards the requests to a Node server; NGINX, in this situation, is the reverse proxy. In reverse proxy setups, it's also quite common that the client communicates with the reverse proxy over HTTPS, yet the proxy communicates with the Node server using plain HTTP. This is an issue when you configure the session middleware to use so-called "secure cookies" (documented here ). The session middleware won't allow these cookies being sent over plain HTTP but requires that they are sent over HTTPS. If your reverse proxy communicates with your Node server over HTTP, this would mean you won't be able to use secure cookies. To solve this problem, the reverse proxy will set the X-Forwarded-Proto header to every request it forwards. It tells the Node server what the original protocol of the request was, regardless of the way the reverse proxy connects to the Node server. With the proxy option of the session middleware, you're telling it to trust this header and allow secure cookies being sent over plain HTTP, provided that X-Forwarded-Proto is set to https . If you are exposing your Node server directly (so clients connect to it), you should set this option to false , because otherwise, a client can fool your server (by sending a X-Forwarded-Proto header itself) into thinking that the connection was secure. However, if you're not using secure cookies anyway, it won't really matter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30802322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3806549/']}
jdg_374435
stackexchange
llm_judgeable_groundtruth_similarity
25553711
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS. WKWebView.h #if !TARGET_OS_IPHONE/* @abstract A Boolean value indicating whether magnify gestures will change the web view's magnification. @discussion It is possible to set the magnification property even if allowsMagnification is set to NO. The default value is NO. */@property (nonatomic) BOOL allowsMagnification; I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible. I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible. Now provide the response and nothing else.
You can prevent your users from zooming by setting the delegate of your WKWebKit's UIScrollView and implementing viewForZooming(in:) as in the following: class MyClass { let webView = WKWebView() init() { super.init() webView.scrollView.delegate = self } deinit() { // Without this, it'll crash when your MyClass instance is deinit'd webView.scrollView.delegate = nil }}extension MyClass: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return nil }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25553711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397453/']}
jdg_374436
stackexchange
llm_judgeable_groundtruth_similarity
46148812
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the following program, ptr points to uninitialized variable x . Before printing ptr , I have assigned 10 to ptr and print it. #include <stdio.h>int main(){ int *ptr; int x; ptr = &x; *ptr = 10; printf(" x = %d\n", x); printf(" *ptr = %d\n", *ptr);} Both ptr and x print the correct value. But, I have doubt, Is it defined behavior? Now provide the response and nothing else.
Yes, it is. You assign a valid value to ptr and then use indirection to assign a valid value to x . The address of a variable like x and its value are separate things. After storage is allocated, taking the address is always well defined, regardless of the value in the variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46148812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7035151/']}
jdg_374437
stackexchange
llm_judgeable_groundtruth_similarity
71435
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a regression problem with 5-6k variables. I divide my data into 3 non-overlapping sets: training, validation, and testing. I train using only the training set, and generate a lot of different linear regression models by choosing a different set of 200 variables for each model (I try about 100k such subsets). I score a model as $\min(R^2_{\text{training data}}, R^2_{\text{validation data}})$. Using this criterion, I end up choosing a model. It turns out that the model chosen has very similar $R^2$ on the training and the validation data. However, when I try this model on the testing data, it has much lower $R^2$. So it seems I am somehow overfitting on both the training and the validation data. Any ideas on how can I get a more robust model? I tried increasing the training data size, but that didn't help. I am thinking of perhaps shrinking the size of each subset. I have tried using regularization. However, the models I obtain using the lasso or the elastic net have much lower $R^2$ on the training set as well as the validation set, as compared to the model I obtain by doing the subset selection approach. Therefore, I don't consider these models, since I assume that if Model A performs better than Model B on both the training set as well as the validation set, Model A is clearly better than Model B. I would be very curious if you disagree with this. On a related note, do you think $R^2$ is a bad criteria for choosing my models? Now provide the response and nothing else.
While this sounds somewhat like overfitting, I think it's actually more likely that you've got some kind of "bug" in your code or your process. I would start by verifying that your test set isn't somehow systematically different from the training/validation set. Suppose your data is sorted by date (or whatever). If you used the first 50% for training, the next 25% for validation, and the rest for testing, you may have accidentally stratified your data in a way that makes the training data somewhat representative of the validation data, but less so for the testing data. This is fairly easy to do by accident. You should also ensure you're not "double-dipping" in the validation data somehow, which sometimes happens accidentally. Alternately, CV's own @Frank Harrell has reported that a single train/test split is often too variable to provide useful information on a system's performance (maybe he can weigh in with a citation or some data). You might consider doing something like cross-validation or bootstrapping, which would let you measure both the mean and variance of your accuracy measure. Unlike Mikera, I don't think the problem is your scoring mechanism. That said, I can't imagine a situation where your $R^2_{training} < R^2_{validation}$, so I'd suggest scoring using the validation data alone. More generally, I think $R^2$ or something like it is a reasonable choice for measuring the performance of a continuous-output model, assuming you're aware of its potential caveats. Depending on exactly what you're doing, you may also want to look at the maximum or worst-case error too. If you are somehow discretizing your output (logistic regression, some external thresholds), then looking at precision/recall/AUC might be a better idea.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/71435', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/27007/']}
jdg_374438
stackexchange
llm_judgeable_groundtruth_similarity
1498694
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a Rails controller method that will respond to get requests made both "normally" (e.g. following a link) and via ajax. Normal Case: The controller should respond with fully decorated HTML using the layout. Ajax Case: The conroller should respond with the HTML snippet generated by the template (no layout) Here's the jQuery code, I've created to run on the client side to do the get request. jQuery.get("http://mydomain.com/some_controller/some_action", {}, function(data, textstatus) { jQuery("#target").html(data); }, "html"); What's the best way to handle this in Rails? Now provide the response and nothing else.
In your controller dynamically select whether to use a layout based on request.xhr? . For example: class SomeController < ApplicationController layout :get_layout protected def get_layout request.xhr? ? nil : 'normal_layout' endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1498694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67676/']}
jdg_374439
stackexchange
llm_judgeable_groundtruth_similarity
58225
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: We are working on LTE Uplink CFO Correction for 3 MHz band. The time domain CFO correction is easy, which depends on the processing of 3840 samples step by step multiply by $\exp(-j 2\pi f_\text{offset}t)$ . . What will be the equivalent frequency domain correction? Now provide the response and nothing else.
Well, when $m=k$ the integral is: $$\int_0^T e^{j(m-k)\Omega_0t} dt = \int_0^T e^{j \cdot 0 \cdot\Omega_0t} dt = \int_0^T dt = T$$ So as Juancho says in the comments, it's the same signal and so can't be orthogonal to itself.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/58225', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/43105/']}
jdg_374440