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
35140716
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 brand new to Aurelia. How would you change the following code to provide a dummy HttpClient, e.g. a json reader instead that would provide just a static set of json data, negating the need for a server in development. import {inject} from 'aurelia-framework';import {HttpClient} from 'aurelia-fetch-client';@inject(HttpClient)export class Users { heading = 'Github Users'; users = []; constructor(http) { http.configure(config => { config .useStandardConfiguration() .withBaseUrl('https://api.github.com/'); }); this.http = http; } activate() { return this.http.fetch('users') .then(response => response.json()) .then(users => this.users = users); }} Now provide the response and nothing else.
There's a couple steps required to get the demo code in your original post to a state where we can substitute HttpClient implementations. Step 1 Remove the configuration code in the class's constructor... These lines: users.js ...http.configure(config => { config .useStandardConfiguration() .withBaseUrl('https://api.github.com/');});... Should move to the main.js file: main.js export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging(); configureContainer(aurelia.container); // <-------- aurelia.start().then(a => a.setRoot());}function configureContainer(container) { let http = new HttpClient(); http.configure(config => { config .useStandardConfiguration() .withBaseUrl('https://api.github.com/'); }); container.registerInstance(HttpClient, http); // <---- this line ensures everyone that `@inject`s a `HttpClient` instance will get the instance we configured above.} Now our users.js file should look like this: users.js import {inject} from 'aurelia-framework';import {HttpClient} from 'aurelia-fetch-client';@inject(HttpClient)export class Users { heading = 'Github Users'; users = []; constructor(http) { this.http = http; } activate() { return this.http.fetch('users') .then(response => response.json()) .then(users => this.users = users); }} Step 2: Mock the HttpClient. The user.js module only uses the fetch method which returns a Response object that has a json method. Here's a simple mock: let mockUsers = [...todo: create mock user data...];let httpMock = { fetch: url => Promise.resolve({ json: () => mockUsers })}; Step 3: Reconfigure the container to use the http mock: In step 1 we added a configureContainer function to the main.js module that registered a configured HttpClient instance in the container. If we wanted to use our mock version the configureContainer function would change to this: main.js ...let mockUsers = [...todo: create mock user data...];let httpMock = { fetch: url => Promise.resolve({ json: () => mockUsers })};function configureContainer(container) { container.registerInstance(HttpClient, httpMock);} More info on configuring the container here: https://github.com/aurelia/dependency-injection/issues/73
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35140716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/844940/']}
jdg_377841
stackexchange
llm_judgeable_groundtruth_similarity
231791
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My understanding of the uncertainty principle and quantum physics is that any given object may, without notice or explanation, spontaneously perform an action it previously was unable to do with a probability that a certain outcome will occur. However, chaos theory begs to differ in the fact that, given every bit of information about a certain scenario, a future outcome is fully predictable (through rigorous mathematics) with the slight of hand that the slightest change in initial conditions can have dramatically extreme affects on the future outcome. So according to quantum physics, things can happen randomly. According to chaos theory, everything is predictable, just extremely difficult. Do the conflict or is my understanding just wrong? Now provide the response and nothing else.
Your question or confusion is mostly based on several misconceptions of the premises: Chaos theory is not a theory in the scientific sense like, e.g., the theories of relativity, evolution or quantum mechanics. It does not make predictions about the laws of nature. You can not make statements about reality like: “According to chaos theory, …”, or: “This observation violates chaos theory.” Rather, chaos theory is a theory in the mathematical sense like, e.g., set theory or number theory: The word describes a field of study, namely that of chaotic systems or (a little bit wider) non-linear dynamical systems. Determinism is the idea that if I completely know the current state of reality, i.e., the position, velocity and other properties of every particle (or whatever reality is actually made of), I can use this information to perfectly predict the future. As measuring the complete state of reality is impossible (even without quantum mechanics), we cannot prove or disprove determinism. However, certain theories or models for reality can be deterministic or not. This does not influence their validity per se – how could it if we do not know whether determinism is true or not? We judge models on their capability of correctly describing observations, be they deterministic or not. Classical mechanics is a sufficient description of reality for many everyday applications, and for all such applications (i.e., when we use it to model reality), it is deterministic. However, there are some pathological examples for which classical mechanics can be indeterministic if you interpret it in a certain way (for details see this recent question ). Quantum mechanics is the best known description of reality, whenever gravity isn’t a major factor. For all practical applications (i.e., when we use it to model reality), it is not deterministic. However, there are some ways to interpret quantum mechanics in a way that would make the universe deterministic ( hidden variables ). This determinism has no bearing on reality though; it is hidden. The indeterminism of quantum mechanics is related to the uncertainty principle: Properties of quantum objects (particles) are not fixed, but are drawn from distributions, i.e., they are uncertain. While some property of a particle can be certain (if you just measured it), there is always an uncertain property. The typical example for these properties are the position and velocity of a particle: If you know one, the other is maximally uncertain. any given object may, without notice or explanation, spontaneously perform an action it previously was unable to do with a probability that a certain outcome will occur. While most of this is technically correct, you probably had something wrong in mind when writing it. Correct is: Objects may do almost everything (e.g., move across the room, vaporize) with a certain probability, but only a small set of behaviours (what we usually observe) has a probability that is measurably different from 0. One of the prominent outcomes of chaos theory is the existence of the butterfly effect, i.e., that certain model systems (chaotic systems) can be sensitive to slight perturbations. More specifically, if I take two chaotic model systems that are identical with exception of tiny difference in the initial conditions, their specific behaviour will differ drastically after a while. (Note that their qualitative behaviour will still be comparable.) These chaotic systems most prominently include deterministic ones. Now, there are many chaotic models based on classical mechanics that are a good description of reality. Thus even with precision measurements, the behaviour of these systems is only predictable for a very short time. If anything, this unpredictability (and not predictability) was the surprising outcome of chaos theory. Or with other words: Chaos theory taught us that reality is even less predictable than we thought it was. Note that if the butterfly effect were the only outcome of chaos theory, it would be rather uninteresting and useless. Its use lies in the capability of understanding other properties of chaotic systems, making qualitative predictions about them and so on. To summarise, there is no conflict. Chaos theory does not claim that reality is deterministic, and quantum theory does not claim it is random (though that’s arguably the easiest practical approach to reality on atomic scales). a future outcome is fully predictable (through rigorous mathematics) Rigour has little to do with this. Rather, I would use the words tedious, painstaking or Sisyphean.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/231791', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/98932/']}
jdg_377842
stackexchange
llm_judgeable_groundtruth_similarity
38613179
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to make an http call using an http client with these characteristics: don't follow redirects (just get the full response of the first call, which returns a 302 redirect code) being able to receive cookies Hence, I am looking for a solution with http.Client rather than with trasport.RoundTrip how can I do that? Now provide the response and nothing else.
If you use a http.Client , you have the option of using the CheckRedirect field . This field takes a custom function which can then handle any redirects if an error is received by the initial request. A simple example might be something like this: client: &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return errors.New("something bad happened") // or maybe the error from the request },} You could also return the http.ErrUseLastResponse error which returns the most recent response with its body unclosed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38613179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/913867/']}
jdg_377843
stackexchange
llm_judgeable_groundtruth_similarity
19765352
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 been working on Native Android App where i face some bug on purticularly Android 2.3.3 versions and below Android 3.0 version . I am not getting where exactly am falling in my code because in Logcat Every Line of code compiled but at the end am getting very strange error describe log below: java.lang.StackOverflowErrorat java.util.concurrent.locks.ReentrantLock$NonfairSync.tryAcquire(ReentrantLock.java:189)at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1171)at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:185)at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:261)at java.util.concurrent.CopyOnWriteArrayList.removeRange(CopyOnWriteArrayList.java:569)at java.util.concurrent.CopyOnWriteArrayList.remove(CopyOnWriteArrayList.java:366)at java.util.concurrent.CopyOnWriteArrayList.remove(CopyOnWriteArrayList.java:376)at android.view.ViewTreeObserver.removeOnPreDrawListener(ViewTreeObserver.java:377)at android.widget.TextView.onDraw(TextView.java:4085)at android.view.View.draw(View.java:6986)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.widget.FrameLayout.draw(FrameLayout.java:361)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466) at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:7093)at android.widget.FrameLayout.draw(FrameLayout.java:361)at android.widget.ScrollView.draw(ScrollView.java:1421)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.drawChild(ViewGroup.java:1737)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.View.draw(View.java:6989)at android.widget.FrameLayout.draw(FrameLayout.java:361)at android.view.ViewGroup.drawChild(ViewGroup.java:1739)at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1466)at android.view.ViewGroup.d As i checked my code i found no trace for stackoverflow . When i run same code on android 3.0 or above version it runs effectively and correct but not on android 2.3.3 & below 3.0 version .Please let me know if any one know about this issue ?? [EDIT] I am using Tab activity so main layout is Main.xml and in that sub activity holds view called firstTab_Results.xml , it holds a table layout which indeed performs the inflating max 20 views of inflate_table_firstTab.xml layout . [EDIT 2] I am not recursing it anyway , it inflate Max 20 views(inflate_table_firstTab.xml) to table layout (firstTab_Results.xml) . Note : Stackoverflow happens on single or dual core processor devices & without fullscreen mode . Now provide the response and nothing else.
Your view hierarchy is too deep. When the hierarchy is drawn recursively, you run out of stack space and cannot go any deeper in the hierarchy, as observed in the stack trace. Why this only occurs in earlier devices is because UI thread stack size is only 12kB in Android 2.3 devices but 16kB in later OS versions ( ref ). How to reduce view hierarchy depth? Simply avoid nesting layouts whenever possible. The layouts you posted are too complex, no point fixing them for you within this Stack Overflow model (it takes some time to do correctly and it is likely too specific to help others), but here are some general guidelines: Remove unnecessary layouts. For example, in your firsttab_results.xml you only need the TableLayout , the RelativeLayout and LinearLayout on top are pretty much useless. In your ScrollView there are at least 6 nested layouts when one or at most two would likely be enough. A single child in a layout is a code smell. Most of the time the same can be achieved moving the child to its parent layout and adjusting the layout with margins. There's usually little need to put layouts inside a RelativeLayout . Relative layout is powerful at laying out its children using relative positioning and child baseline alignment. If you need a nested layout just for a background , try moving the background to e.g. just a View that is of the same size as the nested layout would be and laying out the other elements on top of it. Pay attention to Android Lint warnings. The tool has become quite good at detecting view hierarchy complexities that could be simplified.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19765352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1151710/']}
jdg_377844
stackexchange
llm_judgeable_groundtruth_similarity
52988446
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have written a code here: public class Wizard1 extends GuidedStepFragment implements Callback { private boolean sendPhoneNumber(String userPhoneNumber) { OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("request_magic_code", Urls.REQUEST_MAGIC_CODE) .build(); Request request = new Request.Builder() .url(Urls.HOST + Urls.SEND_PHONE_NUMBER) .post(requestBody) .build(); client.newCall(request).enqueue(this); return success; } @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { ResponseBody myResponse = response.body(); Log.d("SS", response.body().string()); Log.d("SS", response.body().string()); if (myResponse != null) { success = true; }} When I run this, amazingly I get java.lang.IllegalStateException. More amazingly, IF I REMOVE SECOND Log.d LINE, THE EXCEPTION WILL NOT OCCUR! What are happening? Why adding a dummy line in onResponse causes this error? here is the full log of error: 10-24 05:16:38.307 6639-6659/com.example.android.persistence W/System.err: java.lang.IllegalStateException: closed at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398) at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392) at okhttp3.internal.Util.bomAwareCharset(Util.java:431) at okhttp3.ResponseBody.string(ResponseBody.java:174) 10-24 05:16:38.308 6639-6659/com.example.android.persistence W/System.err: at android.support.v17.leanback.supportleanbackshowcase.app.wizard.WizardGetPhoneNumber.onResponse(WizardGetPhoneNumber.java:244) at okhttp3.RealCall$AsyncCall.execute(RealCall.java:141) at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at java.lang.Thread.run(Thread.java:761) Now provide the response and nothing else.
You are using response.body().string() twice From the OkHttp 3 documentation : The response body can be consumed only once. You can create local variable and use it @Overridepublic void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { ResponseBody body = response.body(); if(body != null) { try { //Use it anytime you want String responseString = body.string(); } catch (IOException e) { e.printStackTrace(); } }} Or you can copy ResponseBody @Overridepublic void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { ResponseBody body = response.body(); //Warning: this method loads the requested bytes into memory. Most // applications should set a modest limit on {@code byteCount}, such as 1 MiB. int bufferSize = 1024 * 1024; ResponseBody copy = response.peekBody(bufferSize);} But be careful to use bufferSize correctly, to prevent OutOfMemoryError P.s. you don't need to log string to Logcat. There are few more efficient ways to debug OkHttp client such as https://github.com/itkacher/OkHttpProfiler - plugin for Android studio to profile OkHttp request https://www.charlesproxy.com/ - Proxy application for http (setup manual ) http://facebook.github.io/stetho/ - debug bridge for Android applications
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52988446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5506167/']}
jdg_377845
stackexchange
llm_judgeable_groundtruth_similarity
16391
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 a first approximation, I don't see how a wavelength of less than 2 Planck distances could exist. The question is: Are there any other limits that would come into play before that? For example: Would the energy density cause the photon to turn into a black hole or something like that? Would the energy of the photon exceed the total mass+energy of the universe? Now provide the response and nothing else.
The principle of relativity guarantees that the energy of a particle may always be boosted to a higher value, e.g. by looking at the same situation from a different inertial system. All the situations with 1 particle and arbitrary allowed energy (any number not smaller than the rest mass times $c^2$ : the rest mass of the photon is zero) are physically equivalent. That's why the wavelength (which is linked to the inverse momentum) of a photon, or any other particle, may be arbitrarily short, whether it's shorter than the Planck length or not. You can't produce a black hole just from one particle because it's fast. You only produce a black hole if a sufficient amount of mass is concentrated within the Schwarzschild radius from the center-of-mass reference frame. There's a lot of misconceptions in popular science literature about the Planck length as the "minimum distance". The Planck length is only the minimum allowed distance of "proper distances measured in the rest/otherwise-natural frames" i.e. distances within a hypothetical nearly static object, measured at rest. But the wavelength associated with an arbitrary particle is just some difference of coordinates according to any frame and this quantity can't be constrained because of the principle of relativity. So the answer to both questions of yours is a resounding No: No, a single particle with a vanishing or low rest mass can never turn into a black hole, regardless of the high energy, high momentum, and corresponding high frequency or short wavelength. You need to collide at least 2 particles of Planckian energies to produce a black hole. What matters is the center-of-mass energy (which is also zero for a single photon). No, a photon (or any other particle) whose wavelength is comparable to the Planck length carries the energy equal to the Planck energy which is $c^2$ times the Planck mass. The Planck mass is just 10 micrograms or so, extremely below the mass of the Universe. ;-) It's, in fact, 100 times lighter than a mosquito. It's a big energy if you concentrate it to a single particle – which is what particle physicists usually want to do (in their minds) with the Planck energy. But it is a negligible energy relatively to the latent energy of the macroscopic objects and surely the Universe as well.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/16391', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/754/']}
jdg_377846
stackexchange
llm_judgeable_groundtruth_similarity
331459
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: Did Newton estimate the gravitational constant $\mathrm{G}$ ? In my head, he did this by comparing: acceleration of an object on Earth (let's say, an apple) $9.81 \,\mathrm{m\cdot s^{-2}}$ , $6400 \,\mathrm{km}$ from the centre of the Earth acceleration of the Moon, $384,000 \,\mathrm{km}$ As explained here . But did he actually take the next step and calculate what G must be to explain both accelerations? If so what value did he get? Now provide the response and nothing else.
Without knowing the mass of the Earth, calculating the gravitational constant is impossible from $g$ and the acceleration of the Moon. The best you can do is calculate the product of the gravitational constant and the Earth's mass (GM). This is why Cavendish's experiments with the gravity of lead weights was important, since the mass of the body providing the gravitational force was known. Once $G$ was calculated from this experiment, the Earth could then be weighed from using either $g$ or the Moon's acceleration (both hopefully yielding the same answer). The suggestion in the previous paragraph that Cavendish's experiment resulting in a value for $G$ is still not quite right. While a value for $G$ could have been determined from the experiment, Cavendish only reported the specific gravity (the ratio of a density to water's density) of Earth. According to Wikipedia , the first reference in the scientific literature to the gravitational constant is in 1873--75 years after Cavendish's experiment and 186 years after Newton's Principia was first published: Cornu, A.; Baille, J. B. (1873). "Détermination nouvelle de la constante de l'attraction et de la densité moyenne de la Terre" [New Determination of the Constant of Attraction and the Average Density of Earth]. C. R. Acad. Sci. (in French). Paris. 76: 954–958. Click on the link if you read French or can find a translator. Also, the symbol $f$ is used instead of $G$ . Newton's Principia can be downloaded here: https://archive.org/stream/newtonspmathema00newtrich#page/n0/mode/2up Follow up questions copied from the comments (in case the comment-deletion strike force shows up): So how exactly did Newton express his universal gravitational law. Was it like this " $F_g$ is equal to $GMm/r^2,$ but I must avow that I doth not know neither $G$ nor big $M$ ". Or did he just assign some number " $X$ " to the gravitational effect due to the Earth, which ended up being $GM$ ? Philip Wood: I'm pretty sure that Newton never wrote his law of gravitation in algebraic form, nor thought in terms of a gravitational constant. In fact the Principia looks more like geometry than algebra. Algebra was not the trusted universal tool that it is today. Even as late as the 1790s, Cavendish's lead balls experiment was described as 'weighing [finding the mass of] the Earth', rather than as determining the gravitational constant. Interestingly, Newton estimated the mean density of the Earth pretty accurately (how, I don't know) so he could have given a value for G if he'd thought algebraically Mark H: Philip Wood is correct. Newton wrote Principia in sentences, not equations. The laws of gravity were described in two parts (quoting from a translation): "Tn two spheres mutually gravitating each towards the other, ... the weight of either sphere towards the other will be reciprocally as the square of the distance between their centres." And, "That there is a power of gravity tending to all bodies, proportional to the several quantities of matter which they contain." This is the full statement of the behavior of gravity. No equations or constants used. Who first measured the standard gravitational acceleration 9.80 m/s/s? I assume that was well known by the time of Newton? After a quick search, I can't find who first measured $g=9.8m/s^2$ . It's not a difficult measurement, but would require accurate clocks with subsecond accuracy. This is an interesting article: https://en.wikipedia.org/wiki/Standard_gravity Actually, on page 520, Newton lists the acceleration due to gravity at Earth's surface like so: "the same body, ... falling by the impulse of the same centripetal force as before [Earth's gravity], would, in one second of time, describe 15 1/12 Paris feet." So, the value was first measured sometime between Galileo's experiments and Newton's Principia. Was Newton (and therefore all of us!) just a tiny bit luck y that the ratios worked out so nicely. I'm not putting down Sir Isaac (perhaps the smartest bloke who's ever drawn breath in tights), but even I might notice that $\frac{g(Earth)}{a_c(Moon)}=3600=\left(\frac{r(Earth−to−Moon)}{r(Earth)}\right)^2$ . If the ratio had been a little messier, say one to 47½, it might have been a little harder to spot the connection. Newton knew that the moon was not exactly 60 earth-radii distant. He quotes a number of measurements in Principia: "The mean distance of the moon from the centre of the earth, is, in semi-diameters of the earth, according to Ptolemy, Kepler in his Ephemerides, Bidliuldus, Hevelius, and Ricciolns, 59; according to Flamsted, 59 1/3; according to Tycho, 56 1/2; to Vendelin, 60; to Copernicus, 60 1/3; to Kircher, 62 1/2 (p . 391, 392, 393)." He used 60 as an average, which results in an easily calculable square, but squaring isn't a difficult calculation anyway. The inverse square law was already being talked about by many scientists at the time, including Robert Hooke. Newton used the Moon as a confirmation of the inverse square law, not to discover it. He already knew what the answer should be if the inverse square law was true. In fact, it was the orbital laws discovered by Johannes Kepler--especially the constant ratio of the cube of the average distance from the central body and the square of the orbital period--that provided the best evidence for the inverse square law. In "The System of the World" part of Newton's Principia, he uses astronomical data to show that gravity is a universal phenomena: the planets around the Sun, the moons around Jupiter, the moons around Saturn, and the Moon around Earth. For the last, in order to establish the ratio of forces and accelerations, you need at least two bodies. Since Earth only has one moon, he made the comparison with terrestrial acceleration. I would love to read a proof (requiring less mathematical nous than Sir Isaac had at his disposal) for the connection from Kepler's 3rd law to Newton's inverse square. Do you know of one? A simple version of Kepler's Third Law to the inverse square law can be shown for circular orbits pretty easily. Define $r$ as the constant radius of the orbit, $T$ as the time period of the orbit, $v$ as the planet's velocity, $m$ as the mass of the orbiting planet, $F$ as the gravitational force, and $k$ as some constant. \begin{align}\frac{r^3}{T^2} = k &\iff r^3 = kT^2 \\ &\iff r^3 = k\left(\frac{2\pi r}{v}\right)^2 \\ &\iff r = \frac{4\pi^2k}{v^2} \\ &\iff \frac{v^2}{r} = \frac{4\pi^2k}{r^2} \\ &\iff \frac{mv^2}{r} = \frac{4\pi^2km}{r^2} \\ &\iff F = \frac{4\pi^2km}{r^2}\end{align} The quantity $v^2/r$ is the centripetal acceleration necessary for constant speed circular motion.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/331459', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/133289/']}
jdg_377847
stackexchange
llm_judgeable_groundtruth_similarity
8035029
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 creating Windows Application in C# in which I want to write in multiple files with multiple threads. I am getting data from different ports and there is one file associated with every port. Is it possible that creation of thread for every port and use the same thread again and again for writing data to respective file? Suppose I am getting data from ports 10000,10001,10002 and there are three files as 10000.txt, 10001.txt and 10002.txt. I have to create three threads for writing data to these three files respectively and I want to use these threads again and again. Is it possible? Please can you give a small sample of code if possible? Now provide the response and nothing else.
As mentioned in the comments, this is asking for trouble. So, you need to have a thread-safe writer class: public class FileWriter{ private ReaderWriterLockSlim lock_ = new ReaderWriterLockSlim(); public void WriteData(/*....whatever */) { lock_.EnterWriteLock(); try { // write your data here } finally { lock_.ExitWriteLock(); } }} // eo class FileWriter This is suitable for being called by many threads. BUT, there's a caveat. There may well be lock contention. I used a ReadWriterLockSlim class, because you may want to do read locks as well and hell, that class allows you to upgrade from a read state also.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8035029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025475/']}
jdg_377848
stackexchange
llm_judgeable_groundtruth_similarity
32646
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 are Fourier basis functions? And how do I prove that Fourier basis functions are orthonormal? Now provide the response and nothing else.
An orthonormal basis for $L^2([0,1],\mathbb{R})$ (the space of real valued square integrable functions on the interval $[0,1]$ ) is $1, \sqrt{2}\cos(2\pi nx), \sqrt{2}\sin(2\pi nx)$ for $n=1,2,3,...$ . These functions can be written as (convergence in $L^2$ , many details omitted): $$f(x)=a_0+\sum_{n=1}^{\infty}a_n\cos(2\pi nx)+b_n\sin(2\pi nx)$$ where $a_0=\int_{[0,1]}f(x)\,dx$ , and for $n\geq 1$ $$a_n=2\int_{[0,1]}f(x)\cos(2\pi nx)dx, \quad b_n=2\int_{[0,1]}f(x)\sin(2\pi nx)dx.$$ The orthonormality of the basis functions is established by showing that $$\int_{[0,1]}\cos(2\pi nx)\sin(2\pi mx)dx=0,$$ $$\int_{[0,1]}\cos(2\pi nx)\cos(2\pi mx)dx=\left\{\begin{array}{cc}1/2&\text{ if } n=m\\0&\text{ if } n\neq m\\\end{array}\right.,$$ $$\int_{[0,1]}\sin(2\pi nx)\sin(2\pi mx)dx=\left\{\begin{array}{cc}1/2&\text{ if } n=m\\0&\text{ if } n\neq m\\\end{array}\right.,$$ so they are orthonormal with respect to the inner product $$\langle f,g\rangle=\int_{[0,1]}f(x)g(x)dx.$$ You can learn a lot more by finding a good reference. Most differential equations books cover Fourier series to some extent to provide solutions to the heat/wave/Laplace equations (e.g. Boyce and DiPrima). Here is something random from google showing the orthogonality relations (don't know if its good). EDIT: Since the link is broken (although any other random google search will bring up something), here is a sample derivation of one of the orthogonality relations using integration by parts twice ( $m\neq n$ both non-zero): \begin{align*}&\int_0^1\sin(2\pi nx)\cos(2\pi mx)dx\\&=\frac{1}{2\pi m}\sin(2\pi nx)\sin(2\pi mx)\Bigg|_0^1-\int_0^1\frac{2\pi n}{2\pi m}\cos(2\pi nx)\sin(2\pi m x)dx\\&=-\frac{n}{m}\int_0^1\cos(2\pi nx)\sin(2\pi m x)dx\\&=\frac{n^2}{m^2}\int_0^1\sin(2\pi nx)\cos(2\pi m x)dx\end{align*} Since $n^2/m^2\neq1$ , the integral(s) must be zero (i.e. $x=\lambda x\Rightarrow x=0$ for $\lambda\neq1$ ). The others are left as an exercise (which might be why you looked for this answer in the first place). A more compact way of seeing the orthogonality relations is to use complex exponentials. We have \begin{align*}\int_0^{1}e^{2\pi inx}e^{2\pi imx}dx&=\int_0^1e^{2\pi i(n+m)x}dx\\&=\left\{\begin{array}{cc}1&n+m=0\\\frac{e^{2\pi i(n+m)}-1}{2\pi i(n+m)}&\text{else}\\\end{array}\right.\\&=\left\{\begin{array}{cc}1&n+m=0\\0&\text{else}\\\end{array}\right.\end{align*}
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/32646', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9519/']}
jdg_377849
stackexchange
llm_judgeable_groundtruth_similarity
43048932
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 understand that in a typical ELF binary, functions get called through the Procedure Linkage Table (PLT). The PLT entry for a function usually contains a jump to a Global Offset Table (GOT) entry. This entry will first reference some code to load the actual function address into the GOT, and contain the actual function address after the first call (lazy binding). To be precise, before lazy binding the GOT entry points back into the PLT, to the instructions following the jump into the GOT. These instructions will usually jump to the head of the PLT, from where some binding routine gets called which will then update the GOT entry. Now I'm wondering why there are two indirections (calling into the PLT and then jumping to an address from the GOT), instead of just sparing the PLT and calling the address from the GOT directly. It looks like this could save a jump and the complete PLT. You would of course still need some code calling the binding routine, but this can be outside the PLT. Is there anything I am missing? What is/was the purpose of an extra PLT? Update: As suggested in the comments, I created some (pseudo-) code ASCII art to further explain what I'm referring to: This is the situation, as far as I understand it, in the current PLT scheme before lazy binding: (Some indirections between the PLT and printf are represented by "...".) Program PLT printf+---------------+ +------------------+ +-----+| ... | | push [0x603008] |<---+ +-->| ... || call j_printf |--+ | jmp [0x603010] |----+--...--+ +-----+| ... | | | ... | |+---------------+ +-->| jmp [printf@GOT] |-+ | | push 0xf |<+ | | jmp 0x400da0 |----+ | ... | +------------------+ … and after lazy binding: Program PLT printf+---------------+ +------------------+ +-----+| ... | | push [0x603008] | +-->| ... || call j_printf |--+ | jmp [0x603010] | | +-----+| ... | | | ... | |+---------------+ +-->| jmp [printf@GOT] |--+ | push 0xf | | jmp 0x400da0 | | ... | +------------------+ In my imaginary alternative scheme without a PLT, the situation before lazy binding would look like this: (I kept the code in the "Lazy Binding Table" similar to to the one from the PLT. It could also look differently, I don't care.) Program Lazy Binding Table printf+-------------------+ +------------------+ +-----+| ... | | push [0x603008] |<-+ +-->| ... || call [printf@GOT] |--+ | jmp [0x603010] |--+--...--+ +-----+| ... | | | ... | |+-------------------+ +-->| push 0xf | | | jmp 0x400da0 |--+ | ... | +------------------+ Now after the lazy binding, one wouldn't use the table anymore: Program Lazy Binding Table printf+-------------------+ +------------------+ +-----+| ... | | push [0x603008] | +-->| ... || call [printf@GOT] |--+ | jmp [0x603010] | | +-----+| ... | | | ... | |+-------------------+ | | push 0xf | | | | jmp 0x400da0 | | | | ... | | | +------------------+ | +------------------------+ Now provide the response and nothing else.
The problem is that replacing call printf@PLT with call [printf@GOTPLT] requires that the compiler knows that the function printf exists in a shared library and not a static library (or even in just a plain object file). The linker can change call printf into call printf@PLT , jmp printf into jmp printf@PLT or even mov eax, printf into mov eax, printf@PLT because all it's doing it changing a relocation based on the symbol printf into relocation based on the symbol printf@PLT . The linker can't change call printf into call [printf@GOTPLT] because it doesn't know from the relocation whether it's a CALL or JMP instruction or something else entirely. Without knowing whether it's a CALL instruction or not, it doesn't know whether it should change the opcode from a direct CALL to a indirect CALL. However even if there was a special relocation type that indicated that the instruction was a CALL, you still have the problem that a direct call instruction is a 5 bytes long but a indirect call instruction is 6 bytes long. The compiler would have to emit code like nop; call printf@CALL to give the linker room to insert the additional byte needed and it would have to do it for all calls to any global function. It would probably end up being a net performance loss because of all the extra and not actually necessary NOP instructions. Another problem is that on 32-bit x86 targets the PLT entries are relocated at runtime. The indirect jmp [xxx@GOTPLT] instructions in the PLT don't use relative addressing like the direct CALL and JMP instructions, and since the address of xxx@GOTPLT depends on where the image was loaded in memory the instruction needs to be fixed up to use the correct address. By having all these indirect JMP instructions grouped together in one .plt section means that much smaller number of virtual memory pages need to be modified. Each 4K page that's modified can no longer be shared with other processes, when the instructions that need to modified are scattered all over memory it requires that a much larger part the image to be unshared. Note that this later issue is only a problem with shared libraries and position independent executables on 32-bit x86 targets. Traditional executables can't be relocated, so there's no need to fix the @GOTPLT references, while on 64-bit x86 targets RIP relative addressing is used to access the @GOTPLT entries. Because of that last point new versions of a GCC (6.1 or later) support the -fno-plt flag. On 64-bit x86 targets this option causes the compiler to generate call printf@GOTPCREL[rip] instructions instead of call printf instructions. However it appears to do this for any call to a function that isn't defined in the same compilation unit. That is any function it doesn't know for sure isn't defined in shared library. That would mean that indirect jumps would also be used for calls to functions defined in other object files or static libraries. On 32-bit x86 targets the -fno-plt option is ignored unless compiling position independent code ( -fpic or -fpie ) where it results in call printf@GOT[ebx] instructions being emitted. In addition to generating unnecessary indirect jumps, this also has the disadvantage of requiring the allocation of a register for the GOT pointer though most functions would need it allocated anyways. Finally, Windows is able to do what you suggest by declaring symbols in header files with the "dllimport" attribute, indicating that they exist in DLLs. This way the compiler knows whether or not to generate direct or indirect call instruction when calling the function. The disadvantage of this is that the symbol has to exist in a DLL, so if this attribute used is you can't decide after compilation to link with a static library instead. Read also Drepper's How to write a shared library paper, it explains that quite well in details (for Linux).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43048932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1792200/']}
jdg_377850
stackexchange
llm_judgeable_groundtruth_similarity
34767
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: Inspired by this recently closed question, I'm curious whether there's a way to do the Gaussian integral using techniques in complex analysis such as contour integrals. I am aware of the calculation using polar coordinates and have seen other derivations. But I don't think I've ever seen it done with methods from complex analysis. I am ignorant enough about complex analysis to believe it can somehow be done without knowing how it would be done. Now provide the response and nothing else.
What follows is a list of solutions that I enjoy, and use complex analysis either implicitly or explicitly. I will update the list as I come up with more. ( Note: Solution 4 is my favorite, and is completely complex analysis oriented. I also quite like Solution 6. ) First, let $u=x^{2}$, $du=2xdx$. Then our integral becomes $$\int_{-\infty}^\infty e^{-x^2}dx=\int_{0}^{\infty}u^{-\frac{1}{2}}e^{-u}du=\Gamma\left(\frac{1}{2}\right).$$ where $\Gamma(s)$ is the Gamma function . Solution 1: Since $$\Gamma(1-s)\Gamma(s)=\frac{\pi}{\sin\pi s}$$ for all complex $s$, we conclude $$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}.$$ Solution 2: Recall the Beta function , $$\text{B}(x,y)=\int_{0}^{1}t^{x-1}(1-t)^{y-1}dt=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}.$$ Setting $x=y=\frac{1}{2}$ we have $$ \left(\Gamma\left(\frac{1}{2}\right)\right)^{2}=\int_{0}^{1}\frac{1}{\sqrt{t(1-t)}}dt.$$ To evaluate this, set $t=\sin^{2}(x)$ to find $$\left(\Gamma\left(\frac{1}{2}\right)\right)^{2}=\int_{0}^{\frac{\pi}{2}}\frac{2\sin x\cos x}{\sin x\cos x}dt=\pi.$$ Alternatively, we could evaluate the last integral by choosing branch's such that the integrand is analytic on $\mathbb{C}-[0,1]$ and then integrating around this cut. (The residue then comes from the residue at infinity) Solution 3: Setting $s=\frac{1}{2}$ in the duplication formula, $$\Gamma(s)\Gamma\left(s+\frac{1}{2}\right)=\sqrt{\pi}2^{1-2s}\Gamma(2s),$$ yields $$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}.$$ Solution 4: My personal favorite: Recall the functional equation for the zeta function , namely that $$\pi^{-\frac{z}{2}}\Gamma\left(\frac{z}{2}\right)\zeta(z)=\pi^{-\frac{1-z}{2}}\Gamma\left(\frac{1-z}{2}\right)\zeta(1-z).$$ Taking the limit as $z\rightarrow1$, we know that $\zeta(z)\sim\frac{1}{z-1}$ and $\Gamma\left(\frac{1-z}{2}\right)\sim2\frac{1}{\left(z-1\right)}$ so that we must have the equality $$\pi^{-\frac{1}{2}}\Gamma\left(\frac{1}{2}\right)=2\zeta(0).$$ By taking the limit in the right half plane as $s\rightarrow0$ using the identity $$\zeta(s)=\frac{s}{s-1}-s\int_{1}^{\infty}\{u\}u^{-s}du,$$ which holds for $\sigma>0$, we can find that $\zeta(0)=\frac{1}{2}.$ (notice the pole/zero cancellation). Consequently $$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}.$$ Solution 5: From complex integration, for $a,b>0$ we have the identity $$\int_{-\infty}^{\infty}(1-ix)^{-a}(1+ix)^{-b}dx=\frac{2^{2-a-b}\pi\Gamma(a+b-1)}{\Gamma(a)\Gamma(b)}.$$ Set $a=\frac{1}{2},b=\frac{3}{2}$ to find that $$\int_{-\infty}^{\infty}\frac{1-ix}{\left(1+x^{2}\right)^{\frac{3}{2}}}dx=\frac{2\pi}{\Gamma\left(\frac{1}{2}\right)^{2}}.$$ Hence $$\int_{0}^{\infty}\frac{1}{\left(1+x^{2}\right)^{\frac{3}{2}}}dx=\frac{\pi}{\Gamma\left(\frac{1}{2}\right)^{2}}.$$ Since the integrand on left hand side has anti derivative $\frac{x}{\sqrt{x^{2}+1}}+C$, it follows that the integral is $1$ and hence$$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}.$$ Solution 6: More with the Beta function. Consider the Mellin Transform $$\mathcal{M}\left(\frac{1}{\left(1+t\right)^{a}}\right)(z):=\int_{0}^{\infty}\frac{t^{z-1}}{(1+t)^{a}}dt=\text{B}(a-z,z).$$ The last equality follows by substituting $v=\frac{1}{1+t}$, and then rewriting the integral as $\int_{0}^{1}v^{a-z-1}(1-v)^{z-1}dv.$ Now, plug in $a=1$ and $z=\frac{1}{2}$ to get $$\int_{0}^{\infty}\frac{1}{\sqrt{t}(1+t)}dt=\Gamma\left(\frac{1}{2}\right)^{2}$$ and then let $t=x^{2}$ to find $$2\int_{0}^{\infty}\frac{1}{1+x^{2}}dx=\pi=\Gamma\left(\frac{1}{2}\right)^{2}.$$ Solution 7: We can also prove the result by using Stirling's formula . Admittedly, this isn't really using complex analysis, but I find it interesting. Since $z\Gamma(z)=\Gamma(z+1)$ we see that $$\Gamma\left(n+\frac{1}{2}\right)=\Gamma\left(\frac{1}{2}\right)\cdot\left(\frac{1}{2}\right)\left(\frac{3}{2}\right)\cdots\left(\frac{2n-1}{2}\right)=\Gamma\left(\frac{1}{2}\right)\left(\frac{(2n)!}{n!4^{n}}\right)=\Gamma\left(\frac{1}{2}\right)\binom{2n}{n}\frac{n!}{4^{n}}.$$ By Stirling's formula, $$\binom{2n}{n}\frac{1}{4^{n}}\sim\frac{1}{\sqrt{\pi n}}\ \text{as}\ n\rightarrow\infty$$ and $$\frac{\Gamma\left(n+\frac{1}{2}\right)}{n!}\sim\frac{1}{\sqrt{ne}}\frac{\left(n+\frac{1}{2}\right)^{n}}{n^{n}}.$$ Using the fact that $\lim_{n\rightarrow\infty}\left(1+\frac{a}{n}\right)^{n}=e^{a}$, it then follows that $$\frac{\Gamma\left(n+\frac{1}{2}\right)}{n!}\sim\frac{1}{\sqrt{n}}.$$ Consequently, taking the limit as $n\rightarrow\infty$ in the formula $$\Gamma\left(\frac{1}{2}\right)=\frac{\Gamma\left(n+\frac{1}{2}\right)}{n!}\frac{4^{n}}{\binom{2n}{n}}$$ yields $$\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}.$$ Hope that helps, Remark: All of the formulas used here can be proven without use the fact that $\Gamma(1/2)=\sqrt{\pi}$, so that none of these are cyclic. This is mainly worth pointing out for $4$. Edit: I put what were solutions 2 and 3 together since they were not different.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/34767', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6690/']}
jdg_377851
stackexchange
llm_judgeable_groundtruth_similarity
60651187
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 C, I know we can do this with pointers: int *p; /* an int pointer (ptr to an int) */int **pp; /* a pointer to an int pointer (ptr to a ptr to an int) */ And even: int **app[]; /* an array of pointers to int pointers */int (**ppa)[]; /* a pointer to a pointer to an array of ints */int (**ppf)(); /* a pointer to a pointer to a function returning an int */int *(*pap)[]; /* a pointer to an array of int pointers */int **fpp(); /* a function returning a pointer to an int pointer */ But can we do something like three pointers to limitless? e.g.: int ***ppp; /* a pointer to a pointer to an int pointer */int ****pppp; /* a pointer to a pointer to a pointer to an int pointer */ ...and so on till infinity. Is there any upper limits to the numbers of pointers to a pointer we can have? If so, what is the upper limit? Now provide the response and nothing else.
The standard does not impose any upper limit. What it does say is that a compiler needs to support at least 12. In practical code it can be considered infinite. Only if you write programs that writes programs that no human should ever read could this be relevant. Most coders would say that you should take three stars as a warning. Don't go beyond two without a really good reason. I tried with 10000 on gcc and it worked. I'm now trying with 100000. One interesting thing is that it takes extremely long time to compile. It took several minutes to compile, and the only statement was a pointer declaration with 10000 stars. Code to generate a C file: // gen.c#include <stdio.h>int main(){ const size_t n = 10000; printf("int main(){int "); for(size_t i=0; i<n; i++) printf("*"); printf("p;}\n");} Run: $ gcc gen.c -c gen$ ./gen > stars.c$ gcc stars.c Answer to comments: This was a fun experiment, but I will not investigate this further.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60651187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5160455/']}
jdg_377852
stackexchange
llm_judgeable_groundtruth_similarity
3405749
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 the solutions for the linear system of equations: $$\begin{aligned} 0 + x_2 +3x_3 - x_4 + 2x_5 &= 0 \\ 2x_1 + 3x_2 + x_3 + 3x_4 &= 0 \\ x_1 + x_2 - x_3 + 2x_4 - x_5 &= 0 \end{aligned}$$ is a subspace of $\mathbb R^5$ . What is the dimension of the subspace and determine a basis for the subspace? I really don't know how to solve this problem. I have achieved this augmented matrix through Gaussian elimination: $$ \begin{bmatrix} 1& 0& -4& 3& -3& 0 \\ 0& 1& 3& -1& 2& 0 \\ 0& 0& 0& 0& 0& 0 \end{bmatrix} $$ Any hints or some steps I've missed? Edit My professor says the dimension is $3$ . Now provide the response and nothing else.
You're almost there. Now your free variables are $x_3=s$ , $x_4=t$ and $x_5=u$ . Using backward substitution we get $$x_1=4s-3t+3u \\x_2=-3s+t-2u\\x_3=s \\x_4=t \\x_5=u$$ Therefore we can write every solution as $$\begin{bmatrix}x_1 \\x_2 \\x_3 \\x_4 \\x_5\end{bmatrix}=s\begin{bmatrix}4 \\-3 \\1 \\0 \\0\end{bmatrix}+t\begin{bmatrix}-3 \\1 \\0 \\1 \\0\end{bmatrix}+u\begin{bmatrix}3 \\-2 \\0 \\0 \\1\end{bmatrix}$$ with $s,t,u \in \mathbb{R}$ . Thus the subspace has dimension $3$ and a basis is given by $\begin{bmatrix}4 \\-3 \\1 \\0 \\0\end{bmatrix},\begin{bmatrix}-1 \\1 \\0 \\1 \\0\end{bmatrix},\begin{bmatrix}3 \\-2 \\0 \\0 \\1\end{bmatrix}$ To prove is a subspace you need: $0$ belongs to it: this is clear by taking $s=t=u=0$ It's closed under sums: if $(s,t,u)$ and $(s',t',u')$ gives us two different solutions, the sum of them is given by $(s+s',t+t',u+u')$ It's closed under scalar multiplication: if $(s,t,u)$ gives us a solution and we multiply it by $k \in \mathbb{R}$ , then we still have a solution given by $(ks,kt,ku)$ . Therefore it is a subspace of $\mathbb{R}^5$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3405749', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/556673/']}
jdg_377853
stackexchange
llm_judgeable_groundtruth_similarity
543019
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: A command outputs this: file_0file_1file_10file_11file_12file_13file_14file_15file_2file_3file_4file_5file_6file_7file_8file_9 How can I use awk or some other posix tool to actually sort it by the contiguous digits as a single number: file_0file_1file_2file_3file_4file_5file_6file_7file_8file_9file_10file_11file_12file_13file_14file_15 In general it should also work in case the digits is inside the file name, e.g.: file_0.txtfile_1.txtfile_10.txtfile_11.txtfile_12.txtfile_13.txtfile_14.txtfile_15.txtfile_2.txtfile_3.txtfile_4.txtfile_5.txtfile_6.txtfile_7.txtfile_8.txtfile_9.txt Now provide the response and nothing else.
sort -nt '_' -k2 Output: file_0file_1file_2file_3file_4file_5file_6file_7file_8file_9file_10file_11file_12file_13file_14file_15 or: file_0.txtfile_1.txtfile_2.txtfile_3.txtfile_4.txtfile_5.txtfile_6.txtfile_7.txtfile_8.txtfile_9.txtfile_10.txtfile_11.txtfile_12.txtfile_13.txtfile_14.txtfile_15.txt Tested with FreeBSD and GNU coreutils implementations of sort butwould not work with busybox implementation. All options used arespecified by POSIX .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/543019', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/350619/']}
jdg_377854
stackexchange
llm_judgeable_groundtruth_similarity
45151023
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 wanted to convert an ascii string (well just text to be precise) towards base64.So I know how to do that, I just use the following code: import base64string = base64.b64encode(bytes("string", 'utf-8'))print (string) Which gives me b'c3RyaW5n' However the problem is, I'd like it to just print c3RyaW5n Is it possible to print the string without the "b" and the '' quotation marks?Thanks! Now provide the response and nothing else.
The b prefix denotes that it is a binary string . A binary string is not a string: it is a sequence of bytes (values in the 0 to 255 range). It is simply typesetted as a string to make it more compact. In case of base64 however, all characters are valid ASCII characters, you can thus simply decode it like: print(string.decode('ascii')) So here we will decode each byte to its ASCII equivalent. Since base64 guarantees that every byte it produces is in the ASCII range 'A' to '/' ) we will always produce a valid string. Mind however that this is not guaranteed with an arbitrary binary string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45151023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7032457/']}
jdg_377855
stackexchange
llm_judgeable_groundtruth_similarity
51111
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 what seemed like a very simple issue, but I just cannot figure it out. I have the following circles around a common point: The Green and Blue circles represent circles that orbit the center point. I have been able to calculate the distance/radius from the point to the individual circles, but I am unable to plot the next point on either circle, given an angle from the center point. Presently, my calculation looks like the following: The coordinates of one of my circles is: y1 = 152x1 = 140.5 And my calculation for the next point, 1 degree from the starting point (140.5,152) is: distance = SQRT((160-x1)^2 + (240-y1)^2) = 90.13new x = 160 - (distance x COS(1 degree x (PI / 180)))new y = 240 - (distance x SIN(1 degree x (PI / 180))) My new x and y give me crazy results, nothing even close to my circle. I can't figure out how to calculate the new position, given the offset of 160, 240 being my center, and what I want to rotate around. Where am I going wrong? Update: I have implemented what I believe to be the correct formula, but I'm only getting a half circle, e.g. x1 = starting x coordinate, or updated coordinatey1 = starting y coordinate, or updated y coordinate cx = 100 (horizontal center)cy = 100 (vertical center)radius = SQRT((cx - x1)^2 + (cy - y1)^2)arc = ATAN((y1 - cy) / (x1 - cx))newX = cx + radius * COS(arc - PI - (PI / 180.0))newY = cy + radius * SIN(arc - PI - (PI / 180.0))Set the values so next iteration of drawing, x1 and y1 will be the newbase for the calculation.x1 = newXy1 = newY The circle begins to draw at the correct coordinates, but once it hits 180 degrees, it jumps back up to zero degrees. The dot represents the starting point. Also, the coordinates are going counterclockwise, when they need to go clockwise. Any ideas? Now provide the response and nothing else.
Update 2 : Here is the graph I got for $(x_{1},y_{1})=( 78. 965,12. 354)$, for the parametric circle $(x(t),y(t))$ centered at $(100,100)$ $$x=100+90.135\cos \left( 1.3527+\pi -t\frac{\pi }{180}\right) ,$$ $$y=100+90.135\sin \left( 1.3527+\pi -t\frac{\pi }{180}\right) .$$ together with the 4 points $(x(t),y(t))$ for $t=0,90,180,270$ $$(x_{1},y_{1})=(x(0),y(0)),(x(90),y(90)),(x(180),y(180)),(x(270),y(270)).$$ You might use the following equations in a for loop with $k=0$ to $k=359$, step $1$: $$x=100+90.135\cos \left( 1.3527+\pi -k\frac{\pi }{180}\right) ,$$ $$y=100+90.135\sin \left( 1.3527+\pi -k\frac{\pi }{180}\right) .$$ to draw the "orbit" with a 1 degree interval. Update: corrected coordinates of $(x_{1},y_{1})=(140.5,152)$. You need to consider the new angle and not only the $1{{}^\circ}$ change. The argument of $\cos$ and $\sin$ is this new angle and not $1{{}^\circ}$. Let $(x_{c},y_{c})=(160,240)$ be the center of the set of circles and $(x_{1},y_{1})=(140.5,152)$. The radius $r$ is $$\begin{eqnarray*} r &=&\sqrt{\left( x_{c}-x_{1}\right) ^{2}+\left( y_{c}-y_{1}\right) ^{2}} \\ &=&\sqrt{\left( 160-140.5\right) ^{2}+\left( 240-152\right) ^{2}} \\ &=&90.135 \end{eqnarray*}$$ Call $(x,y)$ the new coordinates of $(x_{1},y_{1})$ rotated by an angle of $-1{{}^\circ}=-\dfrac{\pi }{180}$ around $(x_{c},y_{c})$ with a radius $r$. The new angle is $\theta'=\theta -\frac{\pi }{180}$, $\theta $ being the initial angle. Then $$\begin{eqnarray*} x &=&x_{c}+r\cos \left( \theta -\frac{\pi }{180}\right), \\ y &=&y_{c}+r\sin \left( \theta -\frac{\pi }{180}\right), \end{eqnarray*}$$ where $\theta $ is the angle $\theta =\arctan \dfrac{y_{1}-y_{c}}{x_{1}-x_{c}}:$ $$\begin{eqnarray*}\theta &=&\arctan \frac{152-240}{140.5-160}=1.3527+\pi \text{ rad.}\\&=&\frac{1.3527\times 180{{}^\circ}}{\pi }+180{{}^\circ}=257. 5{{}^\circ}\end{eqnarray*}$$ Thus $$\begin{eqnarray*}x &=&160+90.135\cos \left( 1.3527+\pi -\frac{\pi }{180}\right)= 138. 96 \\y &=&240+90.135\sin \left( 1.3527+\pi -\frac{\pi }{180}\right) = 152. 35\end{eqnarray*}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/51111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10582/']}
jdg_377856
stackexchange
llm_judgeable_groundtruth_similarity
613523
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am doing some research on the different kinds of capacitors. Here is my brief understanding of the use cases for each kind of capacitor: Aluminum Electrolytic: Filtering low frequency, high current signals (such as rectified line voltage.) low ESR at low frequencies (100Hz), therefore high ripple current rating Easy to manufacture large capacitance values with high voltage ratings Aluminum Polymer: Filtering high frequency, high current signals Low ESR at high frequencies (100KHz) means high ripple current rating Easy to manufacture large capacitance values with high Ceramic: Bypass/noise filtering capacitor Low ESR and good frequency response across broad frequency range Small package sizes available Tantalum: [USE CASE] [CHARACTERISTICS OF A TANTALUM CAPACITOR THAT MAKE IT GOOD FOR THIS USE CASE] Now provide the response and nothing else.
Let’s start with some of the advantages of tantalum capacitors They have relatively good stability across frequency, voltage, and temperature range compared to electrolytic and ceramic capacitors They don’t have the piezoelectric properties that you’ll find in ceramic capacitors which makes them vibrate, sometimes causing audible noise. If used under proper conditions, tantalum capacitors can be highly reliable. Tantalum capacitors can have a high density of capacitance. This leads to the following four use cases: Applications that require high stability. Applications that require no buzzing or other piezoelectric artifacts from the capacitors. Applications that require high reliability. Applications that require a high capacitance in a small form factor. Tantalum capacitors are typically used where more than one of these apply. A note on number 3: Many engineers are averse to using tantalum capacitors because one of their failure modes is short circuit which can cause fires (or even in some cases explosions!). If the designer however considers this and accounts for it by reducing the stress on the capacitor both in normal function and considering the possible failure modes of other parts in the circuit, the probability of this type of failure is very small. Reducing stress includes keeping ripple currents, temperatures, and voltages well below the rated values. You may find it interesting that despite the exciting failure mode for solid tantalum capacitors, even NASA allows them to be used on their spacecraft which are supposed to be about as reliable as something can be. They do however have steep requirements on their use cases: voltage must be derated 50%, and they must have at least 0.1 ohm ESR per volt or 1 ohm, whichever is greater, for grade 2 applications (see NASA’s EEE-INST-002 “Instructions for EEE Parts Selection, Screening, Qualification, and Derating”).
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/613523', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/294994/']}
jdg_377857
stackexchange
llm_judgeable_groundtruth_similarity
42295604
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 component and one sitting on another. I need to send an event to main route from child component( both components use in same route) Please let me know is there any standard way to do that. Now provide the response and nothing else.
For short answer you can you can use ember-route-action-helper addon. <button {{action (route-action 'onButtonClick')}}>ClickToCallRouteAction</button> There are three way of actions communication, 1. Old style classic functions style ie., passing function name as string from top to bottom. and in all the places we need to define same function and provide. Use sendAction to bubble. and send method bubble from controller to route hierarchy. This is not encouraged.Sample classic style actions twiddle 2. Closure actions Use action helper pass function instead of just string. so that you don't need to define it everywhere. sample twiddle for closure actions style 3. route-action-helper addon You can directly call route action from anywhere literally by just wrapping functions using route-action helper. Sample twiddle Comparision between Classic style and Closure style and Why Closure is preferrable ? In classic style, You need to define actions at each level and use sendAction to trigger the action at each level until you got all the way out of your nesting. You can return value in closure actions but not in classic actions. You can curry values in closure actions but not in classic actions. Closure actions fail immediately if the action is not found. but classic actions by design,would lazily raise errors only upon invocationvalues. Coding complexity like who will handle actions and do business logic?. In closure, you can combine action and mut helper to set a property with value. onclick=(action (mut title) value="titlevalue") In closure, you can specify target object to invoke function. (action 'save' target=session) would look at the actions hash on the session object instead of the current context. Some of the promising article regarding this, - miguelcamba article ember-closure-actions-in-depth - emberigniter article send-closure-actions-up-data-owner - emberjs blog 1.13 release article - dockyard - ember-best-practice-stop-bubbling-and-use-closure-actions - blog from Ember map Why action helper? - blog from Alisdair McDiarmid ember-closure-actions-have-return-values - blog from alexdiliberto ember-closure-actions
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42295604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3035951/']}
jdg_377858
stackexchange
llm_judgeable_groundtruth_similarity
27268711
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was only able to find the following two differences: The relationships in an E-R model are explicitly defined, while they are implicit in a relational model. Relational models require an intermediate table (often called a "junction table") to hold two foreign keys that implement the many-to-many relationship. And why do we use the relational model, when we have an E-R diagram ? Now provide the response and nothing else.
You have it backwards. The relationships in an E-R model are explicitly defined, while they are implicit in a relational model. No. Each Relational Model (RM) database base table and query result represents an application relationship. Entity-Relationship Modeling (E-RM) schemas are just a way of organizing (but under-using and under-specifying) (but with misunderstanding) relational tables and constraints. Relational models require an intermediate table (often called a "junction table") to hold two foreign keys that implement the many-to-many relationship. No. It is Object-Relational Mapping (ORM) approaches that obscure their underlying straightforward relational application relationships, tables and constraints. The notion of "junction table" arose from ORM misunderstandings of confused presentations of the E-RM which itself misunderstands the RM. As C J Date put it An Introduction to Database Systems, 8th ed: a charitable reading of [Chen's original paper] would suggest that the E/R model is indeed a data model, but one that is essentially just a thin layer on top of the basic relational model [p 426] It is a sad comment on the state of the IT field that simple solutions are popular even when they are too simple. [p 427] The Relational Model Every relational table represents an application relationship. -- employee EID has name NAME and ...E(EID,NAME,...) The mathematical term for such a thing, and also for a mathematical ordered-tuple set representing one, is a "relation". Hence the " Relational Model" (and "Entity- Relationship Modeling"). In mathematics relations are frequently described by parameterized statement templates for which one mathematical term is "characteristic predicate". The parameters of the predicate are columns of the table. In the RM a DBA gives a predicate for each base table and users put the rows that make a true statement from column values and the predicate into the table and leave the rows that make a false statement out. /* now also employee 717 has name 'Smith' and ... AND employee 202 has name 'Doodle' and ...*/INSERT INTO E VALUES (EID,NAME,...) (717,'Smith',...),(202,'Doodle',...) A query expression also has a predicate built from the relation operators and logic operators (in conditions) in it. Its value also holds the rows that make its predicate true and leaves out the ones that make it false. /* rows where FOR SOME E.*, M.*, EID = E.EID AND ... AND MID = M.MID AND employee E.EID has name E.NAME and ... AND manager M.MID has AND E.DEPT = M.DEPT AND E.NAME = 'Smith'/*SELECT E.*, M.MIDFROM E JOIN M ON E.DEPT = M.DEPTWHERE E.NAME = 'Smith' Present rows of tables making true statements and absent rows making false statements is how we record about the application situation in the database and how we interpret what the database is saying about the application situation. One can't use or interpret the database without having and understanding the predicates ie application relationships. Entity-Relationship Modeling E-RM (which does not really understand the RM) is essentially a(n unnecessary, restricted and restrictive) diagramming notation for describing (some parts of) (limited forms of) relational databases. Originally there were "entity (class)" icons/relations where the candidate key (CK) values were 1:1 with application entities plus other columns ("properties" of the "entity") and there were "relationship (class)" icons/tables which had foreign keys (FKs) to entity tables representing application relationships on multiple entities plus other things ("properties" of the "association"). An application relationship was represented by an icon with lines to the various entity icons that participated in it. (Ie the lines represented FKs. Which are not relationships but statements about constraints on tables.) E-RM doesn't understand the relational model. It makes a pointless and misleading distinction between application entities and relationships. After all, every superkey (unique column set) of every base table or query result is in 1:1 correspondence with some application entity, not just the ones that have entity tables. Eg people can be associated by being married; but each such association is 1:1 with an entity called a marriage. This leads to inadequate normalization and constraints, hence redundancy and loss of integrity. Or when those steps are adequately done it leads to the E-R diagram not actually describing the application, which is actually described by the relational database predicates, tables and constraints. Then the E-R diagram is both vague, redundant and wrong. Shorthand E-RM and ORMs A lot of presentations and products claiming to be E-RM warp the E-RM, let alone the RM. They use the word "relationship" to mean a FK constraint. This arises as follows. When an E-RM relationship is binary it is a symbol with two lines to its FKs. So those three things can be replaced by one line between FKs. This kind of line represents that particular binary relationship and its FKs but now the E-R relationship is not explicit in the diagram although the E-R relationship is explicit in the longhand version and it is reflected by a table in what the diagrams are pictures of , namely the relational database they are describing . This gets called a "junction table". And people talk about that line/table being/representing "an X:Y relationship" between entities and/or associations without actually ever noticing that it's a particular application relationship . And there can be many such application relationships between the same two entities and/or associations. ORMs do this too but also replace n-ary associations by just their FKs so that the associated application relationship and table are further obscured. Active Records goes even further by defining several shorthand relationships and their tables at once, equivalent to a chain of FK lines and association icons in the longhand E-RM diagram. This is exacerbated by many modeling techniques, including versions of E-RM and ORMs, also thinking that application relationships can only be binary. Again, this arose historically from lack of understanding of the RM.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27268711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3546389/']}
jdg_377859
stackexchange
llm_judgeable_groundtruth_similarity
38895057
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 json file, nodes that looks like this: [{"toid":"osgb4000000031043205","point":[508180.748,195333.973],"index":1},{"toid":"osgb4000000031043206","point":[508163.122,195316.627],"index":2},{"toid":"osgb4000000031043207","point":[508172.075,195325.719],"index":3},{"toid":"osgb4000000031043208","point":[508513,196023],"index":4}] I am able to read and manipulate this record with Python. I am trying to read this file in scala through the spark-shell . From this tutorial , I can see that it is possible to read json via sqlContext.read.json val vfile = sqlContext.read.json("path/to/file/nodes.json") However, this results in a corrupt_record error: vfile: org.apache.spark.sql.DataFrame = [_corrupt_record: string] Can anyone shed some light on this error? I can read and use the file with other applications and I am confident it is not corrupt and sound json . Now provide the response and nothing else.
Spark cannot read JSON-array to a record on top-level, so you have to pass: {"toid":"osgb4000000031043205","point":[508180.748,195333.973],"index":1} {"toid":"osgb4000000031043206","point":[508163.122,195316.627],"index":2} {"toid":"osgb4000000031043207","point":[508172.075,195325.719],"index":3} {"toid":"osgb4000000031043208","point":[508513,196023],"index":4} As it's described in the tutorial you're referring to: Let's begin by loading a JSON file, where each line is a JSON object The reasoning is quite simple. Spark expects you to pass a file with a lot of JSON-entities (entity per line), so it could distribute their processing (per entity, roughly saying). To put more light on it, here is a quote form the official doc Note that the file that is offered as a json file is not a typical JSON file. Each line must contain a separate, self-contained valid JSON object. As a consequence, a regular multi-line JSON file will most often fail. This format is called JSONL . Basically it's an alternative to CSV.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38895057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3779667/']}
jdg_377860
stackexchange
llm_judgeable_groundtruth_similarity
9260343
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to use usort to sort multiple fields in a multidimensional array? For example, I want to sort name alphabetically and then from those records I want to sort them by age . Is this possible using sort ? Array ( [0] => Array ( [name] => Jonah [age] => 27 ) [1] => Array ( [name] => Bianca [age] => 32 )) Now provide the response and nothing else.
How about: $arr = Array ( 0 => Array ( 'name' => 'Jonah', 'age' => '27', ), 1 => Array ( 'name' => 'Bianca', 'age' => '32', ), 2 => Array ( 'name' => 'Jonah', 'age' => '25', ), 3 => Array ( 'name' => 'Bianca', 'age' => '35', ),);function comp($a, $b) { if ($a['name'] == $b['name']) { return $a['age'] - $b['age']; } return strcmp($a['name'], $b['name']);}usort($arr, 'comp');print_r($arr); output: Array( [0] => Array ( [name] => Bianca [age] => 32 ) [1] => Array ( [name] => Bianca [age] => 35 ) [2] => Array ( [name] => Jonah [age] => 25 ) [3] => Array ( [name] => Jonah [age] => 27 ))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9260343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1205775/']}
jdg_377861
stackexchange
llm_judgeable_groundtruth_similarity
70849182
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 upgrading from rails 6 to rails 7, and running some ActiveStorage methods locally, I see: Could not open library 'vips.42': dlopen(vips.42, 0x0005): tried: 'vips.42' (no such file), '/usr/local/lib/vips.42' (no such file), '/usr/lib/vips.42' (no such file), '/Users/st/rails/myapp/vips.42' (no such file), '/usr/local/lib/vips.42' (no such file), '/usr/lib/vips.42' (no such file). (LoadError)Could not open library 'libvips.42.dylib': dlopen(libvips.42.dylib, 0x0005): tried: 'libvips.42.dylib' (no such file), '/usr/local/lib/libvips.42.dylib' (no such file), '/usr/lib/libvips.42.dylib' (no such file), '/Users/st/rails/myapp/libvips.42.dylib' (no such file), '/usr/local/lib/libvips.42.dylib' (no such file), '/usr/lib/libvips.42.dylib' (no such file) There are a number of GitHub issues with similar: (e.g. here ). I am not sure if I need to install the ruby-vips gem or if there's something problematic with my OS / shared libs. Note some others have reported the same error. I wonder if it could be a bug? Now provide the response and nothing else.
If you have this problem on your local machine.. If you have just upgraded from rails 6 to 7, and have config.load_defaults 7.0 set in config/application.rb, then your app will use vips by default. If that's what you want, just make sure vips is installed locally. You can install it with homebrew (thanks to @timroman for this info): brew install vips However, if you don't want to use vips, and prefer to use mini_magick as in rails 6, just include this line in config/application.rb config.active_storage.variant_processor = :mini_magick Notes Moving from using :mini_magick to :vips will probably require code changes to make your application work as expected. See here for info on that. Further reading: Rails guides here and here This PR If you're having problems with vips on heroku.. If you get a similar issue on heroku, make sure everything works fine locally first (if it doesn't, see above), then to solve the issues on heroku, try the following 3 steps: Add gem "ruby-vips" to your gemfile if it isn't already there Set these two buildpacks (in addition to any you already have, in this example I was also using the heroku/ruby buildpack, hence why it's included as the last buildpack): heroku-community/apthttps://github.com/brandoncc/heroku-buildpack-vipsheroku/ruby I think the order here matters (if you have other buildpacks, best to add them after the first two). You can set buildpacks like this heroku buildpacks:set --index=1 heroku-community/aptheroku buildpacks:set --index=2 https://github.com/brandoncc/heroku-buildpack-vips Create a file in the root directory of your app called Aptfile with this as the contents: libglib2.0-0libglib2.0-devlibpoppler-glib8 Notes: You may wish to add more libraries to the Aptfile depending on what processing needed exactly (for example, pdf processing). Here 's an example of an Aptfile with more libraries included. And here is the rails guide showing which other things you may need. Further reading: Info on vips buildpack in this thread. See here for vips buildpack See here for information about the apt buildpack and Aptfile If you're having problems on GitHub Actions Just like other environments (see above) you have to install libvips. Do so on ubuntu using apt-get , by adding this under 'steps' in your workflow file: - name: Install libvips run: sudo apt-get install -y libvips
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70849182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5783745/']}
jdg_377862
stackexchange
llm_judgeable_groundtruth_similarity
1064297
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently doing a project in C# working with windows forms. During the course of it, I did the following void HideButtons(object sender, EventArgs e) { Button hider = ((Button)sender); foreach(Button tohide in hider.Parent.Controls) tohide.Hide(); hider.Show(); hider.Text = "UnHide"; hider.Click -= new EventHandler(HideButtons); hider.Click += new EventHandler(ShowButtons); } The purpose of this code is to have a button which hides all the other buttons in the container it's in except itself, and then turn into an Unhide button which does the same thing in reverse. Now, that's all well and good, except, as I compile this, I realize to myself I've hit a problem. hider is its unique object, being the return from ((Button)sender). It's not necessarily the reference to sender, and this code will probably do nothing. But low and behold, it works exactly like I wanted it to and initially thought it would. Which got me to wondering, does a cast always return a reference to the original object? If not, how do I guarantee that (button)sender = sender? I know that's not the case for doubles/ints, as public static int Main() { int a; double b; b = 10.5; a = (int)b; a++; return 0; } ends up with a being 11, and b being 10.5 But that may be due to doubles/ints being structs. This behavior worries me, and it'd be nice to know that it will always return a reference so I can put my worrysome mind to rest. Now provide the response and nothing else.
For reference types. if the cast is just up or down the inheritance hierarchy, then yes. This is a reference conversion . From the C# 3.0 language spec, section 6.2.4: Reference conversions, implicit or explicit, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of the reference, it never changes the type or value of the object being referred to. This is the case you're using in your WinForms code. However, in other (still reference type) cases it may invoke a user-defined conversion . For example: using System;class Foo{}class Bar{ public static explicit operator Bar(Foo f) { return new Bar(); }}class Test{ static void Main() { Foo f = new Foo(); Bar b = (Bar) f; Console.WriteLine(object.ReferenceEquals(f, b)); // Prints False }} User-defined conversions like this are relatively rare. For value types, there are boxing and unboxing conversions, along with other conversions (e.g. between int and double ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1064297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78649/']}
jdg_377863
stackexchange
llm_judgeable_groundtruth_similarity
4202687
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 remember reading somewhere that to really optimize & speed up certain section of the code, programmers write that section in Assembly language. My questions are - Is this practice still done? and How does one do this? Isn't writing in Assembly Language a bit too cumbersome & archaic? When we compile C code (with or without -O3 flag), the compiler does some code optimization & links all libraries & converts the code to binary object file. So when we run the program it is already in its most basic form i.e. binary. So how does inducing 'Assembly Language' help? I am trying to understand this concept & any help or links is much appreciated. UPDATE: Rephrasing point 3 as requested by dbemerlin- Because you might be able to write more effective assembly code than the compiler generates but unless you are an assembler expert your code will propably run slower because often the compiler optimizes the code better than most humans can. Now provide the response and nothing else.
The only time it's useful to revert to assembly language is when the CPU instructions don't have functional equivalents in C++ (e.g. single-instruction-multiple-data instructions, BCD or decimal arithmetic operations) AND the compiler doesn't provide extra functions to wrap these operations (e.g. C++11 Standard has atomic operations including compare-and-swap , <cstdlib> has div / ldiv et al for getting quotient and remainder efficiently) AND there isn't a good third-party library (e.g. http://mitpress.mit.edu/catalog/item/default.asp?tid=3952&ttype=2 ) OR for some inexplicable reason - the optimiser is failing to use the best CPU instructions ...AND... the use of those CPU instructions would give some significant and useful performance boost to bottleneck code. Simply using inline assembly to do an operation that can easily be expressed in C++ - like adding two values or searching in a string - is actively counterproductive, because: the compiler knows how to do this equally well to verify this, look at its assembly output (e.g. gcc -S ) or disassemble the machine code you're artificially restricting its choices regarding register allocation, CPU instructions etc., so it may take longer to prepare the CPU registers with the values needed to execute your hardcoded instruction, then longer to get back to an optimal allocation for future instructions compiler optimisers can choose between equivalent-performance instructions specifying different registers to minimise copying between them, and may choose registers in such a way that a single core can process multiple instructions during one cycle, whereas forcing everythingt through specific registers would serialise it in fairness, GCC has ways to express needs for specific types of registers without constraining the CPU to an exact register, still allowing such optimisations, but it's the only inline assembly I've ever seen that addresses this if a new CPU model comes out next year with another instruction that's 1000% faster for that same logical operation, then the compiler vendor is more likely to update their compiler to use that instruction, and hence your program to benefit once recompiled, than you are (or whomever's maintaining the software then is) the compiler will select an optimal approach for the target architecture its told about: if you hardcode one solution then it will need to be a lowest-common-denominator or #ifdef -ed for your platforms assembly language isn't as portable as C++, both across CPUs and across compilers, and even if you seemingly port an instruction, it's possible to make a mistake re registers that are safe to clobber, argument passing conventions etc. other programmers may not know or be comfortable with assembly One perspective that I think's worth keeping in mind is that when C was introduced it had to win over a lot of hardcore assembly language programmers who fussed over the machine code generated. Machines had less CPU power and RAM back then and you can bet people fussed over the tiniest thing. Optimisers became very sophisticated and have continued to improve, whereas the assembly languages of processors like the x86 have become increasingly complicated, as have their execution pipelines, caches and other factors involved in their performance. You can't just add values from a table of cycles-per-instruction any more. Compiler writers spend time considering all those subtle factors (especially those working for CPU manufacturers, but that ups the pressure on other compilers too). It's now impractical for assembly programmers to average - over any non-trivial application - significantly better efficiency of code than that generated by a good optimising compiler, and they're overwhelmingly likely to do worse. So, use of assembly should be limited to times it really makes a measurable and useful difference, worth the coupling and maintenance costs.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4202687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147019/']}
jdg_377864
stackexchange
llm_judgeable_groundtruth_similarity
32494548
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 implement a Settings screen using PreferenceFragmentCompat. My preference xml has a preference subscreen like this: preferences.xml <CheckBoxPreference android:defaultValue="false" android:key="@string/pref_sound_key" android:summary="@string/pref_sound_summary" android:title="@string/pref_sound_title" /> <PreferenceScreen android:title="Inner Screen"> <CheckBoxPreference android:defaultValue="true" android:key="@string/key_1" android:title="@string/title_1" /> <CheckBoxPreference android:defaultValue="true" android:key="@string/key_1" android:title="@string/title_1" /> <CheckBoxPreference android:defaultValue="true" android:key="@string/key_2" android:title="@string/title_2" /> <CheckBoxPreference android:defaultValue="true" android:key="@string/key_3" android:title="@string/title_3" /> </PreferenceScreen></PreferenceScreen> Preference Main Screen Now, in the app, the subscreen does not open until I implement PreferenceFragmentCompat.OnPreferenceStartScreenCallback interface in parent activity, as specified in PreferenceFragmentCompat doc. MainActivity.java public boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat, PreferenceScreen preferenceScreen) { preferenceFragmentCompat.setPreferenceScreen(preferenceScreen); return true;} Here's where the problem arises. On implementing the interface, the subscreen opens, but then there is no way I can find to move back to first screen. Preference Subscreen Pressing back key closes the app. Is there any way I can put a back arrow on app bar so that pressing it will bring the main screen back? Now provide the response and nothing else.
By using setPreferenceScreen you are setting the root preference screen to the sub preference screen which is preventing you from having a hierarchy of preference screens to navigate back through. I suggest that you treat each PreferenceScreen as a Fragment and add a new Fragment when you navigate into a sub screen. @Overridepublic boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat, PreferenceScreen preferenceScreen) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); MyPreferenceFragment fragment = new MyPreferenceFragment(); Bundle args = new Bundle(); args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.getKey()); fragment.setArguments(args); ft.add(R.id.fragment_container, fragment, preferenceScreen.getKey()); ft.addToBackStack(preferenceScreen.getKey()); ft.commit(); return true;} MyPreferenceFragment public class MyPreferenceFragment extends AppPreferenceFragment { public static final String FRAGMENT_TAG = "my_preference_fragment"; public MyPreferenceFragment() { } @Override public void onCreatePreferences(Bundle bundle, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); }} AppPreferenceFragment public abstract class AppPreferenceFragment extends PreferenceFragmentCompat {@Overridepublic void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Set the default white background in the view so as to avoid transparency view.setBackgroundColor( ContextCompat.getColor(getContext(), R.color.background_material_light)); }} That way when you press the back button each Fragment will be popped from the stack. For more information see this GitHub project
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32494548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3857407/']}
jdg_377865
stackexchange
llm_judgeable_groundtruth_similarity
609533
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 trying to make a point that there is curvature of spacetime from the metric expansion that contributes to the dynamics of a galaxy. This curvature would be in addition to the curvature caused by the visible mass/energy content of the galaxy. I got back a note from an editor saying " In the language of relativity physicists, “locally flat”, also called “locally Lorentz”, means flat at first order in separation from any chosen point. Of course, at second order one sees the influence of the Riemann curvature tensor, i.e. of the curvature. " Can someone interpret this for me? When a book says that the local geometry of spacetime is flat, how local is that? Microscopically, the size of a football field, a solar system, a galaxy? What's the cutoff for a 'local' geometry? Now provide the response and nothing else.
In coordinates that have the dimension of length, the dimensions of the Riemann curvature tensor are inverse length squared. Therefore at each point the components of this tensor establish length scales which you can loosely think of as radii of curvature. “Local” refers to a region whose length scales are small compared with any of these curvature-based length scales. For example, near the horizon of a stellar-mass black hole, the radii of curvature are on the scale of kilometers. Therefore dynamics in a local region on the scale of, say, meters is barely affected by the curvature. The differences from the Minkowski metric within this local region are on the order of one part in a million. For an even smaller region, the differences from Minkowskian are even more negligible. For a larger region, they are less negligible. There is no “cutoff”, but just “smaller and more flat” or “bigger and less flat”. Over a scale of kilometers the spacetime is not flat at all. Over no region is it perfectly flat. To understand mathematically how spacetime is “flat at first order”, but not second order, at every point, look at the metric tensor in Riemann normal coordinates : $$g_{\mu\nu}=\eta_{\mu\nu}-\frac13R_{\mu\sigma\nu\tau}x^\sigma x^\tau+O(|x|^3).$$ If we write $$R\sim\left(\frac{1}{L_\text{curvature}}\right)^2$$ then the deviations from the Minkowski metric over a region of linear scale $L_\text{region}$ are of order $$\left(\frac{L_\text{region}}{L_\text{curvature}}\right)^2.$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/609533', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/260164/']}
jdg_377866
stackexchange
llm_judgeable_groundtruth_similarity
120898
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 am planning to run a bash script on a remote Windows system from my local Linux machine. For this purpose, I will have to log in to Windows machine from the local one and then execute the bash Script. First of all, is this possible? If yes, then how can it be done? Now provide the response and nothing else.
This can be done by installing Cygwin and an openssh server on your Windows machine. Cygwin will come with bash, which can run your script, and openssh can be installed under Cygwin, and will allow you to login to the Windows machine remotely. Before logging in, you can transfer your script to the Windows machine using scp, and then run it directly with ssh. openssh can be installed using the cygwin setup program. For more detailed instructions, see http://www.howtogeek.com/howto/41560/how-to-get-ssh-command-line-access-to-windows-7-using-cygwin/
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/120898', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/48188/']}
jdg_377867
stackexchange
llm_judgeable_groundtruth_similarity
3847162
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 went through these topics Generics..? Super T Bounding generics with 'super' keyword However, I still seem to be kind of lost with super keyword: When we declare a collection like that: List<? super Number> list = null;list.add(new Integer(0)); // this compileslist.add(new Object()); // this doesn't compile shouldn't it be the opposite - we have a list that contains some objects (of unknown type) which are parents of Number . So Object should fit (since it is the parent of Number ), and Integer shouldn't. The opposite is the case for some reason. Provided we have the following code static void test(List<? super Number> param) { param.add(new Integer(2));}public static void main(String[] args) { List<String> sList = new ArrayList<String>(); test(sList); // will never compile, however...} It is impossible to compile the above code (and my sanity suggests that this is the right behaviour), but the basic logic could prove the opposite: String is Object, Object is superclass of Number. So String should work. I know this is crazy but isn't this the reason why they didn't allow <S super T> constructs? If yes, then why <? super T> is allowed? Could someone help me restore the missing part of this logic chain? Now provide the response and nothing else.
The bounded wildcard in List<? super Number> can capture Number and any of its supertypes. Since Number extends Object implements Serializable , this means that the only types that are currently capture-convertible by List<? super Number> are: List<Number> List<Object> List<Serializable> Note that you can add(Integer.valueOf(0)) to any of the above types. however, you CAN'T add(new Object()) to a List<Number> or a List<Serializable> , since that violates the generic type safety rule. Hence it is NOT true that you can add any supertype of Number to a List<? super Number> ; that's simply not how bounded wildcard and capture conversion work. You don't declare a List<? super Number> because you may want to add an Object to it (you can't!); you do because you want to add Number objects to it (i.e. it's a "consumer" of Number ), and simply a List<Number> is too restrictive. References Angelika Langer's Generics FAQs What is a bounded wildcard? When would I use a wildcard parameterized type with a lower bound? ("When a concrete parameterized type would be too restrictive.") Why is there no lower bound for type parameters? ("Because it does not make sense.") JLS 5.1.10 Capture Conversion See also Effective Java 2nd Edition , Item 28: Use bounded wildcards to increase API flexibility "PECS stands for producer- extends , consumer- super Related questions Too many to list, PECS, new Integer(0) vs valueOf , etc
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3847162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369317/']}
jdg_377868
stackexchange
llm_judgeable_groundtruth_similarity
2675123
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 industry, there is often a problem where you need to calculate the most efficient use of material, be it fabric, wood, metal etc. So the starting point is X amount of shapes of given dimensions, made out of polygons and/or curved lines, and target is another polygon of given dimensions. I assume many of the current CAM suites implement this, but having no experience using them or of their internals, what kind of computational algorithm is used to find the most efficient use of space? Can someone point me to a book or other reference that discusses this topic? Now provide the response and nothing else.
After Andrew in his answer pointed me to the right direction and named the problem for me, I decided to dump my research results here in a separate answer. This is indeed a packing problem, and to be more precise, it is a nesting problem. The problem is mathematically NP-hard, and thus the algorithms currently in use are heuristic approaches. There does not seem to be any solutions that would solve the problem in linear time, except for trivial problem sets. Solving complex problems takes from minutes to hours with current hardware, if you want to achieve a solution with good material utilization. There are tens of commercial software solutions that offer nesting of shapes, but I was not able to locate any open source solutions, so there are no real examples where one could see the algorithms actually implemented. Excellent description of the nesting and strip nesting problem with historical solutions can be found in a paper written by Benny Kjær Nielsen of University of Copenhagen ( Nielsen ). General approach seems to be to mix and use multiple known algorithms in order to find the best nesting solution. These algorithms include (Guided / Iterated) Local Search , Fast Neighborhood Search that is based on No-Fit Polygon , and Jostling Heuristics . I found a great paper on this subject with pictures of how the algorithms work. It also had benchmarks of the different software implementations so far. This paper was presented at the International Symposium on Scheduling 2006 by S. Umetani et al ( Umetani ). A relatively new and possibly the best approach to date is based on Hybrid Genetic Algorithm (HGA), a hybrid consisting of simulated annealing and genetic algorithm that has been described by Wu Qingming et al of Wuhan University ( Quanming ). They have implemented this by using Visual Studio, SQL database and genetic algorithm optimization toolbox (GAOT) in MatLab.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2675123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24198/']}
jdg_377869
stackexchange
llm_judgeable_groundtruth_similarity
38637
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 a scheduled script that does an hourly svnsync backup of our Subversion repositories. I was running it from an entry in the root crontab without problems, but decided I'd like to run it from /etc/cron.hourly instead for extra visibility (and because one of our engineers accidentally deleted the crontab because he thought "crontab -r" meant "read the crontab ;-)) The svnsync commands in the cron.hourly script all fail with a message saying that the SSL certificate for the SVN repository needs to be accepted (this is the message you get interactively the first time that user accesses the SVN repository, but once the certificate I accepted the message doesn't come up again). So it seems to me that the script is being executed under a different user environment when run from cron.hourly than when it's run via the root crontab. Can anyone explain the difference ? UPDATE: I should have mentioned my distro, I'm using anacron on CentOS 5.1. UPDATE 2: Thanks for the suggestions so far; I think this is turning into more of a Subversion question. I always try to encapsulate my environment into my scripts, but the problem here is that I'm not sure what it is in (or lacking in) the environment that makes SVN ask for the SSL certificate to be accepted when I run my script from cron.hourly. I'm guessing it's something to do with the way that the run-parts script is executed. Now provide the response and nothing else.
On Debian/Ubuntu system cron.daily|weekly|montly are started from the main crontab. 17 * * * * root cd / && run-parts --report /etc/cron.hourly25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) Also keep in mind that you probably could place a crontab fragment in /etc/cron.d/ As you can see there isn't anything particularly special about this environment. At least on Debian/Ubuntu it all is run as the root account. When I write cron scripts at the very start of the script I always set my PATH and other environment variables i will be using, so I can be certain that it will work correctly in any environment.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/38637', 'https://serverfault.com', 'https://serverfault.com/users/1101/']}
jdg_377870
stackexchange
llm_judgeable_groundtruth_similarity
13825085
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 my UserLogin page loads, i want to check for user database, and if it doesn't exist, or can't be read, i want to direct it to NewUser page. protected override void OnNavigatedTo(NavigationEventArgs e){ CheckForUser(); if (UserExists == false) this.Frame.Navigate(typeof(NewUser));} The problem is that it never navigates to NewUser , even when i comment out the if condition. Now provide the response and nothing else.
Navigate can't be called directly form OnNavigatedTo method. You should invoke your code through Dispatcher and it will work: protected override void OnNavigatedTo(NavigationEventArgs e){ base.OnNavigatedTo(e); CheckForUser(); if (UserExists == false) Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.Frame.Navigate(typeof(NewUser)));}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13825085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1067005/']}
jdg_377871
stackexchange
llm_judgeable_groundtruth_similarity
42965537
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 started to implement my own genetic algorithm and I'm at the stage of deciding how to select the parents for the new generation. I've done some reading and it seems there's a number of different ways to go about it. I'm aware of the various selection techniques (tournament, roulette) but the information I can't seem to find is exactly how many parents should be selected. The initial population size I'll be dealing with will be anywhere between 50-75 individuals. I was thinking of perhaps selecting half of the population for the next generation, so every generation the population decreases by exactly half, not sure if that's the best route to take though. Any advice would be great. Now provide the response and nothing else.
I took a course in genetic algorithms as part of my master's degree study. As @et_l correctly said, the population generally should be the same size each iteration, so it doesn't make sense that you want less and less solutions each generation (decreasing the population by half as you say). A population of 50-75 is also very small. I'd suggest to have at least a 100 solutions in your population. How many parents to select is entirely up to you. You can select your whole population, or only a few. The number of parents usually only effects how quickly your population will converge to a single solution. Generally the less parents you select the more quickly you converge. Now say (for example) you choose the top 10 solutions of your population of 100 as parents for your next generation. You kill off the other 90 of your population and keep the top 10. (Note that there are variations on how many you kill off too, this doesn't always need to be the part of your population that didn't get in the top and became a parent.) Next you combine your 10 parents to create new solutions. There are many ways to combine. At this step it is important to get your population back to the intial size of your population, which is 100. You can choose to keep your 10 parents in your new generation, or kill them off to and have a population entirely made of 100 children combined of the 10 parents as opposed to a population of 10 parents + 90 children. Optionally, you can now also perform some mutation on your new population to get a wider variety of solutions. Whether you do so is entirely up to you, and I would suggest to experiment with this to see what kind of effects this might have. If you choose to include mutation, usually only a small percentage of your population should mutate. Finally you have your new population and you can start another iteration if you like. Keep doing iterations until you get solutions you are satisfied with in your population. I hope I've made it clear there are many ways to implement a genetic algorithm, and it takes some experimentation to find out what implementation is best for your specific problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42965537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4752761/']}
jdg_377872
stackexchange
llm_judgeable_groundtruth_similarity
7581133
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it? ). But how should I read the JSON string from the JavaScript? <html> <head> <script src="jquery-1.6.2.min.js"></script> <script src="myscript.js">{"org": 10, "items":["one","two"]}</script> </head> <body> Hello </body></html> In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don't know if it's best to do it with jQuery or without. $(function() { // read JSON alert("the json is:")}) Now provide the response and nothing else.
I would change the script declaration to this: <script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script> Note type and id fields. After that var data = JSON.parse(document.getElementById('data').textContent); will work just fine in all browsers. The type="application/json" is needed to prevent browser from parsing it while loading. And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7581133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213269/']}
jdg_377873
stackexchange
llm_judgeable_groundtruth_similarity
4678730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an .pxf (AFAIK PKCS#12) certificate. How can I confirm a given password for this certificate using the openssl C API? Now provide the response and nothing else.
One approach to finding answers like this is to find an OpenSSL utility that performs the same functionality as what you are trying to do. In this case, you can use the pkcs12 utility that comes with OpenSSL to verify the password. The command to verify a pfx file is the following: openssl pkcs12 -in mypfx.pfx -noout With that information, you can then look at its source code ( {openssl_src}/apps/pkcs12.c ) to see how they do it. The source code shows that it calls PKCS12_verify_mac to verify the password. First to verify that there is no password: if( PKCS12_verify_mac(p12, NULL, 0) ){ printf("PKCS12 has no password.\n");} And then if there is a password, verify it by passing it as an argument: if( PKCS12_verify_mac(p12, password, -1) ){ printf("PKCS12 password matches.\n");} OpenSSL also has demos for working with PKCS12 in openssl/demos/pkcs12 . The pkread.c demo provides an example for parsing a pfx file with a password. EVP_PKEY *pkey;X509 *cert;STACK_OF(X509) *ca = NULL;if (!PKCS12_parse(p12, password, &pkey, &cert, &ca)) { fprintf(stderr, "Error parsing PKCS#12 file\n"); ERR_print_errors_fp(stderr); exit(1);} Full example, compiled with gcc -std=c99 verifypfx.c -o verifypfx -lcrypto : #include <stdio.h>#include <errno.h>#include <openssl/pkcs12.h>#include <openssl/err.h>int main(int argc, char *argv[]){ const char *password = "mypassword"; PKCS12 *p12; // Load the pfx file. FILE *fp = fopen("mypfx.pfx", "rb"); if( fp == NULL ) { perror("fopen"); return 1; } p12 = d2i_PKCS12_fp(fp, NULL); fclose(fp); OpenSSL_add_all_algorithms(); ERR_load_PKCS12_strings(); if( p12 == NULL ) { ERR_print_errors_fp(stderr); exit(1); } // Note: No password is not the same as zero-length password. Check for both. if( PKCS12_verify_mac(p12, NULL, 0) ) { printf("PKCS12 has no password.\n"); } else if( PKCS12_verify_mac(p12, password, -1) ) { printf("PKCS12 password matches.\n"); } else { printf("Password not correct.\n"); } return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4678730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76663/']}
jdg_377874
stackexchange
llm_judgeable_groundtruth_similarity
64426196
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was working on web design which contains dark colour UI analog clock. I made the clock using HTML and CSS. i included script inside HTML, but it is not working. Here is the code of that.This i tried running locally but no use.am new to web designing so i don't know what mistakes i have made. script part of the html has the problem. * { margin: 0; padding: 0; box-sizing: border-box;}body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #091921;}.clock { width: 350px; height: 350px; display: flex; justify-content: center; align-items: center; background: url(../images/_clock.png); background-size: cover; border: 4px solid #091921; border-radius: 50%; box-shadow: 0 -15px +15px rgba(255, 255, 255, 0.05), inset 0 -15px +15px rgba(255, 255, 255, 0.05), 0 15px 15px rgba(0, 0, 0, 0.05), inset 0 15px 15px rgba(0, 0, 0, 0.05);}.clock:before { content: ''; position: absolute; width: 15px; height: 15px; background: #fff; border-radius: 50%; z-index: 10000;}.clock .hour,.clock .min,.clock .sec { position: absolute;}.clock .hour,.hr { width: 160px; height: 160px;}.clock .min,.mn { width: 190px; height: 190px;}.clock .sec,.sc { width: 230px; height: 230px;}.hr,.mn,.sc { display: flex; justify-content: center; /*align-items: center;*/ position: absolute; border-radius: 50%;}.hr:before { content: ''; position: absolute; width: 8px; height: 80px; background: #ff105e; z-index: 10; border-radius: 6px 6px 0 0;}.mn:before { content: ''; position: absolute; width: 4px; height: 90px; background: #fff; z-index: 11; border-radius: 6px 6px 0 0;}.sc:before { content: ''; position: absolute; width: 2px; height: 150px; background: #fff; z-index: 12; border-radius: 6px 6px 0 0;} <<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Javascript Clack UI Dark</title> <link rel="stylesheet" href="css/style.css"></head><body> <div class="clock"> <div class="hour"> <div class="hr" id="hr"></div> </div> <div class="min"> <div class="mn" id="mn"></div> </div> <div class="sec"> <div class="sc" id="sc"></div> </div> </div> <script type="text/javascript"> const deg = 6; const hr = document.querySelector('#hr'); const mn = document.querySelector('#mn'); const sc = document.querySelector('#sc'); let day = new Date(); let hh = day.getHours() * 30; let mm = day.getMinutes * deg; let ss = day.getSeconds * deg; hr.style.transform = `rotateZ(${(hh)+(mm/12)}deg)`; mn.style.transform = `rotateZ(${mm}deg)`; sc.style.transform = `rotateZ(${ss}deg)`; </script></body></html> Now provide the response and nothing else.
Well, there's a compound action here. You get the map value given a key, increment it by one, and place it back in the map against the same key. You have to guarantee that all these statements execute atomically. But the given implementation does not impose that prerequisite. Hence you end up with a safety failure. To fix this, you can use the atomic merge operation defined in ConcurrentHashMap . The entire method invocation is performed atomically. Here's how it looks. Map<String, Integer> voting = new ConcurrentHashMap<>();for (int i = 0; i < 16; i++) new Thread(() -> { voting.merge("GERB", 1, Integer::sum); }).start();for (int i = 0; i < 100; i++) voting.merge("GERB", 1, Integer::sum);Thread.sleep(5000); // Waits for the threads to finishfor (String s : voting.keySet()) System.out.println(s + ": " + voting.get(s)); Running this program produces the following output: GERB: 116
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64426196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14334189/']}
jdg_377875
stackexchange
llm_judgeable_groundtruth_similarity
18130164
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 installed nodejs on ubuntu from instructions given here When I write node --version in the terminal I see this : -bash: /usr/sbin/node: No such file or directory I can see node in the /usr/sbin/ directory, though. Writing npm --version shows 1.3.5 Writing nodejs --version shows v0.10.15 Also, I can see node in the /usr/bin/ directory. So, how do I get node working? Also, If I use zsh instead of bash, then node command works. Now provide the response and nothing else.
You need to manually create a symlink /usr/bin/node . Shortcut for bash compatible shells: sudo ln -s `which nodejs` /usr/bin/node Or if you use non-standard shells, just hardcode the path you find with which nodejs : sudo ln -s /usr/bin/nodejs /usr/bin/node Later edit I found this explanation in the link you posted There is a naming conflict with the node package (Amateur Packet Radio Node Program), and the nodejs binary has been renamed from node to nodejs. You'll need to symlink /usr/bin/node to /usr/bin/nodejs or you could uninstall the Amateur Packet Radio Node Program to avoid that conflict. Later later edit It's been a while since I answered this. Although the solution I posted up here worked for me several times, users have reported a few more solutions within the comments: From @user229115 sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10 From AskUbuntu (user leftium) sudo apt-get --purge remove nodesudo apt-get --purge remove nodejssudo apt-get install nodejs
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/18130164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/912703/']}
jdg_377876
stackexchange
llm_judgeable_groundtruth_similarity
96977
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to re-install grub from a USB drive. I run the following: sudo mount /dev/sda6 /mntsudo grub-install --root-directory=/mnt /dev/sda I get the following error: grub-probe: error: failed to get canonical path of /cow. can someone explain the error, and how to solve it? Edit I'm trying to repair a broken dual-boot system, running from a USB containing linux mint. Now provide the response and nothing else.
Follow these steps: Boot into a Live Linux session. Mount the / partition of your installed OS to /mnt sudo mount /dev/sda6 /mnt Set up a chroot environment: sudo chroot /mnt You are now in a "fake" Linux install that treats /mnt as / . This means that all the files necessary for GRUB are in /boot where the system expects them to be and you can install GRUB just as if you were actually running your installed system: sudo update-grubsudo grub-install /dev/sda Now reboot and you should see the GRUB menu appear normally.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/96977', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22599/']}
jdg_377877
stackexchange
llm_judgeable_groundtruth_similarity
49568940
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: one spark has one oracle query. so I have to run multiple jobs in parallel so that all queries will fire at the same time. How to run multiple jobs in parallel? Now provide the response and nothing else.
Quoting the official documentation on Job Scheduling : Second, within each Spark application, multiple "jobs" (Spark actions) may be running concurrently if they were submitted by different threads. In other words, a single SparkContext instance can be used by multiple threads that gives the ability to submit multiple Spark jobs that may or may not be running in parallel. Whether the Spark jobs run in parallel depends on the number of CPUs (Spark does not track the memory usage for scheduling). If there are enough CPUs to handle the tasks from multiple Spark jobs they will be running concurrently. If however the number of CPUs is not enough you may consider using FAIR scheduling mode (FIFO is the default): Inside a given Spark application (SparkContext instance), multiple parallel jobs can run simultaneously if they were submitted from separate threads. By “job”, in this section, we mean a Spark action (e.g. save, collect) and any tasks that need to run to evaluate that action. Spark’s scheduler is fully thread-safe and supports this use case to enable applications that serve multiple requests (e.g. queries for multiple users). By default, Spark’s scheduler runs jobs in FIFO fashion. Each job is divided into “stages” (e.g. map and reduce phases), and the first job gets priority on all available resources while its stages have tasks to launch, then the second job gets priority, etc. If the jobs at the head of the queue don’t need to use the whole cluster, later jobs can start to run right away, but if the jobs at the head of the queue are large, then later jobs may be delayed significantly. Just to clear things up a bit. spark-submit is to submit a Spark application for execution (not Spark jobs). A single Spark application can have at least one Spark job. RDD actions may or may not be blocking. SparkContext comes with two methods to submit (or run) a Spark job, i.e. SparkContext.runJob and SparkContext.submitJob , and so it does not really matter whether an action is blocking or not but what SparkContext method to use to have non-blocking behaviour. Please note that "RDD action methods" are already written and their implementations use whatever Spark developers bet on (mostly SparkContext.runJob as in count ): // RDD.countdef count(): Long = sc.runJob(this, Utils.getIteratorSize _).sum You'd have to write your own RDD actions (on a custom RDD) to have required non-blocking feature in your Spark app.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49568940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9573218/']}
jdg_377878
stackexchange
llm_judgeable_groundtruth_similarity
8257311
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been away from marking up sites for some time. So, now we have HTML5 and a lot of new features in CSS. I have a common site layout with fixed size header and footer. And of course main content area in between. By default page should take 100% of window height (i.e. content area expands). And if content is long page vertical scrollbar appears and all like usual.Usually I used to do it by something like this: <body> <table id="main" ...> <tr> <td id="header-and-content"> <div id="header">contains logo, nav and has fixed height</div> <div id="content">actual content</div> </td> </tr> <tr> <td id="footer"> fixed size footer </td> </tr> </table></body> And accompanying css: html, body { height:100% }table#main { height:100% }td#footer { height:123px } So, it's obsolete. You, who keeps abreast of new markup techniques, how it is done by now in 2011? UPD People, issue not about semantic markup or using divs. I know what it does mean. Issue now in - how do I tell footer to stay at bottom even while content is empty or short. When content is long enough footer just go down as it would do in other case. Absolute and fixed is not the solution (at least at its basic form) SOME SUMMARY UPDATE I've tried method with usage of display:table and display:table-row and it works: little content , more content Method Make the Footer Stick to the Bottom of a Page was adviced by Andrej. It works also: little content , more content Some disappointment though I feel: first method is just those tables but without table tag. The second is really old, I've avoided to use it because it resembles hack. My god, nothing new :) Now provide the response and nothing else.
Well, first of all in 2011 we dont use tables for layout anymore! If I were you, I would write the markup like so: <body> <div id="main" role="main"> <header> contains logo, nav and has fixed height </header> <div class="content"> /*use <article> or <section> if it is appropriate - if not sure what to use, use a div*/ actual content </div> <footer> fixed size footer </footer> </div></body> And the CSS would be the same except the changed selectors html, body { height:100% }#main { height:100% }footer { height:123px } For a fixed footer, I would suggest to use position:absolute or maybe position:fixed - it depends how you want it to behave (scroll with page or always stay at bottom). To make a "sticky" footer, that will be at the bottom of the page but move with the content, this method will do the trick.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8257311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/978664/']}
jdg_377879
stackexchange
llm_judgeable_groundtruth_similarity
5130367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have two anonymous objects like this: var objA = new { test = "test", blah = "blah" };var objB = new { foo = "foo", bar = "bar" }; I want to combine them to get: new { test = "test", blah = "blah", foo = "foo", bar = "bar" }; I won't know what the properties are for both objA and objB at compile time.I want this to be like jquery's extend method. Anybody know of a library or a .net framework class that can help me do this? Now provide the response and nothing else.
If you truly do mean dynamic in the C# 4.0 sense, then you can do something like: static dynamic Combine(dynamic item1, dynamic item2){ var dictionary1 = (IDictionary<string, object>)item1; var dictionary2 = (IDictionary<string, object>)item2; var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary foreach (var pair in dictionary1.Concat(dictionary2)) { d[pair.Key] = pair.Value; } return result;} You could even write a version using reflection which takes two objects (not dynamic) and returns a dynamic.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5130367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60117/']}
jdg_377880
stackexchange
llm_judgeable_groundtruth_similarity
12046161
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 projects: Mvc3TestSvcRef & Mvc4TestSvcRef.Mvc3TestSvcRef is from the ASP.NET MVC 3 template for an intranet application.Mvc4TestSvcRef is from the ASP.NET MVC 4 template for an intranet application. I'm trying to add a service reference.In Mvc3TestSvcRef, I right-click the project (or the References folder) and choose Add Service Reference. I point to the URL, click Go. When the reference is resolved, I enter a namespace and click OK. As expected, I see the section added to config with the bindings and client tags completed. I can import: "using Mvc3TestSvcRef.MySvcRef;"And write code like: using (var cl = new MyServiceClient()) { cl.DoStuff(); } In Mvc4TestSvcRef, I follow the same steps, but there is no system.servicemodel added to config. Additionally the import: "using Mvc4TestSvcRef.MySvcRef;" cannot be resolved.I've tried this for MVC 4 from both Visual Studio 2010 and Visual Studio 2012. Was there a major change to the process for adding service references in ASP.NET MVC 4 project type, or am I missing something or have corrupt install? Now provide the response and nothing else.
There was no code in Reference.cs, just comments: //------------------------------------------------------------------------------// <auto-generated>// This code was generated by a tool.// Runtime Version:4.0.30319.17929//// Changes to this file may cause incorrect behavior and will be lost if// the code is regenerated.// </auto-generated>//------------------------------------------------------------------------------ I copied the reference.cs from the project that worked and modified the namespace, then added the section from the working project into the MVC 4 project and was still having an issue. I tried to build and I got several warnings and an error. Failed to generate code for the service reference 'MySvcRef'. Please check other error and warning messages for details. That led me to this article: Service Reference Error: Failed to generate code for the service reference So I unchecked the Reuse types in all referenced assemblies from the Advanced section. This seems to have generated a good service reference. Although, I should point out that if you have something in say System, like System.TimeSpan for example, that is used as a DataMember in one of your DataContracts, the reference will now have TimeSpan in the reference namespace, not from it's origin. So, the client would see any System.Timespan properties as ReferenceNameSpace.Timespan, which may throw off comparisons and such. The better answer here is to include specific assemblies from the reference and don't check the box for System.Web.Http, as pointed out in the comments below
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12046161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/780130/']}
jdg_377881
stackexchange
llm_judgeable_groundtruth_similarity
8141802
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Fast modulo 3 or division algorithm? Everyone knows that modulo arithmetic can be a huge drawback on performance. Does anyone know of a good alternative for x%3 operations? I know that one exists for x%2, but I really need one for modulo 3 since I want to alternate between three buffers in a for loop. Thanks! Now provide the response and nothing else.
Well instead of the usual "measure it" stuff an actual answer - because that stuff is actually real fun math. Although the compiler could and probably does this as well (at least modern optimizing c++ compilers, javac certainly won't and I've got no idea if the JVM does this) - so better check if it isn't already doing the work for you. But still fun to know the theory behind the optimization: I'll use assembly because we need the higher 32bit word of a multiplication. The following is from Warren's book on bit twiddling: n is the input integer we want the modulo from: li M, 0x55555556 ; load magical number (2^32 + 2) / 3mulhs q, M, n ; q = higher word of M * n; i.e. q = floor(M*n / 2^32)shri t, n, 31 ; add 1 to q if it is negativeadd q, q, t Here q contains the divisor of n / 3 so we just compute the remainder as usual: r = n - q*3 The math is the interesting part - latex would be rather cool here: q = Floor( (2^32+2)/ 3 * (n / 2^32) ) = Floor( n/3 + 2*n/(3*2^32) ) Now for n = 2^31-1 (largest n possible for signed 32bit integers) the error term is less than 1/3 (and non negative) which makes it quite easy to show that the result is indeed correct. For n = -2^31 we have the correction by 1 above and if you simplify that you'll see that the error term is always larger than -1/3 which means it holds for negative numbers as well. I leave the proof with the error term bounds for the interested - it's not that hard.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8141802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151939/']}
jdg_377882
stackexchange
llm_judgeable_groundtruth_similarity
195989
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: Lately I've been trying to split long methods into several short ones. For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url() , and then pass it over to process_components() function, which then passes the components to assign_components() function. At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods. Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url() . This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments. Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods? UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions. SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode . Now provide the response and nothing else.
Testing code that does lots of things is difficult. Debugging code that does lots of things is difficult. The solution to both of these problems is to write code that doesn't do lots of things. Write each function so that it does one thing and only one thing. This makes them easy to test with a unit test (one doesn't need umpteen dozen unit tests). A co-worker of mine has the phrase he uses when judging if a given method needs to be broken up into smaller ones: If, when describing the activity of the code to another programmer you use the word 'and', the method needs to be split into at least one more part. You wrote: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. This should be at least two methods. It is ok to wrap them in one publicly facing method, but the workings should be two different methods.
{}
{'log_upvote_score': 9, 'links': ['https://softwareengineering.stackexchange.com/questions/195989', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/89095/']}
jdg_377883
stackexchange
llm_judgeable_groundtruth_similarity
122231
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am looking for a closed-form formula for the following sum: $\displaystyle \sum_{k=0}^{N}{\frac{\sin^{2}(\frac{k\pi}{N})}{a \cdot \sin^{2}(\frac{k\pi}{N})+1}}=\sum_{k=0}^{N}{\frac{1}{a+\csc^{2}(\frac{k\pi}{N})}}$. Is such a formula known? Now provide the response and nothing else.
Two other references to similar sums are Bruce C. Berndt and Boon Pin Yeap, Explicit evaluations and reciprocity theorems for finite trigonometric sums , Advances in Applied MathematicsVolume 29, Issue 3, October 2002, Pages 358--385 and Ira Gessel, Generating Functions and Generalized Dedekind Sums , Electronic J. Combinatorics, Volume 4, Issue 2 (1997) (The Wilf Festschrift volume), R11. The paper of Berndt and Yeap uses contour integration and has an extensive list of references. My paper uses elementary methods, including partial fractions. Here are the details of the partial fraction approach: First we convert the trigonometric sum to a sum over roots of unity.Let $\eta_k=e^{k\pi i /N}$ and let $\zeta_k=\eta_k^2 = e^{2k\pi i/N}$.Then \begin{equation*}\csc^2(k\pi/N) = \left(\frac{2i}{\eta_k -\eta_k^{-1}}\right)^2 =\frac{-4\eta_k^2}{(\eta_k^2-1)^2} =\frac{-4\zeta_k}{(\zeta_k-1)^2}.\end{equation*}Thus (since the summand vanishes for $k=0$) the sum is \begin{equation*}\sum_{\zeta^N=1} \frac{1} {a-4\zeta/(\zeta-1)^2} =\sum_{\zeta^N=1} \frac{(\zeta-1)^2}{a(\zeta-1)^2 - 4\zeta}.\end{equation*}To apply the partial fraction method, we need to find the partial fraction expansion of \begin{equation*}F(z)=\frac{(z-1)^2}{a(z-1)^2 - 4z}\end{equation*}Factoring the denominator shows that we can simplify things if we make the substitution $a=4c/(c-1)^2$, so that\begin{equation*}c = \frac{a+2+2\sqrt{a+1}}{a}.\end{equation*}Then we have\begin{equation*}F(z) =\frac{(c-1)^2}{4c} +\frac{(c-1)^3}{4(c+1)}\left(\frac{1}{z-c} -\frac{1}{c(cz-1)}\right)\end{equation*}We have \begin{equation*}\sum_{\zeta^N=1} (\zeta-c)^{-1} = - \frac{Nc^{N-1}}{c^N-1}\end{equation*}and\begin{equation*}\sum_{\zeta^N=1} (c\zeta-1)^{-1} = \frac{N}{c^N-1}\end{equation*}So the sum is \begin{equation*}\sum_{\zeta^N=1} F(\zeta) = N\frac{(c-1)^2}{4c} \left(1-\frac{(c-1)}{(c+1)}\frac{(c^N+1)}{(c^N-1)}\right).\end{equation*}where $c=(a+2+2\sqrt{a+1})/a$.In terms of $a$, we can simplify this a little to\begin{equation*}\frac{N}{a} \left(1-\frac{1}{\sqrt{a+1}}\frac{(c^N+1)}{(c^N-1)}\right).\end{equation*}If you really want an expression which is rational in $a$, it's possible to write this as a quotient of polynomials in $a$ that are given by generating functions.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/122231', 'https://mathoverflow.net', 'https://mathoverflow.net/users/22051/']}
jdg_377884
stackexchange
llm_judgeable_groundtruth_similarity
28529584
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say we have an entity called MyEntity . It is possible to query pageable results using @Query and with named queries, e.g. @Query(value = "select e from MyEntity e where e.enabled = true") Page<MyEntity> findAllEnabled(Pageable pageable); However, it is not possible to achieve the same with native query, so this @Query(value = "select * from my_entity where enabled = true", nativeQuery = true) Page<MyEntity> findAllEnabled(Pageable pageable); won't work. What are the reasons behind this? Is it possible to make Pageable working with native queries? Now provide the response and nothing else.
This is description, given in spring data jpa documentation ( http://docs.spring.io/spring-data/jpa/docs/1.8.0.M1/reference/html/ ) Native queriesThe @Query annotation allows to execute native queries by setting the nativeQuery flag to true. Note, that we currently don’t support execution of pagination or dynamic sorting for native queries as we’d have to manipulate the actual query declared and we cannot do this reliably for native SQL. JPQL abstracts SQL implementation and it's providers specifics, and makes it responsibility of ORM framework to generate correct SQL. So by using Pagination in JPQL form, Spring just needs to generate correct JPQL, and it will be interpreted on ORM level to correct SQL. While doing so with SQL, would imply that Spring knows how to generated correct SQL for the vast majorities of RDBMS, duplicating ORM functionality, which is too much overhead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28529584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1534407/']}
jdg_377885
stackexchange
llm_judgeable_groundtruth_similarity
3295938
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 noticed the following code is legal in Python. My question is why? Is there a specific reason? n = 5while n != 0: print n n -= 1else: print "what the..." Many beginners accidentally stumble on this syntax when they try to put an if / else block inside of a while or for loop, and don't indent the else properly. The solution is to make sure the else block lines up with the if , assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error , and what the resulting code means. See also I'm getting an IndentationError. How do I fix it? , for the cases where there is a syntax error reported. Now provide the response and nothing else.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed. One way to think about it is as an if/else construct with respect to the condition: if condition: handle_true()else: handle_false() is analogous to the looping construct: while condition: handle_true()else: # condition is false now, handle and go on with the rest of the program handle_false() An example might be along the lines of: while value < threshold: if not process_acceptable_value(value): # something went wrong, exit the loop; don't pass go, don't collect 200 break value = update(value)else: # value >= threshold; pass go, collect 200 handle_threshold_reached()
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3295938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340453/']}
jdg_377886
stackexchange
llm_judgeable_groundtruth_similarity
12684
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: Black-box penetration testing is one to check a web application for vulnerabilities. It can find some vulnerabilities, but not all. What fraction of vulnerabilities does black-box pentesting find, on average? Is anyone aware of any data or evidence on this? Now provide the response and nothing else.
One paper in the literature provides some partial data on this subject [1]. The paper analyzed 9 web applications using two methods: (1) black-box penetration testing, and (2) manual code review by an expert. It compared how many vulnerabilities were found by each. In total, the analysis found a total of 91 vulnerabilities. 39 ofthem (43%) were found by black-box penetration testing. 71 of them(78%) were found by manual code review. There's no way to know how many morevulnerabilities might be present that neither technique discovered. Therefore, one possible conclusion is that black-box penetration testing finds less than half of all vulnerabilities present in a web application, on average. Another conclusion is that the combination of both methods seems to be better than either one alone; they each detect some vulnerabilities that are missed by the other. In the paper mentioned above, neither method alone was enough to detect all vulnerabilities:manual review found 52 vulnerabilities (57%) that were not detected byblack-box pentesting, and black-box pentesting found 20 vulnerabilities(22%) that were not detected by manual code review. However, this paper has a number of limitations. It looks at only 9 web applications. It is hard to know whether these are representative of all web applications in the wild. Manual code review was performed by only one reviewer. Black-box pentesting was performed by only one tester, and using only one tool. It is not clear whether the effectiveness of these methods might vary from person to person, or from pentesting tool to another. Therefore, this data is only a first glimpse, and can't be treated as the final answer. [1] Matthew Finifter, David Wagner. Exploring the Relationship Between Web Application Development Tools and Security . WebApps 2011.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/12684', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/971/']}
jdg_377887
stackexchange
llm_judgeable_groundtruth_similarity
61685
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The following Example 20 Obs and i used Goodness of fit test with Exponential distribution, another time with Weibull distribution and third time with Pareto distribution .All of them are significant but the question which of them are the best fitted model?? so i want compare between them by Akaike information criterion and likelihood ratio test statistic and so on R={0.742089, 1.30406, 0.662704, 0.387884, 0.131098, 0.168853, 0.181532, 0.336997, 0.163182, 0.14527, 0.781211, 0.533697, 1.22093, 0.343433, 0.332585, 0.179971, 0.487594, 1.14555, 0.402918, 0.757988} first: with respect to Exponential Distribution H = DistributionFitTest[R, ExponentialDistribution[a], "HypothesisTestData"]H["TestDataTable", All] Second:with respect to Weibull Distribution H = DistributionFitTest[R, WeibullDistribution[a, b], "HypothesisTestData"] H["TestDataTable", All] Third with respect to pareto distribution H = DistributionFitTest[R, ParetoDistribution[a, b], "HypothesisTestData"]H["TestDataTable", All] Now provide the response and nothing else.
edistdata = Table[{x, CDF[EmpiricalDistribution[R], x]}, {x, R}];cdfw[a_, b_, x_] := Simplify[CDF[WeibullDistribution[a, b], x], x > 0];cdfe[a_, x_] := Simplify[CDF[ExponentialDistribution[a], x], x > 0];cdfp[a_, b_, x_] := Simplify[CDF[ParetoDistribution[a, b], x], x > 0];nlmw = NonlinearModelFit[edistdata, cdfw[a, b, x], {a, b}, x];nlme = NonlinearModelFit[edistdata, cdfe[a, x], {a}, x];nlmp = NonlinearModelFit[edistdata, cdfp[a, b, x], {a, b}, x];Transpose[{{"", Weibull, Exponential, Pareto}, {"AIC", nlmw["AIC"], nlme["AIC"], nlmp["AIC"]}, {"BIC", nlmw["BIC"], nlme["BIC"], nlmp["BIC"]}, {"Adj-R^2", nlmw["AdjustedRSquared"], nlme["AdjustedRSquared"], nlmp["AdjustedRSquared"]}, {"R^2", nlmw["RSquared"], nlme["RSquared"], nlmp["RSquared"]}}] // TableForm[#, TableAlignments -> Center] &
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/61685', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20229/']}
jdg_377888
stackexchange
llm_judgeable_groundtruth_similarity
359387
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: First, I would like to identify an SMD part in this image, having 02B k printed on it. Where can I find some documentation? I think it should work as some kind of AND gate. There are three of them on this board, and two of them are probably misbehaving. For both inputs fully open (+12V, +12V), it should output +12V. This way does work only one of them, the second outputs nothing at all, and the third one outputs just a small fraction of the input voltage. What are these parts?What may have caused the failures? Edit:Whole board: Well, it seems that the problem is not caused by these transistors after all. On the control circuit (C4-C6) aren't the same inputs, so I suspect the problem will be somewhere else. Edit2:This board is a three-color (RGB) LED stripe driver, controlled by an IR remote Now provide the response and nothing else.
They are likely to be transistors as @Rev1.0 suggests. As to whether they are MOSFETs or BJTs, it's hard to tell beyond educated guesswork. A quick search for SOT-23 packages bearing the marking O2B finds the LN2302BLT1G NMOS. The pin-out for the NMOS makes good sense - gate to U2, resistor from gate to source, and drain going to output. The Guesswork The circuit as you point out is an RGB LED driver, so there are three outputs which drive the LED cathodes using transistors, with the fourth pin being power to the anode. The transistors frying could be the result of a current surge on the power rail frying the outputs. There is a sensor input which as you point out is an IR controller ( V = power, S = sensor, G = ground at a guess) connected to U2. The three transistors also connect to U2. The bottom right corner of your circuit is a Zener diode base shunt voltage regulator of some sort - series resistor, smoothing capacitor, then series diode (reverse polarity protection probably), and parallel zener diode. U1 is an I2C EEPROM connected to U2, so U2 is probably some form of microcontroller which could be something like a PIC12F series MCU. The PIC12F's are 8-pin devices with VDD/VSS pins in the correct place and pins 2,3,5,6,7 are all IO pins which would match your circuit. Pin 4 of U2 has a pull-up resistor and connects to the sensor input. That corresponds to the reset pin of the MCU, so the sensor could be some form of shutdown pin. Each transistor has a 47kOhm pull-down on what is either it's gate (NMOS) or base (BJT). There is also a 10kOhm series resistor between the gate/base and the output. 10kOhm base resistor seems quite high for a BJT - it would limit the current through the base quite heavily. The linked MOSFET has a <1V threshold voltage, so the 10k/47k divider that results wouldn't have too much affect.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/359387', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/179899/']}
jdg_377889
stackexchange
llm_judgeable_groundtruth_similarity
8452
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 done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? Now provide the response and nothing else.
Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does. You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so: public static class CommandBank{ /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; } /// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); // ... } Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above: /// Closes the window provided as a parameterpublic static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e){ ((Window)e.Parameter).Close();}/// Allows a Command to execute if the CommandParameter is not a null valuepublic static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e){ e.CanExecute = e.Parameter != null; e.Handled = true;} The second method there can even be shared with other Commands without me having to repeat it all over the place. Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close. public partial class SimpleWindow : Window{ private void WindowLoaded(object sender, RoutedEventArgs e) { // ... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull)); foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count > 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } } // menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; // ... } // ....} I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event. Let me know if you have any follow up questions. :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/580/']}
jdg_377890
stackexchange
llm_judgeable_groundtruth_similarity
14516955
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose if I have an Interface as defined below: public interface IFunctionality{ void Method(); } and I implement this interface for an abstract class as shown below: public abstract class AbstractFunctionality: IFunctionality{ public void Method() { Console.WriteLine("Abstract stuff" + "\n"); } } again I have a concrete class which Inherits from abstract class as below: public class ConcreteFunctionality: AbstractFunctionality{ public void Method() { Console.WriteLine("Concrete stuff" + "\n"); }} Now I have the following code, ConcreteFunctionality mostDerived = new ConcreteFunctionality();AbstractFunctionality baseInst = mostDerived;IFunctionality interfaceInst = mostDerived;mostDerived.Method();baseInst.Method();interfaceInst.Method(); The output which I am getting after execution of this stuff is as following. Concrete stuffAbstract stuffAbstract stuff But what I have been expecting the output to be "Concrete Stuff" in all the three cases as what I am doing here is assigning the reference of ConcreteFunctionality to the variables of type AbstractFunctionality and IFunctionality . What is happening internally. Kindly clarify. Now provide the response and nothing else.
Here: public class ConreteFunctionality:AbstractFunctionality{ public void Method() { Console.WriteLine("Concrete stuff" + "\n"); }} ... you're not overriding the existing method. You're creating a new method which hides the existing one. (You should get a warning, too, suggesting the use of the new modifier if you really want this behaviour.) The interface was implemented in AbstractFunctionality , so the interface mapping table refers to the method in that class. Now if you reimplement the interface: public class ConcreteFunctionality : AbstractFunctionality, IFunctionality ... then the interface mapping will refer to the method in ConcreteFunctionality and you'll get the behaviour you expect for the call through the interface (i.e. your third call) but you'd still get the implementation in AbstractFunctionality for your second call. It would be generally cleaner and more sanity-preserving to make the method in AbstractFunctionality virtual, and override it in ConcreteFunctionality . That way it will use the ConcreteFunctionality implementation in all cases.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14516955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/416059/']}
jdg_377891
stackexchange
llm_judgeable_groundtruth_similarity
8177140
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 .centered-holder { margin-left: auto; margin-right: auto; clear: left; display: inline-block;} Then <div class="centered-holder">misc content 1</div><div class="centered-holder">misc content 2</div><div class="centered-holder">misc content 3</div> I only want one max per line, is this actually possible somehow? It's an iPhone HTML5 app so older browser restrictions aren't an issue. Now provide the response and nothing else.
Depend of your CSS declarations and your markup, but you can try to put this CSS declaration on the parent container: white-space: pre-line; With this approach you avoid to transform the .centered-holder to a block element, and you can still use for example the text-align:center on the parent container. pre-line - This value will cause sequences of whitespace to collapse into a single space character. Line breaks will occur wherever necessary to fill line boxes, and at new lines in the markup (or at occurrences of "\a" in generated content). In other words, it’s like normal except that it’ll honor explicit line breaks. You can find more informations here about white-space: http://reference.sitepoint.com/css/white-space http://www.w3.org/TR/css3-text/#white-space To finish, you can use these CSS declarations : .parent-container { white-space: pre-line /* Create new line for each DIV */; line-height:0 /* Mask the extra lines */; *white-space: pre /*FixIE7*/; *word-wrap: break-word /*FixIE7*/;}.centered-holder { display: inline-block; line-height:100% /* Restore a default line-height */; *display: inline /*FixIE7*/; *zoom: 1 /*FixIE7*/;} I found this question very interesting, so I give also the CSS declarations for IE6-7 ( pre-line and inline-block fixes). It should be usefull for some other people which have a similar problem.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8177140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314963/']}
jdg_377892
stackexchange
llm_judgeable_groundtruth_similarity
46565019
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After copying myexentension@me.com folder to .../gnome-shell/extensions/ I'm executing this command on the terminal: gnome-shell-extension-tool -e myexentension@me.com Then, I restart my session with Alt + F2 and execute r , and everything works fine. But can I start my extension only through the command line? Without Alt + F2 + r ? Without restarting my gnome-shell session? Now provide the response and nothing else.
According to some answers around the internet, sending SIGHUP to the gnome-shell process restarts it (i. e. killall -HUP gnome-shell ), but I haven’t been able to find a clear source on this and couldn’t find the signal handling in the code. What I do know is that this should be exactly equivalent to Alt+F2 r : busctl --user call org.gnome.Shell /org/gnome/Shell org.gnome.Shell Eval s 'Meta.restart("Restarting…")' Because apart from a gettext call on the message, this is exactly what Alt+F2 r is bound to (see runDialog.js – search for _restart ). January 2022 update: Since Gnome 41, calling Eval is restricted and requires “unsafe mode” to be enabled, so by default this will no longer work. I’m not currently aware of a replacement for this particular usage.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46565019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8394280/']}
jdg_377893
stackexchange
llm_judgeable_groundtruth_similarity
18492273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a number of hdf5 files, each of which have a single dataset. The datasets are too large to hold in RAM. I would like to combine these files into a single file containing all datasets separately (i.e. not to concatenate the datasets into a single dataset). One way to do this is to create a hdf5 file and then copy the datasets one by one. This will be slow and complicated because it will need to be buffered copy. Is there a more simple way to do this? Seems like there should be, since it is essentially just creating a container file. I am using python/h5py. Now provide the response and nothing else.
This is actually one of the use-cases of HDF5.If you just want to be able to access all the datasets from a single file, and don't care how they're actually stored on disk, you can use external links . From the HDF5 website : External links allow a group to include objects in another HDF5 file and enable the library to access those objects as if they are in the current file. In this manner, a group may appear to directly contain datasets, named datatypes, and even groups that are actually in a different file. This feature is implemented via a suite of functions that create and manage the links, define and retrieve paths to external objects, and interpret link names: Here's how to do it in h5py : myfile = h5py.File('foo.hdf5','a')myfile['ext link'] = h5py.ExternalLink("otherfile.hdf5", "/path/to/resource") Be careful: when opening myfile , you should open it with 'a' if it is an existing file. If you open it with 'w' , it will erase its contents. This would be very much faster than copying all the datasets into a new file. I don't know how fast access to otherfile.hdf5 would be, but operating on all the datasets would be transparent - that is, h5py would see all the datasets as residing in foo.hdf5 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18492273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1358889/']}
jdg_377894
stackexchange
llm_judgeable_groundtruth_similarity
8774317
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm a fan of the menu button as used in Android <3.0, as it was very useful for my game apps - it allowed me to take important but gameplay irrelevant functionality (saving game, reference info links) and place it somewhere where it did not clutter up the main game interface, but was still easily accessible (the options menu). This use of keys became a problem with 3.0, because it removed the MENU button and substituted it with the Action Bar. The Action bar is really not suitable for a game which likes to run full-screen, so that was a real pain. No action bar - no access to the options menu. However, I could sort of ignore it for a while, since I didn't have that many users on tablets and lacked the time to test this. However, ICS makes this a serious issue, since the MENU button is obviously not coming back. Now I don't only have to deal with this problems on tablets, but on phones as well. My initial solution to this problem has been to simply place a soft button in my GUI to replace the hard MENU button this.openOptionsMenu(); And everything is back to working perfectly in ICS. However, this does not work on Honeycomb. Calling openOptionsMenu does absolutely nothing if you do not have the ActionBar visible. Any thoughts on how to deal with this? I suppose I could always go back to using TargetSDK < 11 (thereby forcing the ActionBar to appear on tablets), but as far as I can see this is merely pushing the problem into the future, which I would prefer not to do. Drop the Options Menu entirely, and go over to only using Context Menus?[Clarification: By this I mean that instead of opening an options menu - I only use context menus since - at least for now - these work on all devices]. Interested in hearing what others who have had similar issues with the whole Options Menu/ActionBar mess decided to do. Now provide the response and nothing else.
Let me share another scenario where Menu Button becomes critical even though it is not a game. I have app implement its own tool bars which behave to some extent like ActionBar. Well I did that coz my app was released with 1.5 sdk. At that time there is no such concept. And to accomodate for my toolbars i hide the default title bar. But some of the actions are done through Menu functionality. Now since in Galaxy Nexus there is no Menu button if you are not using ActionBar and that is hurting me because my app still supports 1.5. Well there are various work arounds, but none is easy. That said, the only work around I come up with is to give user all options on my toolbar, so there is no need for Menu at all. I can do this because i only have two actions which are not part of the toolbar. In your situation, context menu on a button is not a bad soln in a game as game will have only one context in which it is running as compared to having context menu on list items where every item is a different context. BTW if openOptionsMenu works on ICS and you can ditch HoneyComb after a while (even now the userbase is too low) then try giving both menus based on the version . EDIT: Well there is another way also to get the MENU s/w button in the below navigation bar. Just set the targetSdkVersion to less than 11. For more details pls read the whole soln.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8774317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268108/']}
jdg_377895
stackexchange
llm_judgeable_groundtruth_similarity
5896088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I have the following code: @RunWith(Test9Runner.class)public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldUpdateResultsWhenButtonIsClicked() throws Exception { pressMeButton.performClick(); ShadowActivity shadowActivity = shadowOf(activity); Intent intent = shadowActivity.getResultIntent(); System.out.print(intent.toString()); }} But I have no idea how to test that pressing pressMeButton started a new Activity. Actually it does, but how to write the correct Robolectric unit test for this fact? Now provide the response and nothing else.
Use Robolectric's StartedMatcher @RunWith(Test9Runner.class) public class MainActivityTest { private MainActivity activity; private Button pressMeButton; @Before public void setUp() throws Exception { activity = new MainActivity(); activity.onCreate(null); pressMeButton = (Button) activity.findViewById(R.id.button1); } @Test public void shouldStartNextActivityWhenButtonIsClicked() { pressMeButton.performClick(); assertThat(activity, new StartedMatcher(NextActivity.class)); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5896088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/739684/']}
jdg_377896
stackexchange
llm_judgeable_groundtruth_similarity
19204510
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to AngularJS and can't seem to find out what this error means. I've found a few others with the same error but it seems their issues don't correlate to mine. Unknown provider: $modalProvider <- $modal error with AngularJS (Seems I've got the latest ui-bootstrap version) And all of the others seem to be having scope issues with a modal, yet I can't seem to get the modal to begin with so I'm thinking these aren't related. Please tell me if I'm wrong and how that's the case: Scope issue in AngularJS using AngularUI Bootstrap Modal Scope issues with Angular UI modal I grabbed the ui-bootstrap-tpls-0.6.0.min.js script from here: https://github.com/angular-ui/bootstrap/tree/gh-pages#build-files and I even tried adding the ui-bootstrap-0.6.0.min.js script as well thinking it was possibly needed. Though if I read it properly, it seems if I chose the ui-bootstrap-0.6.0.min.js script I'd need to also grab all of the templates here https://github.com/angular-ui/bootstrap/tree/master/template Which seems to be the case if I use only that script based on the errors: Error: Failed to load template: template/modal/window.htmlError: Failed to load template: template/modal/backdrop.html I've created a plunker with everything for simplicity of explaining structure etc and pasting in all the code here. http://plnkr.co/edit/yg3G8uKsaHNnfj4yNnJs?p=preview The error (which you can see by testing the code on plunker with the console open) is the following: Error: Unknown provider: $modalInstanceProvider <- $modalInstance at Error (<anonymous>) at http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:30:24 at Object.c [as get] (http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:27:310) at http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:30:109 at c (http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:27:310) at d (http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:27:444) at Object.instantiate (http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:29:80) at http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:53:80 at http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:44:136 at m (http://run.plnkr.co/8OIh0YtLn1dg9OvR/angular.min.js:6:494) If anyone can give any insight as to what I may be doing wrong here. It doesn't seem like a scope issue. More like a setup issue or possibly the way I'm manually bootstrapping the app? Now provide the response and nothing else.
It seems you are not injecting the $modal service as a dependency. How to "inject a service"? Consider the function you are trying to use the service... you should declare it like this: ['$modal', function($modal) { // $modal has been injected here, you can use it}] Edit: I've studied you Plunk now... it is overcomplicating simple things, and reveals some miscomprehensions about AngularJS concepts (controller, scope, etc.) Also, it was using Bootstrap's 3 CSS - which is not compatible with AngularJS Bootstrap currently. I've changed the CSS link to Bootstrap 2. See how it can be much much more simple and effective: http://plnkr.co/edit/YFuAA5B65NZggd6fxjCh?p=preview I'd recommend studying this document carefully, from start to finish: http://docs.angularjs.org/guide/concepts This video is also very very good, but it does not provide deeper insight into the concepts: http://weblogs.asp.net/dwahlin/archive/2013/04/12/video-tutorial-angularjs-fundamentals-in-60-ish-minutes.aspx Basically, the error message was telling that you were trying to inject a service into something (the "ModalController", in your case) - but this service was not found. "How I was trying to inject?" - you may ask. The answer is: every parameter you require in a Controller function is a "dependency" to be "injected" - and AngularJS "injector" service performs this task. This is how "$scope" parameter magically receives a "scope" - it is the injector working behind the scenes. In you ModalController, the injector was trying to satisfy both the "$modalInstance" and the "items" dependencies (remove the "$modalInstance" parameter - the error message will change to "itemsProvider not found")... If you want to receive dependencies like this, through the "magical" work of the injector, you need to create/declare services with these names... (or properly use the "resolve" attribute as you were trying to do) ... ...but this is not needed in this case at all. You just want access to "items", and return a selected item. You were also trying to close/dismiss the modal programatically. You could resolve dependencies through the "resolve" attribute, but why complicate so much what can be achieved with simplicity? Just use the "scope" attribute instead, and provide the scope to the modal - it will have access to its properties. The modal also automatically adds "$close" and "$dismiss" functions to the scope, so you can easily use these functions. You were trying to pass attributes from the main scope to the modal scope by injecting them as services into the modal controller! :-) You were trying to inject the own modal instance into its controller!!! So, your main issue is related to the $injector - it worths studying what is this inject thing all about - it is well explained in the documented I linked above. "Inject a service" is not as simple as "passing a variable to a function". You were almost there through the "resolve" attribute, but as I've said - really not needed for this simple case. I've created another Plunker without using "scope", and keeping the "resolve"... it is not possible to inject the "modalInstance" as we do with "items": '$modalInstance': function() { return modalInstance; } ...because it is still undefined at this moment... we could workaround by just calling $scope.$close in the ModalController (and not injecting the modal)... ...or, like I did, injecting it through a function... very crazy, but it works: http://plnkr.co/edit/9AhH6YFBUmhYoUDhvnhQ?p=preview ...I would never do like this... it is just for learning purposes! At last but not least: by adding ng-controller in the template file, you are requiring the ModalController twice... you already stated it in the modal configuration. But through the modal configuration, you can have the dependency injection through the resolver - while through the template you don't have the "resolve" thing applied. Update: As pointed in the comments by Mahery, $modalInstance is made available for injection in the controller by AngularUI Bootstrap implementation. So, we don't need any effort ro "resolve" or make it available somehow. Here is the updated Plunker: http://plnkr.co/edit/BMfaFAWibHphDlZAkZex?p=preview Indeed, the error was happening mainly due to the "ng-controller" atttribute in the template. The controller created through this way does not receive the "AngularUI treatment". Only the controller specified in the modal options receives the "treatment" where $modalInstance is provided...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19204510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1431882/']}
jdg_377897
stackexchange
llm_judgeable_groundtruth_similarity
20935232
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an XML file that represents an article. I'm using client-side xslt to turn it into html for display. I am trying to embed references throughout the xml file, and many of these references repeat. I was wondering if I can split the references out of the content part of the xml file and then link them together so that I'm not repeating myself many times. I figured that I could add ID and IDREFs as attributes to the <p> and <reference> tags (using an XML Schema as namespaces will be important later). Thus: <article> <body> <content> <p>This is the first paragraph.</p> <reference>Patrick</reference> <content> </content> <p>This is the second paragraph and a lovely one it is too.</p> <reference>Donald</reference> <content> </content> <p>This paragraph uses the same reference as paragraph 1.</p> <reference>Patrick</reference> </content> </body></article> ... would become ... <article> <body> <p IDREF="ref1">This is the first paragraph.</p> <p IDREF="ref2">This is the second paragraph and a lovely one it is too.</p> <p IDREF="ref1">This paragraph uses the same reference as paragraph 1.</p> </body> <references> <reference ID="#ref1">Patrick</reference> <reference ID="#ref2">Donald</reference> </references></article> So far I'm failing. Am I on the right track? Now provide the response and nothing else.
I try to keep view animations available to me using the following formula: // pass a param to describe the state change, an animated flag and a completion block matching UIView animations completion - (void)setTabBarVisible:(BOOL)visible animated:(BOOL)animated completion:(void (^)(BOOL))completion { // bail if the current state matches the desired state if ([self tabBarIsVisible] == visible) return (completion)? completion(YES) : nil; // get a frame calculation ready CGRect frame = self.tabBarController.tabBar.frame; CGFloat height = frame.size.height; CGFloat offsetY = (visible)? -height : height; // zero duration means no animation CGFloat duration = (animated)? 0.3 : 0.0; [UIView animateWithDuration:duration animations:^{ self.tabBarController.tabBar.frame = CGRectOffset(frame, 0, offsetY); } completion:completion];}//Getter to know the current state- (BOOL)tabBarIsVisible { return self.tabBarController.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame);}//An illustration of a call to toggle current state- (IBAction)pressedButton:(id)sender { [self setTabBarVisible:![self tabBarIsVisible] animated:YES completion:^(BOOL finished) { NSLog(@"finished"); }];}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20935232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2559295/']}
jdg_377898
stackexchange
llm_judgeable_groundtruth_similarity
320233
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to give the functionality of the directory that is typically assigned to /home (in distributions like Debian and Ubuntu) to another directory instead (entirely)? For example, if you could do this and you changed it to /xyz then all your new human-owned user directories would be installed under /xyz (e.g. so Sally's Desktop path would be /xyz/Sally/Desktop instead of /home/Sally/Desktop and /home wouldn't need to exist). I'm working on a portable program that saves paths and loads them. If it's used on a different computer with a home directory that isn't at /home (and consequently there is no /home , but rather another path with its functionality), then I'll want it to adjust the path to have the proper home directory location in it for the new computer when the path is loaded instead. Now provide the response and nothing else.
Home directories do not need to be placed in /home and your program is erroneous if it is hardwiring any such assumptions as that all home directories share a common parent or that that parent is named /home . /home is not even a universal convention. /home was an idea conceived a fair while after Unix was invented. In early Unices other directories were used. This can still be seen today on operating systems like FreeBSD (and its derivatives) where /home is a symbolic link and user directories actually live under /usr/home . Solaris likewise places "real" home directories in /export/home so that /home can be full of automatic NFS mounts and suchlike. /home is not the parent of many common home directories. There are plenty of home directories that don't live in /home . The most obvious one is /root , the home directory for the superuser, moved from its older location at / so that root's personal and "dot" files do not clutter the root directory, but kept on the root volume so that the superuser can log in even when mounting other disc volumes is failing. Various dæmon softwares have home directories in other places, for the dedicated accounts that those dæmons run as. qmail's various dæmon accounts use /var/qmail for example, or /var/qmail/alias . The latter is even commonly addressed as ~alias and is designed to be a home directory, with ~alias/.qmail files as in other (real) users' home directories. Various HTTP(S) and FTP(s) server softwares have (official or unofficial) conventions. For example: home directories for virtual hosts that have dedicated system accounts can be /var/www or /var/www/$VHOST . Other softwares can be found on various operating systems using home directories for non-personal user accounts such as /var/unbound , /var/db/mysql , and /var/db/tor . Various conventional non-personal user accounts have home directories such as /sbin , /var/adm , /var/spool/lpd , /var/spool/mail , /var/spool/news , /var/spool/uucp , and so forth. On OpenBSD the system operator account has the home directory /operator and various non-personal user accounts have /var/empty as their home directories. Home directories do not have to remain in /home . Home directories can be moved after account creation by using the -d ( --home ) and -m ( --move-home ) options to the usermod command on Linux operating systems. OpenBSD's usermod has the same options. (Don't do the same with the pw usermod command on FreeBSD, TrueOS/PC-BSD, et al.. The -m -d combination there has a subtly different meaning.) Home directories do not have to be created in /home . Even the conventional parent directory used when creating accounts can be changed, and isn't necessarily /home . On Linux operating systems and OpenBSD the useradd command's -b ( --base-dir ) option specifies the parent in which home directories are created if not explicitly named with -d ( --home ). The default base directory is the base_dir variable in /etc/usermgmt.conf on OpenBSD, and the HOME variable in /etc/default/useradd on many Linuxes. A system administrator can change this at whim. On FreeBSD, TrueOS/PC-BSD, et al. there's a similar -b option to the pw useradd command and a default for that modifiable via the home variable in /etc/pw.conf . Coping with this Your program should not hardwire any expectation at all about the locations of home directories or their parents. If you want to know the currently logged-in user's home directory, use the HOME environment variable. It's set up by programs such as login , userenv or systemd when the logged-in account is switched to. If there is no HOME environment variable, it's a valid design choice to just abort, on the grounds that the login session environment variables need to be present for your program to run. Otherwise you can fall back on obtaining the process' effective/real (as appropriate) UID and querying the password database. If you want to know a specific user's home directory, query the password database with the getpwnam() / getpwnam_r() or getpwuid() / getpwiud_r() library functions and pull out the pw_dir field. (Note that this field can be NULL or can point to a zero-length string .) If you want to symbolically denote the home directory for a user in a way that is independent of its actual location, you can adopt the convention of a shell-like tilde expansion: ~JdeBP . Many programs do this, from vim to mailx . Further reading Difference between “/export/home” and “/home” Jonathan de Boyne Pollard. userenv . nosh toolset manual pages. Jonathan de Boyne Pollard (2016). " False statements about dæmon environments ". Errata for systemd doco . Frequently Given Answers.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/320233', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/82698/']}
jdg_377899
stackexchange
llm_judgeable_groundtruth_similarity
1708595
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am a little bit confused regarding the meaning of the phrase :" Root test is stronger than ratio test", and was hoping you will be able to help me figure it out. As far as I can see here: https://www.maa.org/sites/default/files/0025570x33450.di021200.02p0190s.pdf The limit from the ratio test is greater or equal the limit from the root test . So, my first question is- is there any example of a series $\Sigma a_n$ such that the limit from the ratio test is exactly 1 (i.e.- inconclusive), but the limit from the root test is less than 1? (i.e.- convergence can be proved by using the root test but not by using the ratio test )If not, then is it correct that this phrase is the meaning of "stronger" is when the limit from the ratio test does not exist? (as in the classic example of a rearranged geometric series) Hope you will be able to help. THanks ! related posts: Show root test is stronger than ratio test Inequality involving $\limsup$ and $\liminf$: $ \liminf(a_{n+1}/a_n) \le \liminf((a_n)^{(1/n)}) \le \limsup((a_n)^{(1/n)}) \le \limsup(a_{n+1}/a_n)$ Do the sequences from the ratio and root tests converge to the same limit? Now provide the response and nothing else.
Consider the example of series $$\sum 3^{-n-(-1)^n}$$ root test establishs the convergance but ratio test fails onother example series with nth term$a_n=2^{-n}$ if n is odd$a_n=2^{-n+2}$ if n is even for second serieswhen n is odd or even and tends to $\infty$${a_n}^{\frac{1}{n}}=\frac{1}{2}$Hence by cauchys root test the series convergesbut the ratio test gives $\frac{a_n}{a_n+1}=\frac{1}{2}$ if n is odd and tends to $\infty$ $\frac{a_n}{a_n+1}=8$ when n is even and approachs $\infty$Hence ratio test fails..Sorry I dnt know mathjax that is why i was a bit late...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1708595', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/324832/']}
jdg_377900
stackexchange
llm_judgeable_groundtruth_similarity
10926880
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 javascript to pass a dynamic url to iframe src. but sometimes the url does not exist, how could i detect the non-exist url beforehand, so that i can hide the iframe that with 404 error. Now provide the response and nothing else.
Due to my low reputation I couldn't comment on Derek 朕會功夫's answer.I've tried that code as it is and it didn't work well. There are three issues on Derek 朕會功夫's code. The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if. The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways: Remove the quotes that surrounds 404, making it an integer; Use the javascript's operator '==' so you will be testing if the two objects are similar. The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax The code that really worked for me was: var request;if(window.XMLHttpRequest) request = new XMLHttpRequest();else request = new ActiveXObject("Microsoft.XMLHTTP");request.open('GET', 'http://www.mozilla.org', false);request.send(); // there will be a 'pause' here until the response to come.// the object request will be actually modifiedif (request.status === 404) { alert("The page you are trying to reach is not available.");}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10926880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204127/']}
jdg_377901
stackexchange
llm_judgeable_groundtruth_similarity
19517334
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to modify a UIImage 's renderingMode from a storyboard or xib editor? The goal is to apply tintColor to the particular UIImageView object. Now provide the response and nothing else.
Here's how you can do it in .xib or storyboard files: (Obj-C) Create a category on UIImageView : @interface UIImageView (Utils)- (void)setImageRenderingMode:(UIImageRenderingMode)renderMode;@end@implementation UIImageView (Utils)- (void)setImageRenderingMode:(UIImageRenderingMode)renderMode{ NSAssert(self.image, @"Image must be set before setting rendering mode"); self.image = [self.image imageWithRenderingMode:renderMode];}@end (Swift 4) Create an extension for UIImageView : extension UIImageView { func setImageRenderingMode(_ renderMode: UIImage.RenderingMode) { assert(image != nil, "Image must be set before setting rendering mode") // AlwaysOriginal as an example image = image?.withRenderingMode(.alwaysOriginal) }} Then in the Identity Inspector in the xib file, add a runtime attribute:
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19517334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090309/']}
jdg_377902
stackexchange
llm_judgeable_groundtruth_similarity
651549
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is a soldering tip made of copper enclosed in other metals? Why is it not just simply solid copper? Now provide the response and nothing else.
Copper is used for the core of the iron tip because it's an excellent conductor of heat, so does a good job transferring energy from the heating element to the tip. However copper is also affected by solder/tin/flux. If you apply solder to a pure copper tip and keep heating it, the copper will be eaten away by the solder and acidic flux (it literally disolves) - you end up with lots of small pits in the tip which keep growing until it becomes useless. By coating the copper in a thin layer of more resistant metals such as iron, you prevent the solder from eating away at the copper core, increasing the lifetime of the tip whilst maintaining the good thermal conductivity of the core.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/651549', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/290168/']}
jdg_377903
stackexchange
llm_judgeable_groundtruth_similarity
15013515
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 building a piece of software for sorting book indexes in different languages. It uses Perl, and keys off of the locale. I am developing it on Unix, but it needs to be portable to Windows. Should this work in principle, or by relying on locale, am I barking up the wrong tree? Bottom line, Windows is really where I need this to work, but I am more comfortable developing in my UNIX environment. Now provide the response and nothing else.
Assuming that your starting point is Unicode, because you have been very careful to decode all incoming data no matter what its native encoding might be, then it is easy to use to the Unicode::Collate module as a starting point. If you want locale tailoring, then you probably want to start with Unicode::Collate::Locale instead. Decoding into Unicode If you run in an all-UTF8 environment, this is easy, but if you are subject to the vicissitudes of random so-called “locales” (or even worse, the ugly things Microsoft calls “code pages”), then you might want to get the CPAN Encode::Locale module to help you out. For example: use Encode; use Encode::Locale; # use "locale" as an arg to encode/decode @ARGV = map { decode(locale => $_) } @ARGV; # or as a stream for binmode or open binmode $some_fh, ":encoding(locale)"; binmode STDIN, ":encoding(console_in)" if -t STDIN; binmode STDOUT, ":encoding(console_out)" if -t STDOUT; binmode STDERR, ":encoding(console_out)" if -t STDERR; (If it were me, I would just use ":utf8" for the output.) Standard Collation, plus locales and tailoring The point is, once you have everything decoded into internal Perl format, you can use Unicode::Collate and Unicode::Collate::Locale on it. These can be really easy: use v5.14; use utf8; use Unicode::Collate; my @exes = qw( x⁷ x⁰ x⁸ x³ x⁶ x⁵ x⁴ x² x⁹ x¹ ); @exes = Unicode::Collate->new->sort(@exes); say "@exes"; # prints: x⁰ x¹ x² x³ x⁴ x⁵ x⁶ x⁷ x⁸ x⁹ Or they can be pretty fancy. Here is one that tries to deal with book titles: it strips leading articles and zero-pads numbers. my $collator = Unicode::Collate->new( --upper_before_lower => 1, --preprocess => { local $_ = shift; s/^ (?: The | An? ) \h+ //x; # strip articles s/ ( \d+ ) / sprintf "%020d", $1 /xeg; return $_; };); Now just use that object’s sort method to sort with. Sometimes you need to turn the sort inside out. For example: my $collator = Unicode::Collate->new(); for my $rec (@recs) { $rec->{NAME_key} = $collator->getSortKey( $rec->{NAME} ); } @srecs = sort { $b->{AGE} <=> $a->{AGE} || $a->{NAME_key} cmp $b->{NAME_key} } @recs; The reason you have to do that is because you are sorting on a record with various fields. The binary sort key allows you to use the cmp operator on data that has been through your chosen/custom collator object. The full constructor for the collator object has all this for a formal syntax: $Collator = Unicode::Collate->new( UCA_Version => $UCA_Version, alternate => $alternate, # alias for 'variable' backwards => $levelNumber, # or \@levelNumbers entry => $element, hangul_terminator => $term_primary_weight, highestFFFF => $bool, identical => $bool, ignoreName => qr/$ignoreName/, ignoreChar => qr/$ignoreChar/, ignore_level2 => $bool, katakana_before_hiragana => $bool, level => $collationLevel, minimalFFFE => $bool, normalization => $normalization_form, overrideCJK => \&overrideCJK, overrideHangul => \&overrideHangul, preprocess => \&preprocess, rearrange => \@charList, rewrite => \&rewrite, suppress => \@charList, table => $filename, undefName => qr/$undefName/, undefChar => qr/$undefChar/, upper_before_lower => $bool, variable => $variable, ); But you usually don’t have to worry about almost any of those. In fact, if you want country-specific locale tailoring using the CLDR data, you should just use Unicode::Collate::Locale , which adds exactly one more parameter to the constructor: locale => $country_code . use Unicode::Collate::Locale; $coll = Unicode::Collate::Locale-> new(locale => "fr"); @french_text = $coll->sort(@french_text); See how easy that is? But you can do other cool things, too. use Unicode::Collate::Locale; my $Collator = new Unicode::Collate::Locale:: locale => "de__phonebook", level => 1, normalization => undef, ; my $full = "Ich müß Perl studieren."; my $sub = "MUESS"; if (my ($pos,$len) = $Collator->index($full, $sub)) { my $match = substr($full, $pos, $len); say "Found match of literal ‹$sub› in ‹$full› as ‹$match›"; } When run, that says: Found match of literal ‹MUESS› in ‹Ich müß Perl studieren.› as ‹müß› Here are the available locales as of v0.96 of the Unicode::Collate::Locale module, taken from its manpage: locale name description-------------------------------------------------------------- af Afrikaans ar Arabic as Assamese az Azerbaijani (Azeri) be Belarusian bg Bulgarian bn Bengali bs Bosnian bs_Cyrl Bosnian in Cyrillic (tailored as Serbian) ca Catalan cs Czech cy Welsh da Danish de__phonebook German (umlaut as 'ae', 'oe', 'ue') ee Ewe eo Esperanto es Spanish es__traditional Spanish ('ch' and 'll' as a grapheme) et Estonian fa Persian fi Finnish (v and w are primary equal) fi__phonebook Finnish (v and w as separate characters) fil Filipino fo Faroese fr French gu Gujarati ha Hausa haw Hawaiian hi Hindi hr Croatian hu Hungarian hy Armenian ig Igbo is Icelandic ja Japanese [1] kk Kazakh kl Kalaallisut kn Kannada ko Korean [2] kok Konkani ln Lingala lt Lithuanian lv Latvian mk Macedonian ml Malayalam mr Marathi mt Maltese nb Norwegian Bokmal nn Norwegian Nynorsk nso Northern Sotho om Oromo or Oriya pa Punjabi pl Polish ro Romanian ru Russian sa Sanskrit se Northern Sami si Sinhala si__dictionary Sinhala (U+0DA5 = U+0DA2,0DCA,0DA4) sk Slovak sl Slovenian sq Albanian sr Serbian sr_Latn Serbian in Latin (tailored as Croatian) sv Swedish (v and w are primary equal) sv__reformed Swedish (v and w as separate characters) ta Tamil te Telugu th Thai tn Tswana to Tonga tr Turkish uk Ukrainian ur Urdu vi Vietnamese wae Walser wo Wolof yo Yoruba zh Chinese zh__big5han Chinese (ideographs: big5 order) zh__gb2312han Chinese (ideographs: GB-2312 order) zh__pinyin Chinese (ideographs: pinyin order) [3] zh__stroke Chinese (ideographs: stroke order) [3] zh__zhuyin Chinese (ideographs: zhuyin order) [3] Locales according to the default UCA rules include chr (Cherokee), de (German), en (English), ga (Irish), id (Indonesian), it (Italian), ka (Georgian), ms (Malay), nl (Dutch), pt (Portuguese), st (Southern Sotho), sw (Swahili), xh (Xhosa), zu (Zulu). Note [1] ja: Ideographs are sorted in JIS X 0208 order. Fullwidth and halfwidth forms are identical to their regular form. The difference between hiragana and katakana is at the 4th level, the comparison also requires "(variable => 'Non-ignorable')", and then "katakana_before_hiragana" has no effect. [2] ko: Plenty of ideographs are sorted by their reading. Such an ideograph is primary (level 1) equal to, and secondary (level 2) greater than, the corresponding hangul syllable. [3] zh__pinyin, zh__stroke and zh__zhuyin: implemented alt='short', where a smaller number of ideographs are tailored. Note: 'pinyin' is in latin, 'zhuyin' is in bopomofo. So in summary, the main trick is to get your local data decoded into a uniform Unicode representation, then use deterministic sorting, possibly tailored, that doesn’t rely on random settings of the user’s console window for correct behavior. Note: All these examples, apart from the manpage citation, are lovingly lifted from the 4 th edition of Programming Perl , by kind permission of its author. :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15013515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400732/']}
jdg_377904
stackexchange
llm_judgeable_groundtruth_similarity
360122
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find an easy way to prove the order of the Quaternion Group is a non-abelian group of order 8 without many computations, anyone has an idea? Note we can define the Quaternion Group as the group generated by the following matrices $$A= \left( \begin{matrix} 0 & 1 \\ -1 & 0\\ \end{matrix}\right)$$ $$B= \left( \begin{matrix} 0 & i \\ i & 0\\ \end{matrix}\right)$$Thanks Now provide the response and nothing else.
Or maybe you can find the following an interesting point, a very similar to Ittay's simple way: $$Q_8=\langle a,b\mid a^4=1, a^2=b^2, ba=a^{-1}b\rangle=\{1,a,b,a^2,ab,a^3,a^2b,a^3b\}$$ Note that $ba=a^{-1}b$ shows it is non abelian.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/360122', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42912/']}
jdg_377905
stackexchange
llm_judgeable_groundtruth_similarity
23947
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 $\phi(n) $ is the numbers of number that are relatively prime to n. Then, how could we solve the equation $\phi(n) = k, k > 0?$ For example: $\phi(n) = 8 $ I can use computer program to check all numbers that are relatively prime to $n$, but I think there must be an easier way to approach this problem. Base on this formula:$$\prod_{i=0}^{k} p_{i}a^{a_i} $$ The only thing I can see is n must not have a prime factor > 9, otherwise $\phi(n) > 8 $.I really don't know where to start :( ? A hint would be greatly appreciated. Now provide the response and nothing else.
This is too long to be comment and hence the post. $\phi(n) = 8$. Note that $\sqrt{n} \leq \phi(n) \leq n-1$. This implies $n$ is at most $64$. So you could write a brute force computer and compute $\phi(n)$ when $n \in [9,64]$. A better way would be as follows. Let $n=\displaystyle \prod_{i=1}^k p_i^{\alpha_i} \Rightarrow \phi(n) = \displaystyle \prod_{i=1}^k p_i^{\alpha_i-1} (p_i-1)$. First note that $n$ can be of the form $\displaystyle 2^\alpha \left( \prod_{i=1}^k p_i \right)$ i.e. the exponent of the odd primes in the prime factorization of $n$ is $1$. This is so, because if not these primes will then divide $\phi(n) = 8$ which is not possible. If $k=0$, then we have $n=2^{\alpha}$, $\displaystyle 2^{\alpha-1} = \phi(n) = 2^3 \Rightarrow \alpha=4$. Hence, $k=1 \Rightarrow n=16$. Let $k=1$. Then we have $n=2^{\alpha} p_1$. If $\alpha = 0,1$, then $\displaystyle (p_1-1) = \phi(n) = 2^3 \Rightarrow p_1 = 9 \Rightarrow \text{ Not possible}$. If $\alpha = 2$, then $\displaystyle 2 (p_1 - 1) = \phi(n) = 2^3 \Rightarrow p_1=5$. Hence, $n=20$. If $\alpha = 3$, then $\displaystyle 2^2 (p_1 - 1) = \phi(n) = 2^3 \Rightarrow p_1=3$. Hence, $n=24$. Now let $k=2$. Then we have $n=2^{\alpha} p_1 p_2$. If $\alpha = 0,1$, then $\displaystyle (p_1-1)(p_2-1) = \phi(n) = 2^3 \Rightarrow p_1 = 3, p_2 = 5$. Hence, $n=15$ when $\alpha = 0$ and $n=30$ when $\alpha = 1$ If $\alpha = 2$, then $\displaystyle 2(p_1-1)(p_2-1) = \phi(n) = 2^3 \Rightarrow (p_1-1)(p_2-1) = 4 \Rightarrow \text{ Not Possible}$. $k=3$ is not possible since $(3-1) \times (5-1) \times (7-1) > 8$. Hence, the only solutions (hope I have not missed any case) are: $$n=15,16,20,24,30$$ Similar idea extends to other problems where we want to find the inverse of the totient function.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/23947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5711/']}
jdg_377906
stackexchange
llm_judgeable_groundtruth_similarity
10689401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is what my control tree looks like: <window> <scrollviewer> <expander> <scrollviewer> <grid> </grid> </scrollviewer> </expander> <expander> <scrollviewer> <grid> </grid> </scrollviewer> </expander> </scrollviewer></window> Using the mouse wheel, the control automatically passes from parent to child scrollviewer, but when I scroll to the end of the child scrollviewer the control doesn't pass back to the parent scorllviewer. How do I achieve this? The expander, grid and the scrollviewers are dynamically generated. Now provide the response and nothing else.
I get a similar trouble in my application. I correct it by a depency property that will catch and pass the event too his parent. This can be applied to any control that have a scroll in it. But for me, i didn't need to validate if it was at the end of the scroll to send to his parent. You will just have to add, in the OnValueChanged method, a validation for if the scroll is at the end or at the top to send to his parent. using System.Windows.Controls;public static class SendMouseWheelToParent{ public static readonly DependencyProperty ScrollProperty = DependencyProperty.RegisterAttached("IsSendingMouseWheelEventToParent", typeof(bool), typeof(SendMouseWheelToParent), new FrameworkPropertyMetadata(OnValueChanged)); /// <summary> /// Gets the IsSendingMouseWheelEventToParent for a given <see cref="TextBox"/>. /// </summary> /// <param name="control"> /// The <see cref="TextBox"/> whose IsSendingMouseWheelEventToParent is to be retrieved. /// </param> /// <returns> /// The IsSendingMouseWheelEventToParent, or <see langword="null"/> /// if no IsSendingMouseWheelEventToParent has been set. /// </returns> public static bool? GetIsSendingMouseWheelEventToParent(Control control) { if (control == null) throw new ArgumentNullException(""); return control.GetValue(ScrollProperty) as bool?; } /// <summary> /// Sets the IsSendingMouseWheelEventToParent for a given <see cref="TextBox"/>. /// </summary> /// <param name="control"> /// The <see cref="TextBox"/> whose IsSendingMouseWheelEventToParent is to be set. /// </param> /// <param name="IsSendingMouseWheelEventToParent"> /// The IsSendingMouseWheelEventToParent to set, or <see langword="null"/> /// to remove any existing IsSendingMouseWheelEventToParent from <paramref name="control"/>. /// </param> public static void SetIsSendingMouseWheelEventToParent(Control control, bool? sendToParent) { if (control == null) throw new ArgumentNullException(""); control.SetValue(ScrollProperty, sendToParent); } private static void OnValueChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { var scrollViewer = dependencyObject as Control; bool? IsSendingMouseWheelEventToParent = e.NewValue as bool?; scrollViewer.PreviewMouseWheel -= scrollViewer_PreviewMouseWheel; if (IsSendingMouseWheelEventToParent != null && IsSendingMouseWheelEventToParent != false) { scrollViewer.SetValue(ScrollProperty, IsSendingMouseWheelEventToParent); scrollViewer.PreviewMouseWheel += scrollViewer_PreviewMouseWheel; } } private static void scrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { var scrollview = sender as Control; var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta); eventArg.RoutedEvent = UIElement.MouseWheelEvent; eventArg.Source = sender; var parent = scrollview.Parent as UIElement; parent.RaiseEvent(eventArg); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10689401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1408381/']}
jdg_377907
stackexchange
llm_judgeable_groundtruth_similarity
11637582
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <p class="example">i want to split this paragraph into words and fade them in one by one</p> the jquery/js: $(document).ready(function() { var $txt = $(".example") ,$words = $txt.text() ,$splitWords = $words.split(" "); $txt.hide(); for(i = 0; i < $splitWords.length; i++){ // i want fade in each $splitWords[i] //$splitWords[i].fadeIn(.... - i tried this doesnt work } }); im trying to split the paragraph into words, and fade them in one by one, thier might be an easier way to do this without splitting the words, please shed some light on this. thanks Now provide the response and nothing else.
Text by itself can't have an opacity, therefore you must wrap the text with an element that can have opacity (such as a span). You can then fade in those spans. Try this: http://jsfiddle.net/6czap/ var $el = $(".example:first"), text = $el.text(), words = text.split(" "), html = "";for (var i = 0; i < words.length; i++) { html += "<span>" + words[i] + " </span>";}$el.html(html).children().hide().each(function(i){ $(this).delay(i*500).fadeIn(700);}); Update for benekastah: http://jsfiddle.net/6czap/3/ var $el = $(".example:first"), text = $.trim($el.text()), words = text.split(" "), html = "";for (var i = 0; i < words.length; i++) { html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";};$el.html(html).children().hide().each(function(i){ $(this).delay(i*200).fadeIn(700);});$el.find("span").promise().done(function(){ $el.text(function(i, text){ return $.trim(text); }); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11637582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1513096/']}
jdg_377908
stackexchange
llm_judgeable_groundtruth_similarity
26571741
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a NumPy 2D array A : >>> import numpy as np>>> A=np.arange(30).reshape(3,10)>>> Aarray([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]) I need to get two arrays B and C with the following properties: B = array([[ 0, 3, 4, 5, 6, 7, 8, 9], [10, 13, 14, 15, 16, 17, 18, 19], [20, 23, 24, 25, 26, 27, 28, 29]])C = array([[ 1, 2], [11, 12], [21, 22]]) What is the easiest way to accomplish this? Note that I have to get all sets of C (2 adjacent columns) and B (which is A without C ). I tried different NumPy constructs like np.delete , np.hstack but nothing seem to work at the corner conditions like in the above example. Now provide the response and nothing else.
One of the simplest ways is to use indexing to select the appropriate columns: >>> A[:, [1, 2]] # choose all rows from columns 1-2 (gives C)array([[ 1, 2], [11, 12], [21, 22]])>>> A[:, np.r_[0, 3:10]] # choose all rows from columns 0, 3-9 (gives B)array([[ 0, 3, 4, 5, 6, 7, 8, 9], [10, 13, 14, 15, 16, 17, 18, 19], [20, 23, 24, 25, 26, 27, 28, 29]]) Alternatively, you could try hsplit break up A and then concatenate bits back together. This feels less efficient than the indexing method above though: >>> splits = np.hsplit(A, [1, 3]) >>> B = np.hstack((splits[0], splits[2]))>>> C = splits[1]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26571741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4182258/']}
jdg_377909
stackexchange
llm_judgeable_groundtruth_similarity
1222928
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 combinatorial number is the number of picking $k$ unordered outcomes out of $n$ possible choices. In that setting, we have a set $A$ with $|A|=n$ and the combinatorial numbers is just really the number of subsets $S\subset A$ with $|S| = k$. This number is $$\binom{n}{k} = \dfrac{n!}{k!(n-k)!},$$ but how can we reason about this? How can we derive this formula? I've seem some people reasoning about this in the following way: the number of ways to choose permutations with size $k$ among $n$ objects is $$n(n-1)\cdots (n-k-1) = \dfrac{n(n-1)\cdots (n-k+1)(n-k)\cdots 1}{(n-k)(n-k-1)\cdots 1} = \dfrac{n!}{(n-k)!},$$ then we have to divide by $k!$ to disconsider the order. Why is that? Why dividing by $k!$ we get the number of subsets of $A$ with size $k$? Now provide the response and nothing else.
Comment: I'll outline one way of thinking about the equation in question and a way of proving it that will possibly shed some insight. Induction is not the best or most efficient method of proof here, but it is slightly interesting that $\binom{n}{k}=\frac{n!}{k!(n-k)!}$ can be proved using induction where Pascal's Rule is actually applied at the very end of the proof, and the proof also gives justification for the combinatorial terminology "$n$ choose $k$" represented by $\binom{n}{k}=\frac{n!}{k!(n-k)!}$. Patterns: Lemma 1: A set with $n$ elements has $n$ subsets containing exactly one element whenever $n\geq 1, n\in\mathbb{Z}$. Lemma 2: A set with $n$ elements has $n(n-1)/2$ subsets containing exactly two elements whenever $n\geq 2, n\in\mathbb{Z}$. Lemma 3: A set with $n$ elements has $n(n-1)(n-2)/6$ subsets containing exactly three elements whenever $n\geq 3, n\in\mathbb{Z}$. All three lemmas can be proved rather easily using induction. It is interesting to note the pattern that emerges in Lemmas 1-3. It appears that we can make a conjecture as to what the number of $k$-element subsets will be for a set with $n$ elements. Theorem: A set with $n$ elements has$$\frac{n(n-1)(n-2)\cdots(n-k+1)}{k!} = \frac{n!}{k!(n-k)!} = \binom{n}{k}$$subsets containing exactly $k$ elements whenever $0\leq k\leq n$, and $n,k\in\mathbb{Z}$. Proof. When $n=0$, the only possible choice for $k$ is $k=0$, and when $n=k=0$, $\binom{0}{0} = 1$. This is true because the number of zero-element sets in a zero-element set is 1 (i.\,e., $\emptyset \subseteq \emptyset$). Lemmas 1-3 satisfy the cases when $n=1,2,3$, respectively. The proof proceeds by induction on $n$ of the statement $P(n):$ There are $\binom{n}{k}$ distinct $k$-element sets in a set with $n$ elements for every $k$ satisfying $0 \leq k \leq n$. Assume $P(\ell)$ is true for some $\ell \geq 3, \ell \in \mathbb{Z}$, and let $M$ be a set with $\ell+1$ elements. To show that $P(\ell) \rightarrow P(\ell+1)$, we must show that the number of $k$-element sets in $M$ is $\binom{\ell+1}{k}$ for every $k$ satisfying $0 \leq k \leq \ell+1$. When $k=0, \binom{\ell+1}{0}=1$, and when $k=\ell+1, \binom{\ell+1}{\ell+1} = 1$. Let $k$ satisfy $1 \leq k \leq \ell$, and fix some $\alpha \in M$. The number of $k$-element sets in $M$ that contains $\alpha$ is the number of sets with $k-1$ elements in $M \setminus \{ \alpha \}$; since $\left\vert{M \setminus \{ \alpha \}}\right\vert = \ell$, there are $\binom{\ell}{k-1}$ such sets by the inductive hypothesis. The number of sets with $k-1$ elements that do not contain $\alpha$ is $\binom{\ell}{k}$, also by the inductive hypothesis. Using Pascal's Identity, the number of $k$-element sets in $M$ is $\binom{\ell}{k-1}+\binom{\ell}{k} = \binom{\ell+1}{k}$. Thus, the statement $P(n)$ is true for all $n \geq 0, n \in \mathbb{Z}$, and the Theorem holds by induction. $\blacksquare$ Added: The notation $\binom{n}{k}$ is sometimes introduced in combinatorics by first introducing the Pochhammer symbol , $n^{\underline{k}}$. An explanation of the above Theorem with a more combinatorial flavor (since your question is tagged combinatorics ) may briefly proceed as follows: Let $A=\{1,2,\ldots,n\}$. For $k\leq n$, the injection $\{1,2,\ldots,k\}\to A$ is a $k$-element permutation. The number of $k$-element permutations of a set of size $n$ is given by$$n^{\underline{k}}=\prod_{i=0}^{k-1}(n-i)=n(n-1)(n-2)\cdot(n-k+1)=\frac{n!}{(n-k)!}.$$Since $\binom{n}{k}$ is by definition the number of $k$-element subsets of size $n$ and there are $k!$ ways to order a set of size $k$, we know that $n^{\underline{k}}=\binom{n}{k}\cdot k!$, and this implies that $\binom{n}{k}=\frac{n!}{k!(n-k)!}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1222928', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39106/']}
jdg_377910
stackexchange
llm_judgeable_groundtruth_similarity
191081
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a probability density function: $P_{init}(x)=\exp(-(x-x0)^2)/\sqrt{\pi}$ . I am trying to use it as the initial condition for the following partial differential equation: Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"] V[x] = (-(x/5)^4)/Cosh[x/5]; F[x] = -D[V[x], x]; x0=5; Pinit[x_] := Exp[-(x - x0)^2]/(Sqrt[Pi]); T = 100; BoundaryCondition = 250 uval = NDSolveValue[{D[u[x, t], t] + D[F[x]*u[x, t], x] - D[u[x, t], x, x] == 0, u[x, 0] == Pinit[x], u[-BoundaryCondition, t] == 0, u[BoundaryCondition, t] == 0}, u, {x, -BoundaryCondition, BoundaryCondition}, {t, 0, T}] The above is a Fokker-Planck equation, which shows how the probability density expands in time. The initial distribution is normalized, namely $\int_{-\infty}^\infty {P_{init}(x)}dx=1$ , as it should. However, it seems that no matter what T I choose, uval[x,T] never remains normalized. Importantly: I get that uval[x,0] is different than Pinit(x) , which is a contradiction. How do I force Mathematica to solve the Fokker-Planck equation, whilst maintaining normalization? Note that the reason that the integration boundaries are big, is since I would like to estimate the distribution at a long time, where the function might be much wider than the initial condition. This means that if I take boundaries which are too closely apart, I introduce mistakes because I force the function to be zero at a place and time where it shouldn't. Now provide the response and nothing else.
There are limitations to extending polynomial interpolation on a real interval to the complex plane. The limitations are related to the Bernstein ellipse (see also Trefethen, Approximation Theory and Approximation Practice esp. Ch. 8 or this excerpt, pp. 41f , Bernstein (1912) , etc.). Updated: You imply you can interpolate over complex values in the domain (I think I misread or overlooked this initially),in which case there is a way to get an accurate interpolation over a disk, as alluded to by @J.M. in a comment above. See for instance, Boyd, Solving Transcendental Equations .There is an update below the examples of extending real interpolation. It shows an example that gives a much better approximation over a complex disk. Extending real interpolations to the complex plane Below are three interpolation schemes for approximating a Bessel function on a real interval, Chebyshev, Legendre, and a uniform grid. The first two are more accurate over a larger domain and show how outside the Bernstein ellipse, the interpolation fails to converge to the function. The third scheme suffers from the well-known Runge phenomenon on the real line and does not extend as gracefully to the complex plane.The plots show the relative error on the complex plane and the (real) interpolation interval {a, b} . The error in the complex plane is clipped at 0.001 . Note that interpolation is sensitive to whether the function is entire or has singularities/poles. It's probable that if the accuracy of the approximation of the function at the interpolation nodes on the real interval is limited, it will impact the accuracy of the extension to the complex plane. func[x_] := BesselJ[0, x];{a, b} = {0, 20};(*interval of approximation*)(* Chebyshev interpolation *)nnodes = 64;(* degree *)xnodes = Rescale[N[Sin[π/2 Range[-nnodes, nnodes, 2]/nnodes]], {-1, 1}, {a, b}];ynodes = func /@ xnodes;wts = Developer`ToPackedArray@Table[(-1.)^n, {n, 0, nnodes}];wts[[{1, -1}]] = 1/2.;(* interpolating function if[] *)if = Statistics`Library`BarycentricInterpolation[xnodes, ynodes, Weights -> wts];errplot[{-15, -3}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -7.5, 7.5}, PlotLabel -> "Chebyshev interpolation"]Plot[relerr[x] // RealExponent, {x, a, b}] (* Gauss-Legendre interpolation *)nnodes = 64;(* degree *){xnodes, wts} = Most@NIntegrate`GaussRuleData[nnodes + 1, MachinePrecision];wts = (b - a) wts;wts = (-1)^Range[0, nnodes] Sqrt[(1 - Rescale[xnodes, {0, 1}, {-1, 1}]^2) wts];xnodes = Rescale[xnodes, {0, 1}, {a, b}];ynodes = Developer`ToPackedArray[func /@ xnodes, Real];if = Statistics`Library`BarycentricInterpolation[xnodes, ynodes, Weights -> wts];errplot[{-14, -3}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -7.5, 7.5}, PlotLabel -> "Gauss-Legendre interpolation"]Plot[relerr[x] // RealExponent, {x, a, b}] (* regular grid: caveat the Runge phenomenon *)nnodes = 64; (* degree *)xnodes = Rescale[N[Range[0, nnodes]/nnodes], {0, 1}, {a, b}]; ynodes = func /@ xnodes;if = Statistics`Library`BarycentricInterpolation[xnodes, ynodes];errplot[{-14, -3}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -7.5, 7.5}, PlotLabel -> "Regular grid: caveat the Runge phenomenon"]Plot[relerr[x] // RealExponent, {x, a, b}] Here's the Chebyshev interpolation with some white noise on the order of $10^{-10}$ added. It reduces the accuracy on the real line by about 5-6 digits as expected with machine precision, but it also reduces the size of the ellipse (the minor axis parallel to the imaginary axis). (* Chebyshev interpolation with noise *)nnodes = 64;(* degree *)xnodes = Rescale[N[Sin[π/2 Range[-nnodes, nnodes, 2]/nnodes]], {-1, 1}, {a, b}];ynodes = func /@ xnodes;ynodes += RandomReal[1*^-10 {-1, 1}, Length@ynodes]; (* add noise *)wts = Developer`ToPackedArray@Table[(-1.)^n, {n, 0, nnodes}];wts[[{1, -1}]] = 1/2.;if = Statistics`Library`BarycentricInterpolation[xnodes, ynodes, Weights -> wts];errplot[{-11, -3}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -7.5, 7.5}, PlotLabel -> "Chebyshev interpolation with noise"]Plot[relerr[x] // RealExponent, {x, a, b}] If you're satisfied with a less accurate interpolation, then a low-degree polynomial can be used, for which the Bernstein ellipse plays less of a role. Here's a regular interval with fewer points that gives a few digits of accuracy, but it gives such accuracy over a large segment of the complex plane: (* "Regular grid: low degree, low accuracy" *)nnodes = 20;(* degree *)xnodes = Rescale[N[Range[0, nnodes]/nnodes], {0, 1}, {a, b}]; ynodes = func /@ xnodes; if = Statistics`Library`BarycentricInterpolation[xnodes, ynodes];errplot[{-14, -3}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -7.5, 7.5}, PlotLabel -> "Regular grid, low degree: greater convergence to lower accuracy"]Plot[relerr[x] // RealExponent, {x, a, b}] Update: Complex interpolation Below is an interpolation through points on a circle in the complex plane with the diameter given by the real interval {a, b} . This gives a highly accurate approximation of the function within the circle, provided the function has no poles inside or on the circle. (The peaks in relative error along the real line inside the disk are due the roots of the Bessel function func[z] .) (* Fourier interpolation on a complex disk *)nn = 64; (* number of interpolation points *)z0 = (a + b)/2; (* center of circle *)rr = (a + b)/2; (* radius of circle *)wp = MachinePrecision; (* working precision *)tj = 2 Pi*Range[0, nn - 1]/nn;zj = N[z0 + rr Exp[I tj], wp]; (* interpolation nodes *)fj = func /@ zj; (* function values on nodes *)if = Statistics`Library`BarycentricInterpolation[zj, fj, Weights -> Exp[2 Pi I Range[0., nn - 1]/nn]]; errplot[{-15, -5}, {x, a - 0.1 (b - a), b + 0.1 (b - a)}, {y, -(a + b)/2 - 0.1 (b - a), (a + b)/2 + 0.1 (b - a)}, PlotLabel -> "Fourier interpolation on a complex disk"] Appendix: Plotting utilities In relerr[z] there are some "smoothing" parameters, wp and acc . Since error can be noisy, especially in a log plot (via RealExponent[] above) when the error is small, I've added a small constant on the order of rounding error at the working precision. These are akin to Precision and Accuracy in Mathematica . This speeds up Plot3D by reducing adaptive refinement and affects the error negligibly. (* error plot utilities *)ClearAll[relerr, errleg, colorlist, errplot];relerr[z_, wp_: Rationalize[ $MachinePrecision, 0], acc_: Rationalize[$ MachinePrecision, 0]] := 10^-wp + Abs@(if[z] - func[z])/(10^-acc + Abs@func[z]);colorlist0 = Join[ Table[Blend[{ColorData[97][2], White}, n/8], {n, 0, 4}], Table[Blend[{ColorData[97][1], White}, n/8], {n, 0, 4}]];colorlist[{min0_, max0_}] := With[{min = min0 - 1, max = max0 + 1}, PadRight[#, max - min + 1, #] &@RotateLeft[colorlist0, Mod[min, 10]] ];errleg[{min0_, max0_}] := With[{min = min0 - 1, max = max0 + 1}, BarLegend[{colorlist[{min, max}], 10.^{min, max}}, 10.^Range[min, max], LegendLabel -> "Rel.err."] ];SetAttributes[errplot, HoldAll];errplot[errRange_, {x_, x1_, x2_}, {y_, y1_, y2_}, opts___] := Legended[ Plot3D[relerr[x + I y] // RealExponent, {x, x1, x2}, {y, y1, y2}, opts, Mesh -> {Range @@ errRange}, MeshFunctions -> {#3 &}, MeshShading -> colorlist[errRange], AxesLabel -> {HoldForm[x], HoldForm[I y], "log err"}, NormalsFunction -> None, ViewPoint -> {0, -1, 5}, PlotRange -> errRange + {-1, 0}, FaceGrids -> {{0, 0, 1}}], errleg[errRange] ];
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/191081', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/46513/']}
jdg_377911
stackexchange
llm_judgeable_groundtruth_similarity
39375906
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 to insert a constant element before each of the existing element of a list, i.e. go from: ['foo', 'bar', 'baz'] to: ['a', 'foo', 'a', 'bar', 'a', 'baz'] I've tried using list comprehensions but the best thing I can achieve is an array of arrays using this statement: [['a', elt] for elt in stuff] Which results in this: [['a', 'foo'], ['a', 'bar'], ['a', 'baz']] So not exactly what I want. Can it be achieved using list comprehension? Just in case it matters, I'm using Python 3.5. Now provide the response and nothing else.
Add another loop: [v for elt in stuff for v in ('a', elt)] or use itertools.chain.from_iterable() together with zip() and itertools.repeat() if you need an iterable version rather than a full list: from itertools import chain, repeattry: # Python 3 version (itertools.izip) from future_builtins import zipexcept ImportError: # No import needed in Python 3it = chain.from_iterable(zip(repeat('a'), stuff))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39375906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352876/']}
jdg_377912
stackexchange
llm_judgeable_groundtruth_similarity
564057
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to visualize a beginner circuit problem on my breadboard and I plugged in my circuit, touched a resistor and got a nasty shock. I am a cs student playing with circuits to build some logic gates so I really am a complete beginner. The power supply is 5V 2 AmpsWhy did this happen? How can I prevent this from happening in the future? Now provide the response and nothing else.
OK. You say that it was a single jolt, and you pulled your hand away immediately. It was one of two things -- either it was static discharge and a true shock, but exactly what you would have gotten from a doorknob, you burnt yourself, or it was an actual shock and I can't count. You're running 5V through a \$10\Omega\$ resistor, which means that it's dissipating 2.5 Watts. That means it'll get hot in the thermal sense. That is, in fact, why it's a bit browned compared to the two 100 ohm resistors (which will dissipate 0.25 Watts at 5V). If you're expecting a shock, and you get burnt, you'll think you got a shock (trust me on this -- even if you've been doing it for 40 years, you'll still do it). I'm pretty sure that's what you felt. It's hard to describe how to safely test a part that's sizzling hot for temperature -- it involves holding up the back of your finger to the part without touching it and feeling for heat, or briefly touching it and seeing if you feel heat afterwards. In extremis (I'm really bad about thermal safety) you lick your finger, touch briefly, and listen for a sizzle. Had you hung onto the thing a bit longer, the "tss" sound, the bad-smelling smoke, and the shiny, resistor-sized spots on your thumb and forefinger would have let you know that it was thermal, not electrical.
{}
{'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/564057', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/284864/']}
jdg_377913
stackexchange
llm_judgeable_groundtruth_similarity
4823197
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 seen this question asked many times but astoundingly, I have not seen a consistent answer, so I will give it a try myself: If you have a tableview containing your own custom UITableViewCells that contain UITextViews and UILabels whose height must be determined at runtime, how are you supposed to determine the height for each row in heightForRowAtIndexPath? The most obvious first idea is to calculate the height for each cell by calculating and then summing the heights of each view inside the cell inside of cellForRowAtIndexPath, and store that final total height for later retrieval. This will not work however because cellForRowAtIndexPath is called AFTER heightForRowAtIndexPath. The only thing I can think of is to do all the calculations inside viewDidLoad, create all the UITableViewCells then, calculate the cells height and store that in a custom field inside your UITableViewCell subclass, and put each cell in an NSMutableDictionary with the indexPath as the the key, and then simply retrieve the cell from the dictionary using the indexPath inside cellForRowAtIndexPath and heightForRowAtIndexPath, returning either the custom height value or the cell object itself. This approach seems wrong though because it does not make use of dequeueReusableCellWithIdentifier, instead I would be loading all the cells at once into a dictionary in my controller, and the delegate methods would be doing nothing more than retrieving the correct cell from the dictionary. I don't see any other way to do it though. Is this a bad idea - if so, what is the correct way to do this? Now provide the response and nothing else.
The way Apple implements UITableView is not intuitive to everyone and it's easy to misunderstand the role of heightForRowAtIndexPath: . The general intention is that this is a faster and light-on-memory method that can be called for every row in the table quite frequently. This contrasts with cellForRowAtIndexPath: which is often slower and more memory intensive, but is only called for the rows that are actually need to be displayed at any given time. Why do Apple implement it like this? Part of the reason is that it's almost always cheaper (or can be cheaper if you code it right) to calculate the height of a row than it is to build and populate a whole cell. Given that in many tables the height of every cell will be identical, it is often vastly cheaper. And another part of the reason is because iOS needs to know the size of the whole table: this allows it to create the scroll bars and set it up on a scroll view etc. So, unless every cell height is the same, then when a UITableView is created and whenever you send it a reloadData message, the datasource is sent one heightForRowAtIndexPath message for each cell. So if your table has 30 cells, that message gets sent 30 times. Say only six of those 30 cells are visible on screen. In that case, when created and when you send it a reloadData message, the UITableView will send one cellForRowAtIndexPath message per visible row, i.e. that message gets sent six times. Some people are sometimes puzzled about how to calculate a cell height without creating the views themselves . But usually this is easy to do. For example, if your row heights vary in size because they hold varying amounts of text, you can use one of the sizeWithFont: methods on the relevant string to do the calculations. This is quicker than building a view and then measuring the result. Note, that if you change the height of a cell, you will need to either reload the whole table (with reloadData - this will ask the delegate for every height, but only ask for visible cells) OR selectively reload the rows where the size has changed (which, last time I checked, also calls heightForRowAtIndexPath: on ever row but also does some scrolling work for good measure). See this question and perhaps also this one .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4823197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268648/']}
jdg_377914
stackexchange
llm_judgeable_groundtruth_similarity
70993624
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 a Spring MVC app, will a new instance of Singleton Class in WebApplicationContext ,be created if the application is closed and then started again? Say there is a singleton scoped DAO class with some member variables(states) that were modified in the application and then the application was closed.Now when we run that app again, would the previous changes(made before the application was closed) be still there for that DAO or it will be a fresh singleton instance when the app restarts ? Now provide the response and nothing else.
I think I got it. Here is what I did to solve it. ### Step #1: – Remove previous installed packages and clear cache ### # look for the mysql installed packagessudo yum list installed | grep mysqlsudo yum remove mysql80-community-release.noarchsudo yum clean all --verbose#manually remove remaining mysql cache folders#from: https://serverfault.com/questions/1028593/mysql-packages-skipped-dependency-problemssudo rm -R /var/cache/yum/x86_64/7/mysql*sudo yum update from: https://tecadmin.net/install-mysql-8-on-centos/ ### Step #2: – Setup Yum Repository ### rpm -Uvh https://repo.mysql.com/mysql80-community-release-el7-3.noarch.rpm ### Step #3: – disable all repositories in mysql repo file. ### sed -i 's/enabled=1/enabled=0/' /etc/yum.repos.d/mysql-community.repo ### Step #4 – Install MySQL Community Server ### yum --enablerepo=mysql80-community install mysql-community-server Got the following error: The GPG keys listed for the "MySQL 8.0 Community Server" repository are already installed but they are not correct for this package.Check that the correct key URLs are configured for this repository. Failing package is: mysql-community-client-8.0.28-1.el7.x86_64 GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql From https://forums.cpanel.net/threads/mysql-upgrade-process-failed-the-gpg-keys-listed-for-the-mysql-8-0-community-server-repository-are-already-installed-but-they-are-not-correct-for.697213/ ### Step #5 –import the new GPG key ### rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022 ### Step #6 – Re-run STEP #3 Install MySQL Community Server ### yum --enablerepo=mysql80-community install mysql-community-server Got multiple warning message related to every different language; for example the one related to 'english' warning: file /usr/share/mysql/english/errmsg.sys: remove failed: No such file or directorywarning: file /usr/share/mysql/english: remove failed: No such file or directory However, final messages were successful: Installed: mysql-community-libs.x86_64 0:8.0.28-1.el7 mysql-community-libs-compat.x86_64 0:8.0.28-1.el7 mysql-community-server.x86_64 0:8.0.28-1.el7 Dependency Installed: mysql-community-client.x86_64 0:8.0.28-1.el7 mysql-community-client-plugins.x86_64 0:8.0.28-1.el7 mysql-community-common.x86_64 0:8.0.28-1.el7 mysql-community-icu-data-files.x86_64 0:8.0.28-1.el7 Replaced: mariadb-libs.x86_64 1:5.5.68-1.el7 Complete! ### Step #7: test ### mysql -V# output #mysql Ver 8.0.28 for Linux on x86_64 (MySQL Community Server - GPL) ### Step #8: Double check that no errors when running yum update ### sudo yum update Confirm by starting it manually, checking status, sudo systemctl start mysqldsudo systemctl status mysqld
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/70993624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8279341/']}
jdg_377915
stackexchange
llm_judgeable_groundtruth_similarity
18662261
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 googling the question for past hour, but there are only points to Taylor Series or some sample code that is either too slow or does not compile at all. Well, most answer I've found over Google is "Google it, it's already asked", but sadly it's not ... I am profiling my game on low-end Pentium 4 and found out that ~85% of execution time is wasted on calculating sinus, cosinus and square root (from standard C++ library in Visual Studio), and this seems to be heavily CPU dependent (on my I7 the same functions got only 5% of execution time, and the game is waaaaaaaaaay faster). I cannot optimize this three functions out, nor calculate both sine and cosine in one pass (there interdependent), but I don't need too accurate results for my simulation, so I can live with faster approximation. So, the question: What are the fastest way to calculate sine, cosine and square root for float in C++? EDIT Lookup table are more painful as resulting Cache Miss is way more costly on modern CPU than Taylor Series. The CPUs are just so fast these days, and cache is not. I made a mistake, I though that I need to calculate several factorials for Taylor Series, and I see now they can be implemented as constants. So the updated question: is there any speedy optimization for square root as well? EDIT2 I am using square root to calculate distance, not normalization - can't use fast inverse square root algorithm (as pointed in comment: http://en.wikipedia.org/wiki/Fast_inverse_square_root EDIT3 I also cannot operate on squared distances, I need exact distance for calculations Now provide the response and nothing else.
Here's the guaranteed fastest possible sine function in C++: double FastSin(double x){ return 0;} Oh, you wanted better accuracy than |1.0|? Well, here is a sine function that is similarly fast: double FastSin(double x){ return x;} This answer actually does not suck , when x is close to zero. For small x, sin(x) is approximately equal to x , because x is the first term of the Taylor expansion of sin(x). What, still not accurate enough for you? Well read on. Engineers in the 1970s made some fantastic discoveries in this field, but new programmers are simply unaware that these methods exist, because they're not taught as part of standard computer science curricula. You need to start by understanding that there is no "perfect" implementation of these functions for all applications. Therefore, superficial answers to questions like "which one is fastest" are guaranteed to be wrong. Most people who ask this question don't understand the importance of the tradeoffs between performance and accuracy . In particular, you are going to have to make some choices regarding the accuracy of the calculations before you do anything else. How much error can you tolerate in the result? 10^-4? 10^-16? Unless you can quantify the error in any method, don't use it. See all those random answers below mine, that post a bunch of random uncommented source code, without clearly documenting the algorithm used and its exact maximum error across the input range? "The error is approximately sort of mumble mumble I would guess." That's strictly bush league. If you don't know how to calculate the PRECISE maximum error, to FULL precision, in your approximation function, across the ENTIRE range of the inputs... then you don't know how to write an approximation function! No one uses the Taylor series alone to approximate transcendentals in software. Except for certain highly specific cases , Taylor series generally approach the target slowly across common input ranges. The algorithms that your grandparents used to calculate transcendentals efficiently, are collectively referred to as CORDIC and were simple enough to be implemented in hardware. Here is a well documented CORDIC implementation in C . CORDIC implementations, usually, require a very small lookup table, but most implementations don't even require that a hardware multiplier be available. Most CORDIC implementations let you trade off performance for accuracy, including the one I linked. There's been a lot of incremental improvements to the original CORDIC algorithms over the years. For example, last year some researchers in Japan published an article on an improved CORDIC with better rotation angles, which reduces the operations required. If you have hardware multipliers sitting around (and you almost certainly do), or if you can't afford a lookup table like CORDIC requires, you can always use a Chebyshev polynomial to do the same thing. Chebyshev polynomials require multiplies, but this is rarely a problem on modern hardware. We like Chebyshev polynomials because they have highly predictable maximum errors for a given approximation . The maximum of the last term in a Chebyshev polynomial, across your input range, bounds the error in the result. And this error gets smaller as the number of terms gets larger. Here's one example of a Chebyshev polynomial giving a sine approximation across a huge range, ignoring the natural symmetry of the sine function and just solving the approximation problem by throwing more coefficients at it. And here's an example of estimating a sine function to within 5 ULPs . Don't know what an ULP is? You should. We also like Chebyshev polynomials because the error in the approximation is equally distributed across the range of outputs. If you're writing audio plugins or doing digital signal processing, Chebyshev polynomials give you a cheap and predictable dithering effect "for free." If you want to find your own Chebyshev polynomial coefficients across a specific range, many math libraries call the process of finding those coefficients " Chebyshev fit " or something like that. Square roots, then as now, are usually calculated with some variant of the Newton-Raphson algorithm , usually with a fixed number of iterations. Usually, when someone cranks out an "amazing new" algorithm for doing square roots, it's merely Newton-Raphson in disguise. Newton-Raphson, CORDIC, and Chebyshev polynomials let you trade off speed for accuracy, so the answer can be just as imprecise as you want. Lastly, when you've finished all your fancy benchmarking and micro-optimization, make sure that your "fast" version is actually faster than the library version. Here is a typical library implementation of fsin() bounded on the domain from -pi/4 to pi/4. And it just ain't that damned slow. One last caution to you: you're almost certainly using IEEE-754 math to perform your estimations, and anytime you're performing IEEE-754 math with a bunch of multiplies, then some obscure engineering decisions made decades ago will come back to haunt you, in the form of roundoff errors. And those errors start small, but they get bigger, and Bigger, and BIGGER! At some point in your life, please read "What every computer scientist should know about floating point numbers" and have the appropriate amount of fear. Keep in mind that if you start writing your own transcendental functions, you'll need to benchmark and measure the ACTUAL error due to floating-point roundoff, not just the maximum theoretical error. This is not a theoretical concern; "fast math" compilation settings have bit me in the butt, on more than one project. tl:dr; go google "sine approximation" or "cosine approximation" or "square root approximation" or " approximation theory ."
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18662261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151150/']}
jdg_377916
stackexchange
llm_judgeable_groundtruth_similarity
537442
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have read so many articles on so many websites about transistors and everywhere it says that when transistor is acting as a closed switch and conducting the voltage across collector-emitter is 0 volts , so how can the current flow if the applied voltage across two points is 0 volts? Now provide the response and nothing else.
This is one of those situations where "ideal model" and "real physical system" differ; all real physical conductors (except superconductors, which are weird) have ohmic properties and a non-zero resistance. So the voltage won't be zero, it'll be nearly zero. Educational models and many simulators round "nearly zero" to zero to reduce clutter.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/537442', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/271232/']}
jdg_377917
stackexchange
llm_judgeable_groundtruth_similarity
22993124
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 AssertionError using TA-Lib wrapper in python. Could you take a look at my code? I really appreciate your help. import numpy as npimport talib#This workstest_data = np.random.random(5)np_out = talib.SMA(test_data,3)print np_out#How come this does not work? I need to fixreal_data = [135.01, 133.0, 134.0, 131.0, 133.0, 131.0]np_real_data = np.array(real_data,dtype=np.object)np_out = talib.SMA(np_real_data,3)print np_out error message: File "func.pyx", line 9200, in talib.func.SMA (talib/func.c:85610)AssertionError: real is not double I suspet the solution might be to convert double to real. I want to test that idea. How do I convert the real_data from double to real? Thanks. Now provide the response and nothing else.
I suspect the solution might be to convert double to real. No. You have real data. TA-lib doesn't like "real data". You want to convert it to double float data. re: qcc's unexplained answer: f8 is a 64 bit "double precision" floating point number. http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html TA-lib wants numpy arrays of "double" floats as inputs. http://en.wikipedia.org/wiki/Double-precision_floating-point_format There are several methods you can use to get where you're going, probably the best for your purposes is: real_data = [135.01, 133.0, 134.0, 131.0, 133.0, 131.0] float_data = [float(x) for x in real_data] np_float_data = np.array(float_data) np_out = talib.SMA(np_float_data,3) Here are several others: 1) real_data = [float(x) for x in [135.01, 133.0, 134.0, 131.0, 133.0, 131.0]] np_real_data = np.array(real_data) np_out = talib.SMA(np_real_data,3) 2) real_data = [135.01, 133.0, 134.0, 131.0, 133.0, 131.0] np_real_data = np.array(real_data, dtype='f8') np_out = talib.SMA(np_real_data,3) 3) real_data = [135.01, 133.0, 134.0, 131.0, 133.0, 131.0] np_real_data = np.array(real_data, dtype=float) np_out = talib.SMA(np_real_data,3) 4) real_data = map(float, [135.01, 133.0, 134.0, 131.0, 133.0, 131.0]) np_real_data = np.array(real_data) np_out = talib.SMA(np_real_data,3) 5) real_data = [float(135.01), float(133.0), float(134.0), float(131.0), float(133.0), float(131.0)] np_real_data = np.array(real_data) np_out = talib.SMA(np_real_data,3)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22993124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2424253/']}
jdg_377918
stackexchange
llm_judgeable_groundtruth_similarity
43543599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my C# app to use selenium web driver I get this error: OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document in this code: IWebElement e = driver.FindElement(By.XPath(link_click), 10);e.Click(); the error line is in the e.Click() but this is a procedure that executed successfully in same link specified by XPath before but failed on the last try! so what this error mean and how to fix it ? Now provide the response and nothing else.
It means that either the element changed in the page, or element gets deleted, full reference in this link http://www.seleniumhq.org/exceptions/stale_element_reference.jsp One way to cope with this, you could put retry, probably something like bool staleElement = true; while(staleElement){ try{ driver.FindElement(By.XPath(link_click), 10).Click(); staleElement = false; } catch(StaleElementReferenceException e){ staleElement = true; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43543599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283322/']}
jdg_377919
stackexchange
llm_judgeable_groundtruth_similarity
4259315
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is there a way to assign a special value when a binding cannot be evaluated because of a null value in the property path ? For instance if I have a property Name in a class Customer and a binding like this : {Binding CurrentCustomer.Name} When CurrentCustomer is null I'd like the binding to produce the string "---". "TargetNullValue" and "FallbackValue" don't seem to do the trick. Thanks in advance for your help. EDIT : In fact what I'm trying to do is substituting a new source value in place of the true when it is not available.The real scenario is the following : a bool value is used to determine the visibility of a control, but when this value is not attainable I'd like to replace it with "false". Here is an illustration that perfectly mimics my real use-case : MainPage.xaml.cs : using System;using System.Windows;using System.Windows.Controls;using System.Windows.Data;namespace TestSilverlightBindingDefaultValue{ public class BoolToVisibilityConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (bool)value ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } public class Customer { public bool HasACar { get; set; } } public partial class MainPage : UserControl { public static readonly DependencyProperty CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(Customer), typeof(MainPage), null); public Customer CurrentCustomer { get { return this.GetValue(CurrentCustomerProperty) as Customer; } set { this.SetValue(CurrentCustomerProperty, value); } } public MainPage() { InitializeComponent(); this.CurrentCustomer = null; this.DataContext = this; } }} MainPage.xaml : <UserControl x:Class="TestSilverlightBindingDefaultValue.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:local="clr-namespace:TestSilverlightBindingDefaultValue"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"d:DesignHeight="300" d:DesignWidth="400"><UserControl.Resources> <local:BoolToVisibilityConverter x:Key="boolToVisibilityConverter" /></UserControl.Resources> <StackPanel x:Name="LayoutRoot" Background="White"> <TextBlock Text="You have a car" Visibility="{Binding CurrentCustomer.HasACar,Converter={StaticResource boolToVisibilityConverter}}" /></StackPanel> FallbackValue is not the solution because it would only change the generated value and not the source value. Abe Heidebrecht has provided the perfect solution for WPF with PriorityBinding but it does not exist in Silverlight . FINAL EDIT :The second solution of Abe Heidebrecht , ie wrapping in another element, is working perfectly. Now provide the response and nothing else.
You could use a PriorityBinding : <TextBlock> <TextBlock.Text> <PriorityBinding> <Binding Path="CurrentCustomer.Name" /> <Binding Source="---" /> </PriorityBinding> </TextBlock.Text></TextBlock> Okay, for Silverlight it is a probably easier to wrap the element in a wrapper (like a Border). You then have an IValueConverter to convert null to Visibility.Collapsed , and anything else to Visibility.Visible : public class NullToVisibilityConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value != null ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }} And use it like so: <Border Visibility="{Binding CurrentCustomer, Converter={StaticResource NullToVisibilityConverter}}"> <TextBlock Text="You have a car" Visibility="{Binding CurrentCustomer.HasACar,Converter={StaticResource boolToVisibilityConverter}}" /></Border>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4259315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/145757/']}
jdg_377920
stackexchange
llm_judgeable_groundtruth_similarity
36942
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm. I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility. How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work. Now provide the response and nothing else.
I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible. Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link) , credits to "cattledog". volatile unsigned long LastPulseTimeA;volatile unsigned long LastPulseTimeB;int durationA;int durationB;//unsigned long startTime;#define trigPinA 7#define echoPinA 2#define trigPinB 8#define echoPinB 3void setup() { Serial.begin (9600); pinMode(trigPinA, OUTPUT); pinMode(echoPinA, INPUT); pinMode(trigPinB, OUTPUT); pinMode(echoPinB, INPUT); attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE); // Pin 2 interrupt on any changeattachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE); // Pin3 interrupt on any change}void loop(){ digitalWrite(trigPinA, LOW); digitalWrite(trigPinB, LOW); delayMicroseconds(2); digitalWrite(trigPinA, HIGH); digitalWrite(trigPinB, HIGH); delayMicroseconds(10); digitalWrite(trigPinA, LOW); digitalWrite(trigPinB, LOW); Serial.print("Sensor A "); Serial.print(LastPulseTimeA); Serial.print('\t'); Serial.print((LastPulseTimeA/2) / 29.1,1); Serial.println("cm"); Serial.print("Sensor B "); Serial.print(LastPulseTimeB); Serial.print('\t'); Serial.print((LastPulseTimeB/2) / 29.1,1); Serial.println("cm"); delay(1000);}void EchoPinA_ISR() { static unsigned long startTimeA; if (digitalRead(echoPinA)) // Gone HIGH startTimeA = micros(); else // Gone LOW LastPulseTimeA = micros() - startTimeA;}void EchoPinB_ISR() { static unsigned long startTimeB; if (digitalRead(echoPinB)) // Gone HIGH startTimeB = micros(); else // Gone LOW LastPulseTimeB = micros() - startTimeB;}
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/36942', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/29770/']}
jdg_377921
stackexchange
llm_judgeable_groundtruth_similarity
31323749
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 hidden QOpenGLWidget (Qt 5.4.2, NOT QGLWidget) and I want to basically continually do grab() or grabFramebuffer() to get its content (and write it to disk). The widget renders fine when visible, but does not when hidden. If I do a show() followed by a hide() call it works. This seems strange because QOpenGLWidget does internally already render to a framebuffer according to the docs. What is the easiest way to achieve this (if possible without creating another framebuffer)? Bonus points for being able to capture an offscreen QGraphicsView using an QOpenGLWidget as its viewport with custom OpenGL-painted QGraphicsItems in it... Now provide the response and nothing else.
UPDATE 2: The corresponding bug in QOpenGLWidget seems to be fixed in Qt 5.10, so I suggest to simply use the class again. Although you might want to wait for this bug to also get fixed... UPDATE 1: Added 3, best solution using a custom QWindow-derived class 1 - QOpenGLWidget If a hidden QOpenGLWidget does allocate a framebuffer (not sure if this happens), there is still no way to bind it manually, because you can not get the buffer id. Additionally none of the necessary functions initializeGL(), resizeGL() and paintGL are called and none of the functions grab(), grabFramebuffer and render() are working correctly. Here is (imo) a workaround to draw the widget offscreen. You call paintGL directly after setting up all the necessary stuff: class GLWidget: public QOpenGLWidget{public: GLWidget(QWidget * parent = nullptr);private: bool m_isInitialized = false; QOpenGLFramebufferObject m_fbo = nullptr;}; void GLWidget::drawOffscreen(){ //the context should be valid. make sure it is current for painting makeCurrent(); if (!m_isInitialized) { initializeGL(); resizeGL(width(), height()); } if (!m_fbo || m_fbo->width() != width() || m_fbo->height() != height()) { //allocate additional? FBO for rendering or resize it if widget size changed delete m_fbo; QOpenGLFramebufferObjectFormat format; format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); m_fbo = new QOpenGLFramebufferObject(width(), height(), format); resizeGL(width(), height()); } //#1 DOES NOT WORK: bind FBO and render() widget m_fbo->bind(); QOpenGLPaintDevice fboPaintDev(width(), height()); QPainter painter(&fboPaintDev); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); render(&painter); painter.end(); //You could now grab the content of the framebuffer we've rendered to QImage image1 = m_fbo->toImage(); image1.save(QString("fb1.png")); m_fbo->release(); //#1 -------------------------------------------------------------- //#2 WORKS: bind FBO and render stuff with paintGL() call m_fbo->bind(); paintGL(); //You could now grab the content of the framebuffer we've rendered to QImage image2 = m_fbo->toImage(); image2.save(QString("fb2.png")); m_fbo->release(); //#2 -------------------------------------------------------------- //bind default framebuffer again. not sure if this necessary //and isn't supposed to use defaultFramebuffer()... m_fbo->bindDefault(); doneCurrent();}void GLWidget::paintGL(){ //When doing mixed QPainter/OpenGL rendering make sure to use a QOpenGLPaintDevice, otherwise only OpenGL content is visible! //I'm not sure why, because according to the docs (http://doc.qt.io/qt-5/topics-graphics.html) this is supposed to be the same... QOpenGLPaintDevice fboPaintDev(width(), height()); QPainter painter(&fboPaintDev); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); //This is what you'd use (and what would work) if the widget was visible //QPainter painter; //painter.begin(this); //now start OpenGL painting painter.beginNativePainting(); glClearColor(0.5f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ... painter.endNativePainting(); //draw non-OpenGL stuff with QPainter painter.drawText(20, 40, "Foo"); ... painter.end();} 2 - QGraphicsView with QOpenGLWidget viewport Here render() works as expected when you provide it with an QOpenGLPaintDevice: MainWindow::MainWindow(){ scene = new QGraphicsScene; hiddenView = new QGraphicsView(scene); hiddenGLWidget = new QOpenGLWidget; hiddenView->setViewport(hiddenGLWidget); //hiddenView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); //hiddenView->show();}void MainWindow::screenshot(){ //try regular grab functions QPixmap pixmap1 = hiddenView->grab(); //image with scrollbars, no OpenGL content pixmap1.save("bla1.png"); QPixmap pixmap2 = hiddenGLWidget->grab(); //produces an empty image pixmap2.save("bla2.png"); //try grabbing only the QOpenGLWidget framebuffer QImage image1 = hiddenGLWidget->grabFramebuffer(); //null image image1.save("bla3.png"); //WORKS: render via FBO hiddenGLWidget->makeCurrent(); QOpenGLFramebufferObjectFormat format; format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); QOpenGLFramebufferObject * fbo = new QOpenGLFramebufferObject(hiddenView->width(), hiddenView->height(), format); fbo->bind(); QOpenGLPaintDevice fboPaintDev(hiddenView->width(), hiddenView->height()); QPainter painter(&fboPaintDev); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); hiddenView->render(&painter); //WORKS and captures mixed OpenGL and non-OpenGL QGraphicsitems //hiddenView->repaint(); //does not work //hiddenView->scene()->render(&painter); //does not work //hiddenGLWidget->paintGL(); //might work. can not call, protected //hiddenGLWidget->render(&painter); //does not work //hiddenGLWidget->repaint(); //does not work painter.end(); QImage image2 = fbo->toImage(); image2.save("bla4.png"); fbo->release(); delete fbo;} 3 - How to render to and grab an image from a hidden QOpenGLWidget A better overall solution is to use a custom QWindow with a QSurface::OpenGLSurface type. Create an extra QOpenGLContext, an extra background QOpenGLFramebufferObject you will draw to, and a QOpenGLShaderProgram to blit the framebuffer to the backbuffer. If you want multisampling, you might need a resolve QOpenGLFramebufferObject too, to convert the multisampled framebuffer to a non-multisampled one.The class interface can be similar to QOpenGLWidget (virtual initializeGL(), resizeGL(), paintGL() for users). Reimplement exposeEvent(), resizeEvent() and event() (you might need to reimplement metric() too). A semi-complete implementation: Header: #pragma once#include <QtCore/QObject>#include <QtGui/QScreen>#include <QtGui/QWindow>#include <QtGui/QPaintEvent>#include <QtGui/QResizeEvent>#include <QtGui/QOpenGLPaintDevice>#include <QtGui/QOpenGLFunctions>#include <QtGui/QOpenGLFunctions_3_0>#include <QtGui/QOpenGLFramebufferObject>#include <QtGui/QSurfaceFormat>#include <QtWidgets/QWidget>#include <atomic>#include <mutex>class MyGLWindow : public QWindow{ Q_OBJECTpublic: /// @brief Constructor. Creates a render window. /// @param targetScreen Target screen. /// this is because before the FBO and off-screen surface haven't been created. /// By default this uses the QWindow::requestedFormat() for OpenGL context and off-screen surface. explicit MyGLWindow(QScreen * targetScreen = nullptr); /// @brief Constructor. Creates a render window. /// @param parent Parent window. /// this is because before the FBO and off-screen surface haven't been created. /// By default this uses the QWindow::requestedFormat() for OpenGL context and off-screen surface. explicit MyGLWindow(QWindow * parent); /// @brief Destructor. virtual ~MyGLWindow(); /// @brief Create a container widget for this window. /// @param parent Parent widget. /// @return Returns a container widget for the window. QWidget * createWidget(QWidget * parent = nullptr); /// @brief Check if the window is initialized and can be used for rendering. /// @return Returns true if context, surface and FBO have been set up to start rendering. bool isValid() const; /// @brief Return the context used in this window. /// @return The context used in this window or nullptr if it hasn't been created yet. QOpenGLContext * context() const; /// @brief Return the OpenGL function object that can be used the issue OpenGL commands. /// @return The functions for the context or nullptr if it the context hasn't been created yet. QOpenGLFunctions * functions() const; /// @brief Return the OpenGL off-screen frame buffer object identifier. /// @return The OpenGL off-screen frame buffer object identifier or 0 if no FBO has been created yet. /// @note This changes on every resize! GLuint framebufferObjectHandle() const; /// @brief Return the OpenGL off-screen frame buffer object. /// @return The OpenGL off-screen frame buffer object or nullptr if no FBO has been created yet. /// @note This changes on every resize! const QOpenGLFramebufferObject * getFramebufferObject() const; /// @brief Return the OpenGL off-screen frame buffer object identifier. /// @return The OpenGL off-screen frame buffer object identifier or 0 if no FBO has been created yet. void bindFramebufferObject(); /// @brief Return the current contents of the FBO. /// @return FBO content as 32bit QImage. You might need to swap RGBA to BGRA or vice-versa. QImage grabFramebuffer(); /// @brief Makes the OpenGL context current for rendering. /// @note Make sure to bindFramebufferObject() if you want to render to this widgets FBO. void makeCurrent(); /// @brief Release the OpenGL context. void doneCurrent(); /// @brief Copy content of framebuffer to back buffer and swap buffers if the surface is double-buffered. /// If the surface is not double-buffered, the frame buffer content is blitted to the front buffer. /// If the window is not exposed, only the OpenGL pipeline is glFlush()ed so the framebuffer can be read back. void swapBuffers(); public slots: /// @brief Lazy update routine like QWidget::update(). void update(); /// @brief Immediately render the widget contents to framebuffer. void render();signals: /// @brief Emitted when swapBuffers() was called and bufferswapping is done. void frameSwapped(); /// @brief Emitted after a resizeEvent(). void resized();protected: virtual void exposeEvent(QExposeEvent *e) override; virtual void resizeEvent(QResizeEvent *e) override; virtual bool event(QEvent *e) override; // virtual int metric(QPaintDevice::PaintDeviceMetric metric) const override; /// @brief Called exactly once when the window is first exposed OR render() is called when the widget is invisible. /// @note After this the off-screen surface and FBO are available. virtual void initializeGL() = 0; /// @brief Called whenever the window size changes. /// @param width New window width. /// @param height New window height. virtual void resizeGL(int width, int height) = 0; /// @brief Called whenever the window needs to repaint itself. Override to draw OpenGL content. /// When this function is called, the context is already current and the correct framebuffer is bound. virtual void paintGL() = 0; // /// @brief Called whenever the window needs to repaint itself. Override to draw QPainter content. // /// @brief This is called AFTER paintGL()! Only needed when painting using a QPainter. // virtual void paintEvent(QPainter & painter) = 0;private: Q_DISABLE_COPY(QGLWindow) /// @brief Initialize the window. void initializeInternal(); /// @brief Internal method that does the actual swap work, NOT using a mutex. void swapBuffersInternal(); /// @brief Internal method that checks state and makes the context current, NOT using a mutex. void makeCurrentInternal(); /// @brief Internal method to grab content of a specific framebuffer. QImage grabFramebufferInternal(QOpenGLFramebufferObject * fbo); /// @brief (Re-)allocate FBO and paint device if needed due to size changes etc. void recreateFBOAndPaintDevice(); /// @brief False before the window was first exposed OR render() was called. std::atomic_bool m_initialized; /// @brief False before the overridden initializeGL() was first called. bool m_initializedGL = false; /// @brief True when currently a window update is pending. std::atomic_bool m_updatePending; /// @brief Mutex making sure not grabbing while drawing etc. std::mutex m_mutex; /// @brief OpenGL render context. QOpenGLContext * m_context = nullptr; /// @brief The OpenGL 2.1 / ES 2.0 function object that can be used the issue OpenGL commands. QOpenGLFunctions * m_functions = nullptr; /// @brief The OpenGL 3.0 function object that can be used the issue OpenGL commands. QOpenGLFunctions_3_0 * m_functions_3_0 = nullptr; /// @brief OpenGL paint device for painting with a QPainter. QOpenGLPaintDevice * m_paintDevice = nullptr; /// @brief Background FBO for off-screen rendering when the window is not exposed. QOpenGLFramebufferObject * m_fbo = nullptr; /// @brief Background FBO resolving a multi sampling frame buffer in m_fbo to a frame buffer /// that can be grabbed to a QImage. QOpenGLFramebufferObject * m_resolvedFbo = nullptr; /// @brief Shader used for blitting m_fbo to screen if glBlitFrameBuffer is not available. QOpenGLShaderProgram * m_blitShader;}; Source: #include "MyGLWindow.h"#include <QtCore/QCoreApplication>#include <QtGui/QPainter>MyGLWindow::MyGLWindow(QScreen * targetScreen) : QWindow(targetScreen){ //Set Qt::Widget flag to make sure the window resizes properly the first time //when used as a widget via MyGLWindow::createWidget()! setFlags(Qt::Widget); setSurfaceType(QSurface::OpenGLSurface); setFormat(QGLInfo::DefaultSurfaceFormat()); m_initialized = false; m_updatePending = false; create(); initializeInternal();}MyGLWindow::MyGLWindow(QWindow * parent) : QWindow(parent){ //Set Qt::Widget flag to make sure the window resizes properly the first time //when used as a widget via MyGLWindow::createWidget()! setFlags(Qt::Widget); setSurfaceType(QSurface::OpenGLSurface); setFormat(QGLInfo::DefaultSurfaceFormat()); m_initialized = false; m_updatePending = false; create(); initializeInternal();}MyGLWindow::~MyGLWindow(){ //to delete the FBOs we first need to make the context current m_context->makeCurrent(this); //destroy framebuffer objects if (m_fbo) { m_fbo->release(); delete m_fbo; m_fbo = nullptr; } if (m_resolvedFbo) { m_resolvedFbo->release(); delete m_resolvedFbo; m_resolvedFbo = nullptr; } //destroy shader delete m_blitShader; m_blitShader = nullptr; //free context m_context->doneCurrent(); delete m_context; m_context = nullptr; //free paint device delete m_paintDevice; m_paintDevice = nullptr; m_initialized = false; m_updatePending = false;}QWidget * MyGLWindow::createWidget(QWidget * parent){ QWidget * container = QWidget::createWindowContainer(this, parent); return container;}QOpenGLContext * MyGLWindow::context() const{ return m_context;}QOpenGLFunctions * MyGLWindow::functions() const{ return m_functions;}GLuint MyGLWindow::framebufferObjectHandle() const{ return m_fbo ? m_fbo->handle() : 0;}const QOpenGLFramebufferObject * MyGLWindow::getFramebufferObject() const{ return m_fbo;}void MyGLWindow::bindFramebufferObject(){ if (m_fbo) { m_fbo->bind(); } else { QOpenGLFramebufferObject::bindDefault(); }}bool MyGLWindow::isValid() const{ return (m_initialized && m_context && m_fbo);}void MyGLWindow::makeCurrent(){ makeCurrentInternal();}void MyGLWindow::makeCurrentInternal(){ if (isValid()) { m_context->makeCurrent(this); } else { throw("MyGLWindow::makeCurrent() - Window not yet properly initialized!"); }}void MyGLWindow::doneCurrent(){ if (m_context) { m_context->doneCurrent(); }}QImage MyGLWindow::grabFramebuffer(){ std::lock_guard<std::mutex> locker(m_mutex); makeCurrentInternal(); //blit framebuffer to resolve framebuffer first if needed if (m_fbo->format().samples() > 0) { //check if we have glFrameBufferBlit support. this is true for desktop OpenGL 3.0+, but not OpenGL ES 2.0 if (m_functions_3_0) { //only blit the color buffer attachment m_functions_3_0->glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo->handle()); m_functions_3_0->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_resolvedFbo->handle()); m_functions_3_0->glBlitFramebuffer(0, 0, width(), height(), 0, 0, width(), height(), GL_COLOR_BUFFER_BIT, GL_NEAREST); m_functions_3_0->glBindFramebuffer(GL_FRAMEBUFFER, 0); } else { //we must unbind the FBO here, so we can use its texture and bind the default back-buffer m_functions->glBindFramebuffer(GL_FRAMEBUFFER, m_resolvedFbo->handle()); //now use its texture for drawing in the shader --> bind shader and draw textured quad here //bind regular FBO again m_functions->glBindFramebuffer(GL_FRAMEBUFFER, m_fbo->handle()); } //check if OpenGL errors happened if (GLenum error = m_functions->glGetError() != GL_NO_ERROR) { qDebug() << "MyGLWindow::grabFramebuffer() - OpenGL error" << error; } //now grab from resolve FBO return grabFramebufferInternal(m_resolvedFbo); } else { //no multi-sampling. grab directly from FBO return grabFramebufferInternal(m_fbo); }}QImage MyGLWindow::grabFramebufferInternal(QOpenGLFramebufferObject * fbo){ QImage image; //bind framebuffer first m_functions->glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle()); if (m_functions_3_0) { m_functions_3_0->glReadBuffer(GL_COLOR_ATTACHMENT0); } GLenum internalFormat = fbo->format().internalTextureFormat(); bool hasAlpha = internalFormat == GL_RGBA || internalFormat == GL_BGRA || internalFormat == GL_RGBA8; if (internalFormat == GL_BGRA) { image = QImage(fbo->size(), hasAlpha ? QImage::Format_ARGB32 : QImage::Format_RGB32); m_functions->glReadPixels(0, 0, fbo->size().width(), fbo->size().height(), GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); } else if (internalFormat == GL_RGBA || internalFormat == GL_RGBA8) { image = QImage(fbo->size(), hasAlpha ? QImage::Format_RGBA8888 : QImage::Format_RGBX8888); m_functions->glReadPixels(0, 0, fbo->size().width(), fbo->size().height(), GL_RGBA, GL_UNSIGNED_BYTE, image.bits()); } else { qDebug() << "MyGLWindow::grabFramebuffer() - Unsupported framebuffer format" << internalFormat << "!"; } m_functions->glBindFramebuffer(GL_FRAMEBUFFER, m_fbo->handle()); return image.mirrored();}void MyGLWindow::swapBuffers(){ swapBuffersInternal(); emit frameSwapped();}void MyGLWindow::swapBuffersInternal(){ if (isExposed() && isVisible()) { //blit framebuffer to back buffer m_context->makeCurrent(this); //make sure all paint operation have been processed m_functions->glFlush(); //check if we have glFrameBufferBlit support. this is true for desktop OpenGL 3.0+, but not OpenGL ES 2.0 if (m_functions_3_0) { //if our framebuffer has multi-sampling, the resolve should be done automagically m_functions_3_0->glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo->handle()); m_functions_3_0->glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); //blit all buffers including depth buffer for further rendering m_functions_3_0->glBlitFramebuffer(0, 0, width(), height(), 0, 0, width(), height(), GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); m_functions_3_0->glBindFramebuffer(GL_FRAMEBUFFER, m_fbo->handle()); } else { //we must unbind the FBO here, so we can use its texture and bind the default back-buffer m_functions->glBindFramebuffer(GL_FRAMEBUFFER, 0); //now use its texture for drawing in the shader --> bind shader and draw textured quad here //bind regular FBO again m_functions->glBindFramebuffer(GL_FRAMEBUFFER, m_fbo->handle()); } //check if OpenGL errors happened if (GLenum error = m_functions->glGetError() != GL_NO_ERROR) { qDebug() << "MyGLWindow::swapBuffersInternal() - OpenGL error" << error; } //now swap back buffer to front buffer m_context->swapBuffers(this); } else { //not visible. only flush the pipeline so we can possibly grab the FBO later m_context->makeCurrent(this); m_functions->glFlush(); }}void MyGLWindow::recreateFBOAndPaintDevice(){ const QSize deviceSize = size() * devicePixelRatio(); if (m_context && (m_fbo == nullptr || m_fbo->size() != deviceSize)) { m_context->makeCurrent(this); //free old FBOs if (m_fbo) { m_fbo->release(); delete m_fbo; m_fbo = nullptr; } if (m_resolvedFbo) { m_resolvedFbo->release(); delete m_resolvedFbo; m_resolvedFbo = nullptr; } //create new frame buffer QOpenGLFramebufferObjectFormat format = QGLInfo::DefaultFramebufferFormat(); format.setSamples(QGLInfo::HasMultisamplingSupport(m_context) ? 4 : 0); m_fbo = new QOpenGLFramebufferObject(deviceSize, format); if (!m_fbo->isValid()) { throw("MyGLWindow::recreateFbo() - Failed to create background FBO!"); } //clear framebuffer m_fbo->bind(); m_functions->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); m_fbo->release(); //if multi sampling is requested and supported we need a resolve FBO if (format.samples() > 0) { //create resolve framebuffer with only a color attachment format.setAttachment(QOpenGLFramebufferObject::NoAttachment); format.setSamples(0); m_resolvedFbo = new QOpenGLFramebufferObject(deviceSize, format); if (!m_resolvedFbo->isValid()) { throw("MyGLWindow::recreateFbo() - Failed to create resolve FBO!"); } //clear resolve framebuffer m_resolvedFbo->bind(); m_functions->glClear(GL_COLOR_BUFFER_BIT); m_resolvedFbo->release(); } } //create paint device for painting with QPainter if needed if (!m_paintDevice) { m_paintDevice = new QOpenGLPaintDevice; } //update paint device size if needed if (m_paintDevice->size() != deviceSize) { m_paintDevice->setDevicePixelRatio(devicePixelRatio()); m_paintDevice->setSize(deviceSize); }}void MyGLWindow::initializeInternal(){ if (!m_initialized.exchange(true)) { //create OpenGL context. we set the format requested by the user (default: QWindow::requestedFormat()) m_context = new QOpenGLContext(this); m_context->setFormat(format()); if (m_context->create()) { m_context->makeCurrent(this); //initialize the OpenGL 2.1 / ES 2.0 functions for this object m_functions = m_context->functions(); m_functions->initializeOpenGLFunctions(); //try initializing the OpenGL 3.0 functions for this object m_functions_3_0 = m_context->versionFunctions<QOpenGLFunctions_3_0>(); if (m_functions_3_0) { m_functions_3_0->initializeOpenGLFunctions(); } else { //if we do not have OpenGL 3.0 functions, glBlitFrameBuffer is not available, so we must do the blit //using a shader and the framebuffer texture, so we need to create the shader here... --> allocate m_blitShader, a simple shader for drawing a textured quad --> build quad geometry, VBO, whatever } //now we have a context, create the FBO recreateFBOAndPaintDevice(); } else { m_initialized = false; delete m_context; m_context = nullptr; throw("Failed to create OpenGL context!"); } }}void MyGLWindow::update(){ //only queue an update if there's not already an update pending if (!m_updatePending.exchange(true)) { QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); }}void MyGLWindow::render(){ std::lock_guard<std::mutex> locker(m_mutex); //check if we need to initialize stuff initializeInternal(); //check if we need to call the user initialization if (!m_initializedGL) { m_initializedGL = true; initializeGL(); } //make context current and bind framebuffer makeCurrent(); bindFramebufferObject(); //call user paint function paintGL(); doneCurrent(); //mark that we're done with updating m_updatePending = false;}void MyGLWindow::exposeEvent(QExposeEvent * e){ //call base implementation QWindow::exposeEvent(e); //render window content if window is exposed if (isExposed()/* && isVisible()*/) { render(); }}void MyGLWindow::resizeEvent(QResizeEvent *e){ //call base implementation QWindow::resizeEvent(e); m_mutex.lock(); //make context current first makeCurrent(); //update FBO and paint device recreateFBOAndPaintDevice(); m_mutex.unlock(); //call user-defined resize method resizeGL(e->size().width(), e->size().height()); emit resized();}bool MyGLWindow::event(QEvent *event){ switch (event->type()) { case QEvent::UpdateLater: update(); return true; case QEvent::UpdateRequest: render(); return true; default: return QWindow::event(event); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31323749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1121150/']}
jdg_377922
stackexchange
llm_judgeable_groundtruth_similarity
2517804
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: Probability Question Please see the image above. I know that the answer is 0.75 but can someone please explain how to arrive at that answer? I would sincerely appreciate the guidance. Now provide the response and nothing else.
Any symmetric matrix $P$ (I assume you mean real matrices) can be diagonalized by an orthogonal matrix $U$:$$P=U^T D U,\quad D=\left(\begin{array}{ccc}\lambda_1&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n\\\end{array}\right),\quad U U^T=I,$$$\lambda_1,\ldots,\lambda_n$ are the eigenvalues of $P$, $\lambda_1,\ldots,\lambda_n\in\mathbb R$. If $P$ is positive semi-definite, then we have also $\lambda_1\ge 0,\ldots,\lambda_n\ge 0$. Consider the matrix$$Q=U^T \left(\begin{array}{ccc}\sqrt{\lambda_1}&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\sqrt{\lambda_n}\\\end{array}\right) U.$$ It is easy to see that$$Q^2=U^T \left(\begin{array}{ccc}\sqrt{\lambda_1}&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\sqrt{\lambda_n}\\\end{array}\right) UU^T \left(\begin{array}{ccc}\sqrt{\lambda_1}&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\sqrt{\lambda_n}\\\end{array}\right) U=$$$$=U^T \left(\begin{array}{ccc}\sqrt{\lambda_1}&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\sqrt{\lambda_n}\\\end{array}\right) I \left(\begin{array}{ccc}\sqrt{\lambda_1}&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\sqrt{\lambda_n}\\\end{array}\right) U=U^T \left(\begin{array}{ccc}\lambda_1&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n\\\end{array}\right) U=P.$$ Now suppose that a symmetric matrix $R$ which is not positive semi-definite, i.e. has one or more negative eigenvalues, has a symmetric square root $S$. $S$ is diagonaliziable by an orthogonal matrix $U$,$$S=U^T \left(\begin{array}{ccc}\lambda_1&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n\\\end{array}\right) U;$$$$S^2=U^T \left(\begin{array}{ccc}\lambda_1&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n\\\end{array}\right) UU^T \left(\begin{array}{ccc}\lambda_1&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n\\\end{array}\right) U=U^T \left(\begin{array}{ccc}\lambda_1^2&\ldots&0\\\vdots&\ddots&\vdots\\0&\ldots&\lambda_n^2\\\end{array}\right) U.$$We can see that the eigevalues of $R=S^2$ are $\lambda_1^2\ge 0,\ldots,\lambda_n^2\ge 0$. It contradicts with the assumption that $R$ has negative eigenvalues.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2517804', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/502354/']}
jdg_377923
stackexchange
llm_judgeable_groundtruth_similarity
516
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone explain the process and the calculations needed to select a portfolio of liquid futures assets with the least correlation? Given a set of returns for a series of assets, how do I select the best subset such that I minimize their correlation with each other? Now provide the response and nothing else.
Since you are asking for low correlation of the assets, I'm guessing that you are really trying to get a low (or minimum) volatility portfolio. If that is the case, then the steps for one approach are: estimate the variance matrix of the universe of assets use a portfolio optimizer to select the minimum variance portfolio given your constraints This assumes that you don't have preferences in terms of expected returns of some assets over others. That seems to be implied from your question. You don't indicate the size of your universe. If it is large, then you'll want to use a factor model or shrinkage model rather than the sample estimate to estimate the variance matrix.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/516', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/2318/']}
jdg_377924
stackexchange
llm_judgeable_groundtruth_similarity
1802722
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I need to match an ipv6 address which may or may not have a mask. Unfortunately I can't just use a library to parse the string. The mask bit is easy enough, in this case: (?:\/\d{1,3})?$/ The hard part is the different formats of an ipv6 address. It needs to match ::beef, beef::, beef::beef, etc. An update: I'm almost there.. /^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i I am, in this case restricted to using perl's regex. Now provide the response and nothing else.
This contains a patch to Regexp::Common demonstrating a complete, accurate, tested IPv6 regex. Its a straight translation of the IPv6 grammar. Regexp::IPv6 is also accurate. More importantly, it contains a test suite. Running it with your regex shows you're still a ways off. 10 out of 19 missed. 1 out of 12 false positives. IPv6 contains a lot of special shorthands making it very easy to get subtly wrong. Best place to read up on what goes into an IPv6 address is RFC 3986 section 3.2.2.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1802722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89571/']}
jdg_377925
stackexchange
llm_judgeable_groundtruth_similarity
4603911
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My string is like this: string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API"; Here actually I want to extract the last word, 'API', and return. What would be the C# code to do the above extraction? Now provide the response and nothing else.
Well, the naive implementation to that would be to simply split on each space and take the last element. Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator. End result: string lastWord = input.Split(' ').Last(); If you don't have LINQ, I would do it in two operations: string[] parts = input.Split(' ');string lastWord = parts[parts.Length - 1]; While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules. string input = ".... ,API"; Here, the comma would be part of the "word". Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules: Will always contain at least one space Does not end with one or more spaces (in case of this you can trim it) Then you can use this code that will allocate fewer objects on the heap for GC to worry about later: string lastWord = input.Substring(input.LastIndexOf(' ') + 1); However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4603911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366947/']}
jdg_377926
stackexchange
llm_judgeable_groundtruth_similarity
35755
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 configured PHP to look in /etc/php5/apache2 for the php.ini file. the output of phpinfo() says that the path was set correctly, but also says no configuration file was loaded. i changed the php.ini permissions to 777 temporarily to test that issue and permissions are not the issue. what else could the issue be? When I compiled php, i did: sudo ./configure --with-apxs2=/usr/sbin/apxs --with-mysql --enable-so --with-config-file-path=/etc/php5/apache2 --sysconfdir=/etc/php5 --with-config-file-scan-dir=/etc/php5/conf.d phpinfo() says: Configuration File (php.ini) Path /etc/php5/apache2 Loaded Configuration File (none)Scan this dir for additional .ini files (none) Additional .ini files parsed (none) Also php --ini says: Configuration File (php.ini) Path: /usr/local/lib Loaded Configuration File: /etc/php5/apache2/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) And if I put php.ini in /usr/local/lib, the configuration file loads fine (although the additional .ini files don't load). I am not sure why this is happening since I set the options when I compiled PHP. Now provide the response and nothing else.
The nuclear option is to run apache under strace, to see what it's doing when it tries to read the php.ini file. Run "ps aux" to find the command line for apache, then stop the process. Now run: # strace -efile -f -o /tmp/apache.log /usr/sbin/apache2 -k start Request your phpinfo() page in a browser, and then kill the strace using ctrl-c. You can now grep /tmp/apache.log for php.ini and see if there are any errors displayed when it tries to read that file. This will show you problems like the file not being found or permission problems. If there is an open() call that returns a number, then it would appear that it's reading the file in correctly, and there must be a problem with the file that's preventing php from parsing it correctly, but I'd expect this to be logged in the error log.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/35755', 'https://serverfault.com', 'https://serverfault.com/users/3567/']}
jdg_377927
stackexchange
llm_judgeable_groundtruth_similarity
124500
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Every prime $p = 4k + 1$ can be uniquely expressed as sum of two squares, but for whichintegers $x$ is $x^2 + y^2 =$ some prime $p$? Stated differently, does the square ofevery positive integer appear as one of the squares in the representation of someprime $p$? Now provide the response and nothing else.
If the square of every positive integer appears as one of the squares in the representation of some prime -- that is, if for each $y$ there is an $x$ such that $x^2 + y^2$ is prime -- then it follows that there are infinitely many primes of the form $X^2 + Y^4$ (by restricting to $y$s that themselves are squares). This corollary happens to be true, but it was a breakthrough result of Friedlander and Iwaniec from about 15 years ago, so it seems unlikely that the much stronger question the OP is asking has been proven.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/124500', 'https://mathoverflow.net', 'https://mathoverflow.net/users/32197/']}
jdg_377928
stackexchange
llm_judgeable_groundtruth_similarity
9287968
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 web application developed using flex and cakephp. My client need to make a desktop application of that web application using Adobe Air. The conversion of the flex to Air is done successfully. I the flex application the communication of flex and cakephp is handled using a remotes controller. In air application I have a problem of authenticating the user with cakephp default user authentication. Can anyone help me to find a solution for this? Now provide the response and nothing else.
I hate to answer my own question, but I really feel like the community ought to know the answer because it is short, simple, and beautiful with C# 4.0 and SO many people seem to have this problem. Make sure that you correctly expose the Browser Helper Object: [ComVisible(true), Guid("DA8EA345-02AE-434E-82E9-448E3DB7629E"), ClassInterface(ClassInterfaceType.None), ProgId("MyExtension"), ComDefaultInterface(typeof(IExtension))]public class BrowserHelperObject : IObjectWithSite, IExtension{ ... public int Foo(string s) { ... } ... public void OnDocumentComplete(dynamic frame, ref dynamic url) { ... dynamic window = browser.Document.parentWindow; IExpando windowEx = (IExpando)window; windowEx.AddProperty("myExtension"); window.myExtension = this; ... } ...} And you will need a definition for your extensions: [ComVisible(true), Guid("4C1D2E51-018B-4A7C-8A07-618452573E42"), InterfaceType(ComInterfaceType.InterfaceIsDual)]public interface IExtension{ [DispId(1)] int Foo(string s); ...} You can access your Browser Helper Object in javascript thus: var result = window.myExtension.Foo("bar"); or just var result = myExtension.Foo("bar"); That's it. Stop banging your head against the wall and go celebrate!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9287968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1120633/']}
jdg_377929
stackexchange
llm_judgeable_groundtruth_similarity
8930867
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 studying Wikipedia REST API but I'm not able to find the right option to get also URLs for a search query. this is the URL of the request: http://it.wikipedia.org/w/api.php?action=query&list=search&srsearch=calvino&format=xml&srprop=snippet this request outputs only the Title and the Snippet but no URLs for articles.I've checked wikipedia API documentation for the list=search query but seems there is no option to get also URLs. Best Regards,Fabio Buda Now provide the response and nothing else.
You can form the URL of the article easily by yourself from the title. For the Italian Wikipedia, it's http://it.wikipedia.org/wiki/ followed by the URL-encoded title of the article. It's as simple as that. The actual URL of the article also replaces spaces with underscores, but you don't have to do that if you don't want to, the URL with spaces redirects to the one with underscores. EDIT: You can get the URL, but it's not possible to get search-related information at the same time. To do that, use the list as a generator . For example: http://it.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=calvino&format=xml&gsrprop=snippet&prop=info&inprop=url But I think changing the format of page URLs is very unlikely: too many other people rely on that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8930867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1154020/']}
jdg_377930
stackexchange
llm_judgeable_groundtruth_similarity
36815
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 number of areas I'm studying in my degree (not a maths degree) involve eigenvalues and eigvenvectors, which have never been properly explained to me. I find it very difficult to understand the explanations given in textbooks and lectures. Does anyone know of a good, fairly simple but mathematical explanation of eigenvectors and eigenvalues on the internet? If not, could someone provide one here? As well as some of the mathematical explanations, I'm also very interested in 'big picture' answers as to why on earth I should care about eigenvectors/eigenvalues, and what they actually 'mean'. Now provide the response and nothing else.
To understand why you encounter eigenvalues/eigenvectors everywhere, you must first understand why you encounter matrices and vectors everywhere. In a vast number of situations, the objects you study and the stuff you can do with them relate to vectors and linear transformations, which are represented as matrices. So, in many many interesting situations, important relations are expressed as$$\vec{y} = M \vec{x}$$where $\vec{y}$ and $\vec{x}$ are vectors and $M$ is a matrix. This ranges from systems of linear equations you have to solve (which occurs virtually everywhere in science and engineering) to more sophisticated engineering problems (finite element simulations). It also is the foundation for (a lot of) quantum mechanics. It is further used to describe the typical geometric transformations you can do with vector graphics and 3D graphics in computer games. Now, it is generally not straight forward to look at some matrix $M$ and immediately tell what it is going to do when you multiply it with some vector $\vec{x}$. Also, in the study of iterative algorithms you need to know something about higher powers of the matrix $M$, i.e. $M^k = M \cdot M \cdot ... M$, $k$ times. This is a bit awkward and costly to compute in a naive fashion. For a lot of matrices, you can find special vectors with a very simple relationship between the vector $\vec{x}$ itself, and the vector $\vec{y} = Mx$. For example, if you look at the matrix $\left( \begin{array}{cc} 0 & 1 \\ 1 & 0\end{array}\right)$, you see that the vector $\left(\begin{array}{c} 1\\ 1\end{array}\right)$ when multiplied with the matrix will just give you that vector again! For such a vector, it is very easy to see what $M\vec{x}$ looks like, and even what $M^k \vec{x}$ looks like, since, obviously, repeated application won't change it. This observation is generalized by the concept of eigenvectors. An eigenvector of a matrix $M$ is any vector $\vec{x}$ that only gets scaled (i.e. just multiplied by a number) when multiplied with $M$. Formally,$$M\vec{x} = \lambda \vec{x}$$for some number $\lambda$ (real or complex depending on the matrices you are looking at). So, if your matrix $M$ describes a system of some sort, the eigenvectors are those vectors that, when they go through the system, are changed in a very easy way. If $M$, for example, describes geometric operations, then $M$ could, in principle, stretch and rotate your vectors. But eigenvectors only get stretched, not rotated. The next important concept is that of an eigenbasis . By choosing a different basis for your vector space, you can alter the appearance of the matrix $M$ in that basis. Simply speaking, the $i$-th column of $M$ tells you what the $i$-th basis vector multiplied with $M$ would look like. If all your basis vectors are also eigenvectors, then it is not hard to see that the matrix $M$ is diagonal . Diagonal matrices are a welcome sight, because they are really easy to deal with: Matrix-vector and Matrix-matrix multiplication becomes very efficient, and computing the $k$-th power of a diagonal matrix is also trivial. I think for a "broad" introduction this might suffice?
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/36815', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10445/']}
jdg_377931
stackexchange
llm_judgeable_groundtruth_similarity
20457856
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've read quite a lot answers but couldn't figure out why xdebug doesn't work. php.ini: [xdebug]zend_extension="/usr/lib/php5/20090626/xdebug.so" php -v: PHP 5.5.6-1+debphp.org~precise+2 (cli) (built: Nov 21 2013 14:31:41) Copyright (c) 1997-2013 The PHP GroupZend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies /usr/lib/php5/20090626/xdebug.so does exist. No zend optimizer in php.ini. Also if I try to install xdebug: pecl/xdebug is already installed and is the same as the released version 2.2.3install failed Thanks in advance. Now provide the response and nothing else.
Ok so I've stumbled upon this myself. First of all, the 20090626 lib is compiled for php 5.3. So you can't really use that. Here are the steps I've performed in order to be able to use xdebug with php 5.5: Download the source via xdebug download page. Follow this guide for compiling your source into lib. So now the extension is in correct source folder: 20121212, and you need to enable xdebug in your config. I'm on ubuntu 12.04, so next steps might not work with your system: create 20-xdebug.ini config and copy it to both /etc/php5/apache/conf.d and /etc/php5/cli/conf.d folders (if you plan on using xdebug in your cli of course). Insert next line of code there: zend_extension=xdebug.so enable xdebug in both apache2 and cli php.ini configuration files: xdebug.remote_enable = 1xdebug.renite_enable = 1xdebug.max_nesting_level = 1000xdebug.profiler_enable_trigger = 1xdebug.profiler_output_dir = '/var/log' See more about xdebug settings: http://xdebug.org/docs/all_settings php -v: PHP 5.5.7-1+sury.org~precise+1 (cli) (built: Dec 12 2013 21:37:40) Copyright (c) 1997-2013 The PHP GroupZend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20457856', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064428/']}
jdg_377932
stackexchange
llm_judgeable_groundtruth_similarity
3198803
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 certain country has a cricket squad of 16 people, consisting of 7 batsmen, 5 bowlers, 2 all- rounders and 2 wicket-keepers. The manager chooses a team of 11 players consisting of 5 batsmen, 4 bowlers, 1 all-rounder and 1 wicket keeper. Find the number of different teams the manager can choose if one particular batsman refuses to be in the team when one particular bowler is in the team. I did it $6C5 \cdot 5C4 \cdot 2 \cdot 2 + 7C5 \cdot 4C3 \cdot 2 \cdot 2$ . It is completely wrong. How to do it? Now provide the response and nothing else.
$\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,} \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\ic}{\mathrm{i}} \newcommand{\mc}[1]{\mathcal{#1}} \newcommand{\mrm}[1]{\mathrm{#1}} \newcommand{\pars}[1]{\left(\,{#1}\,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$ \begin{align}&\bbox[10px,#ffd]{\left.\vphantom{\Large A}\mrm{I}\pars{M,N}\,\right\vert_{\ M, N\ \in\ \mathbb{N}_{\large\ \geq 0}}} \equiv\int_{0}^{\pi}{\sin\pars{\bracks{M + 1/2}\theta}\sin\pars{\bracks{N + 1/2}\theta} \over \sin^{2}\pars{\theta/2}}\,\dd\theta\\[5mm] = &\{1 \over 2}\int_{0}^{\pi}{\cos\pars{\bracks{M - N}\theta}-\cos\pars{\bracks{M + N + 1}\theta} \over \sin^{2}\pars{\theta/2}}\,\dd\theta\\[5mm] = &\{1 \over 2}\int_{0}^{\pi}{1 - \cos\pars{\bracks{M + N + 1}\theta} \over \sin^{2}\pars{\theta/2}}\,\dd\theta -{1 \over 2}\int_{0}^{\pi}{1 - \cos\pars{\verts{M - N}\theta} \over \sin^{2}\pars{\theta/2}}\,\dd\theta\\[5mm] = &\\bbox[10px,#ffd]{\mc{J}\pars{M + N + 1} - \mc{J}\pars{\verts{M - N}}}\label{1}\tag{1}\\[5mm] &\ \mbox{where}\quad\left\{\begin{array}{rcl}\ds{\left.\vphantom{\Large A}\mc{J}\pars{a}\,\right\vert_{\ a\ \in\ \mathbb{N}_{\ \geq\ 0}}} & \ds{\equiv} & \ds{\int_{0}^{\pi/2}{1 - \cos\pars{2a\theta} \over \sin^{2}\pars{\theta}}\,\dd\theta}\\[2mm]& \ds{=} & \ds{\Re\int_{0}^{\pi/2}{1 + 2\ic a\theta - \expo{2\ic a\theta} \over \sin^{2}\pars{\theta}}\,\dd\theta}\end{array}\right.\end{align} Lets evaluate $\ds{\mrm{J}\pars{a}}$ : \begin{align}\mc{J}\pars{a} & =\Re\int_{0}^{\pi/2}{1 + 2\ic a\theta - \expo{2\ic a\theta} \over \sin^{2}\pars{\theta}}\,\dd\theta\\[5mm] & =\left.\Re\int_{\theta\ =\ 0}^{\theta\ =\ \pi/2}{1 + 2\ic a\bracks{-\ic\ln\pars{z}} - z^{2a} \over-\pars{1 - z^{2}}^{2}/\pars{4z^{2}}}\,{\dd z \over \ic z}\,\right\vert_{\ z\ =\ \exp\pars{\ic\theta}}\\[5mm] & =\left.4\,\Im\int_{\theta\ =\ 0}^{\theta\ =\ \pi/2}{z^{2a} - 2a\ln\pars{z} - 1 \over\pars{1 - z^{2}}^{2}}\,z\,\dd z\,\right\vert_{\ z\ =\ \exp\pars{\ic\theta}}\\[5mm] & =-4\,\Im\int_{1}^{0}{y^{2a}\expo{\ic\pars{2a}\pi/2} - 2a\bracks{\ln\pars{y} + \ic\pi/2} - 1 \over\pars{1 + y^{2}}^{2}}\pars{\ic y}\,\ic\,\dd y\\[5mm] & =-4\int_{0}^{1}{y^{2a}\\overbrace{\sin\pars{\pi a}}^{\ds{\color{red}{=\ 0}}}\ -\\pi a \over\pars{1 + y^{2}}^{2}}\,y\,\dd y\\[5mm] & \stackrel{y^{2}\ \mapsto\ y}{=}\,\,\,2\pi a\int_{0}^{1}{\dd y \over\pars{1 + y}^{2}} = \bbx{\pi a}\label{2}\tag{2}\end{align} With \eqref{1} and \eqref{2}: $$\bbx{\mrm{I}\pars{M,N} =\pi\pars{M + N + 1 - \verts{M - N}}}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3198803', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/666909/']}
jdg_377933
stackexchange
llm_judgeable_groundtruth_similarity
4876740
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Thats my error: dyld: Library not loaded: /usr/local/lib/libofa.0.dylibReferenced from: /sers/david/Projekte/Test/build/Debug/Test.app/Contents/MacOS/TestReason: image not found I've done some research and changed the path inside the dylib with install_name_tool: davids-macbook:Test david$ otool -L libofa.0.0.0.dylib libofa.0.0.0.dylib:@executable_path/../Frameworks/libofa.0.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.1)/System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate (compatibility version 1.0.0, current version 4.0.0)/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0) But Xcode keeps searching for it in /usr/lib/: build/Debug/Test.app/Contents/MacOS/Test:/System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa (compatibility version 1.0.0, current version 15.0.0)/System/Library/Frameworks/AudioToolbox.framework/Versions/A/AudioToolbox (compatibility version 1.0.0, current version 1.0.0)/opt/local/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.5)@executable_path/../Frameworks/TagLib.framework/Versions/A/TagLib (compatibility version 1.0.0, current version 1.0.0)/System/Library/Frameworks/QTKit.framework/Versions/A/QTKit (compatibility version 1.0.0, current version 1.0.0)/opt/local/lib/libexpat.1.dylib (compatibility version 7.0.0, current version 7.2.0)/System/Library/Frameworks/Quartz.framework/Versions/A/Quartz (compatibility version 1.0.0, current version 1.0.0)/opt/local/lib/libcurl.4.dylib (compatibility version 7.0.0, current version 7.0.0)/usr/local/lib/libofa.0.dylib (compatibility version 1.0.0, current version 1.0.0)/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0)/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 103.0.0)/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0)/usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 227.0.0)/System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices (compatibility version 1.0.0, current version 44.0.0)/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 550.29.0)/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 751.29.0)/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit (compatibility version 45.0.0, current version 1038.32.0) Is there a way to set this in Xcode??? Thanks Edit: The library is not a Xcode project. Its build with ./configure; make Now provide the response and nothing else.
Normally what I do is this: Set the Installation Directory of the library to @rpath . This will set the install name to @rpath/libofa.0.0.0.dylib . If you're building the library yourself, you can set this in Xcode; otherwise, use install_name_tool to change it. Set the Runpath Search Paths of the application using the library to the location of the directory containing the library. For example, if you put the library in the app's Frameworks directory, you'd set Runpath Search Paths to @executable_path/../Frameworks (or @loader_path/../Frameworks ). This blog post and this one go into more detail.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4876740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174373/']}
jdg_377934
stackexchange
llm_judgeable_groundtruth_similarity
62091146
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 for react class component we have componentWillMount() lifecycle method, where we can perform tasks before loading the component. Tasks like, a call to backend and use the response to show that data in that frontend. What if I want the same thing in a functional component? like I have used react chartJS and for that the data values I want to be retrieved from backend response, and then the chart will populate based on those datas. I hope I explained the problem statement well, if not please ask for any information. Now provide the response and nothing else.
componentWillMount is call only one time before initial render.I make a sample code, check it out below import React, { useState, useEffect } from "react";import "./styles.css";export default function App() { const [mounted, setMounted] = useState(false) if(!mounted){ // Code for componentWillMount here // This code is called only one time before intial render } useEffect(() =>{ setMounted(true) },[]) return ( <div className="App"> </div> );} As you mentioned you want to make an api call, it usually happen in componentDidmount and you can simply use useEffect hook with empty array as dependencies in functional component import React, { useState, useEffect } from "react";import "./styles.css";export default function App() { const [mounted, setMounted] = useState(false) useEffect(() =>{ // This is similar to componentDidMount // Call back-end api here },[]) return ( <div className="App"> </div> );}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62091146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8290251/']}
jdg_377935
stackexchange
llm_judgeable_groundtruth_similarity
57846127
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'm trying to understand them, It seem like they are both used to route/map the request to a certain endpoint Now provide the response and nothing else.
UseRouting : Matches request to an endpoint. UseEndpoints : Execute the matched endpoint. It decouples the route matching and resolution functionality from the endpoint executing functionality, which until now was all bundled in with the MVC middleware. This makes the ASP.NET Core framework more flexible and allows othermiddlewares to act between UseRouting and UseEndpoints . That allowsthose middlewares to utilize the information from endpoint routing,for example, the call to UseAuthentication must go after UseRouting , so that route information is available for authentication decisions and before UseEndpoints so that users areauthenticated before accessing the endpoints. Update .NET 6 In ASP.NET Core 6, there's no need to have explicit calls to UseRouting or UseEndpoints to register routes. UseRouting can still be used to specify where route matching happens, but UseRouting doesn't need to be explicitly called if routes should be matched at the beginning of the middleware pipeline. Depending on where app.Use is called in the pipeline, there may not be an endpoint: app.Use(async (context, next) =>{ Console.WriteLine("Before routing runs, endpoint is always null here"); Console.WriteLine($"Endpoint: {context.GetEndpoint()?.DisplayName ?? "null"}"); await next(context);});app.UseRouting();app.Use(async (context, next) =>{ Console.WriteLine("After routing runs, endpoint will be non-null if routing found a match."); Console.WriteLine($"Endpoint: {context.GetEndpoint()?.DisplayName ?? "null"}"); await next(context);});app.MapGet("/", (HttpContext context) =>{ Console.WriteLine("Runs when this endpoint matches"); Console.WriteLine($"Endpoint: {context.GetEndpoint()?.DisplayName ?? "null"}"); return "Hello World!";}).WithDisplayName("/");app.UseEndpoints(_ => { });app.Use(async (context, next) =>{ Console.WriteLine("Runs after UseEndpoints - will only run if there was no match."); Console.WriteLine($"Endpoint: {context.GetEndpoint()?.DisplayName ?? "null"}"); await next(context);});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57846127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2766753/']}
jdg_377936
stackexchange
llm_judgeable_groundtruth_similarity
46613243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Only at the checkout and on individual product pages I am getting the following error in the console log: VM35594:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at run (layout.min.js:9) at app.min.js:1 at main.min.js:2 at Object.execCb (require.min.js:112) at Module.check (require.min.js:56) at Module.<anonymous> (require.min.js:72) at require.min.js:11 at require.min.js:74 at each (require.min.js:3) I am using a one page checkout extension, but when I disable that the error still shows. I thought it might had something to do with the reviews on the product page (as I moved the reviews out of the tabs), but undoing that change didn't fix the error on the product pages. Now provide the response and nothing else.
Try this in the console: JSON.parse(undefined) Here is what you will get: Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at <anonymous>:1:6 In other words, your app is attempting to parse undefined , which is not valid JSON. There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode). window.foobar = '{"some":"data"}';JSON.parse(window.foobarn) // oops, misspelled! The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't. Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint . This will give you pretty good confidence that there are no typos.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/46613243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3204827/']}
jdg_377937
stackexchange
llm_judgeable_groundtruth_similarity
24706708
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to run a docker container that hosts a simple web application, however I do not understand how to design/run the image as a server. For example: docker run -d -p 80:80 ubuntu:14.04 /bin/bash This will start and immediately shutdown the container. Instead we can start it interactively: docker run -i -p 80:80 ubuntu:14.04 /bin/bash This works, but now I have to keep open the interactive shell for every container that is running? I would rather just start it and have it running in the background. A hack would be using a command that never returns: docker run -d -p 80:80 {image} tail -F /var/log/kern.log But now I cannot connect to the shell anymore, to inspect what is going on if the application is acting up. Is there a way to start the container in the background (as we would do for a vm), in a way that allows for attaching/detaching a shell from the host? Or am I completely missing the point? Now provide the response and nothing else.
The final argument to docker run is the command to run within the container. When you run docker run -d -p 80:80 ubuntu:14.04 /bin/bash , you're running bash in the container and nothing more. You actually want to run your web application in a container and to keep that container alive, so you should do docker run -d -p 80:80 ubuntu:14.04 /path/to/yourapp . But your application probably depends on some configuration in order to run. If it reads its configuration from environment variables, you can use the -e key=value arguments with docker run . If your application needs a configuration file to be in place, you should probably use a Dockerfile to set up the configuration first. This article provides a nice complete example of running a node application in a container.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24706708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318752/']}
jdg_377938
stackexchange
llm_judgeable_groundtruth_similarity
6903337
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Up until two days ago, I was able to use Visual Studio 2010's "Publish Web" option by right clicking on my project and clicking the publish button on the context menu. Now when I try to do the same thing, I get the following output: ------ Build started: Project: ELMS, Configuration: Debug Any CPU ------Build started 8/1/2011 3:08:03 PM.GenerateTargetFrameworkMonikerAttribute:Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files areup-to-date with respect to the input files._CopyOutOfDateSourceItemsToOutputDirectoryAlways:Copying file from "C:\SVN\TrakNet\trunk\MTS\lib\Newtonsoft.Json.Net35.dll" to "bin\lib\Newtonsoft.Json.Net35.dll".CopyFilesToOutputDirectory: LMS -> C:\SVN\TrakNet\trunk\MTS\bin\LMS.dllBuild succeeded.Time Elapsed 00:00:00.04------ Publish started: Project: LMS, Configuration: Debug Any CPU ------Object reference not set to an instance of an object.========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==================== Publish: 0 succeeded, 1 failed, 0 skipped ========== This is while attempting to publish to localhost (for debugging purposes) Here are the settings of the publish profile that I'm using: Publish Method: Web DeployService URL: localhostSite/application: default web site/ELMS[x] Mark as IIS application on destination[x] Leave extra files on destination (do not delete) I have already attempted: - Cleaning/rebuilding the project- Deleting the bin folder of the project- Running reg_iis.exe -i- Reinstalling VS2010 but nothing I've changed has fixed the error. Any insight into what might be causing the issue would be greatly appreciated :) EDIT: The problem actually resolved itself as of my last reboot. I must have rebooted 6-7 times since the problem first manifested itself, but this time no Object Reference message. Here's the log from the build/publish now: ------ Build started: Project: LMS, Configuration: Debug Any CPU ------Build started 8/3/2011 9:10:12 AM.GenerateTargetFrameworkMonikerAttribute:Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files._CopyOutOfDateSourceItemsToOutputDirectoryAlways: Copying file from "C:\SVN\TrakNet\trunk\MTS\lib\Newtonsoft.Json.Net35.dll" to "bin\lib\Newtonsoft.Json.Net35.dll".CopyFilesToOutputDirectory: LMS -> C:\SVN\TrakNet\trunk\MTS\bin\LMS.dllBuild succeeded.Time Elapsed 00:00:00.04------ Publish started: Project: LMS, Configuration: Debug Any CPU ------Gather all files from Project items @(IntermediateAssembly). Adding:bin\LMS.dll to bin\LMS.dllbin\LMS.pdb to bin\LMS.pdbGather all files from Project items @(Content). Adding:Global.asax;lib\Newtonsoft.Json.Net35.dll;MtsSchemas\MtsSchema.xml;Web.configGather all files from Project output (IntermediateSatelliteAssembliesWithTargetPath).Adding:Gather all files from Project items@(ReferenceCopyLocalPaths,ReferenceComWrappersToCopyLocal,ResolvedIsolatedComModules,_DeploymentLooseManifestFile,NativeReferenceFile).Gather all files from Project items @(AllExtraReferenceFiles). Adding:Gather all files from Project items@(_SourceItemsToCopyToOutputDirectoryAlways,_SourceItemsToCopyToOutputDirectory). Adding:bin\lib\Newtonsoft.Json.Net35.dllGather all files from Project items @(_binDeployableAssemblies). Adding:Publish Pipeline Collect Files PhaseFound The following for Config tranformation:Web.configCreating directory "C:\SVN\TrakNet\trunk\MTS\obj\Debug\TransformWebConfig\transformed\".Publish Pipeline Transform PhaseCreating directory "C:\SVN\TrakNet\trunk\MTS\obj\Debug\CSAutoParameterize\transformed\".Copying Web.config to obj\Debug\CSAutoParameterize\original\Web.config.Transforming Source File: C:\SVN\TrakNet\trunk\MTS\Web.config Applying Transform File: <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <add connectionString="{% token='$(ReplacableToken_#(parameter)_#(tokennumber))' xpathlocator='name' parameter='$(name)-Web.config Connection String' description='$(name) Connection String used in web.config by the application to access the database.' defaultValue='$(connectionString)' tags='SqlConnectionString' %}" xdt:Transform="SetTokenizedAttributes(connectionString)" xdt:SupressWarnings="True" /> </connectionStrings> </configuration> Output File: obj\Debug\CSAutoParameterize\transformed\Web.config Transformation succeededAuto ConnectionString Transformed Web.config into obj\Debug\CSAutoParameterize\transformed\Web.config.Creating directory "obj\Debug\Package\PackageTmp".Copying all files to temporary location below for package/publish:obj\Debug\Package\PackageTmp.Copying bin\LMS.dll to obj\Debug\Package\PackageTmp\bin\LMS.dll.Copying bin\LMS.pdb to obj\Debug\Package\PackageTmp\bin\LMS.pdb.Copying Global.asax to obj\Debug\Package\PackageTmp\Global.asax.Copying lib\Newtonsoft.Json.Net35.dll to obj\Debug\Package\PackageTmp\lib\Newtonsoft.Json.Net35.dll.Copying MtsSchemas\MtsSchema.xml to obj\Debug\Package\PackageTmp\MtsSchemas\MtsSchema.xml.Copying C:\SVN\TrakNet\trunk\MTS\lib\Newtonsoft.Json.Net35.dll to obj\Debug\Package\PackageTmp\bin\lib\Newtonsoft.Json.Net35.dll.Copying obj\Debug\CSAutoParameterize\transformed\Web.config to obj\Debug\Package\PackageTmp\Web.config.Publish Pipeline Deploy phase Pre-Deploy CopyAllFilesToOneFolder StageGenerate source manifest file for Web Deploy package/publish ...Creating directory "obj\Debug\Database".Starting Web deployment task from source:manifest(C:\SVN\TrakNet\trunk\MTS\obj\Debug\Package\LMS.SourceManifest.xml) to Destination:auto().Updating filePath (default web site/LMS\bin\ELMS.dll).Updating filePath (default web site/LMS\bin\ELMS.pdb).Updating filePath (default web site/LMS\bin\lib\Newtonsoft.Json.Net35.dll).Updating filePath (default web site/LMS\lib\Newtonsoft.Json.Net35.dll).Updating filePath (default web site/LMS\Web.config).Updating setAcl (default web site/LMS).Updating setAcl (default web site/LMS).Successfully executed Web deployment task.Publish is successfully deployed.========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==================== Publish: 1 succeeded, 0 failed, 0 skipped ========== Like I said: No idea what changed. I had been manually moving the DLLs into the website's virtual directory, then just for kicks I tried publishing this morning, and everything worked out fine. Now provide the response and nothing else.
In my experience this can happen when files are added/removed from different branches of your source control and an imperfect merge causes the project file structure and the actual file structure to diverge. This could be one of several options: A file was deleted but the project still references it. Will fail to compile, will fail to publish. A file was added but is not referenced by the project. May compile, depends whether the class/methods are referenced elsewhere in the project/solution. If compiles, will publish. A file was added, but the project merge caused it to appear more than once in the project listing. Will compile, will fail to publish. The solution is to look at the source control logs and trying to identify the bad merge to the project file for the above issues, then fixing the project file accordingly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6903337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873339/']}
jdg_377939
stackexchange
llm_judgeable_groundtruth_similarity
3287315
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 Killing-Hopf theorem says that if $M$ is a complete connected Riemannian manifold of constant sectional curvature $K$ , its universal cover is one of the following: if $K > 0$ , it is the sphere; if $K = 0$ , it is the Euclidean space; if $K < 0$ , it is the hyperbolic space. Of these possibilities, only the first one implies a compact topology. Are there any texts or references that delve into the connection between compactness and curvature more deeply? Is there anything that classifies manifolds in the spirit of the Killing-Hopf theorem for more general cases? Now provide the response and nothing else.
There are two relevant theorems of differential geometry. One is the Cartan-Hadamard theorem , which says that if $M$ is a geodesically complete, simply connected Riemannian $m$ -manifold such that all sectional curvatures of $M$ are $\le 0$ , then $M$ is diffeomorphic to Euclidean space $\mathbb R^m$ , and so in particular $M$ is noncompact. One application is that every compact Riemannian manifold whose sectional curvatures are $\le 0$ has infinite fundamental group, because its universal cover satisfies the hypotheses of the Cartan-Hadamard theorem and hence is not compact. The other is the Bonnet-Myer theorem . A weak form of this theorem (due to Bonnet) says that if $M$ is a geodesically complete Riemannian $m$ -manifold such that all sectional curvatures of $M$ are $> k$ where $k$ is some positive constant, then $M$ is compact. It follows that the fundamental group of $M$ is finite, because the same hypotheses hold for the universal cover of $M$ which is therefore compact.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3287315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/352912/']}
jdg_377940