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
182555
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 does the concept of wave reflection seem to only apply to transmission lines? For example, for a simple circuit with two resistances R1 = 50\$\Omega\$ and R2 = 75\$\Omega\$, is the voltage wave coming from the first resistance reflected by the amount: \$ \Gamma = \dfrac{75-50}{75+50} = 0.2\$ ? Then it would mean a \$(0.2)^2 = 0.04 = 4\%\$ power reflection and a \$1 - 0.04 = 96\%\$ power transfer. But then what is the incident power? I guess you could brush it off as "transmission lines and resistances are different things" but then what IS the fundamental distinction between them? You kind of have a "wave" of electrons "travelling" in a resistance, and I guess that if they hit another resistance with a different ability to let electrons "travel", then they should partially go back, hence be reflected. Now provide the response and nothing else.
Reflections happen everywhere, not just in transmission lines. Transmission line is a model of the physical situation, which is easy to apply to a pair of conductors whose length is comparable to or larger than the wavelength of the signal, and which is regular in cross section. What determines whether reflections matter is the frequencies in and the physical size of the circuit. If you have unmatched impedances then you do get reflected waves just as you describe, and either you have to deal with them or they are negligible for some reason. Here are two reasons: For exclusively low-frequency circuits, the reflections reflect repeatedly and settle down on a timescale much faster than the signals change. That is, each double reflection is an extra signal which is merely out of phase with the original signal, but as they get more out of phase their amplitude drops quickly enough that they can be neglected. (Even RF circuits can be built this way, as can be seen from a lot of homebuilt HF amateur radio gear.) As frequency increases, wavelength decreases, and the physical size of your components becomes relatively larger, and you start having to worry about avoiding impedance “bumps”. This is where you start using microstrip design techniques in printed circuits. In digital circuits, sharp transitions may have high-frequency components that will reflect but you don't have to worry about this as long as your clock speed is much slower than the length of your traces/wires (there's a conversion via c to make that make sense, of course) because by the time the clock makes its next tick all the signals have settled down to a steady state. (Note that there are no standing waves here because within the period of a single clock tick the driving signals are steps (high to low or low to high logic levels), not periodic signals.) As clock speed increases, the settling time available decreases, requiring you to either minimize reflections or minimize signal travel time (so that the settling occurs faster).
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/182555', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/82123/']}
jdg_70541
stackexchange
llm_judgeable_groundtruth_similarity
43380704
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 queries file that looks like this: import {gql} from 'react-apollo';const queries = { getApps: gql` { apps { id name } } `, getSubjects: gql` { subjects { id name } } `};export default queries; I then import this file to my React component: import React, {Component} from 'react'import queries from './queries'class Test extends Component {...}export default graphql(queries.getSubjects)(graphql(queries.getApps)(Test)); This will only get data for one of the queries (getApps) and not both. If I do one at a time so that it looks like this: export default graphql(queries.getSubjects)(Test); then it works but I don't have my other query. Yes, I have tested both separately and they work. How do I get it so that both queries show up in my props.data? Now provide the response and nothing else.
My preferred way is to use the compose functionality of the apollo client ( docu ). EDIT:If you have more than one query you should name them. So in your case, it could look like this: import React, {Component} from 'react'import queries from './queries'import { graphql, compose } from 'react-apollo';class Test extends Component {... render() { ... console.log(this.props.subjectsQuery, this.props.appsQuery); // should show both ... }}export default compose( graphql(queries.getSubjects, { name: "subjectsQuery" }), graphql(queries.getApps, { name: "appsQuery" }),)(Test);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43380704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2465134/']}
jdg_70542
stackexchange
llm_judgeable_groundtruth_similarity
29161323
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 try to iterate over an associative array in Bash. It seems to be simple, but the loop doesn't follow the initial order of the array. Here is a simple script to try: #!/bin/bashecho -e "Workspace\n----------";lsb_release -aecho -e "\nBash version\n----------";echo -e $BASH_VERSION."\n";declare -A groups;groups["group1"]="123";groups["group2"]="456";groups["group3"]="789";groups["group4"]="abc";groups["group5"]="def";echo -e "Result\n----------";for i in "${!groups[@]}"do echo "$i => ${groups[$i]}";done The output: Workspace----------No LSB modules are available.Distributor ID: UbuntuDescription: Ubuntu 14.04.2 LTSRelease: 14.04Codename: trustyBash version----------4.3.11(1)-release.Result----------group3 => 789group2 => 456group1 => 123group5 => defgroup4 => abc Why I don't have group1 , group2 , etc.? I don't want to have an alphanum order, I just want that the loop follow the initial declaration's order of the array... Is there a way? Now provide the response and nothing else.
As already pointed out, there is no mistake. Associative arrays are stored in a 'hash' order. If you want ordering, you don't use associative arrays. Or, you use a non-associative array as well as an associative array. Keep a second (non-associative) array that identifies the keys in the order that they're created. Then step through the second array, using its contents to key the first (associative) array when printing the data. Like this: declare -A groups; declare -a orders;groups["group1"]="123"; orders+=( "group1" )groups["group2"]="456"; orders+=( "group2" )groups["group3"]="789"; orders+=( "group3" )groups["group4"]="abc"; orders+=( "group4" )groups["group5"]="def"; orders+=( "group5" )# Convoluted option 1for i in "${!orders[@]}"do echo "${orders[$i]}: ${groups[${orders[$i]}]}"doneecho# Convoluted option 1 - 'explained'for i in "${!orders[@]}"do echo "$i: ${orders[$i]}: ${groups[${orders[$i]}]}"doneecho# Simpler option 2 - thanks, PesaThefor i in "${orders[@]}"do echo "$i: ${groups[$i]}"done The 'simpler option 2' was suggested by PesaThe in a comment , and should be used in preference to the 'convoluted option'. Sample output: group1: 123group2: 456group3: 789group4: abcgroup5: def0: group1: 1231: group2: 4562: group3: 7893: group4: abc4: group5: defgroup1: 123group2: 456group3: 789group4: abcgroup5: def You probably don't want to have two statements per line like that, but it emphasizes the parallelism between the handling of the two arrays. The semicolons after the assignments in the question are not really necessary (though they do no active harm, beyond leaving the reader wondering 'why?').
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29161323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348124/']}
jdg_70543
stackexchange
llm_judgeable_groundtruth_similarity
1006072
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: Update is at bottom of my post. I saw on YouTube ( https://www.youtube.com/watch?v=_rJdkhlWZVQ ) a way to approximate $\pi$ starting with a hexagon inscribed inside a circle of unit radius. It uses formulas and relies on doubling the numbers of sides of the inscribed polygon (from $6$ to $12$ to $24$ to $48$ to $96$). Here is a list of the values for the approximation of $\pi$ based on those: $5$ tuple is: (# of polygon sides, estimate of $\pi$, diff. in prev $\pi$ estimate, d=prev. diff./curr. diff., $4$-d) $$(6, 3.00000000000000, 3.00000000000000, xxxxxxxxxxxxxx, xxxxxxxxxxxxxx)$$ $$(12, 3.10582854123025, .10582854123025, xxxxxxxxxxxxxx, xxxxxxxxxxxxxx)$$ $$(24, 3.13262861328124, .02680007205099, 3.94881554903670, .05118445096330)$$ $$(48, 3.13935020304687, .00672158976563, 3.98716270785101, .01283729214899)$$ $$(96, 3.14103195089051, .00168174784364, 3.99678809818983, .00321190181017)$$ I added most of my extrapolated data here for ease of viewing but I explain later how I got it. x1 = extrapolation # $1$, x2 = extrapolation # $2$... $$(x1, 3.14145247226851, .00042052137800, 3.99919702454746, .00080297545254)$$ $$(x2, 3.14155760788934, .00010513562083, 3.99979925613686, .00020074386314)$$ $$(x3, 3.14158389212432, .00002628423498, 3.99994981403422, .00005018596578)$$ $$(x4, 3.14159046320368, .00000657107936, 3.99998745350855, .00001254649145)$$ $$(x5, 3.14159210597481, .00000164277113, 3.99999686337714, .00000313662286)$$ $$(x6, 3.14159251666767, .00000041069286, 3.99999921584428, .00000078415572)$$ $$(x7, 3.14159261934089, .00000010267322, 3.99999980396107, .00000019603893)$$ $$(x8, 3.14159264500919, .00000002566831, 3.99999995099027, .00000004900973)$$ $$(x9, 3.14159265142627, .00000000641708, 3.99999998774757, .00000001225243)$$... $$(x18, 3.14159265356529,.00000000000002, 3.99999999999995, .00000000000005)$$ I believe Archimedes stopped at a $96$ sided inscribed polygon because the calculations by hand became too tedious at that point so the data above is the end of the data we get from the $96$ sided polygon but you can see that there is a predictable pattern to these tuples. To get the approximation of $\pi$, I simply sum up (accumulate) the $3$rd entries from each tuple. Notice how much quicker this is converging on the real value of $\pi$ and with minimal work. Just playing around in my Excel spreadsheet with these values, I noticed that these approximations of $\pi$ converge on the real value of $\pi$ in a predictable way so I encoded this in the spreadsheet and I came up with an extrapolated estimate of $\pi$ to be $3.14159265356529$ which I am quite happy with because it is as accurate as using about a $400,000$ sided polygon using Archimedes method but my method is much simpler. In a nutshell, I looked at the difference between the estimate from $12$ to $6$ and from $24$ to $12$... and I see that it is approximately "quartering" each time. I took that a step farther and analyzed how close to $1/4$ the difference is at each doubling and encoded that as well and just from those two simple calculations, I got a pretty decent $\pi$ accurate to $10$ digits after the decimal point. If I had the data on the circumscribed polygons, I suppose the # of accurate digits would increase even more. It makes sense that there is predictability since we are doubling the # of sides each time and not some random increase like from $6$ to $10$ to $25$ sides. So in my extrapolation method, my first step would be to take the last known "delta" of $.00321190181017$ and "quarter" it to $0.00080297545254$ so that the next tuple entry would be (extrapolation 1, $3.14145247226851, 0.00042052137800, 3.99919702454746, 0.00080297545254$) Also it is worth mentioning that using only data from up to $24$ inscribed polygons, my extrapolation method yields a quite good approximation of $3.14159265308398$ which is accurate to $9$ places after the decimal and that is as good as using about a $100,000$ sided polygon using Archimedes method. So does anyone know if there is documentation that Archimedes knew about this extrapolation method (or similar) during his lifetime? UPDATE: I revisited my spreadsheet and got a more accurate version of $ \pi$ using this method. The tweak is in the determination/extrapolation of the 5th parameter. I am not sure how or why this tweak works (maybe someone can explain the math behind it), but it gives an even better approximation of $ \pi$. Rather than list a bunch more numbers in an already cluttered post, I will just describe the tweak and leave it at that. $x1$ (extrapolation 1) is exactly the same as in my previous effort (I took the 5th parameter $.00321190181017$ in the "$96$ sided polygon" entry and divided it by $4$ to get $.00080297545254$. However, for $x2$, I did NOT do a divide by $4$ to get the 5th parameter. Instead, I used the 4th parameter of the "$48$gon" entry which is $3.98716270785101$. The "new" 5th parm of $x2$ is now $.00020139018931$. I repeat this pattern for getting the next 5th parameter by "dropping down a line" each time. The "bottom line" is the approximation of $\pi$ this way improves from my previous value of $3.14159265356529$ to $3.14159265358983$. Notice how the previous estimate was on the low side of the actual value of $\pi$ but the new estimate is slightly on the high side. Also, here is the follow up YouTube video link for the Archimedes method of circumscribed polygon to "sandwich" the value of $\pi$ between. With those two values, the confidence level of $\pi$ goes way up. https://www.youtube.com/watch?v=9zO0-QOcJQ0 Now provide the response and nothing else.
This is not an answer, just an alternative exposition of your findings as far as I was able to reproduce them. First, the video describes Archimedes' method for approximating $\pi$ via the following recurrence for the side length of a regular $3\cdot2^n$-gon inscribed in a circle, which I'll call $\ell_n$:$$ \ell_1=1 \text{ ,}\qquad \ell_{n+1} = 2\sqrt{2-\sqrt{4-\ell_n^2}} \tag1 $$Then we approximate $\pi$ as half the perimeter of that $3\cdot2^n$-gon, that is,$$ h_n = 3\cdot 2^{n-1} \ell_n $$ What you've noticed numerically is that$$ \frac{h_n-h_{n-1}}{h_{n-1}-h_{n-2}} \approx \frac14 \tag2 $$(Nice observation, by the way. If you do the trigonometry, it turns out that$$ \frac{h_n-h_{n-1}}{h_{n-1}-h_{n-2}} = \frac1{2\cos\theta_n(1+\cos\theta_n)}\text{ ,}\quad\text{ where } \theta_n = \frac{\pi}{3\cdot2^n} $$which confirms your finding because $\cos\theta\to 1$ as $\theta\to 0$. This also shows that the LHS is always $\ge\frac14$.) Next, you started approximating $h_n$ using (2) instead of the Archimedean recurrence (1). Actually, you say you have something more precise than $\frac14$ on the RHS of (2), but you don't say what it is, so I'll just proceed as if you used $\frac14$. Let's call the values obtained by this method $\hat h_n$. Since you started using this method after the $96$-gon, the sequence is given by the rules$$ \hat h_4 = h_4 \text{ ,}\quad \hat h_5 = h_5 \text{ ,}\quad \frac{\hat h_n-\hat h_{n-1}}{\hat h_{n-1}-\hat h_{n-2}} = \frac14 $$By telescoping product, we get$$ \hat h_n - \hat h_{n-1} = (\hat h_5 - \hat h_4) \prod_{k=6}^n \frac{\hat h_k-\hat h_{k-1}}{\hat h_{k-1}-\hat h_{k-2}}= \frac{\hat h_5 - \hat h_4}{4^{n-5}} $$and then, by telescoping sum,$$ \hat h_n = \hat h_5 + \sum_{k=6}^n (\hat h_k-\hat h_{k-1})= \hat h_5 + (\hat h_5-\hat h_4)\sum_{k=6}^n \frac1{4^{k-5}}= \hat h_5 + \frac13 (\hat h_5-\hat h_4) \Big(1-\frac1{4^{n-4}}\Big)$$Now you can see that as $n\to\infty$, we have$$ \hat h_n \to \hat h_5 + \frac13 (\hat h_5-\hat h_4)= \frac{4h_5-h_4}{3}\approx 3.1415925335$$So, this sequence is not actually tending to $\pi$, but to something a bit smaller. Update: I don't know whether Archimedes knew your method, but I will note that the summation of the infinite geometric series used here was absolutely something he knew — he did that as part of his computation of the area of a parabolic sector. Update: It occurs to me that another way to use your idea is to compute $h_n$ via (1) as usual, but rather than report that as your estimate, report $(4h_n-h_{n-1})/3$. This is as if you had used (2) starting from $n$ instead of starting from $6$, and it gives a sharper lower bound for $\pi$. (It's a lower bound because, as noted above, in (2) we have $\ge$.) You still have to use (1), unfortunately.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1006072', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/175745/']}
jdg_70544
stackexchange
llm_judgeable_groundtruth_similarity
21805868
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't see anything functionally wrong in terms of what gets executed, but I've just wasted an hour proving my code and the compiler are doing what they're supposed to. Consider this code: public int getAnswer(int a) { int retval = 18; int x = 25; int y = 50; while (a-- > 0) { if (a == 3) { retval = a; return retval; } } x = 10; y = 20; return 0;} Called with int theAnswer = getAnswer(6); Breakpoint both of the lines containing return and before you run the code, try and predict the result, and therefore which line will be hit. As you might imagine from the tone of my question, the wrong line is highlighted, but the right result is returned. If you step through the code, it dances around quite a bit. Is there anything that can be configured differently such that the correct lines are displayed? (I'm using the latest Android Studio, which I appreciate is potentially unstable, but I'm sure I've seen similar behaviour on Eclipse a while back but I never spent the time then tracking it down; perhaps it's a java thing). Now provide the response and nothing else.
This is a problem with dx, which is the part of the build that turns your Java .class files into .dx files for packaging into Android. According to this: https://code.google.com/p/android/issues/detail?id=34193 if a function has multiple return paths, dx merges the return instruction into a single return instruction, so during debugging, the debugger can't tell which line a return belongs to and things jump around. This corresponds to what I see when I try to reproduce your problem: each time through the loop it does the if (a == 3) check, jumps to the return 0 at the end, and then jumps back into the loop. You're seeing that last return 0 get merged with the return retval in the middle of the loop. I doubt this will be fixed any time soon, so you may just have to learn to live with it. Sorry, I know it's kinda crazy.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21805868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70545
stackexchange
llm_judgeable_groundtruth_similarity
23743217
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 application that usually runs silent in the background, so I compile it with go build -ldflags -H=windowsgui <gofile> To check the version at the command line, I wanted to pass a -V flag to the command line to get the string holding the version to be printed to the command prompt then have the application exit. I added the flag package and code. When I test it with go run <gofile> -V ...it prints the version fine. When I compile the exe, it just exits, printing nothing. I suspect it's the compilation flag causing it to not access the console and sending my text into the bit bucket. I've tried variations to print to stderr and stdout, using println and fprintf and os.stderr.write, but nothing appears from the compiled application. How should I try printing a string to the command prompt when compiled with those flags? Now provide the response and nothing else.
The problem is that when a process is created using an executable which has the "subsystem" variable in its PE header set to "Windows", the process has its three standard handles closed and it is not associated with any console —no matter if you run it from the console or not. (In fact, if you run an executable which has its subsystem set to "console" not from a console, a console is forcibly created for that process and the process is attached to it—you usually see it as a console window popping up all of a sudden.) Hence, to print anything to the console from a GUI process on Windows you have to explicitly connect that process to the console which is attached to its parent process (if it has one), like explained here for instance. To do this, you call the AttachConsole API function. With Go, this can be done using the syscall package: package mainimport ( "fmt" "syscall")const ( ATTACH_PARENT_PROCESS = ^uint32(0) // (DWORD)-1)var ( modkernel32 = syscall.NewLazyDLL("kernel32.dll") procAttachConsole = modkernel32.NewProc("AttachConsole"))func AttachConsole(dwParentProcess uint32) (ok bool) { r0, _, _ := syscall.Syscall(procAttachConsole.Addr(), 1, uintptr(dwParentProcess), 0, 0) ok = bool(r0 != 0) return}func main() { ok := AttachConsole(ATTACH_PARENT_PROCESS) if ok { fmt.Println("Okay, attached") }} To be truly complete, when AttachConsole() fails, this code should probably take one of these two routes: Call AllocConsole() to get its own console window created for it. It'd say this is pretty much useless for displaying version information as the process usually quits after printing it, and the resulting user experience will be a console window popping up and immediately disappearing; power users will get a hint that they should re-run the application from the console but mere mortals won't probably cope. Post a GUI dialog displaying the same information. I think this is just what's needed: note that displaying help/usage messages in response to the user specifying some command-line argument is quite often mentally associated with the console, but this is not a dogma to follow: for instance, try running msiexec.exe /? at the console and see what happens.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23743217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74361/']}
jdg_70546
stackexchange
llm_judgeable_groundtruth_similarity
31485
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can someone explain how to calculate the number of geometrical isomers in allenes like $\ce{CH3-(CH=CH)4-CH3}$ or $\ce{CH3-(CH=CH)5-CH3}$ Now provide the response and nothing else.
If we have one double bond in a hydrocarbon compound we have an olefin or alkene. Ethylene is the simplest example of this class of compounds. The carbons in the double bond and the 4 atoms attached to them lie in the same plane. One pair of cis-trans isomers is possible in compounds with a single double bond. If we add a nother double bond directly on to the end of the double bond in ethylene such that an sp hybridized carbon is created in the process, then we have formed an allene. The 4 substituents at the end of the double bonds in allene lie in planes that are oriented 90° to one another. Look at the allene (bottom line) in the following drawing. One set of substituents (R3, R4) are located in the plane of the screen; the other set of substituents (R1, R2) are located in a plane perpendicular to the screen. Allenes cannot generate cis-trans isomers, but they can generate enantiomers. Now let's add one more double bond to allene such that we now have 2 sp hybridized carbons (top line in the above drawing). We see that, like in ethylene, the 4 atoms connected to the double bond lie in the same plane as the double bond and one pair of cis-trans isomers is possible. Any compound with 3 or more cumulative double bonds is a member of the cumulene family. Any cumulene with an odd number of double bonds is geometrically structured like ethylene (the 4 atoms connected to the double bond lie in the same plane as the double bond) and is capable of having one pair of cis-trans isomers. Cumulenes with an even number of double bonds are structured like allene (the 4 atoms connected to the double bonds lie in perpendicular planes) and cannot display cis-trans isomerization, but can have enantiomers.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/31485', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/-1/']}
jdg_70547
stackexchange
llm_judgeable_groundtruth_similarity
4513450
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 $A \in \mathbb R^{n \times n}$ . We consider the map $$f_A : \mathbb R^{n \times n} \to \mathbb R^{n \times n} ,\quad X \mapsto AX.$$ By considering easy examples of $A$ one comes up quite fast with the conjecture $\det(D f_A) = \det(A)^n$ . Here $D f_A$ is the Jacobian matrix of $f_A$ . Is there an elegant proof which does not result in a long confusing computation? Idea (edit): I just came up with an idea. Obviously, the statement has only to be proven for non-singular $A$ . They are generated by elementary matrices. So it suffices to consider them since we have $f_A \circ f_B = f_{AB}$ . Now provide the response and nothing else.
Consider $X$ to be $n$ separate column vectors and then stack them on top of each other to form one large column vector $x=(x_{1,1},x_{2,1},\ldots,x_{n,1},x_{1,2},\ldots)^\top$ . The map $f_A$ can thus be represented by a block diagonal matrix $B$ of $n$ blocks, each block being $A$ . The linear map $f_A$ can be viewed as $\mathbb{R}^{n^2}\rightarrow\mathbb{R}^{n^2},x\mapsto Bx$ . The derivative of this linear map is just $B$ . Its determinant is (block diagonal matrix!): $$\det(B)=\det(A)^n.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4513450', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131887/']}
jdg_70548
stackexchange
llm_judgeable_groundtruth_similarity
33512725
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 make this script create a directory, then write stuff in it. Simple XML dumps & stuff. I cant get anything of FS to work. isDirectory, createDirectory, readFile, writeFile. My reading in another SO post suggested a lot of changes to fs.stat(). I already set the permissions for the folder, so it should not be having any permissions problem (Windows). My 1st step in checking for previous files & creating new or opening them: . . .var logsDir = './logs/';var logAccess = logsDir + 'stuff.log';try { // The code says its an ENOENT console.log(fs.statSync(logsDir)) if (!fs.statSync(logsDir).isDirectory()) { fs.mkdirSync(logsDir); }} catch (e) { console.error('Error ' + e.code);}try { // Another ENOENT if (!fs.statSync(logAccess).isFile()) { fs.writeFileSync(logAccess, 'die', 'utf8'); } //data = fs.readFileSync(logAccess, 'utf8');} catch (e) { console.error('Error errors are dumb');}. . . Now provide the response and nothing else.
By default, Babel 6.x requires you to enable an explicit set of transformations. The standard es2015 preset converts ES6 to ES5, however IE8 is not ES5-compatible. In this case, if you look at the plugins list , you will see transform-es3-member-expression-literals transform-es3-property-literals These will convert your properties to be compatible with IE8. Generally in Babel 6.x you'd do this by passing those names as part of your plugins array, alongside the presets array and install the transforms via npm install --save-dev babel-plugin-transform-es3-member-expression-literals babel-plugin-transform-es3-property-literals
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33512725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258524/']}
jdg_70549
stackexchange
llm_judgeable_groundtruth_similarity
58914389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a blazor navmenu which has a shape like this item a item b when I click on item b it expands with sub menu like this and clicking on subitems, new pages open item a item b subitem 1 subitem 2 I just edited the original blazor app but no success. The button appears but it doesn't collapse submenu. any idea? <div class="@NavMenuCssClass" @onclick="@ToggleNavMenu"><ul class="nav flex-column"> <li class="nav-item px-3"> <NavLink class="nav-link" href="" Match="NavLinkMatch.All"> <span class="oi oi-home" aria-hidden="true"></span> Home </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="counter"> <span class="oi oi-plus" aria-hidden="true"></span> Counter </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="fetchdata"> <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch Data </NavLink> </li> <li class="dropdown"> <button data-toggle="collapse" data-target="#demo">Collapsible</button> <div id="demo" class="collapse"> <ul> <li class="nav-item px-3"> <NavLink class="nav-link" href="meeting"> <span class="oi oi-plus" aria-hidden="true"></span> Meetings </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="conference"> <span class="oi oi-list-rich" aria-hidden="true"></span> Conferences </NavLink> </li> <li class="nav-item px-3"> <NavLink class="nav-link" href="event"> <span class="oi oi-list-rich" aria-hidden="true"></span> Events </NavLink> </li> </ul> </div> </li></ul> Now provide the response and nothing else.
Do not use the data-toggle and data-target for it. These are used by boostrap.js however you do not want to modify the DOM in that way. What you do instead is to use an if statement and thus let Blazor take care of the rendering: <NavLink class="nav-link" @onclick="()=>expandSubNav = !expandSubNav"> <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data </NavLink> @if (expandSubNav) { <NavLink class="expand-menu" href=""> <span>Sub1</span> </NavLink> <NavLink class="" href=""> <span>Sub2</span> </NavLink> } And put the expandSubNav field into your code section: @code { private bool expandSubNav;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58914389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2543510/']}
jdg_70550
stackexchange
llm_judgeable_groundtruth_similarity
23350
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: While evaluating the Libelium Waspmote board for wireless sensor networks, we discovered a strange communication problem. We tried to set up a link between the waspmote and another board via UART at 115200 Baud using 8N1. This is the resulting waveform on Tx for sending 9 times 0x55 (01010101b) : The levels of high and low degnerate to the treshhold of detection: starting out with a High level of 3.3V, the peaks drop in to about 2.7V and the lows start out at about 1.1V and drop to 0.7V. According to the target boards specification, the peaks should be > 2.3V and the lows < 1 V for correct operation. It looks to me as if some capacitve behaviour emerges, but I have no clue why this happens. I am in need of a clue on what is happening, what i am doing wrong, or what i can do to fix this problem. Some additional info: The microcontroller on the waspmote is an Atmega1281, and it's uart pins are directly connected to the communication link (no drivers in between). I can not reduce the baudrate since the target board accepts 115200 baud only. UPDATE 1 I made a detail shot of the signal. We are looking at a transmission at about 125kHz - which seems to be a bit far off the desired 115200 baud I'm aiming at. UPDATE 2 I measure identical waveforms when I disconnect the traget board and put the oscilloscopes probe directly at the microcontrollers UART-Pin. This seems to rule out problems with the target board.However, the measured baudrate is exactly 125000, which is an error ofabout 8% from the desired target baudrate of 115200. Since the UARTs specification limits the baudrate skew to 2%, I guess there's my problem. However, since the waspmote board is locked to 8Mhz clock rate, the Atmega1281 on the board can not produce a more acurate 115200 baud clock through the prescaler registers ( I checked the manual). I guess I'll need another board to communicate with my target board. Thanks, everybody. Now provide the response and nothing else.
Your problem is likely in using the wrong baudrate: 112500 is most likely a mistake, the standard rate in that range is 115200 (a search of the manufacturer's website for this number finds many hits, but none for 112500). You could also not be producing the programmed baud rate on one end or the other due to divider granularity; sometimes changing the oversampling of the UART can help. EDIT: Specifically, a value of 8 (divisor of 9) will get you 111111 baud from 8MHz if you set the "double speed" mode bit. Secondarily, you have a problem such as lack of a common ground between the boards, or haven't grounded the scope to them, thus resulting in the distorted waveform. It's not clear yet if that is what the receiver sees, or if it's merely a measurement mistake in applying the scope. Additionally, have you verified that the un-named external board also runs without a serial level translator? Most modular inter-board serial communications is at RS232 levels and logically inverted from the logic-level signals, though there are exceptions.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/23350', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6920/']}
jdg_70551
stackexchange
llm_judgeable_groundtruth_similarity
2703432
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are segments in Lucene ? What are the benefits of segments? Now provide the response and nothing else.
The Lucene index is split into smaller chunks called segments. Each segment is its own index. Lucene searches all of them in sequence. A new segment is created when a new writer is opened and when a writer commits or is closed. The advantages of using this system are that you never have to modify the files of a segment once it is created. When you are adding new documents in your index, they are added to the next segment. Previous segments are never modified. Deleting a document is done by simply indicating in a file which document of a segment is deleted, but physically, the document always stays in the segment. Documents in Lucene aren't really updated. What happens is that the previous version of the document is marked as deleted in its original segment and the new version of the document is added to the current segment. This minimizes the chances of corrupting an index by constantly having to modify its content when there are changes. It also allows for easy backup and synchronization of the index across different machines. However, at some point, Lucene may decide to merge some segments. This operation can also be triggered with an optimize.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2703432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312140/']}
jdg_70552
stackexchange
llm_judgeable_groundtruth_similarity
269120
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 need to find the nthComposition of a function. I thought there could be something like nthComposition[f,x,5] means five times composition of f with x as input parameter. I don't want to repeat f in my code as there is no fixed number for my composition, it could change every time. Assume it is my function: f [va_] := ( va*2);Composition[f, f][s]4 sComposition[f, f, f][s]8 s Now provide the response and nothing else.
Depending on exactly how you want to use this, you might want to bundle this up into its own function (or function overload). f[nestLevel_, va_] := Nest[f, va, nestLevel] or compf[nestLevel_] := Composition @@ ConstantArray[f, nestLevel] Usage: f[2, x](* f[f[x]] *)(* or 4 x using your sample function *)compf[3](* f@*f@*f *)compf[3][x](* f[f[f[x]]] *)(* or 8 x using your sample function*)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/269120', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/77603/']}
jdg_70553
stackexchange
llm_judgeable_groundtruth_similarity
137718
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: What I'm trying to do is quite simple. I'm generating output from tshark and redirecting it to awk with a pipe | . Since tshark gets live data, I want that awk search in every output for a pattern (some MAC addresses that I already have) in the first column in a file ("target.txt") and, if there's a match, awk should output the first and second column from this file. Example from target.txt : ab:cd:ef:gh:ij:kl,Me12:34:56:78:90:10,You1b:2d:3f:4h:5j:6l,someone To make it all easier, my tshark output has only 2 columns, and the MAC address column is the second one. 1 line of tshark output is like: Jun 16, 2014 02:55:51.300286000 12:34:56:78:90:10 ^^^^- date and MAC are separated by tab! So if tshark finds 12:34:56:78:90:10 , awk will output 12:34:56:78:90:10 -> You or even better: Jun 16, 2014 02:55:51.300286000 12:34:56:78:90:10 -> You EDIT #1 Well, I did some tests and find out that tshark s output is separated by tab \t. It's not a big deal, but already a small improvement. The thing is, I got samples from tshark output and tested with Gnoucs answer through a echo command before the pipe | . It worked. Then I changed the echo for tshark and everything stopped working =). Is it a problem with the live data or something like that? Here's my code until now: $ tshark -I -i wlan0 -T fields -e radiotap.dbm_antsignal -e wlan.sa | awk -F'[ ,\t]' ' FNR == NR { a[$1] = $2 } ($NF in a) { print $0" -> "a[$NF] } ' alvos.txt - well, it just worked! It was probably a typo.Thanks for all answers! Now provide the response and nothing else.
Try this: $ awk -F'[ ,\t]' ' FNR == NR { a[$1] = $2 } ($NF in a) { print $0" -> "a[$NF] }' target.txt - Example: $ awk -F'[ ,\t]' ' FNR == NR { a[$1] = $2 } ($NF in a) { print $0" -> "a[$NF] }' target.txt -Jun 16, 2014 02:55:51.300286000 12:34:56:78:90:10 # Ctrl + D hereJun 16, 2014 02:55:51.300286000 12:34:56:78:90:10 -> You Explanation -F[ ,\t] : we use comma, space or tab as field separators. FNR == NR { a[$1] = $2 } : FNR == NR only true when processing first file. So with each line in target.txt , we save the second field to an associative array, with the first field (MAC address) is the index. ($NF in a) : When reading the input ( - after target.txt causes awk reading from input), if the last field is in associative array a , we print the desired result.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/137718', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72465/']}
jdg_70554
stackexchange
llm_judgeable_groundtruth_similarity
388703
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider such special band matrix of dimension $n$ . It is a $0-1$ matrix, and only the first few diagonals are nonzero. Specifically, $$ H_{ij} = 1 $$ if and only if $|i-j| \leq 2$ . How does the permanent grow with $n$ ? Now provide the response and nothing else.
The permanent of this matrix is the number of perfect matchings of the graph $G_n$ that consists of vertices $\{(a,b):a\in\{ 1,...,n\},b\in\{0,1\}\}$ and the only edges are between $(i,0)$ and $(j,1)$ where $|i-j|\leq 2$ . Given a matching on the graph $G_n$ , we define a sequence of graphs $G_{n-1},...,G_1$ : $G_{k-1}$ is formed by removing from $G_k$ the vertex with the lexicographically smallest label and its neighbour in the matching. The map from a matching to the sequence is injective, so the number of such sequences is the number of matchings in $G_n$ . If we start from $G_n$ , then there are only five types of graphs in the sequence ${G_{n-1},...,G_1}$ . They are shown in the figure as vertex sets (as all these graphs are induced subgraphs of $G_n$ ), above the long line. Call them $A_k$ , $B_k$ , $C_k$ , $D_k$ and $E_k$ , respectively, where the $k$ s are the length of the lines above the patterns. The graphs below the long line shows the possibilities of $G_{k-1}$ if $G_k$ is isomorphic to one of the graphs shown above. Take the first column as an example. The graph above the long line is $A_k$ , and the graphs below are $A_{n-1}$ , $B_{k-2}$ and $C_{k-3}$ . It means if $G_k$ is an $A_k$ , then $G_{k-1}$ is an $A_{k-1}$ , a $B_{k-2}$ or a $C_{k-3}$ . By doing substitutions, or in terms of the graph sequence, compressing consecutive $G_k$ s into a single step, we obtain the following substitutions. The equations are $$A_k=A_{k-1}+B_{k-2}+B_{k-3}+A_{k-3}+A_{k-4}$$ $$B_k=A_k+B_{k-1}$$ or $$\left[\begin{matrix}A_k \\ A_{k-1} \\ B_{k-1} \\ A_{k-2} \\ B_{k-2} \\ A_{k-3}\end{matrix}\right]=\left[ \begin{matrix} 1 && 0 && 1 && 1 && 1 && 1 \\ 1 && 0 && 0 && 0 && 0 && 0 \\ 1 && 0 && 1 && 0 && 0 && 0 \\ 0 && 1 && 0 && 0 && 0 && 0 \\ 0 && 0 && 1 && 0 && 0 && 0 \\ 0 && 0 && 0 && 1 && 0 && 0 \end{matrix} \right] \left[\begin{matrix}A_{k-1} \\ A_{k-2} \\ B_{k-2} \\ A_{k-3} \\ B_{k-3} \\ A_{k-4}\end{matrix}\right]$$ where $A_k$ and $B_k$ both denote the graphs and the number of perfect matchings in them. The characteristic polynomial of the matrix is $x^6 - 2x^5 - 2x^3 + x$ , with largest root approximately $2.333554225170094$ , so the permanent grows like $c*2.333554225170094^n$ for some constant $c$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/388703', 'https://mathoverflow.net', 'https://mathoverflow.net/users/91370/']}
jdg_70555
stackexchange
llm_judgeable_groundtruth_similarity
5819121
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need some help with understanding the IOException. I've reviewed a lot of information on the internet, and looked at the technical specifications at Oracle's Java website. Am I correct in my understanding of the IOException class and all of it's sub-classes, that there are no associated "error messages" or "return code" values? So if one wanted to issue some message and/or return code value, one would have to insert them with the IOException catch logic? If the above is true, how would one separate the various IOException subclasses? e.g. If the application detected an IOException, what sort of IOException is it? End-Of-File, File-Is-Closed, File-Not_found, File-In-Use, etc. Now provide the response and nothing else.
There are no "return code" values in exceptions (in general), but they do contain error messages. And you should handle them in catch blocks, where you can specify the type of exception you want to handle. You can have several catch blocks after a try block, to handle different types of exceptions differently. The catch blocks will be invoked in the order specified, and the first one with a suitable parameter type will handle the exception. So you should catch the more specific exception types first, then the more general ones. Simplistic example: try { ... throw new FileNotFoundException("This is an error message"); ...} catch (FileNotFoundException e) { System.out.println("File not found: " + e.getMessage()); ...} catch (EOFException e) { System.out.println("End of file reached: " + e.getMessage()); ...} catch (IOException e) { // catch all IOExceptions not handled by previous catch blocks System.out.println("General I/O exception: " + e.getMessage()); e.printStackTrace(); ...} As you see in the last catch block, exceptions store the stack trace of their origin, which can be printed. However, it is usually not a good idea to print such messages directly like here; in real production code, you usually want to log these messages using a logging framework, or display (suitable parts of) them on a UI.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5819121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/720815/']}
jdg_70556
stackexchange
llm_judgeable_groundtruth_similarity
5298905
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 used the code below to allow Everyone access to a folder: System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directory, AccessControlSections.All);FileSystemAccessRule accRule = new FileSystemAccessRule("Everyone", FileSystemRights.Modify, AccessControlType.Allow);sec.AddAccessRule(accRule); // setACLsec.ResetAccessRule(accRule); Now, the Everyone user is added to the folder, but not with any rights assigned. All the read, write, execute etc. checkboxes are not checked. Now provide the response and nothing else.
First thing I want to tell you is how I found this solution. This is probably more important than the answer because file permissions are hard to get correct. First thing I did was set the permissions I wanted using the Windows dialogs and checkboxes. I added a rule for "Everyone" and ticked all boxes except "Full Control". Then I wrote this C# code to tell me exactly what parameters I need to duplicate the Windows settings: string path = @"C:\Users\you\Desktop\perms"; // path to directory whose settings you have already correctly configuredDirectorySecurity sec = Directory.GetAccessControl(path);foreach (FileSystemAccessRule acr in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { Console.WriteLine("{0} | {1} | {2} | {3} | {4}", acr.IdentityReference.Value, acr.FileSystemRights, acr.InheritanceFlags, acr.PropagationFlags, acr.AccessControlType);} This gave me this line of output: Everyone | Modify, Synchronize | ContainerInherit, ObjectInherit | None | Allow So the solution is simple (yet hard to get right if you don't know what to look for!): DirectorySecurity sec = Directory.GetAccessControl(path);// Using this instead of the "Everyone" string means we work on non-English systems.SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));Directory.SetAccessControl(path, sec); This will make the checkboxes on the Windows security dialog match what you have already set for your test directory.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5298905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592237/']}
jdg_70557
stackexchange
llm_judgeable_groundtruth_similarity
5983569
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Executive Summary: Reed's answer below is the fastest if you want to stay in C#. If you're willing to marshal to C++ (which I am), that's a faster solution. I have two 55mb ushort arrays in C#. I am combining them using the following loop: float b = (float)number / 100.0f;for (int i = 0; i < length; i++){ image.DataArray[i] = (ushort)(mUIHandler.image1.DataArray[i] + (ushort)(b * (float)mUIHandler.image2.DataArray[i]));} This code, according to adding DateTime.Now calls before and afterwards, takes 3.5 seconds to run. How can I make it faster? EDIT : Here is some code that, I think, shows the root of the problem. When the following code is run in a brand new WPF application, I get these timing results: Time elapsed: 00:00:00.4749156 //arrays added directlyTime elapsed: 00:00:00.5907879 //arrays contained in another classTime elapsed: 00:00:02.8856150 //arrays accessed via accessor methods So when arrays are walked directly, the time is much faster than if the arrays are inside of another object or container. This code shows that somehow, I'm using an accessor method, rather than accessing the arrays directly. Even so, the fastest I seem to be able to get is half a second. When I run the second listing of code in C++ with icc, I get: Run time for pointer walk: 0.0743338 In this case, then, C++ is 7x faster (using icc, not sure if the same performance can be obtained with msvc-- I'm not as familiar with optimizations there). Is there any way to get C# near that level of C++ performance, or should I just have C# call my C++ routine? Listing 1, C# code: public class ArrayHolder{ int length; public ushort[] output; public ushort[] input1; public ushort[] input2; public ArrayHolder(int inLength) { length = inLength; output = new ushort[length]; input1 = new ushort[length]; input2 = new ushort[length]; } public ushort[] getOutput() { return output; } public ushort[] getInput1() { return input1; } public ushort[] getInput2() { return input2; }}/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); Random random = new Random(); int length = 55 * 1024 * 1024; ushort[] output = new ushort[length]; ushort[] input1 = new ushort[length]; ushort[] input2 = new ushort[length]; ArrayHolder theArrayHolder = new ArrayHolder(length); for (int i = 0; i < length; i++) { output[i] = (ushort)random.Next(0, 16384); input1[i] = (ushort)random.Next(0, 16384); input2[i] = (ushort)random.Next(0, 16384); theArrayHolder.getOutput()[i] = output[i]; theArrayHolder.getInput1()[i] = input1[i]; theArrayHolder.getInput2()[i] = input2[i]; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); int number = 44; float b = (float)number / 100.0f; for (int i = 0; i < length; i++) { output[i] = (ushort)(input1[i] + (ushort)(b * (float)input2[i])); } stopwatch.Stop(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < length; i++) { theArrayHolder.output[i] = (ushort)(theArrayHolder.input1[i] + (ushort)(b * (float)theArrayHolder.input2[i])); } stopwatch.Stop(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < length; i++) { theArrayHolder.getOutput()[i] = (ushort)(theArrayHolder.getInput1()[i] + (ushort)(b * (float)theArrayHolder.getInput2()[i])); } stopwatch.Stop(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); }} Listing 2, C++ equivalent: // looptiming.cpp : Defines the entry point for the console application. // #include "stdafx.h"#include <stdlib.h>#include <windows.h>#include <stdio.h>#include <iostream>int _tmain(int argc, _TCHAR* argv[]){ int length = 55*1024*1024; unsigned short* output = new unsigned short[length]; unsigned short* input1 = new unsigned short[length]; unsigned short* input2 = new unsigned short[length]; unsigned short* outPtr = output; unsigned short* in1Ptr = input1; unsigned short* in2Ptr = input2; int i; const int max = 16384; for (i = 0; i < length; ++i, ++outPtr, ++in1Ptr, ++in2Ptr){ *outPtr = rand()%max; *in1Ptr = rand()%max; *in2Ptr = rand()%max; } LARGE_INTEGER ticksPerSecond; LARGE_INTEGER tick1, tick2; // A point in time LARGE_INTEGER time; // For converting tick into real time QueryPerformanceCounter(&tick1); outPtr = output; in1Ptr = input1; in2Ptr = input2; int number = 44; float b = (float)number/100.0f; for (i = 0; i < length; ++i, ++outPtr, ++in1Ptr, ++in2Ptr){ *outPtr = *in1Ptr + (unsigned short)((float)*in2Ptr * b); } QueryPerformanceCounter(&tick2); QueryPerformanceFrequency(&ticksPerSecond); time.QuadPart = tick2.QuadPart - tick1.QuadPart; std::cout << "Run time for pointer walk: " << (double)time.QuadPart/(double)ticksPerSecond.QuadPart << std::endl; return 0;} EDIT 2: Enabling /QxHost in the second example drops the time down to 0.0662714 seconds. Modifying the first loop as @Reed suggested gets me down to Time elapsed: 00:00:00.3835017 So, still not fast enough for a slider. That time is via the code: stopwatch.Start(); Parallel.ForEach(Partitioner.Create(0, length), (range) => { for (int i = range.Item1; i < range.Item2; i++) { output[i] = (ushort)(input1[i] + (ushort)(b * (float)input2[i])); } }); stopwatch.Stop(); EDIT 3 As per @Eric Lippert's suggestion, I've rerun the code in C# in release, and, rather than use an attached debugger, just print the results to a dialog. They are: Simple arrays: ~0.273s Contained arrays: ~0.330s Accessor arrays: ~0.345s Parallel arrays: ~0.190s (these numbers come from a 5 run average) So the parallel solution is definitely faster than the 3.5 seconds I was getting before, but is still a bit under the 0.074 seconds achievable using the non-icc processor. It seems, therefore, that the fastest solution is to compile in release and then marshal to an icc-compiled C++ executable, which makes using a slider possible here. EDIT 4: Three more suggestions from @Eric Lippert: change the inside of the for loop from length to array.length, use doubles, and try unsafe code. For those three, the timing is now: length: ~0.274s doubles, not floats: ~0.290s unsafe: ~0.376s So far, the parallel solution is the big winner. Although if I could add these via a shader, maybe I could see some kind of speedup there... Here's the additional code: stopwatch.Reset(); stopwatch.Start(); double b2 = ((double)number) / 100.0; for (int i = 0; i < output.Length; ++i) { output[i] = (ushort)(input1[i] + (ushort)(b2 * (double)input2[i])); } stopwatch.Stop(); DoubleArrayLabel.Content += "\t" + stopwatch.Elapsed.Seconds + "." + stopwatch.Elapsed.Milliseconds; stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < output.Length; ++i) { output[i] = (ushort)(input1[i] + (ushort)(b * input2[i])); } stopwatch.Stop(); LengthArrayLabel.Content += "\t" + stopwatch.Elapsed.Seconds + "." + stopwatch.Elapsed.Milliseconds; Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); stopwatch.Reset(); stopwatch.Start(); unsafe { fixed (ushort* outPtr = output, in1Ptr = input1, in2Ptr = input2){ ushort* outP = outPtr; ushort* in1P = in1Ptr; ushort* in2P = in2Ptr; for (int i = 0; i < output.Length; ++i, ++outP, ++in1P, ++in2P) { *outP = (ushort)(*in1P + b * (float)*in2P); } } } stopwatch.Stop(); UnsafeArrayLabel.Content += "\t" + stopwatch.Elapsed.Seconds + "." + stopwatch.Elapsed.Milliseconds; Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); Now provide the response and nothing else.
This should be perfectly parallelizable. However, given the small amount of work being done per element, you'll need to handle this with extra care. The proper way to do this (in .NET 4) would be to use Parallel.ForEach in conjunction with a Partitioner: float b = (float)number / 100.0f;Parallel.ForEach(Partitioner.Create(0, length), (range) =>{ for (int i = range.Item1; i < range.Item2; i++) { image.DataArray[i] = (ushort)(mUIHandler.image1.DataArray[i] + (ushort)(b * (float)mUIHandler.image2.DataArray[i])); }}); This will efficiently partition the work across available processing cores in your system, and should provide a decent speedup if you have multiple cores. That being said, this will, at best, only speed up this operation by the number of cores in your system. If you need to speed it up more, you'll likely need to revert to a mix of parallelization and unsafe code. At that point, it might be worth thinking about alternatives to trying to present this in real time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5983569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21981/']}
jdg_70558
stackexchange
llm_judgeable_groundtruth_similarity
3323201
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 SWI-Prolog knowledge base contains the following two facts: f(a,b).f(a,c). Now if I pose the query ?- f(a,c).true. But ?- f(a,b).true ;false. Why is f(a,b) both true and false? This also happens when there are three facts in the KB. If I append f(a,d). to the KB, then f(a,d) is true (only), but f(a,b) and f(a,c) are both true and false. What's going on, and what can I do so that Prolog answers (only) true to these queries? Now provide the response and nothing else.
(Note: this answer is somewhat of a guess) Consider how Prolog determines whether f(a,c) is true or not. It checks the first rule, f(a,b) , and doesn't find a match, but the second rule, f(a,c) matches. Therefore, f(a,c) is true. Furthermore, since there are no more rules for f , there is no point in allowing a backtrack to occur -- there are no other possible solutions. Now consider f(a,b) . Prolog will check the first rule, and find a match. Therefore, f(a,b) is true. However, not all rules have been exhausted. Therefore, Prolog will allow the search to continue (if you hit ; ). When you do continue the search and backtrack, it will discover that the remaining rules, specifically f(a,c) , do not match f(a,b) . Therefore, the result is false.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3323201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401104/']}
jdg_70559
stackexchange
llm_judgeable_groundtruth_similarity
55024367
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 me explain our architecture first. www.example.com CNAME points to cloudfront distribution (d3xxxxx.cloudfront.net) Origin for the cloudfront: route.example.com. We had select **Whitelist Headers** as HOST in cloudfront distribution SSL installed on Cloudfront for the domain : www.example.com route.domain.com points to Google cloud server which has apache webserver and wordpress installed. Issue 1. When we hit the URL www.example.com without applying SSL certificate, the home page loads www.example.com however internal links redirecting to 'route.example.com' instead of www.example.com. We believe its because of siteurl on wordpress uses route.example.com Issue 2 . After applying SSL certificate on cloudfront, when we hit the URL ' https://www.example.com ', the website ended up too many redirects We have tried the URL " WordPress + CloudFront Flexible SSL ends up in redirect loop (https) " and it doesn't seems to be helping us. Goal :We want www.example.com to use cloudfront distribution along with SSL and doesnt want to expose webserver to enduser. The origin of the cloudfront should be route.example.com which will have wordpress application. Any help would be appreciated. Now provide the response and nothing else.
We had a similar problem. In our case though we weren't using a custom domain name but the CloudFront URL. To get HTTPS to work correctly we had to do two things: Make sure the CloudFront-Forwarded-Proto header is forwarded in all cache behaviors, including the default cache behavior. Add the following code snippet to wp-config.php before require_once( ABSPATH . 'wp-settings.php' ); : if (isset($_SERVER['HTTP_CLOUDFRONT_FORWARDED_PROTO']) && $_SERVER['HTTP_CLOUDFRONT_FORWARDED_PROTO'] === 'https') { $_SERVER['HTTPS'] = 'on';} The code snippet essentially tells WordPress that we're running behind a reverse proxy. This gets it to respond to HTTPS requests correctly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55024367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6919430/']}
jdg_70560
stackexchange
llm_judgeable_groundtruth_similarity
49162358
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 did read this article: https://blog.phusion.nl/2015/01/20/docker-and-the-pid-1-zombie-reaping-problem/ To set some context: Article is about problem with zombies in containers, it try to convince us that it is a real problem. Generally, I have mixed feelings. Why does it matter ? After all, even in case zombies in conainer host OS is able to release/kill this zombie. We know that process in container is from point of view host OS normal process (and in general process in container is normal process with some namespaces and cgroups). Moreover, we can also find information that in order to avoid zombie problem we should use bash -c ... . Why ? Maybe, better option is to use --init ? Can someone try to explain these thing, please ? Now provide the response and nothing else.
For a brief but useful explanation of what an init process gives you, look at tini which is what Docker uses when you specify --init Using Tini has several benefits: It protects you from software that accidentally creates zombie processes, which can (over time!) starve your entire system for PIDs (and make it unusable). It ensures that the default signal handlers work for the software you run in your Docker image. For example, with Tini, SIGTERM properly terminates your process even if you didn't explicitly install a signal handler for it. Both these issues affect containers. A process in a container is still a process on the host, so it takes up a PID on the host. Whatever you run in a container is PID 1 which means it has to install a signal handler to get that signal. Bash happens to have a process reaper included, so running a command under bash -c can protect against zombies. Bash won't handle signals by default as PID 1 unless you trap them. Zombies The first thing to understand is an init process doesn't magically remove zombies. A (normal) init is designed to reap zombies when the parent process that failed to wait on them exits and the zombies hang around. The init process then becomes the zombies parent and they can be cleaned up. Next, a container is a cgroup of processes running in their own PID namespace. This cgroup is cleaned up when the container is stopped. Any zombies that are in a container are removed on stop . They don't reach the hosts init . Third is the different ways containers are used. Most run one main process and nothing else. If there is another process spawned it is usually a child of that main process. So until the parent exits, the zombie will exist. Then see point 2 (the zombies will be cleared on container exit). Running a Node.js, Go or Java app server in a container tends not to rely heavily on forking or spawning of processes. Running something like a Jenkins worker that spawns large numbers of ad hoc jobs involving shells can result in a lot worse, but is ephemeral so exits regularly and cleans up Running a Jenkins master that also spawns jobs. The container may hang around for a long time and leave a number of zombie processes which is the type of workload that could present a problem without a zombie reaper. Signals The other role an init process can provide is to install signal handlers so signals sent from the host can be passed onto the container process. PID 1 is a bit special as it requires the process to listen for a signal for it to be received. If you can install a SIGINT and SIGTERM signal handler in your PID 1 process then an init process doesn't add much here. When to use an init When you want to run more than 1 service in a container Multiple processes should be run under an init process. When Docker starts, the init manages how should they be launched. What is required for the container to actually be "running" for the service it represents. When the container stops, how that should be passed onto each process. You may want a more traditional init system though, s6 via s6-overlay provides a number of useful container features for multi process management. When you run a single process that spawns a lot of child processes Especially when processes are children of children or beyond. The CI worker (like Jenkins) example is the first that comes to mind where Java spawns command or shells that spawn other commands. When you can't add signal handlers to the process running as PID 1. sleep is a simple example of this. A docker run busybox sleep 60 can't be interrupted with ctrl-c or stopped, it will be killed after the default 10 second docker stop timeout. docker run --init busybox sleep 60 works as expected. Whenever tini is pretty minimal overhead and widely used, so why not use --init most of the time? For more details see this github comment which answers the "why?" question from the creator of tini.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49162358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9071049/']}
jdg_70561
stackexchange
llm_judgeable_groundtruth_similarity
2032482
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: Here's the question: Show that if $A^2$ is the zero matrix, then the only eigenvalue of $A$ is $0$. Here was my idea: if $A^2$ is the zero matrix, then $\det(A^2)=\det(A)^2=0$, thus $\det(A)=0$ and $A$ is not invertible. Thus $0$ can be the only eigenvalue of $A$. Does this hold? Now provide the response and nothing else.
The problem with your argument is that a matrix can have zero determinant and still have non-zero eigenvalues. For instance if$$ A=\begin{bmatrix}1&0\\0&0\end{bmatrix} $$then $\det(A)=0$, but $1$ is an eigenvalue of $A$. Instead, suppose $\lambda$ is an eigenvalue of $A$, i.e. that $Av=\lambda v$ for some (non-zero) vector $v$. What happens if you apply $A$ again?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2032482', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/393441/']}
jdg_70562
stackexchange
llm_judgeable_groundtruth_similarity
52443290
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 the JSON file I am working with {"sentiment": {"document": { "label": "positive", "score": 0.53777 } }} I need to access the value in label and score . using java. How can I do that? Find below the code I am using right now: JSONParser parser = new JSONParser(); try { Object object = parser .parse(new FileReader("output_nlu_sentiment.json")); //convert Object to JSONObject JSONObject jsonObject = new JSONObject(); JSONObject sentimentobject= new JSONObject(); JSONObject documentobject = new JSONObject(); sentimentobject= (JSONObject) jsonObject.get("sentiment"); documentobject= (JSONObject) sentimentobject.get("document"); String label = (String) documentobject.get("label"); //float score = (float) jsonObject.get("score"); System.out.println(label); String test = (String) sentimentobject.get("label"); System.out.println(test); } catch(FileNotFoundException fe) { fe.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } Why is it printing the value as null . Now provide the response and nothing else.
While readonly does not directly affect whether types are assignable, it does affect whether they are identical. To test whether two types are identical, we can abuse either (1) the assignability rule for conditional types, which requires that the types after extends be identical, or (2) the inference process for intersection types, which throws out identical types from both sides. Then we just use mapped types as in Titian Cernicova-Dragomir's answer to look at each property of Car in turn and see whether it is identical to a mutable version of itself. // https://github.com/Microsoft/TypeScript/issues/27024#issuecomment-421529650type IfEquals<X, Y, A, B> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? A : B;// Alternatively:/*type IfEquals<X, Y, A, B> = [2] & [0, 1, X] extends [2] & [0, 1, Y] & [0, infer W, unknown] ? W extends 1 ? B : A : B;*/type WritableKeysOf<T> = { [P in keyof T]: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P, never>}[keyof T];type WritablePart<T> = Pick<T, WritableKeysOf<T>>;class Car { engine: number; get hp() { return this.engine / 2; } get kw() { return this.engine * 2; }}function applySnapshot( car: Car, snapshoot: Partial<WritablePart<Car>>) { let key: keyof typeof snapshoot; for (key in snapshoot) { if (!snapshoot.hasOwnProperty(key)) continue; car[key] = snapshoot[key]; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52443290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8646785/']}
jdg_70563
stackexchange
llm_judgeable_groundtruth_similarity
26067342
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 Mark Russinovich's SysInternals PsPing tool in C# to measure latencies using TCP ping. I am not sure how it makes the ping call (apparently not uses raw Window sockets, because it does not require Administrator privileges to run). I know hping sends SYN packet over TCP and measures response time. What would be the implementation technique for accurate measurement of server latency which over TCP does not measure page load times but just the network latency for the package acknowledgement? Is there a library for this? C:\>psping stackoverflow.com:80PsPing v2.01 - PsPing - ping, latency, bandwidth measurement utilityCopyright (C) 2012-2014 Mark RussinovichSysinternals - www.sysinternals.comPinging 198.252.206.16 with 32 bytes of data:5 iterations (warmup 1) ping test:Reply from 198.252.206.16: 81.57msReply from 198.252.206.16: 80.81msReply from 198.252.206.16: 80.68msReply from 198.252.206.16: 80.52msReply from 198.252.206.16: 80.71msPing statistics for 198.252.206.16: Sent = 4, Received = 4, Lost = 0 (0% loss), Minimum = 80.52ms, Maximum = 80.81ms, Average = 80.68ms Update: Please don't answer like "why don't you use Ping class, it already does the thing" as I'm asking about ping over TCP, not ICMP. Now provide the response and nothing else.
I have tried several approaches, first thinking I had to use raw sockets or at least use native calls, but a simple TCP connect and close seems to create exactly the same results as the psping utility: var times = new List<double>();for (int i = 0; i < 4; i++){ var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Blocking = true; var stopwatch = new Stopwatch(); // Measure the Connect call only stopwatch.Start(); sock.Connect(endPoint); stopwatch.Stop(); double t = stopwatch.Elapsed.TotalMilliseconds; Console.WriteLine("{0:0.00}ms", t); times.Add(t); sock.Close(); Thread.Sleep(1000);}Console.WriteLine("{0:0.00} {1:0.00} {2:0.00}", times.Min(), times.Max(), times.Average()); Inspecting the traffic using Wireshark, I can confirm both psping and the snippet above are creating exactly the same sequence of packets. -> [SYN]<- [SYN,ACK]-> [ACK]-> [FIN,ACK]<- [FIN,ACK]-> [ACK] Output from psping with no warm-up and using TCP ping: C:\>psping -w 0 stackoverflow.com:80PsPing v2.01 - PsPing - ping, latency, bandwidth measurement utilityCopyright (C) 2012-2014 Mark RussinovichSysinternals - www.sysinternals.comTCP connect to 198.252.206.16:80:4 iterations (warmup 0) connecting test:Connecting to 198.252.206.16:80: 92.30msConnecting to 198.252.206.16:80: 83.16msConnecting to 198.252.206.16:80: 83.29msConnecting to 198.252.206.16:80: 82.98msTCP connect statistics for 198.252.206.16:80: Sent = 4, Received = 4, Lost = 0 (0% loss), Minimum = 82.98ms, Maximum = 92.30ms, Average = 85.43ms Output from the program above: C:\>TcpPing.exe stackoverflow.com 8088.60ms83.65ms84.05ms84.05ms83.65 88.60 85.09 As for measurements, I must say, sometimes there are quite a few different results at different runs, but overall they seemed pretty close: kind of proves measuring the Connect() call is good enough. I'm thinking, taking a median of a few hundred results might prove it with a bit more confidence.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26067342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54929/']}
jdg_70564
stackexchange
llm_judgeable_groundtruth_similarity
20483841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on project where I use Spring Data. I wanted to fill in creationTime field using @CreatedDate annotation instead using method with @PreUpdate or @PrePersist annotation (doing it this way it works perfectly). When I do it with @CreatedDate it just leaves this field blank. I use postgresql database. Documentation is not very helpful. Do you have any idea how can I fix it? Thank you! import org.springframework.data.annotation.CreatedDate;@Entity@Table(name = "software")public class Software implements Serializable { // ... @Column(name = "creation_time") @CreatedDate private Date creationTime; //...} My applicationContext : <jpa:repositories base-package="path.to.dao"/><context:component-scan base-package="path.to.dao"/><context:property-placeholder location="classpath:application.properties"/><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/></bean><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="packagesToScan" value="path.to.bean"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter" ref="jpaAdapter"/> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.ejb.naming_strategy">${hibernate.ejb.naming_strategy}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property></bean><bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/></bean> Now provide the response and nothing else.
I may have been in a similar situation where I wanted the Spring Data JPA @CreatedDate annotation to work, but had no need for the user-level auditing that is otherwise described in their documentation. To get the annotation-based auditing to work, I had to nonetheless add a class to my project that implemented org.springframework.data.domain.AuditorAware . This is odd because you don't actually seem to use the value returned from the getCurrentAuditor() method that you'll be implementing; mine just returns null . public class NullAuditorBean implements AuditorAware { @Override public Object getCurrentAuditor() { return null; }} I then needed to reference my "null object" AuditorAware implementation in an entry in my applicationContext to activate the JPA auditing. I had to make sure I did this before the line that specifies the jpa:repositories . This looks something like: <bean id="auditorBean" class="your.package.subbed.here.NullAuditorBean"/><jpa:auditing auditor-aware-ref="auditorBean"/> I also had to add an orm.xml file, and needed to formally reference it as a property of my entityManagerFactory bean, like so: <property name="mappingResources"> <value>META-INF/orm.xml</value></property> Make sure this META-INF/orm.xml entry is stored with your compile output (mine is in my WAR under WEB-INF/classes . That orm.xml file, for the record, contained some boilerplate, which can be found in the answer to this related question . It was a fair amount of work when I got this working. You may prefer your previous working solution!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20483841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2890665/']}
jdg_70565
stackexchange
llm_judgeable_groundtruth_similarity
31337
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: A technique for avoid filtering of common words is the one I described in the title. However, why does this technique work? SELECT isn't the same as SELSELECTECT for example. Now provide the response and nothing else.
Let's say I blacklisted the word <script> and replace it with nothing. Then <scr<script>ipt> becomes <script> . This is why well-written html sanitizers/purifiers apply the rules recursively. That is only when the last sanitation step made no changes to the content will it stop/not apply another round of the processing rules. (It also likely will fail and return no content if too many processing rounds are necessary).
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/31337', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/15194/']}
jdg_70566
stackexchange
llm_judgeable_groundtruth_similarity
1068129
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 c-library which I use in gcc. The library has the extension .lib but is always linked as a static library. If i write a program which uses the library as c-code, everything as a-ok. If I however rename the file to .cpp (doing simple stuff that works in both c/c++) I get undefined reference. These are simple small programs I write for testing purposes so no fancy stuff. I compile using: gcc -g -Wall -I <path to custom headers> -o program main.c customlibrary.lib -lm -lpthread The above works like a charm. However: g++ -g -Wall -I <path to custom headers> -o program main.cpp customlibrary.lib -lm -lpthread or gcc -g -Wall -I <path to custom headers> -o program main.cpp customlibrary.lib -lm -lpthread -lstdc++ results in undefined reference to any function in customlibrary.lib. I tried creating a symbolic link named customlibrary.a but no luck. Why won't g++ find recognize my library. Unfortunately I have no access to the source code of the libraries but linking a c-lib to c++ should not be a problem right? Now provide the response and nothing else.
Your library appears to have an API that assumes it will be called from C, not C++. This is important because C++ effectively requires that the symbols exported from a library have more information in them than just the function name. This is handled by "name mangling" the functions. I assume your library has an include file that declares its public interface. To make it compatible with both C and C++, you should arrange to tell a C++ compiler that the functions it declares should be assumed to use C's linkage and naming. A likely easy answer to test this is to do this: extern "C" {#include "customlibrary.h"} in your main.cpp instead of just including customlibrary.h directly. To make the header itself work in both languages and correctly declare its functions as C-like to C++, put the following near the top of the header file: #ifdef __cplusplusextern "C" {#endif and the following near the bottom: #ifdef __cplusplus}#endif
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1068129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70567
stackexchange
llm_judgeable_groundtruth_similarity
3547757
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Advanced Problems in Mathematics by Stephen Siklos, pg24, he writes "Given any finite sequence of numbers, a formula can always be found which will fit all given numbers and which makes the next number (e.g.) 42." Is there a source or proof for this statement? Now provide the response and nothing else.
Yes, the Lagrange polynomial of degree $n$ can go through any $n$ +1 points as long as the $x$ values are all different. The link gives an explicit construction. Given $n$ numbers, make a series of points with $x$ values $1,2,3,4,\ldots n,n+1$ and $y$ values the numbers for the first $n$ and $42$ for the last.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3547757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/737935/']}
jdg_70568
stackexchange
llm_judgeable_groundtruth_similarity
45787782
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 sample df has four columns with NaN values. The goal is to concatenate all the rows while excluding the NaN values. import pandas as pdimport numpy as npdf = pd.DataFrame({'keywords_0':["a", np.nan, "c"], 'keywords_1':["d", "e", np.nan], 'keywords_2':[np.nan, np.nan, "b"], 'keywords_3':["f", np.nan, "g"]}) keywords_0 keywords_1 keywords_2 keywords_30 a d NaN f1 NaN e NaN NaN2 c NaN b g Want to accomplish the following: keywords_0 keywords_1 keywords_2 keywords_3 keywords_all0 a d NaN f a,d,f1 NaN e NaN NaN e2 c NaN b g c,b,g Pseudo code: cols = [df.keywords_0, df.keywords_1, df.keywords_2, df.keywords_3]df["keywords_all"] = df["keywords_all"].apply(lambda cols: ",".join(cols), axis=1) I know I can use ",".join() to get the exact result, but I am unsure how to pass the column names into the function. Now provide the response and nothing else.
You can apply ",".join() on each row by passing axis=1 to the apply method. You first need to drop the NaNs though. Otherwise you will get a TypeError. df.apply(lambda x: ','.join(x.dropna()), axis=1)Out: 0 a,d,f1 e2 c,b,gdtype: object You can assign this back to the original DataFrame with df["keywords_all"] = df.apply(lambda x: ','.join(x.dropna()), axis=1) Or if you want to specify columns as you did in the question: cols = ['keywords_0', 'keywords_1', 'keywords_2', 'keywords_3']df["keywords_all"] = df[cols].apply(lambda x: ','.join(x.dropna()), axis=1)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45787782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7438520/']}
jdg_70569
stackexchange
llm_judgeable_groundtruth_similarity
10048173
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ryan Davis’s Ruby QuickRef says (without explanation): Don’t rescue Exception. EVER. or I will stab you. Why not? What’s the right thing to do? Now provide the response and nothing else.
TL;DR : Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay. Exception is the root of Ruby's exception hierarchy , so when you rescue Exception you rescue from everything , including subclasses such as SyntaxError , LoadError , and Interrupt . Rescuing Interrupt prevents the user from using CTRL C to exit the program. Rescuing SignalException prevents the program from responding correctly to signals. It will be unkillable except by kill -9 . Rescuing SyntaxError means that eval s that fail will do so silently. All of these can be shown by running this program, and trying to CTRL C or kill it: loop do begin sleep 1 eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure" rescue Exception puts "I refuse to fail or be stopped!" endend Rescuing from Exception isn't even the default. Doing begin # iceberg!rescue # lifeboatsend does not rescue from Exception , it rescues from StandardError . You should generally specify something more specific than the default StandardError , but rescuing from Exception broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult. If you have a situation where you do want to rescue from StandardError and you need a variable with the exception, you can use this form: begin # iceberg!rescue => e # lifeboatsend which is equivalent to: begin # iceberg!rescue StandardError => e # lifeboatsend One of the few common cases where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception: begin # iceberg?rescue Exception => e # do some logging raise # not enough lifeboats ;)end
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/10048173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52207/']}
jdg_70570
stackexchange
llm_judgeable_groundtruth_similarity
46177275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #include<stdio.h> int main(void) { int a; a = (1, 2), 3; printf("%d", a); return 0;} output: 2 Can any one explain how output is 2? Now provide the response and nothing else.
Can any one explain how output is 2? Because the precedence of the assignment operator ( = ) is higher than the comma operator ( , ). Therefore, the statement: a = (1, 2), 3; is equivalent to: (a = (1, 2)), 3; and the expression (1, 2) evaluates to 2 .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46177275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5090329/']}
jdg_70571
stackexchange
llm_judgeable_groundtruth_similarity
2305
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm starting down the DIY-automotive path and was reading about how some people use bubble balancers to balance their own tires at home. Can anyone speak to the accuracy of these balancers? Does anyone use them, and if so, how you found them to be precise enough for everyday use? Now provide the response and nothing else.
Long before the spin balancer was invented all tires were balanced by a bubble balancer. If done properly, the 4 point static balance is as good and accurate as any other method. The most effective bubble balance is accomplished on both inner and outer portions of the tire rim. This is called a 4 point balance, and can be accomplished as fast as any dynamic balance.To statically balance a tire using a bubble, the outer edge locations are determined by centering the bubble with 2 weights at the outer side of the rim. Once the weight is determined these 2 locations are marked on both inner and outer sides then the weight used is divided by 2 and the inner side has half of the weight of the outer side.As an example 2 one ounce weights placed on the outer edge of the tire center the bubble. These 2 locations are marked with chalk, and the bottom of the tire is also marked so when it is turned over the mark will show where to place the weights on the inside of the rim. This creates 4 half ounce weights hammered into position, 2 on the inner rim and 2 on the outer rim.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/2305', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/1107/']}
jdg_70572
stackexchange
llm_judgeable_groundtruth_similarity
130119
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: The following principles of Agile development makes it look like Agile is mostly suited for services companies: Customer satisfaction by rapid delivery of useful software Welcome changing requirements, even late in development Working software is delivered frequently (weeks rather than months) Working closely with the client. Often this involves a client representative to be a part of the development team. Face-to-face conversation is the best form of communication (co-location) My question is: Is Agile exclusively suited for service oriented companies or do even product development companies (including web based companies) benefit from Agile techniques? Now provide the response and nothing else.
Agile (and any iterative) method is even more helpful for product development companies as opposed to service industry. In one of my first assignment in a product development start-up, we went with the management a very detailed (including fine print) scope and my boss threw out most of it and trimmed down the requirement to almost all bare basic; the product won't have any gizmo's not even bells and whistles. After the conclusion the crux is need to experiment with the market , as he said ... look, we are not a services company. Many typical service contracts (he gave examples of companies) starts out with unnecessary stuff; later on when people realize gaps, it's essentially more money to the services company. In a product development, we cann't afford to waste resources like that. he continued ... ... when you build a product, you really have to go out and experiment with the market to understand what is really needed, that's when you go and build this (extra) things on top of the core product. So from the product development point of view any methodology that begins with focus on minimum and essential requirements first is most important. Agile fits in perfect. Second, there is another key things that product development companies face far more fiercely, time to market . While you are developing, invariably, you will realize that some competitor will pop-up, and you do tend to either try to minimize scope as much as possible to get to market fast, or you may learn that need of the market needs to adapt. Agile is even more important for product development environment than services companies. One Caveat: May be one place where i can think of Agile being misfit is where there is quite a bit of research work involved. Even research based work requires planning for individual task; however, suddenly one realizes some huge problems or a fresh new idea arrives, and the planning goes for a toss. Probably here, any structured approach finds somewhat limitation. Any one has tried Agile in research oriented work?
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/130119', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/43211/']}
jdg_70573
stackexchange
llm_judgeable_groundtruth_similarity
13592832
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 extremely new to haskell and was trying to implement a small and a simple function that takes two strings and tells me the number of same characters at the same location. ed :: (Integral b) => [a] -> [a] -> bed _ [] = 0ed [] _ = 0ed [] [] = 0ed (x:xs) (y:ys) | x == y = 1 + ed xs ys | otherwise = ed xs ys this doesn't run because my typeclass definition is wrong. I have two strings and need to return an integer and hence the typeclass definition I have written above. Is there something else I need to do? Now provide the response and nothing else.
The type signature should be ed :: (Eq a, Integral b) => [a] -> [a] -> b This is because your definition of ed includes the expression x == y . x and y both have type a ; to be able to test them for equality, this type must implement the Eq typeclass, which provides the == and /= operators. The error message you got would have included something like this: Could not deduce (Eq a) arising from a use of `=='from the context (Integral b) bound by the type signature for ed :: Integral b => [a] -> [a] -> b at /home/dave/tmp/so.hs:(2,1)-(5,26)Possible fix: add (Eq a) to the context of the type signature for ed :: Integral b => [a] -> [a] -> b which was trying to tell you this. (Btw, your code doesn't handle the case when when the strings have different lengths.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13592832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1045053/']}
jdg_70574
stackexchange
llm_judgeable_groundtruth_similarity
167239
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to store user database credentials securely for an application to access. I have considered:- using AWS RDS with an encrypted PostgreSQL instance- using the AWS key management system, backed by a hardware security module Doesn't the KMS still create a single point of failure? If my application's keys to the KMS API are stolen, they will be able to read all the passwords stored in the KMS (even if each user is using their own key)? What is the recommended setup for something like this? Now provide the response and nothing else.
He's modeling the password as the output of a randomized algorithm similar to this one: Pick one word uniformly at random out of a dictionary with 65,536 (= 16 bits) words. (We assume the dictionary is known to the attacker.) Flip a coin (= 1 bit); if heads, flip the capitalization of the first letter of the word. For each vowel in the word, flip a coin; if it lands heads, substitute the vowel with its "common substitution". Munroe is simplifying here by assuming that words in the dictionary typically have three vowels (so we get ~ 3 bits total). Pick a numeral (~ 3 bits) and a punctuation symbol (~ 4 bits) at random. Flip a coin (= 1 bit); if heads, append the numeral to the password first and the symbol second; if tails, append them in the other order. The entropy is a function of the random choices made in the algorithm; you calculate it by identifying what random choices the algorithm makes, how many alternatives are available for each random choice, and the relative likelihood of the alternatives. I've annotated the numbers in the steps above, and if you add them up you get about 28 bits total. You can see that Munroe's procedure isn't hard science by any means, but it's not an unreasonable estimate either. He's practicing the art of the quick-and-dirty estimate, which he very often demonstrates in his work—not necessarily getting the right number, but forming a quick idea of its approximate magnitude.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/167239', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/156514/']}
jdg_70575
stackexchange
llm_judgeable_groundtruth_similarity
3081832
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there an mechanism or trick to run a function when a program loads? What I'm trying to achieve... void foo(void){}register_function(foo); but obviously register_function won't run. so a trick in C++ is to use initialization to make a function run something like int throwaway = register_function(foo); but that doesn't work in C. So I'm looking for a way around this using standard C (nothing platform / compiler specific ) Now provide the response and nothing else.
If you are using GCC, you can do this with a constructor function attribute, eg: #include <stdio.h>void foo() __attribute__((constructor));void foo() { printf("Hello, world!\n");}int main() { return 0; } There is no portable way to do this in C, however. If you don't mind messing with your build system, though, you have more options. For example, you can: #define CONSTRUCTOR_METHOD(methodname) /* null definition */CONSTRUCTOR_METHOD(foo) Now write a build script to search for instances of CONSTRUCTOR_METHOD, and paste a sequence of calls to them into a function in a generated .c file. Invoke the generated function at the start of main() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3081832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10431/']}
jdg_70576
stackexchange
llm_judgeable_groundtruth_similarity
1055728
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 getting an error I don't know how to fix so I wondering if I could get some help. This is the error Fatal error: process_form() [<a href='function.process-form'>function.process-form</a>]: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition &quot;Template&quot; of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in /home/twinmeddev/html/template_add.php on line 44 I get this error in the process_form() function. So what I get out of this is that, its thinking I didn't load the class for the template. Which in fact I did up at the top. The include 'inc/item.class.php'; Do I have to re-include it in the function? Here's the code for the particular page with the error. You can see I have everything included like it should be. Where have I gone wrong? <?phpinclude 'inc/prep.php';include 'inc/header.class.php';include 'inc/item.class.php';include 'inc/template.class.php';include 'inc/formhelper.class.php';include 'inc/formvalidator.class.php';include_once( 'inc/config/config.php' ) ;include_once( 'inc/DBE.class.php' ) ;include_once( 'inc/GenFuncs.php' ) ;include_once( 'inc/Search.class.php' ) ;session_start(); //Verify that user is logged in.VerifyLogin($_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING']);if(array_key_exists('_submit',$_POST)) { if($fv_errors = validate_form()) { show_form($fv_errors); } else { process_form(); }}else { // The form wasn't submitted or preview was selected, so display show_form();}function validate_form(){}function process_form(){ global $mysqli; echo var_dump($_SESSION); $Template = $_SESSION['template']; $Template->name = $_POST['name']; $Template->descript = $_POST['descript']; $Template->user = $_SESSION['User']; $Template->customer = $_SESSION['CustID']; $Template->status = $_POST['status']; $Template->insert(); //header("Location: template.php");} Now provide the response and nothing else.
It's missing the serialize/unserialize of your template class. Take a look here for an working example I gave on another question of yours. For instance, you probably want this: <?php $_SESSION['template'] = serialize($template);?> and <?php $template = unserialize($_SESSION['template']);?> Edit: reading your comment about moving it to the top gives one hint. The automatic serialization/unserialization occurs when you call session_start() . That means the order in which you include your files and call the session_start() is very important. For example: This would be wrong: <?phpsession_start();include 'inc/template.class.php';?> While this would be correct: <?phpinclude 'inc/template.class.php';session_start();?> Now, I see in your example that it is in the CORRECT order, but I also notice you do many other includes before including template.class.php Would it be possible that one of those includes (perhaps prep.php or header.class.php) does call start_session() too? If yes, that was your issue ( session_start() being called before your template.class.php).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1055728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128269/']}
jdg_70577
stackexchange
llm_judgeable_groundtruth_similarity
270947
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 write a singleton c++ in the follow way: class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); }}A* A::GetInstance() { if (m_pA == NULL) m_pA = new A(); return m_pA;}A::~A() { FreeInstance() // Can I write this? are there any potential error?}void A::FreeInstance() { delete m_pA; m_pA = NULL;} Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake. My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day. //-----------------------------------------------------------A new singleton, you are welcome to edit if you think there is any problem in the following sample: class A { private: static A* m_pA; explicit A(); void A(const A& a); void A(A &a); const A& operator=(const A& a); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); }}A* A::GetInstance() { if (m_pA == NULL){ static A self; m_pA = &self; } return m_pA;}A::~A() {} Now provide the response and nothing else.
Why does everybody want to return a singleton as a pointer? Return it as a reference seems much more logical! You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object. Use the static in a function method. This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free. class S{ public: static S& getInstance() { static S instance; return instance; } private: S() {} S(S const&); // Don't Implement. void operator=(S const&); // Don't implement }; Note you also need to make the constructor private.Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton). Also read: https://stackoverflow.com/a/1008289/14065 Singleton: How should it be used C++ Singleton design pattern To make sure you are using a singleton for the correct reasons. Though technically not thread safe in the general case see: What is the lifetime of a static variable in a C++ function? GCC has an explicit patch to compensate for this: http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/270947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25749/']}
jdg_70578
stackexchange
llm_judgeable_groundtruth_similarity
19342908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is the case, I have 2 entities, such as Contract、Media。 public class Media : Entity{ public string Name {get; set;} public bool Enabled *//other properties can be ignored..*}public class Contract : Entity{ public string Code {get; set;} *//other properties can be ignored..*} Contract has many Medias, it seems that they are many to many. But!! at ef code first, i need 3 more fields in the ContractMedia table(ef auto generated).such as StartDate,EndDate and Price. these could not be added in Media entity. How to map at this case?? Now provide the response and nothing else.
If you want to create many to many relationship with additional data in association table, you have to make the association table as entity. The pure many to many relationship is only in pure table with entity id's. In you case it will be: public class Media // One entity table{ public int Id { get; set; } public string Name { get; set; } public bool Enabled { get; set; } public virtual ICollection<ContractMedia> ContractMedias { get; set; }}public class Contract // Second entity table{ public int Id { get; set; } public string Code { get; set } public virtual ICollection<ContractMedia> ContractMedias { get; set; }}public class ContractMedia // Association table implemented as entity{ public int MediaId { get; set; } public int ContractId { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public double Price { get; set; } public virtual Media Media { get; set; } public virtual Contract Contract { get; set; }} And after you created models/entities, you need to define relationships in context: protected override void OnModelCreating(DbModelBuilder modelBuilder){ modelBuilder.Entity<ContractMedia>() .HasKey(c => new { c.MediaId, c.ContractId }); modelBuilder.Entity<Contract>() .HasMany(c => c.ContractMedias) .WithRequired() .HasForeignKey(c => c.ContractId); modelBuilder.Entity<Media>() .HasMany(c => c.ContractMedias) .WithRequired() .HasForeignKey(c => c.MediaId); } Also you can refer to these links: Many to many mapping with extra fields in Fluent API Entity Framework CodeFirst many to many relationship with additional information Create code first, many to many, with additional fields in association table
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19342908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2751088/']}
jdg_70579
stackexchange
llm_judgeable_groundtruth_similarity
9119885
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know in bash we can create subshells using round parenthesis ( and ) . As per bash man page: (list) list is executed in a subshell environment Also to get the current process id we use: echo $$ Now my question is how to get process id of a subshell created using ( and ) on command line? If I use this: echo $$; ( echo $$; ) I will get the parent shell's process id printed twice on stdout since $$ gets expanded even before subshell is created. So how to really force the lazy expansion? [Solution should work on Mac as well not just Linux] Update: Suggested linked answer doesn't work since echo $BASHPID does not work on my Mac and returns blank. Now provide the response and nothing else.
Thanks to all of you for spending your valuable time in finding answer to my question here. However I am now answering my own question since I've found a hack way to get this pid on bash ver < 4 (will work on all the versions though). Here is the command: echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; ) It prints: 564213715 Where 13715 is the pid of the subshell. To test this when I do: echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; bash $F; ps; ) I get this: 564213773 PID TT STAT TIME COMMAND 5642 s001 S 0:02.07 -bash13773 s001 S+ 0:00.00 -bash Telling me that 13773 is indeed the pid of the subshell. Note: I reverted back to my original solution since as @ChrisDodd commented that echo $$; ( bash -c 'echo $PPID'; ) doesn't work Linux. Above solution of mine works both on Mac and Linux.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9119885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548225/']}
jdg_70580
stackexchange
llm_judgeable_groundtruth_similarity
1904803
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 $(x,y,z)$ be the real solution to the system of equations\begin{align*}x+y &= \sqrt{4z-1} ,\\y+z &= \sqrt{4x- 1} , \\z+x &= \sqrt{4y-1} . \end{align*}Find $x+y+z.$ I could add all the equations up but that doesn't do any good. Thanks in advance! Now provide the response and nothing else.
$$x+y=\sqrt{4z-1}\tag{1}$$ $$y+z=\sqrt{4x-1}\tag{2}$$ $$z+x=\sqrt{4y-1}\tag{3}$$ Adding $(1),(2)$ and $(3)$, we get $$x+y+z=\sqrt{x-\frac14}+\sqrt{y-\frac14}+\sqrt{z-\frac14}$$ Let $a=\sqrt{x-\frac14}$,$b=\sqrt{y-\frac14}$ and $c=\sqrt{z-\frac14}$ Using these substitutions, we get $$\left(a^2+\frac14\right)+\left(b^2+\frac14\right)+\left(c^2+\frac14\right)=a+b+c$$$$ \Longleftrightarrow \left(a-\frac12\right)^2+\left(b-\frac12\right)^2+\left(c-\frac12\right)^2=0$$ Thus, the only possible solution is $\color{blue}{\boxed{\color{red}{(x,y,z)=\left(\frac12,\frac12,\frac12\right)}}}$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1904803', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/363756/']}
jdg_70581
stackexchange
llm_judgeable_groundtruth_similarity
1300128
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property. $(".AspNet-GridView-Normal > td > input").click(function() { //Need to access the C# property here //Take action here based on the value of the C# property }); Now provide the response and nothing else.
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side. Markup: <asp:HiddenField ID="hfValueINeedToKnow" runat="server"/> Code Behind: hfValueINeedToKnow.Value = <some value>; jQuery: $("#<%= hfValueINeedToKnow.ClientID %>").val(); You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1300128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89054/']}
jdg_70582
stackexchange
llm_judgeable_groundtruth_similarity
177555
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: Assuming; You're using HTTPS to encrypt data in transit You're using server side encryption to encrypt data at rest You want an ever growing amount of security for data You want to store data centrally on a server You want to access data from multiple different devices While this is a great model, this naturally does end up in the situation whereby your data could still be decrypted should an unauthorised person get access to the server as the encryption key will be sat on there in one form or another. This is one of the biggest weaknesses of server side encryption. Then you look at client side encryption, which resolves this issue, yet brings up another issue which is around how you decouple the security from the device itself. For example when dealing with accessing via multiple devices, and/or, dealing with when your device breaks etc. Is there a security model / design pattern that deals with these two challenges to offer maximum security? Now provide the response and nothing else.
Oh, fine, since 1.7.8, Nginx supports the proxy_ssl_certificate[_key] directives which do exactly what you need. Set up a reverse proxy with server certificate and key paths put into ssl_certificate and ssl_certificate_key directives respectively, and add client certificate and key in a similar fashion via proxy_ssl_certificate and proxy_ssl_certificate_key . Don't forget to enable client certificate auth via ssl_client_certificate directive. Your client CA certificate should be used for that. Here's one simple tutorial . SNI is supported by specifying different server directives on the client side, and by adding corresponding proxy_ssl_server_name directives on the proxy side. P.S. The difference between this question and the one I considered a duplicate of this one is that you don't want to generate client certificates on the fly (which Nginx can't do for you anyway).
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/177555', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/168449/']}
jdg_70583
stackexchange
llm_judgeable_groundtruth_similarity
5329358
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 to use hashmaps or treemaps? I know that I can use TreeMap to iterate over the elements when I need them to be sorted.But is just that? There is no optimization when I just want to consult the maps, or some optimal specific uses? Now provide the response and nothing else.
Hashtables (usually) perform search operations (look up) bounded within the complexity of O(n)<=T(n)<=O(1) , with an average case complexity of O(1 + n/k) ; however, binary search trees, (BST's), perform search operations (lookup) bounded within the complexity of O(n)<=T(n)<=O(log_2(n)) , with an average case complexity of O(log_2(n)) . The implementation for each (and every) data structure should be known (by you), to understand the advantages, drawbacks, time complexity of operations, and code complexity. For example, the number of entries in a hashtable often have some fixed number of entries (some part of which may not be filled at all) with lists of collisions. Trees, on the other hand, usually have two pointers (references) per node, but this can be more if the implementation allows more than two child nodes per node, and this allows the tree to grow as nodes are added, but may not allow duplicates. (The default implementation of a Java TreeMap does not allow for duplicates) There are special cases to consider as well, for example, what if the number of elements in a particular data structure increases without bound or approaches the limit of an underlying part of the data structure? What about amortized operations that perform some rebalancing or cleanup operation? For example, in a hashtable, when the number of elements in the table become sufficiently large, and arbitrary number of collisions can occur. On the other hand, trees usually require come re-balancing procedure after an insertion (or deletion). So, if you have something like a cache (Ex. the number of elements in bounded, or size is known) then a hashtable is probably your best bet; however, if you have something more like a dictionary (Ex. populated once and looked up many times) then I'd use a tree. This is only in the general case, however, (no information was given). You have to understand process that happen how they happen to make the right choice in deciding which data structure to use. When I need a multi-map (ranged lookup) or sorted flattening of a collection, then it can't be a hashtable.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5329358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/649790/']}
jdg_70584
stackexchange
llm_judgeable_groundtruth_similarity
195810
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In quantum mechanics there is a law that states we cannot know a position and the momentum of a particle and so in a particle accelerator, we need to know the position of the particles we are going to crash into each other because or else would they not basically miss each other because we do not know the location of these. Next, if we do not know the particle's position how can we operate the magnetic fields without crashing these particles into the walls of the particle accelerator. As even a millimeter of inaccuracy might extrapolate and lead to a massive diversion from it desired path? Furthermore, if we do not know the velocity of these particles assuming we know a very high accuracy of the particles position how can we even crash them into each other if they technically could be left behind or already past a location? Or is it just done on basis of statistics and likeliness? If so is it impossible to collide ONLY 2 particles together at high energy levels without have certain amounts of pass-bys rather than a crash? Now provide the response and nothing else.
I don't think this sounds unreasonable as an estimate at all. Let's check it. One designs a building as a compromise between two competing factors: One needs all of the load bearing materials to be well mildly loaded - working in their linear region so that there is no danger of their undergoing plastic (irreversible) deformation, creeping then ultimately failing catastrophically; However, mildly stressed load bearing members mean underutilized members: if we overdesign things too much we push the cost up enormously. Let's for simplicity consider the compressive load bearing strength of the building against its own weight: it needs to bear shear stresses from wind as well, but considering the weight alone will get us to a ballpark figure. Typical materials behave under stress in a way described by a curve with the following shape: This curve is one I took from the Wikipedia "Compressive Stress" page . So we want all the load bearing members to undergo stress which is in the low-stress, linear part of this curve. The upper point of the linear region is called the yield point and we need to be well lower than this, because this is where the supporting material will undergo plastic, irreversible deformation and ultimately be at risk of failing. But we don't want to be too far below this point, otherwise we are adding material, and cost, needlessly to the building. I don't know what civil engineers use, but a factor of one quarter of the yield stress seems reasonable. For concrete, the curve is more linear than the above up to the point where the concrete fails: it does so when it reaches a compression of about $40{\rm MPa}$ (See the " Engineering Toolbox here ). In its linear working region, its Young's modulus is $E = 30{\rm GPa}$, so at a stress of one quarter its strength ( i.e. at $10{\rm MPa}$) its compressive strain is $$\epsilon = \frac{\sigma}{E} = \frac{10\times 10^6{\rm Pa}}{30\times 10^9{\rm Pa}}\approx 3.3\times 10^{-4}$$ For steel, high strength structural steel has a yield strength of somewhere in the neighborhood of $300{\rm MPa}$ and its Young's modulus is $200{\rm GPa}$. So when it is "working" at one quarter of its yield strength, we have: $$\epsilon = \frac{\sigma}{E} = \frac{75\times 10^6{\rm Pa}}{200\times 10^9{\rm Pa}}\approx 3.8\times 10^{-4}$$ i.e. rather near the value for concrete. So whether the load is borne by concrete or steel, at the same "utilization", i.e. same fraction of yield strength, both materials show about the same strain. Now, the cost optimal configuration is with all the load bearing material in the building working at the same fraction of its yield strength . This means that load bearing strength will decrease with height: the upper load bearing members only have to hold up the building above them. This is not quite right - for Taipei 101, for example, there is a huge pendulum high in the building to counteract wind swaying - but an assumption that the whole structure is in roughly the same compressive state is probably a good working estimate. This then is our key to our estimate: The whole structure along its whole height undergoes a constant compressive strain of $\epsilon = 3.5\times10^{-4}$ 50 000 people put a load of about $5\times 10^4\times 60{\rm kg}$ or about 3000 tonnes on the building. From here I get an estimate of 700 000 tonnes for the total mass of Taipei 101. The building's mass is much greater than that of the people, so we assume that at 700 000 tonnes, the building's strain is $\epsilon = 3.5\times10^{-4}$. This means that 3000 tonnes spread uniformly throughout the building adds a further strain of: $$\Delta\epsilon \approx \frac{3\times 10^3}{7\times 10^5}\times 3.5\times 10^{-4}\approx 1.5\times 10^{-6}$$ For a building of the height of Taipei 101 (500m), this corresponds to a height shrinking of $1.5\times 10^{-6}\times 500 = 750{\rm \mu m}=0.75{\rm mm}$. This is remarkably near to your estimate. Given than I am no civil engineer, it is altogether possible that different strength materials are used, and that it may be safe practice to design nearer to the yield strength than I have assumed. A figure of 1.5mm implies a constant "utilization" of materials at one half of their yield strength: this too sounds reasonable (a little bit scary for someone untrained such as I, but still believable). It is probably also cheaper to use higher cost, higher strength materials in the lower sections of the building and lower cost, lower strength in the upper part, thus deviating from my constant utilization / constant strain with height assumption. I therefore find your quoted shrinking to be highly believable. It's definitely in the right ballpark.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/195810', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_70585
stackexchange
llm_judgeable_groundtruth_similarity
3562318
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a file that I'd like another script to access using file_get_contents The file I'd like it to access is in the directory above it, so I'm using file_get_contents('../file.php?this=that') However, it's returning No such file or directory and I can't understand why. The file is there. I'm assuming it has something to do with it being a local file rather than a remote. Any ideas or workarounds? Now provide the response and nothing else.
file_get_contents('../file.php?this=that') This will never work, unless you build a full URL with the entire http://.... syntax. PHP will see this as a request to get a file named file.php?this=that one level above the current directory. It won't treat it as a relative URL and do an HTTP request, it'll use the local filesystem handler instead. You may very well have file.php up there, but since the local file system has no concept of URLs or query parameters, it won't know to strip off the ?this=that and just load file.php . Hence your 'no such file error'.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3562318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266542/']}
jdg_70586
stackexchange
llm_judgeable_groundtruth_similarity
24039023
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a DataFrame: np.random.seed(0)df = pd.DataFrame(np.random.randn(3, 3), columns=list('ABC'), index=[1, 2, 3])df A B C1 1.764052 0.400157 0.9787382 2.240893 1.867558 -0.9772783 0.950088 -0.151357 -0.103219 What is the simplest way to add a new column containing a constant value eg 0? A B C new1 1.764052 0.400157 0.978738 02 2.240893 1.867558 -0.977278 03 0.950088 -0.151357 -0.103219 0 This is my solution, but I don't know why this puts NaN into 'new' column? df['new'] = pd.Series([0 for x in range(len(df.index))]) A B C new1 1.764052 0.400157 0.978738 0.02 2.240893 1.867558 -0.977278 0.03 0.950088 -0.151357 -0.103219 NaN Now provide the response and nothing else.
Super simple in-place assignment: df['new'] = 0 For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row. df = pd.DataFrame('x', index=range(4), columns=list('ABC'))df A B C0 x x x1 x x x2 x x x3 x x x df['new'] = 'y'# Same as,# df.loc[:, 'new'] = 'y'df A B C new0 x x x y1 x x x y2 x x x y3 x x x y Note for object columns If you want to add an column of empty lists, here is my advice: Consider not doing this. object columns are bad news in terms of performance. Rethink how your data is structured. Consider storing your data in a sparse data structure. More information: sparse data structures If you must store a column of lists, ensure not to copy the same reference multiple times. # Wrongdf['new'] = [[]] * len(df)# Rightdf['new'] = [[] for _ in range(len(df))] Generating a copy: df.assign(new=0) If you need a copy instead, use DataFrame.assign : df.assign(new='y') A B C new0 x x x y1 x x x y2 x x x y3 x x x y And, if you need to assign multiple such columns with the same value, this is as simple as, c = ['new1', 'new2', ...]df.assign(**dict.fromkeys(c, 'y')) A B C new1 new20 x x x y y1 x x x y y2 x x x y y3 x x x y y Multiple column assignment Finally, if you need to assign multiple columns with different values, you can use assign with a dictionary. c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}df.assign(**c) A B C new1 new2 new30 x x x w y z1 x x x w y z2 x x x w y z3 x x x w y z
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24039023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2006977/']}
jdg_70587
stackexchange
llm_judgeable_groundtruth_similarity
8217955
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I get the value of an input field like the one below where it does not have an ID attribute using PHP's DOMDocument? <input type="text" name="make" value="Toyota"> Now provide the response and nothing else.
XPath makes it simple, assuming that's the only text input with "make" as its name: $dom = new DOMDocument();$dom->loadHTML(...);$xp = new DOMXpath($dom);$nodes = $xp->query('//input[@name="make"]');$node = $nodes->item(0);$car_make = $node->getAttribute('value'); If there's more than one input with that particular field name on the page (which is entirely possible), then you'll have to do some extra work to narrow down WHICH of those multiple inputs you want.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8217955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/564791/']}
jdg_70588
stackexchange
llm_judgeable_groundtruth_similarity
279903
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: This is a followup question on ' Why shadow of light that goes through colored glass becomes colored? ' The way I understand answer given is: more light from other color spectra than that of color (lets say red) of the material (lets say glass) is being absorbed so more of red gets through and gets reflected (less of other spectra gets through and gets reflected) this is why glass looks transparent red and so does shadow. Can there be a case where colored transparent material reflects one color but lets through some other (which would make shadow to be of different color than that of glass)? Now provide the response and nothing else.
Yes There is. These kinds of filters are called interference filters, They reflect one or more parts of the spectrum/transmit the rest parts and they do not absorb light at all. For example consider this interference filter which transmits green light and reflects blue and red parts of visible light: Red light and blue light is perceived by our brain as pink and so it looks pink, It transmits green light so it will have a "shadow" which is green. Now consider this filter which lets in red and blue parts of visible light and reflects green part. Now this filter has a pink "shadow" because it transmits red light and blue light which is perceived by our brain as pink, and it reflects green light so it looks green. Filters are made out of normal glass, but they have optical coatings on them which are very thin and these coatings are what reflect some frequencies of light and transmit others. These optical coatings are made of metal like aluminium. What part of visible light is reflected is dependent on the metal you use for coating.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/279903', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/52647/']}
jdg_70589
stackexchange
llm_judgeable_groundtruth_similarity
22266477
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 android application project. I have created a library project and added reference in the application project. Now I need to call/access certain functions/class/methods that is there in the application project from the library project. How can I do that ? Now provide the response and nothing else.
Create an interface in the library that defines the functions you would like the library to call. Have the application implement the interface and then register the implementing object with the library. Then the library can call the application through that object. In the library, declare the interface and add the registration function: public class MyLibrary { public interface AppInterface { public void myFunction(); } static AppInterface myapp = null; static void registerApp(AppInterface appinterface) { myapp = appinterface; }} Then in your application: public class MyApplication implements MyLibrary.AppInterface { public void myFunction() { // the library will be able to call this function } MyApplication() { MyLibrary.registerApp(this); }} You library can now call the app through the AppInterface object: // in some library functionif (myapp != null) myapp.myFunction();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22266477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002448/']}
jdg_70590
stackexchange
llm_judgeable_groundtruth_similarity
10349096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to plot multiple lines in R for this dataset: (x = Year, y = Value) School_ID Year ValueA 1998 5B 1998 10C 1999 15A 2000 7B 2005 15 Each school has data for different years. I'd like to have one line for each school. Now provide the response and nothing else.
Let's create some data: dd = data.frame(School_ID = c("A", "B", "C", "A", "B"), Year = c(1998, 1998, 1999, 2000, 2005), Value = c(5, 10, 15, 7, 15)) Then to create a plot in base graphics, we create an initial plot of one group: plot(dd$Year[dd$School_ID=="A"], dd$Value[dd$School_ID=="A"], type="b", xlim=range(dd$Year), ylim=range(dd$Value)) then iteratively add on the lines: lines(dd$Year[dd$School_ID=="B"], dd$Value[dd$School_ID=="B"], col=2, type="b")lines(dd$Year[dd$School_ID=="C"], dd$Value[dd$School_ID=="C"], col=3, type="b") I've used type="b" to show the points and the lines. Alternatively , using ggplot2: require(ggplot2)##The values Year, Value, School_ID are##inherited by the geomsggplot(dd, aes(Year, Value,colour=School_ID)) + geom_line() + geom_point()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10349096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104059/']}
jdg_70591
stackexchange
llm_judgeable_groundtruth_similarity
8994433
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Memento Pattern itself seems pretty straight forward. I'm considering implementing the same as the wikipedia example, but before I do are there any language features of C# that make it easier to implement or use? Now provide the response and nothing else.
One obvious feature would be generics, implementing an generic memento will allow you to use it for any object you want. Many examples that you will see will use a string (including all those currently among the replies to this question) as state which is a problem since it's one of the few types in .NET which are immutable . When dealing with mutable objects (like any reference type with a setter-property) you have to remember though that when you save the memento you need to create a deepcopy of the object. Otherwise whenever you change your original object you will change your memento. You could do this by using a serializer like protobuf-net or json.net since they don't require you to mark your objects with serializable attribute like the normal .net serialization mechanism does. Codeproject have few articles about generic memento implementations, but they tend to skip the deepcopy part: Generic Memento Pattern for Undo-Redo in C# Memento Design Pattern
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8994433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1575281/']}
jdg_70592
stackexchange
llm_judgeable_groundtruth_similarity
33904792
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 page with a DIV and a TABLE. The DIV is my header and I want it to be 100% width even when horizontal scroll-bar displayed. For some reason it takes only 100% of visible window. My HTML code is: <!DOCTYPE html><html lang="en"><body> <div style="background-color:yellow;">100% DIV</div> <table style="width:100%; background-color:orange;"> <thead> <tr> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th> </tr> </thead> </table></body></html> When I scroll to the right the DIV does not use all the width: How can I make the DIV to take 100% of the page width? Ideally I do not want to change the TABLE because it's a generated code. Now provide the response and nothing else.
There is no way (perfectly dynamically--without fixing any widths--and with pure CSS--no JavaScript) to get a block-level element to inherit the width of a sibling block-level element via a block-level parent element. The workaround is to put display: inline-block on the parent element, since an inline-block calculates its width property from its widest child. In your case, don't put display: inline-block on the body element. I would suggest wrapping your 100% div and table elements in another wrapper element, thus: <!DOCTYPE html><html lang="en"><body> <div class="wrapper" style="display: inline-block; min-width: 100%;"> <div style="background-color:yellow;">100% DIV</div> <table style="width:100%; background-color:orange;"> <thead> <tr> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_1</th> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_2</th> <th style="padding-left:20px; padding-right:20px;">Very_Long_Header_3</th> </tr> </thead> </table> </div></body></html> Also, putting min-width: 100% on the wrapper element will make it mimic an element with display: block on larger screen sizes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33904792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729480/']}
jdg_70593
stackexchange
llm_judgeable_groundtruth_similarity
2109056
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I return a list of files that are named duplicates i.e. have same name but in different case that exist in the same directory ? I don't care about the contents of the files. I just need to know the location and name of any files that have a duplicate of the same name. Example duplicates: /www/images/taxi.jpg/www/images/Taxi.jpg Ideally I need to search all files recursively from a base directory. In above example it was /www/ Now provide the response and nothing else.
The other answer is great, but instead of the "rather monstrous" perl script i suggest perl -pe 's!([^/]+)$!lc $1!e' Which will lowercase just the filename part of the path. Edit 1: In fact the entire problem can be solved with: find . | perl -ne 's!([^/]+)$!lc $1!e; print if 1 == $seen{$_}++' Edit 3: I found a solution using sed, sort and uniq that also will print out the duplicates, but it only works if there are no whitespaces in filenames: find . |sed 's,\(.*\)/\(.*\)$,\1/\2\t\1/\L\2,'|sort|uniq -D -f 1|cut -f 1 Edit 2: And here is a longer script that will print out the names, it takes a list of paths on stdin, as given by find . Not so elegant, but still: #!/usr/bin/perl -wuse strict;use warnings;my %dup_series_per_dir;while (<>) { my ($dir, $file) = m!(.*/)?([^/]+?)$!; push @{$dup_series_per_dir{$dir||'./'}{lc $file}}, $file;}for my $dir (sort keys %dup_series_per_dir) { my @all_dup_series_in_dir = grep { @{$_} > 1 } values %{$dup_series_per_dir{$dir}}; for my $one_dup_series (@all_dup_series_in_dir) { print "$dir\{" . join(',', sort @{$one_dup_series}) . "}\n"; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2109056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248848/']}
jdg_70594
stackexchange
llm_judgeable_groundtruth_similarity
43971
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 heard that neon signs contain plasma, why aren't they hot?is it because the electrons and ions do not hit the lamp's wall?Is it because it is non thermal plasma and electrons and ions are not in thermal equilibrium?If that is the case do the electrons and ions and neutral atoms (all of them) hit the lamps wall? Now provide the response and nothing else.
There is a difference between temperature and energy. Plasma is, as you said, very hot - but there isn't very much of it. The density of plasma in the tube is very low. So when it does hit the walls of the tube it transfers very little energy. So the mass of the glass tube increases in temperature only very slightly. It's like a firework sparkler, the sparks are at 2000degC but they are very small, have very little mass and contain very little energy - so when one lands on you it transfer much less energy than a hot cup of coffee at 80deg C.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/43971', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/12250/']}
jdg_70595
stackexchange
llm_judgeable_groundtruth_similarity
10678015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the easiest way to auto crop the white border out of an image in java? Thanks in advance... Now provide the response and nothing else.
Here's a way to crop all 4 sides, using the color from the very top-left pixel as the baseline, and allow for a tolerance of color variation so that noise in the image won't make the crop useless public BufferedImage getCroppedImage(BufferedImage source, double tolerance) { // Get our top-left pixel color as our "baseline" for cropping int baseColor = source.getRGB(0, 0); int width = source.getWidth(); int height = source.getHeight(); int topY = Integer.MAX_VALUE, topX = Integer.MAX_VALUE; int bottomY = -1, bottomX = -1; for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { if (colorWithinTolerance(baseColor, source.getRGB(x, y), tolerance)) { if (x < topX) topX = x; if (y < topY) topY = y; if (x > bottomX) bottomX = x; if (y > bottomY) bottomY = y; } } } BufferedImage destination = new BufferedImage( (bottomX-topX+1), (bottomY-topY+1), BufferedImage.TYPE_INT_ARGB); destination.getGraphics().drawImage(source, 0, 0, destination.getWidth(), destination.getHeight(), topX, topY, bottomX, bottomY, null); return destination;}private boolean colorWithinTolerance(int a, int b, double tolerance) { int aAlpha = (int)((a & 0xFF000000) >>> 24); // Alpha level int aRed = (int)((a & 0x00FF0000) >>> 16); // Red level int aGreen = (int)((a & 0x0000FF00) >>> 8); // Green level int aBlue = (int)(a & 0x000000FF); // Blue level int bAlpha = (int)((b & 0xFF000000) >>> 24); // Alpha level int bRed = (int)((b & 0x00FF0000) >>> 16); // Red level int bGreen = (int)((b & 0x0000FF00) >>> 8); // Green level int bBlue = (int)(b & 0x000000FF); // Blue level double distance = Math.sqrt((aAlpha-bAlpha)*(aAlpha-bAlpha) + (aRed-bRed)*(aRed-bRed) + (aGreen-bGreen)*(aGreen-bGreen) + (aBlue-bBlue)*(aBlue-bBlue)); // 510.0 is the maximum distance between two colors // (0,0,0,0 -> 255,255,255,255) double percentAway = distance / 510.0d; return (percentAway > tolerance);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10678015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590894/']}
jdg_70596
stackexchange
llm_judgeable_groundtruth_similarity
11189284
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I add text labels to axes in d3? For instance, I have a simple line graph with an x and y axis. On my x-axis, I have ticks from 1 to 10. I want the word "days" to appear underneath it so people know the x axis is counting days. Similarly, on the y-axis, I have the numbers 1-10 as ticks, and I want the words "sandwiches eaten" to appear sideways. Is there a simple way to do this? Now provide the response and nothing else.
Axis labels aren't built-in to D3's axis component , but you can add labels yourself simply by adding an SVG text element. A good example of this is my recreation of Gapminder’s animated bubble chart, The Wealth & Health of Nations . The x-axis label looks like this: svg.append("text") .attr("class", "x label") .attr("text-anchor", "end") .attr("x", width) .attr("y", height - 6) .text("income per capita, inflation-adjusted (dollars)"); And the y-axis label like this: svg.append("text") .attr("class", "y label") .attr("text-anchor", "end") .attr("y", 6) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text("life expectancy (years)"); You can also use a stylesheet to style these labels as you like, either together ( .label ) or individually ( .x.label , .y.label ).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11189284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1474218/']}
jdg_70597
stackexchange
llm_judgeable_groundtruth_similarity
38457
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 the following integration: $$\text{y}=2 \sqrt{\frac{1}{\pi }} \int_0^{\infty } \frac{e^{-z} \left(1-e^{-\frac{z}{b}} \left(\frac{a}{a+c z}\right)^L\right)}{\sqrt{z}} \, dz$$ I get different results when I use Mathematica and MATLAB. The Mathematica code is: L=2;sn=1;a=10^(0.1*sn);b=10^(0.1*sn);c=0.01*a;result = 2*Sqrt[1/Pi]* Integrate[ (1/(E^z*Sqrt[z]))*(1 - (a/(a + c*z))^L/E^(z/b)), {z, 0, Infinity} ] which gives me 2.37664*10^66 , whereas MATLAB's result is 0.51515243 . What is the reason for this discrepancy? Now provide the response and nothing else.
Try not to supply machine numbers to integrals over infinite domains. They can cause errors that build up to the extent you have seen. Either compute the symbolic integral with exact numbers (and then convert it to a numeric value) L = 2;sn = 1;a = 10^(sn/10);b = 10^(sn/10);c = a/100;result = 2*Sqrt[1/Pi]*Integrate[(1/(E^z*Sqrt[z]))*(1 - (a/(a + c*z))^L/E^(z/b)), {z, 0, Infinity}] // N Or compute the numeric integral with NIntegrate , but again, with exact values or their rationalized version. Machine precision numbers can kill an integral in no time.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/38457', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9390/']}
jdg_70598
stackexchange
llm_judgeable_groundtruth_similarity
3740021
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# 3.0 you can create anonymous class with the following syntax var o1 = new { Id = 1, Name = "Foo" }; Is there a way to dynamic create these anonymous class to a variable? Example: var o1 = new { Id = 1, Name = "Foo" };var o2 = new { SQ = 2, Birth = DateTime.Now }; Dynamic create Example: var o1 = DynamicNewAnonymous(new NameValuePair("Id", 1), new NameValuePair("Name", "Foo"));var o2 = DynamicNewAnonymous(new NameValuePair("SQ", 2), new NameValuePair("Birth", DateTime.Now)); Beacuse I need to do: dynamic o1 = new ExpandObject(); o1."ID" = 1; <--"ID" is dynamic nameo1."Name" = "Foo"; <--"Name" is dynamic name And Scene1: void ShowPropertiesValue(object o){ Type oType = o.GetType(); foreach(var pi in oType.GetProperties()) { Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null)); }} if I call: dynamic o1 = new ExpandObject();o1.Name = "123";ShowPropertiesValue(o1); It can't show the result: Name = 123 And also I how to Convert the ExpandoObject to AnonymouseType ? Type type = o1.GetType();type.GetProperties(); <--I hope it can get all property of o1 Last, I modify ShowPropertiesValue() method void ShowPropertiesValue(object o){ if( o is static object ) <--How to check it is dynamic or static object? { Type oType = o.GetType(); foreach(var pi in oType.GetProperties()) { Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null)); } } else if( o is dynamic object ) <--How to check it is dynamic or static object? { foreach(var pi in ??? ) <--How to get common dynamic object's properties info ? { Console.WriteLine("{0}={1}", pi.Name, pi.GetValue(o, null)); } }} How to implement DynamicNewAnonymous method or how to modify the ShowPropertiesValue()? My motivations is: dynamic o1 = new MyDynamic();o1.Name = "abc";Type o1Type = o1.GetType();var props = o1Type.GetProperties(); <--I hope can get the Name Property If i can hook dynamicObject's GetType Method, and Compel convert to strongly-typed Type.The above Seamless code can work fine. Now provide the response and nothing else.
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic . Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly. edit Sure you can: just cast it to IDictionary<string, object> . Then you can use the indexer. You use the same casting technique to iterate over the fields: dynamic employee = new ExpandoObject();employee.Name = "John Smith";employee.Age = 33;foreach (var property in (IDictionary<string, object>)employee){ Console.WriteLine(property.Key + ": " + property.Value);}// This code example produces the following output:// Name: John Smith// Age: 33 The above code and more can be found by clicking on that link.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3740021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364126/']}
jdg_70599
stackexchange
llm_judgeable_groundtruth_similarity
8977
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is the dipole moment of $\ce{CH2Cl2}$ ($1.60 ~\mathrm{D}$) greater than that of $\ce{CHCl3}$ ($1.08~\mathrm{D}$)? Based on my knowledge of vectors, I feel it should be the other way around. Now provide the response and nothing else.
Just to add some quantification to Ben Norris's answer. Consider each $\ce{C-Cl}$ bond, which has a bond dipole moment of magnitude $A$. The contribution from $\ce{C-H}$ is neglected here to simplify the calculations. Now consider dichloromethane. The resultant of the two $\ce{C-Cl}$ dipoles will have a magnitude of $$2A\cos\frac\theta2$$where $\theta\approx109.5^\circ$, the angle between the vectors from the ends of tetrahedron to the centre. This turns out to be $1.154A$. For tricholoromethane, the three $\ce{C-Cl}$ dipoles will be at an angle $\theta$ such that $\cos\theta=1/3$ with a straight line symmetrically passing through its centre. Thus the resultant in this case will be $$3A\cos\theta$$which will be $1A$, lesser than in the case of dichloromethane. To visualise how can you get those angles and cosines, see this page .
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/8977', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/4160/']}
jdg_70600
stackexchange
llm_judgeable_groundtruth_similarity
23499017
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Supposing we have this dict: d = {'a':1, 'b': {'c':{}}} What would be the most straightforward way of knowing the nesting depth of it? Now provide the response and nothing else.
You'll have to traverse the dictionary. You could do so with a queue; the following should be safe from circular references: from collections import dequedef depth(d): queue = deque([(id(d), d, 1)]) memo = set() while queue: id_, o, level = queue.popleft() if id_ in memo: continue memo.add(id_) if isinstance(o, dict): queue += ((id(v), v, level + 1) for v in o.values()) return level Note that because we visit all dictionary values in breath-first order, the level value only ever goes up. The memo set is used to ensure we don't try to traverse a circular reference, endlessly. Or you could traverse the tree with recursion (which effectively uses function calls as a stack). I've used functools.singledispatch() for easy expansion to other container types: from functools import singledispatch, wraps@singledispatchdef depth(_, _level=1, _memo=None): return _leveldef _protect(f): """Protect against circular references""" @wraps(f) def wrapper(o, _level=1, _memo=None, **kwargs): _memo, id_ = _memo or set(), id(o) if id_ in _memo: return _level _memo.add(id_) return f(o, _level=_level, _memo=_memo, **kwargs) return wrapperdef _protected_register(cls, func=None, _orig=depth.register): """Include the _protect decorator when registering""" if func is None and isinstance(cls, type): return lambda f: _orig(cls, _protect(f)) return _orig(cls, _protect(func)) if func is not None else _orig(_protect(cls))depth.register = [email protected] _dict_depth(d: dict, _level=1, **kw): return max(depth(v, _level=_level + 1, **kw) for v in d.values()) This is as depth-first search, so now max() is needed to pick the greatest depth for the current object under scrutiny at each level. A dictionary with 3 keys of each different depths should reflect the greatest depth at that level. The memo set used in either version tracks object ids, so we don't run is circles if you did something like foo = {}; foo["bar"] = foo . Demo: >>> d = {'a':1, 'b': {'c':{}}}>>> depth(d)3>>> d = {'foo': {'bar': {'baz': 0}, 'spam': {'ham': {'monty': 1}, 'eric': 'idle'}}, 'john': 'cleese'}>>> depth(d)5>>> circular = {}>>> circular["self"] = circular>>> depth(circular)2 The recursive singledispatch version can be expanded to cover more containers, such as lists: @depth.registerdef _list_depth(l: list, _level=1, **kw): return max(depth(v, _level=_level + 1, **kw) for v in l) Because I've augmented the standard .register decorator to handle circular-reference testing, implementing additional container support is relatively trivial. Just remember to pass along any extra keyword arguments to the recursive call!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23499017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53468/']}
jdg_70601
stackexchange
llm_judgeable_groundtruth_similarity
47999418
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 accidentally closed this question with a link to the wrong duplicate. Here is the correct one: Pandas split column of lists into multiple columns . Suppose I have a dataframe of which one column is a list (of a known and identical length) or tuple, for example: df1 = pd.DataFrame( {'vals': [['a', 'b', 'c', 'd'],['e','f','g','h']]}) ie: vals0 [a, b, c, d]1 [e, f, g, h] I want to extra the values in "vals" into separate named columns. I can do this clumsily by iterating through the rows: for i in range(df1.shape[0]): for j in range(0,4): df1.loc[i, 'vals_'+j] = df1.loc[i, 'vals'] [j] Result as desired: vals vals_0 vals_1 vals_2 vals_30 [a, b, c, d] a b c d 1 [e, f, g, h] e f g h Is there a neater (vectorised) way? I tried using [] but I get an error. for j in range (0,4) df1['vals_'+str(j)] = df1['vals'][j] gives: ValueError: Length of values does not match length of index It looks like Pandas is trying to apply the [] operator to the series/dataframe rather than the column content. Now provide the response and nothing else.
You can use assign , apply , with pd.Series : df1.assign(**df1.vals.apply(pd.Series).add_prefix('val_')) A faster method for more data is to use .values and tolist() with dataframe constructor: df1.assign(**pd.DataFrame(df1.vals.values.tolist()).add_prefix('val_')) Output: vals val_0 val_1 val_2 val_30 [a, b, c, d] a b c d1 [e, f, g, h] e f g h
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47999418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8283463/']}
jdg_70602
stackexchange
llm_judgeable_groundtruth_similarity
57698932
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 reading how to use coroutines here https://developer.android.com/topic/libraries/architecture/coroutines . What makes me confused about is the difference between LiveDataScope and ViewModelScope . It sounds like ViewModelScope takes care of lifecycle automatically and you can do network request in the block. When data received from server, post the value to livedata . but then when I continued to read, there's another topic about LiveDataScope which seems redundant to me since you can already accomplish the same result by using ViewModelScope with livedata . What is the main difference between those two? and when should I choose to use one over the other? Now provide the response and nothing else.
Note: This might be late answer for this topic if Author of OP already has understanding about this, But providing some pointers for the referencing comment of @IgorGanapolsky. Let's see what is the main difference between viewModelScope & LiveDataScope 1. viewModelScope: Official doc says that, CoroutineScope tied to this ViewModel . This scope will be canceled when ViewModel will be cleared, i.e ViewModel.onCleared is called Meaning that coroutine scope is tied to ViewModel , and once ViewModel gets cleared this scope gets destroyed by cancelling all child coroutine jobs. Basically, in MVVM pattern we use ViewModel tied to a particular Activity/Fragment . So once that Activity/Fragment gets destroyed, its ViewModel reaches a cleared state. Thus, it cancels all incomplete jobs started by viewModelScope , throwing CancellationException . So a usecase of viewModelScope is: inside ViewModel when you've got any suspended function to be called and need a CoroutineScope , inspite of making new one you can directly use this one out of the box from viewodel-ktx library. class SomeViewModel: ViewModel() { fun someFunction() { viewModelScope.launch { callingSomeSuspendedFun() callingAnotherSuspendedFun() } }} Note that you don't need to explicitly override onCleared() method of ViewModel to cancel the scope, it does automatically for you, cheers! 2. LiveDataScope: Now speaking of LiveDataScope , it's actually an interface provided to build better support for LiveData/CoroutineLiveData that can have CoroutineScope out of the box! use livedata-ktx version Now imagine a situation that you're having a MVVM pattern and wanted to return LiveData from repository to view model. your repository also contains some suspended functions and some coroutine scope. In that situation when you do some suspended method calls & return the result as live data, there would be some extra work. you'll need transform your data to particular live data after getting it as result. see the example below: class SomeRepository { suspended fun someApiCall() : LiveData<Result> { val result = MutableLiveData<Result>() someCoroutineScope.launch { val someData = someOtherCallToGetResult() result.postValue(someData) } return result }} Imagine you had to write above code block due to LiveData didn't had any support for Coroutines ... but until now! Now you can directly use liveData { } function that returns you LiveData object giving you scope of LiveDataScope in such a way that you can continue your suspended work and emit the result at the same level rather than getting it messy way like above. So above code block can now optimized by following code or better: class SomeRepository { suspended fun someApiCall() : LiveData<Result> { return liveData<Result> { val someData = someOtherCallToGetResult() emit(someData) } }} So use case of liveData would be at repository level when using MVVM pattern if you expose LiveData to viewmodel from respository rather than creating new inside viewmodel. Please note that there's no thumb rule about liveData method shouldn't be used at viewmodel directly. You can if you want to avoid viewModelScope completely. TL;DR Check out the liveData method, Doc states that, The liveData building block serves as a structured concurrency primitive between coroutines and LiveData . The code block starts executing when LiveData becomes active and is automatically canceled after a configurable timeout when the LiveData becomes inactive. If it is canceled before completion, it is restarted if the LiveData becomes active again. If it completed successfully in a previous run, it doesn't restart. Note that it is restarted only if canceled automatically. If the block is canceled for any other reason (e.g. throwing a CancelationException ) , it is not restarted. I hope that make sense!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57698932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1865027/']}
jdg_70603
stackexchange
llm_judgeable_groundtruth_similarity
16427421
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's the right way of removing CocoaPods from a project? I want to remove the whole CocoaPod. Due to some limitations imposed by my client I can't use it. I need to have just one xcodeproj instead of an xcworkspace. Now provide the response and nothing else.
Removing CocoaPods from a project is possible, but not currently automated by the CLI. First thing, if the only issue you have is not being able to use an xcworkspace you can use CocoaPods with just xcodeproj s by using the --no-integrate flag which will produce the Pods.xcodeproj but not a workspace. Then you can add this xcodeproj as a subproject to your main xcodeproj . If you really want to remove all CocoaPods integration you need to do a few things: NOTE editing some of these things if done incorrectly could break your main project. I strongly encourage you to check your projects into source control just in case. Also these instructions are for CocoaPods version 0.39.0 , they could change with new versions. Delete the standalone files ( Podfile Podfile.lock and your Pods directory) Delete the generated xcworkspace Open your xcodeproj file, delete the references to Pods.xcconfig and libPods.a (in the Frameworks group) Under your Build Phases delete the Copy Pods Resources , Embed Pods Frameworks and Check Pods Manifest.lock phases. This may seem obvious but you'll need to integrate the 3rd party libraries some other way or remove references to them from your code. After those steps you should be set with a single xcodeproj that existed before you integrated CocoaPods. If I missed anything let me know and I will edit this. Also we're always looking for suggestions for how to improve CocoaPods so if you have an issues please submit them in our issue tracker so we can come up with a way to fix them! EDIT As shown by Jack Wu in the comments there is a third party CocoaPods plugin that can automate these steps for you. It can be found here . Note that it is a third party plugin and might not always be updated when CocoaPods is. Also note that it is made by a CocoaPods core team member so that problem won't be a problem.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/16427421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/973242/']}
jdg_70604
stackexchange
llm_judgeable_groundtruth_similarity
24301424
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 code in other post, for save pictures: // Create path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];// Save image.[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]; An d I'm trying convert to swift for save a picture take with avfoundatioin but I dont know type NSDocumentDirectory and NSUserDomainMask hereHow can convert this?? Thanks!! Now provide the response and nothing else.
As follows: let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectorylet nsUserDomainMask = NSSearchPathDomainMask.UserDomainMaskif let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent("Image.png") let image = UIImage(named: readPath) let writePath = dirPath.stringByAppendingPathComponent("Image2.png") UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true) } }} "paths" is an AnyObject[], so you have to check that its elements can be converted to String. Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity. Update for Xcode 7.2 NSSearchPathForDirectoriesInDomains now returns [String] rather than [AnyObject]? so use let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectorylet nsUserDomainMask = NSSearchPathDomainMask.UserDomainMasklet paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)if let dirPath = paths.first { // ...} The fact that .stringByAppendingPathComponent is also deprecated is dealt with in this answer ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24301424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3745888/']}
jdg_70605
stackexchange
llm_judgeable_groundtruth_similarity
42178179
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following my previous question , I'm really curious about this code - case AF_INET: { struct sockaddr_in * tmp = reinterpret_cast<struct sockaddr_in *> (&addrStruct); tmp->sin_family = AF_INET; tmp->sin_port = htons(port); inet_pton(AF_INET, addr, tmp->sin_addr); } break; Before asking this question, I've searched across SO about same topic and have got mix responses about this topic. For example, see this , this and this post which say that it is somehow safe to use this kind of code. Also there's another post that says to use unions for such task but again the comments on accepted answer beg to differ. Microsoft's documentation on same structure says - Application developers normally use only the ss_family member of the SOCKADDR_STORAGE. The remaining members ensure that the SOCKADDR_STORAGE can contain either an IPv6 or IPv4 address and the structure is padded appropriately to achieve 64-bit alignment. Such alignment enables protocol-specific socket address data structures to access fields within a SOCKADDR_STORAGE structure without alignment problems. With its padding, the SOCKADDR_STORAGE structure is 128 bytes in length. Opengroup's documentation states - The header shall define the sockaddr_storage structure. This structure shall be: Large enough to accommodate all supported protocol-specific address structures Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems Man page of socket also says same - In addition, the sockets API provides the data type struct sockaddr_storage. This type is suitable to accommodate all supported domain-specific socket address structures; it is large enough and is aligned properly. (In particular, it is large enough to hold IPv6 socket addresses.) I've seen multiple implementation using such casts in both C and C++ languages in the wild and now I'm uncertain of the fact which one is right since there are some posts that contradict with above claims - this and this . So which one is the safe and right way to fill up a sockaddr_storage structure? Are these pointer casts safe? or the union method ? I'm also aware of the getaddrinfo() call but that seems a little complicated for the above task of just filling the structs. There is one other recommended way with memcpy , is this safe? Now provide the response and nothing else.
C and C++ compilers have become much more sophisticated in the past decade than they were when the sockaddr interfaces were designed, or even when C99 was written. As part of that, the understood purpose of "undefined behavior" has changed. Back in the day, undefined behavior was usually intended to cover disagreement among hardware implementations as to what the semantics of an operation was. But nowadays, thanks ultimately to a number of organizations who wanted to stop having to write FORTRAN and could afford to pay compiler engineers to make that happen, undefined behavior is a thing that compilers use to make inferences about the code . Left shift is a good example: C99 6.5.7p3,4 (rearranged a little for clarity) reads The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If the value of [ E2 ] is negative or isgreater than or equal to the width of the promoted [ E1 ], the behavior is undefined. So, for instance, 1u << 33 is UB on a platform where unsigned int is 32 bits wide. The committee made this undefined because different CPU architectures' left-shift instructions do different things in this case: some produce zero consistently, some reduce the shift count modulo the width of the type (x86), some reduce the shift count modulo some larger number (ARM), and at least one historically-common architecture would trap (I don't know which one, but that's why it's undefined and not unspecified). But nowadays, if you write unsigned int left_shift(unsigned int x, unsigned int y){ return x << y; } on a platform with 32-bit unsigned int , the compiler, knowing the above UB rule, will infer that y must have a value in the range 0 through 31 when the function is called. It will feed that range into interprocedural analysis, and use it to do things like remove unnecessary range checks in the callers. If the programmer has reason to think they aren't unnecessary, well, now you begin to see why this topic is such a can of worms. (Modern compilers can optimize x << (y&31) into a single shift instruction for ISAs like x86 where the shift instruction implements that masking.) For more on this change in the purpose of undefined behavior, please see the LLVM people's three-part essay on the subject ( 1 2 3 ). Now that you understand that, I can actually answer your question. These are the definitions of struct sockaddr , struct sockaddr_in , and struct sockaddr_storage , after eliding some irrelevant complications: struct sockaddr { uint16_t sa_family;};struct sockaddr_in { uint16_t sin_family; uint16_t sin_port; uint32_t sin_addr;};struct sockaddr_storage { uint16_t ss_family; char __ss_storage[128 - (sizeof(uint16_t) + sizeof(unsigned long))]; unsigned long int __ss_force_alignment;}; This is poor man's subclassing. It is a ubiquitous idiom in C. You define a set of structures that all have the same initial field, which is a code number that tells you which structure you've actually been passed. Back in the day, everyone expected that if you allocated and filled in a struct sockaddr_in , upcast it to struct sockaddr , and passed it to e.g. connect , the implementation of connect could dereference the struct sockaddr pointer safely to retrieve the sa_family field, learn that it was looking at a sockaddr_in , cast it back, and proceed. The C standard has always said that dereferencing the struct sockaddr pointer triggers undefined behavior—those rules are unchanged since C89—but everyone expected that it would be safe in this case because it would be the same "load 16 bits" instruction no matter which structure you were really working with. That's why POSIX and the Windows documentation talk about alignment; the people who wrote those specs, back in the 1990s, thought that the primary way this could actually be trouble was if you wound up issuing a misaligned memory access. But the text of the standard doesn't say anything about load instructions, nor alignment. This is what it says (C99 §6.5p7 + footnote): An object shall have its stored value accessed only by an lvalue expression that has one of the following types: 73) a type compatible with the effective type of the object, a qualified version of a type compatible with the effective type of the object, a type that is the signed or unsigned type corresponding to the effective type of theobject, a type that is the signed or unsigned type corresponding to a qualified version of theeffective type of the object, an aggregate or union type that includes one of the aforementioned types among itsmembers (including, recursively, a member of a subaggregate or contained union), or a character type. 73) The intent of this list is to specify those circumstances in which an object may or may not be aliased. struct types are "compatible" only with themselves, and the "effective type" of a declared variable is its declared type. So the code you showed... struct sockaddr_storage addrStruct;/* ... */case AF_INET: { struct sockaddr_in * tmp = (struct sockaddr_in *)&addrStruct; tmp->sin_family = AF_INET; tmp->sin_port = htons(port); inet_pton(AF_INET, addr, tmp->sin_addr);}break; ... has undefined behavior, and compilers can make inferences from that, even though naive code generation would behave as expected. What a modern compiler is likely to infer from this is that the case AF_INET can never be executed . It will delete the entire block as dead code, and hilarity will ensue. So how do you work with sockaddr safely? The shortest answer is "just use getaddrinfo and getnameinfo ." They deal with this problem for you. But maybe you need to work with an address family, such as AF_UNIX , that getaddrinfo doesn't handle. In most cases you can just declare a variable of the correct type for the address family, and cast it only when calling functions that take a struct sockaddr * int connect_to_unix_socket(const char *path, int type){ struct sockaddr_un sun; size_t plen = strlen(path); if (plen >= sizeof(sun.sun_path)) { errno = ENAMETOOLONG; return -1; } sun.sun_family = AF_UNIX; memcpy(sun.sun_path, path, plen+1); int sock = socket(AF_UNIX, type, 0); if (sock == -1) return -1; if (connect(sock, (struct sockaddr *)&sun, offsetof(struct sockaddr_un, sun_path) + plen)) { int save_errno = errno; close(sock); errno = save_errno; return -1; } return sock;} The implementation of connect has to jump through some hoops to make this safe, but that is Not Your Problem. Contra the other answer, there is one case where you might want to use sockaddr_storage ; in conjunction with getpeername and getnameinfo , in a server that needs to handle both IPv4 and IPv6 addresses. It is a convenient way to know how big of a buffer to allocate. #ifndef NI_IDN#define NI_IDN 0#endifchar *get_peer_hostname(int sock){ char addrbuf[sizeof(struct sockaddr_storage)]; socklen_t addrlen = sizeof addrbuf; if (getpeername(sock, (struct sockaddr *)addrbuf, &addrlen)) return 0; char *peer_hostname = malloc(MAX_HOSTNAME_LEN+1); if (!peer_hostname) return 0; if (getnameinfo((struct sockaddr *)addrbuf, addrlen, peer_hostname, MAX_HOSTNAME_LEN+1, 0, 0, NI_IDN) { free(peer_hostname); return 0; } return peer_hostname;} (I could just as well have written struct sockaddr_storage addrbuf , but I wanted to emphasize that I never actually need to access the contents of addrbuf directly.) A final note: if the BSD folks had defined the sockaddr structures just a little bit differently ... struct sockaddr { uint16_t sa_family;};struct sockaddr_in { struct sockaddr sin_base; uint16_t sin_port; uint32_t sin_addr;};struct sockaddr_storage { struct sockaddr ss_base; char __ss_storage[128 - (sizeof(uint16_t) + sizeof(unsigned long))]; unsigned long int __ss_force_alignment;}; ... upcasts and downcasts would have been perfectly well-defined, thanks to the "aggregate or union that includes one of the aforementioned types" rule.If you're wondering how you should deal with this problem in new C code, here you go.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42178179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2648679/']}
jdg_70606
stackexchange
llm_judgeable_groundtruth_similarity
4021893
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 writing a C# application that needs to read about 130,000 (String, Int32) pairs at startup to a Dictionary. The pairs are stored in a .txt file, and are thus easily modifiable by anyone, which is something dangerous in the context. I would like to ask if there is a way to save this dictionary so that the information can be reasonably safely stored, without losing performance at startup. I have tried using BinaryFormatter , but the problem is that while the original program takes between 125ms and 250ms at startup to read the information from the txt and build the dictionary, deserializing the resulting binary files takes up to 2s, which is not too much by itself but when compared to the original performance is a 8-16x decrease in speed. Note: Encryption is important, but the most important should be a way to save and read the dictionary from the disk - possibly from a binary file - without having to use Convert.ToInt32 on each line, thus improving performance. Now provide the response and nothing else.
interesting question. I did some quick tests and you are right - BinaryFormatter is surprisingly slow: Serialize 130,000 dictionary entries: 547ms Deserialize 130,000 dictionary entries: 1046ms When I coded it with a StreamReader/StreamWriter with comma separated values I got: Serialize 130,000 dictionary entries: 121ms Deserialize 130,000 dictionary entries: 111ms But then I tried just using a BinaryWriter/BinaryReader: Serialize 130,000 dictionary entries: 22ms Deserialize 130,000 dictionary entries: 36ms The code for that looks like this: public void Serialize(Dictionary<string, int> dictionary, Stream stream){ BinaryWriter writer = new BinaryWriter(stream); writer.Write(dictionary.Count); foreach (var kvp in dictionary) { writer.Write(kvp.Key); writer.Write(kvp.Value); } writer.Flush();}public Dictionary<string, int> Deserialize(Stream stream){ BinaryReader reader = new BinaryReader(stream); int count = reader.ReadInt32(); var dictionary = new Dictionary<string,int>(count); for (int n = 0; n < count; n++) { var key = reader.ReadString(); var value = reader.ReadInt32(); dictionary.Add(key, value); } return dictionary; } As others have said though, if you are concerned about users tampering with the file, encryption, rather than binary formatting is the way forward.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4021893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/477505/']}
jdg_70607
stackexchange
llm_judgeable_groundtruth_similarity
621474
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'm currently building a PC peripheral that uses an AC to DC converter to power a set of DC fans. I'm not a trained EE or electrician, so I want to make sure I'm not putting myself a risk with this setup. Essentially, I have the AC to DC converter pictured below with a screw terminal block on the DC end plugged into my breadboard power rails: Assuming I'm using a standard 120V US outlet, am I putting myself at serious risk? I know it doesn't take much current to kill someone, so I get really concerned with this exposed wiring when I see this can output 3A at 12V. Now provide the response and nothing else.
These can be good. They're usually good. You don't need to guess about quality. You only need to consider the source, and look at the markings to see if it has the mark of an NRTL (Nationally Recognized Testing Lab, a list curated by USA OSHA which many countries rely on). The most common NRTL marks you encounter in North America are UL CSA ETL There's really no problem finding listed Wall Wart power supplies, as the things are absolute commodities made in billion quantity, and the vast majority of units are sold to consumer electronics manufacturers like Philips or Linksys who need listed supplies. Listed ones are so common I'm surprised to see one that is not listed. Maybe it's the multi-voltage switch that is the problem. Whatever, get a single-voltage unit . There are many, many ways to shortcut the design so one of the DC output pins is energized at AC line voltage or AC line neutral (which is line voltage if certain malfunctions occur). However, UL won't allow that on a listed unit . And since the vast majority of wall warts are approved, it's understandable to assume they all are. Not this one, though. All NRTL marks are conspicuous in their absence from this one. What you see is the marks that are universally faked in the North American market, because there are no consequences for doing so when your boots are on a faraway territory of a nation that does not cooperate with mark enforcement. FCC. That is a self-certification that it complies with radio emissions rules, but self-certification is meaningless from overseas junk sellers, because the US agency FCC does not have the public funds to go on overseas adventures into uncooperative nations to defend their mark. * CE. This is a European self-certification of compliance with EU safety rules. But the EU also won't spend public funds chasing miscreants outside the EU, so the mark has no force outside the EU proper. RoHS. Ditto for EU electronic waste rules, e.g. use of lead-free solder. CCC. China's competitor to CE, that China doesn't enforce on goods destined for export. Reputable suppliers help. It is rare to see falsification of NRTL marks in the consumer space , because the Federal law that enables NRTLs requires them to legally defend their mark aggressively. However, it is not impossible for someone to sneak something out before UL notices, and that is where it helps to use reputable suppliers who have a chain of custody . I.E. the item was shipped from Philips' warehouse to Home Depot or Mouser's warehouse. Reputable bricks-and-mortar stores are almost always reliable product, as they have good chain of custody and are heavily focused-on by consumer protection agencies. Direct-mail sites such as eBay or Amazon generally involve 3rd party sellers, and there is no chain of custody whatsoever. I don't see much risk of forged NRTL marks in the consumer space, but if it happens anywhere, it'll happen there. * If I were the FCC, I would go after wholesalers and drop-shippers of this garbage, but I am not the FCC.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/621474', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/274262/']}
jdg_70608
stackexchange
llm_judgeable_groundtruth_similarity
21070101
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a website I'm doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript. This is my current code function replaceContentInContainer(target, source) { document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;}function replaceContentInOtherContainer(replace_target, source) { document.getElementById(replace_target).innerHTML = document.getElementById(source).innerHTML;} <html><button onClick="replaceContentInContainer('target', 'replace_target')">View Portfolio</button><button onClick="replaceContentInOtherContainer('replace_target', 'target')">View Results</button><div> <span id="target">div1</span></div><div style="display:none"> <span id="replace_target">div2</span></div> The second function that replaces div2 is not working, but the first one is. Now provide the response and nothing else.
How to show or hide an element: In order to show or hide an element, manipulate the element's style property . In most cases, you probably just want to change the element's display property : element.style.display = 'none'; // Hideelement.style.display = 'block'; // Showelement.style.display = 'inline'; // Showelement.style.display = 'inline-block'; // Show Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility property instead: element.style.visibility = 'hidden'; // Hideelement.style.visibility = 'visible'; // Show Hiding a collection of elements: If you want to hide a collection of elements, just iterate over each element and change the element's display to none : function hide (elements) { elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) { elements[index].style.display = 'none'; }} // Usage:hide(document.querySelectorAll('.target'));hide(document.querySelector('.target'));hide(document.getElementById('target')); hide(document.querySelectorAll('.target'));function hide (elements) { elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) { elements[index].style.display = 'none'; }} <div class="target">This div will be hidden.</div><span class="target">This span will be hidden as well.</span> Showing a collection of elements: Most of the time, you will probably just be toggling between display: none and display: block , which means that the following may be sufficient when showing a collection of elements. You can optionally specify the desired display as the second argument if you don't want it to default to block . function show (elements, specifiedDisplay) { elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) { elements[index].style.display = specifiedDisplay || 'block'; }} // Usage:var elements = document.querySelectorAll('.target');show(elements);show(elements, 'inline-block'); // The second param allows you to specify a display value var elements = document.querySelectorAll('.target');show(elements, 'inline-block'); // The second param allows you to specify a display valueshow(document.getElementById('hidden-input'));function show (elements, specifiedDisplay) { elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) { elements[index].style.display = specifiedDisplay || 'block'; }} <div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div><span>Inline span..</span><input id="hidden-input" /> Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element. function show (elements, specifiedDisplay) { var computedDisplay, element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) { element = elements[index]; // Remove the element's inline display styling element.style.display = ''; computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display'); if (computedDisplay === 'none') { element.style.display = specifiedDisplay || 'block'; } }} show(document.querySelectorAll('.target'));function show (elements, specifiedDisplay) { var computedDisplay, element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) { element = elements[index]; // Remove the element's inline display styling element.style.display = ''; computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display'); if (computedDisplay === 'none') { element.style.display = specifiedDisplay || 'block'; } }} <span class="target" style="display: none">Should revert back to being inline.</span><span class="target" style="display: none">Inline as well.</span><div class="target" style="display: none">Should revert back to being block level.</div><span class="target" style="display: none">Should revert back to being inline.</span> (If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won't have to hardcode a value in order to get the desired results.) Toggling the display: Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it's visible, set the display to none , otherwise remove the inline display styling, and if it's still hidden, set the display to the specified value or the hardcoded default, block . function toggle (elements, specifiedDisplay) { var element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) { element = elements[index]; if (isElementHidden(element)) { element.style.display = ''; // If the element is still hidden after removing the inline display if (isElementHidden(element)) { element.style.display = specifiedDisplay || 'block'; } } else { element.style.display = 'none'; } } function isElementHidden (element) { return window.getComputedStyle(element, null).getPropertyValue('display') === 'none'; }} // Usage:document.getElementById('toggle-button').addEventListener('click', function () { toggle(document.querySelectorAll('.target'));}); document.getElementById('toggle-button').addEventListener('click', function () { toggle(document.querySelectorAll('.target'));});function toggle (elements, specifiedDisplay) { var element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) { element = elements[index]; if (isElementHidden(element)) { element.style.display = ''; // If the element is still hidden after removing the inline display if (isElementHidden(element)) { element.style.display = specifiedDisplay || 'block'; } } else { element.style.display = 'none'; } } function isElementHidden (element) { return window.getComputedStyle(element, null).getPropertyValue('display') === 'none'; }} .target { display: none; } <button id="toggle-button">Toggle display</button><span class="target">Toggle the span.</span><div class="target">Toggle the div.</div>
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/21070101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2491669/']}
jdg_70609
stackexchange
llm_judgeable_groundtruth_similarity
41791802
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 having problems trying to create a new record in my PostgreSQL database. I just want to POST to the REST service a new user (int:id, String:email, String:password) but, I'm having this error: "exception": "org.springframework.dao.DataIntegrityViolationException","message": "could not execute statement; SQL [n/a]; constraint [id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement These are my Java classes: Domain @Entity@Table(name = "users")public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String email; private String password; public User() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }} Controller @RestController@RequestMapping("/users")public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET) public List<User> findAll() { return userService.findAll(); } @RequestMapping(method = RequestMethod.POST) public User addUser(@RequestBody User user) { userService.addUser(user); return user; }} Service @Servicepublic class UserService { @Autowired private UserRepository userRepository; public List<User> findAll() { return (List<User>) userRepository.findAll(); } public User addUser(User user) { userRepository.save(user); return user; }} Repository public interface UserRepository extends CrudRepository<User, Integer> { // TODO} SQL CREATE TABLE users( id INT PRIMARY KEY NOT NULL, email TEXT NOT NULL, password CHAR(20) NOT NULL); Please, somebody help me, because I don't know how to tackle this issue. Now provide the response and nothing else.
I found the solution. I need to change the script for these one: CREATE TABLE users( id SERIAL PRIMARY KEY NOT NULL, email TEXT NOT NULL, password TEXT NOT NULL); Then, the Entity should be annotated with this: @Entity@Table(name = "users")public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(columnDefinition = "serial") private Long id; private String email; private String password; public User() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41791802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7046367/']}
jdg_70610
stackexchange
llm_judgeable_groundtruth_similarity
43759
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why do thin plastic sheets contract when heated, contradictory to the behavior of most other materials ? What are the things going on at the molecular level ? Now provide the response and nothing else.
When plastic sheets are produced, they are rapidly cooled to keep the polymer chains oriented in a way that makes the sheets nice and flat. This is a relatively high-strain orientation since it is associated with the energy level of the molecules at the casting temperature. Once the plastic is heated above its glass transition temperature , the polymer chains are no longer locked in that high strain orientation. They relax to a low energy orientation- curled and bending in a way that shrinks the bulk material. As for the precise mechanism, I'm not exactly sure. I would guess that the shrunken conformation is entropically favorable because there are more arbitrary bends. This would decrease the Gibbs free energy, making it a more stable shape. Alternatively, it could be that hydrogen bonding between chain elements makes the folded shape more enthalpically favorable.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/43759', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/17698/']}
jdg_70611
stackexchange
llm_judgeable_groundtruth_similarity
2378632
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 wanted to know if there's anything wrong with my proof below. $f(x)=x^2$ and let $c$ be an arbitrary constant. $\mathbf1.$ First, $0<|x-c|<\delta$ Now,$|x^2-c^2|=|x+c||x-c|\le(|x|+|c|)|x-c|<\epsilon\Rightarrow|x-c|<{\epsilon\over|x|+|c|}\le{\epsilon\over|x|}\Rightarrow|x-c|<{\epsilon\over|x|}$ So we have $\delta={\epsilon\over|x|}$ that satisfies the necessary condition: if $0<|x-c|<\delta$ then $|f(x)-f(c)|=|x^2-c^2|<\epsilon$ $c$ was arbitrary, so we can see that $f(x)$ is continuous, except not necessarily at $x=0$. We need to make sure that $f(x)=x^2$ is continuous at $x=0$, since in the previous section, we can't have $|x|=0$. $\mathbf2.$ For $x=0$, $0<|x-0|<\delta\Rightarrow|x|<\delta$ , and $|x^2-0|=|x^2|=(|x|)^2<\epsilon\Rightarrow|x|<\sqrt\epsilon$ So we have $\delta=\sqrt\epsilon$ , and thus we can see that $f(x)=x^2$ is continuous at $x=0$ as well. From conclusions drawn at the end of $\mathbf1$ and $\mathbf2$, we have shown that $f(x)$ is continuous on $x\in\mathbb R$ I just started learning about $\epsilon-\delta$. If you spot any error(s), please let me know how to correct them. Thanks! Now provide the response and nothing else.
You have probably seen an $\epsilon$-$\delta$ proof before, so writing a basic proof won't tell you anything new. So I will write how I think when I prove something like this. First off, the definition: $f(x) = x^2$ is continuous at $x_0$ if, for any $\epsilon>0$, we can find a $\delta>0$ such that for any $c$ with $|x_0-c|<\delta$, we have $|f(x_0)-f(c)|<\epsilon$. $f$ is continuous if it is continuous at every real number. In terms of how we write the proof, that means we're given arbitrary $x_0, \epsilon$, and we must find a $\delta$ that works. You have already deduced that $|f(x_0)-f(c)| = |x_0^2 - c^2| = |x_0-c|\cdot |x_0+c|$, which is good. We will need that. Why will we need that? Because the first factor of that factorisation is the one thing we have real control over: it will be smaller than $\delta$, and we are free to choose $\delta$. We want the entire expression to be smaller than whatever $\epsilon$ we're given, so the only thing left is to make sure that the second factor, $|x_0+c|$ doesn't ruin things too much. The standard thing to do to gain control over that term is to declare that whatever happens, I will never choose a $\delta$ which is larger than $1$ (nothing special about $1$ here, I might as well choose $1000$ or $\pi$, but I like $1$). That forces $c$ to be rather close to $x_0$, which means explicitly that $|x_0+c|<2|x_0| + 1$. Thus, as long as we vow to never pick $\delta$ larger than $1$, that gives us$$|f(x_0)-f(c)| = |x_0^2 - c^2| = |x_0-c|\cdot |x_0+c|<\delta(2|x_0| + 1)\tag{*}$$Note that we haven't really picked a $\delta$ yet, we just know that whichever one we pick, as long as it's smaller than or equal to $1$, the inequality $\text{(*)}$ holds, which is good. Why is that good? Because ultimately, we want to be able to choose a $\delta$ so that the left-hand side is smaller than the $\epsilon$ we're given. This is easily achieved by picking a $\delta$ that makes the right-hand side of $\text{(*)}$ no bigger than $\epsilon$. Thus we have$$\begin{align}\epsilon &\geq \delta(2|x_0| + 1)\\\delta&\leq\frac{\epsilon}{2|x_0| + 1}\tag{**}\end{align}$$So, which $\delta$ do we actually pick? Well, we vowed never to choose a $\delta$ greater than $1$. While under that vow, we found that any $\delta$ which fulfills $\text{(**)}$ works. Thus, if we pick exactly $\frac{\epsilon}{2|x_0| + 1}$, as long as that's smaller than $1$, and we pick $1$ if $\frac{\epsilon}{2|x_0| + 1}>1$, then we really have fulfilled both requirements, and we are done. Explicitly, this means that we have picked $\delta = \min\left(1, \dfrac{\epsilon}{2|x_0| + 1}\right)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2378632', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468686/']}
jdg_70612
stackexchange
llm_judgeable_groundtruth_similarity
22654932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From the Kotlin documentation: If a function does not return any useful value, its return type is Unit. Unit is a type with only one value — Unit.VALUE. This value does not have to be returned explicitly: fun printHello(name : String?) : Unit { if (name != null) print("Hello, $name!") else print("Hi there!") // We don't need to write 'return Unit.VALUE' or 'return', although we could } What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE? Now provide the response and nothing else.
The purpose is the same as C's or Java's void . Only Unit is a proper type, so it can be passed as a generic argument etc. Why we don't call it "Void": because the word "void" means "nothing", and there's another type, Nothing , that means just "no value at all", i.e. the computation did not complete normally (looped forever or threw an exception). We could not afford the clash of meanings. Why Unit has a value (i.e. is not the same as Nothing): because generic code can work smoothly then. If you pass Unit for a generic parameter T, the code written for any T will expect an object, and there must be an object, the sole value of Unit. How to access that value of Unit: since it's a singleton object, just say Unit
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22654932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548894/']}
jdg_70613
stackexchange
llm_judgeable_groundtruth_similarity
38949257
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 confused for a while, I follow the rails doc , and it say Client.select("viewable_by, locked") will only select only a subset of fields. Now I got a model call Goods class Goods < ActiveRecord::Base { :id => :integer, :name => :string, :translate_key => :string, :created_at => :datetime, :updated_at => :datetime, :discount_json => :text, :price_mapping => :text, :goods_type => :string, :reference_id => :integer, :available => :boolean} When I try Goods.select(:name) , it works fine.However, when I did Goods.select(:name,:translate_key) It threw ArgumentError: wrong number of arguments (2 for 0..1) Now provide the response and nothing else.
The Swift compiler translates the ObjC headers into Swift which leads to naming collisions: UIImageView+WebCache.h: o1) - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;o2) - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; Their only difference is the additional options parameter in o2 . Generated Swift declaration: s1) open func sd_setImage(with url: URL!, placeholderImage placeholder: UIImage!, completed completedBlock: SDWebImage.SDWebImageCompletionBlock!)s2) open func sd_setImage(with url: URL!, placeholderImage placeholder: UIImage!, options: SDWebImageOptions = [], completed completedBlock: SDWebImage.SDWebImageCompletionBlock!) Because options was translated into an optional parameter (default assigned an empty array) calling s1 in Swift leads to an ambiguous use. Calling s2 could simply have the same implementation.When providing such methods in Swift code one would add the options parameter as optional in a single function implementation. Workaround As a workaround the options parameter could be set or o1 or o2 could be renamed temporarily until SDWebImage will be translated into Swift.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38949257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3732906/']}
jdg_70614
stackexchange
llm_judgeable_groundtruth_similarity
34601497
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 ran into some jquery code which attempts to use hasOwnProperty to access an html attribute. <input type="text" name="fname" placeholder="First name"><script> var e = $element.find('input')[0]; if(!e.hasOwnProperty("placeholder")){...}</script> To my understanding, this should always be if(!e.hasAttribute("placeholder")){...} but what is the difference between hasAttribute and hasOwnProperty? Are they ever equivalent? Now provide the response and nothing else.
hasAttribute() hasAttribute() works only for html elements and returns true if that element has the same attribute name as the given argument. <div class="myClass"></div><script> document.querySelector('div').hasAttribute('class'); //true document.querySelector('div').hasOwnProperty('class'); //false</script> hasOwnProperty() hasOwnProperty() works only for JavaScript objects and returns true if that object has a property with the same name as the given argument. var obj = { myProp: "my attribute"}obj.hasOwnProperty("myProp") //trueobj.hasAttribute("myProp") //false Some html elements can be constructed inside javascript, thats why hasOwnProperty works sometimes for it, but hasAttribute never works for javascript objects.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34601497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1457295/']}
jdg_70615
stackexchange
llm_judgeable_groundtruth_similarity
15865912
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 not sure I understand the difference really between using redis pub/ sub and using node/ express' event emitter. Does the pub/sub interact with my database in any way? In what cases would I use one over the other? Now provide the response and nothing else.
Redis allows you to build fast and powerful inter-process communication. Redis pub/sub uses your Redis process to deliver your messages, but it never affects the data stored in Redis DB. Event emitter works only within the single node process. So, even if you have a single node cluster, events, emitted by one worker, wont be visible to another. Hence, event emitter is the perfect choice for within-the-process communication. But if you need inter-process communication, you should use Redis.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15865912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1447962/']}
jdg_70616
stackexchange
llm_judgeable_groundtruth_similarity
15753390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use Pythons mock package to mock Pythons requests module. What are the basic calls to get me working in below scenario? In my views.py, I have a function that makes variety of requests.get() calls with different response each time def myview(request): res1 = requests.get('aurl') res2 = request.get('burl') res3 = request.get('curl') In my test class I want to do something like this but cannot figure out exact method calls Step 1: # Mock the requests module# when mockedRequests.get('aurl') is called then return 'a response'# when mockedRequests.get('burl') is called then return 'b response'# when mockedRequests.get('curl') is called then return 'c response' Step 2: Call my view Step 3: verify response contains 'a response', 'b response' , 'c response' How can I complete Step 1 (mocking the requests module)? Now provide the response and nothing else.
This is how you can do it (you can run this file as-is): import requestsimport unittestfrom unittest import mock# This is the class we want to testclass MyGreatClass: def fetch_json(self, url): response = requests.get(url) return response.json()# This method will be used by the mock to replace requests.getdef mocked_requests_get(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data if args[0] == 'http://someurl.com/test.json': return MockResponse({"key1": "value1"}, 200) elif args[0] == 'http://someotherurl.com/anothertest.json': return MockResponse({"key2": "value2"}, 200) return MockResponse(None, 404)# Our test case classclass MyGreatClassTestCase(unittest.TestCase): # We patch 'requests.get' with our own method. The mock object is passed in to our test case method. @mock.patch('requests.get', side_effect=mocked_requests_get) def test_fetch(self, mock_get): # Assert requests.get calls mgc = MyGreatClass() json_data = mgc.fetch_json('http://someurl.com/test.json') self.assertEqual(json_data, {"key1": "value1"}) json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json') self.assertEqual(json_data, {"key2": "value2"}) json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json') self.assertIsNone(json_data) # We can even assert that our mocked method was called with the right parameters self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list) self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list) self.assertEqual(len(mock_get.call_args_list), 3)if __name__ == '__main__': unittest.main() Important Note: If your MyGreatClass class lives in a different package, say my.great.package , you have to mock my.great.package.requests.get instead of just 'request.get'. In that case your test case would look like this: import unittestfrom unittest import mockfrom my.great.package import MyGreatClass# This method will be used by the mock to replace requests.getdef mocked_requests_get(*args, **kwargs): # Same as aboveclass MyGreatClassTestCase(unittest.TestCase): # Now we must patch 'my.great.package.requests.get' @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get) def test_fetch(self, mock_get): # Same as aboveif __name__ == '__main__': unittest.main() Enjoy!
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/15753390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/835927/']}
jdg_70617
stackexchange
llm_judgeable_groundtruth_similarity
1995933
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 standard/common method/formula to calculate the number of months between two dates in R? I am looking for something that is similar to MathWorks months function Now provide the response and nothing else.
I was about to say that's simple, but difftime() stops at weeks. How odd. So one possible answer would be to hack something up: # turn a date into a 'monthnumber' relative to an originR> monnb <- function(d) { lt <- as.POSIXlt(as.Date(d, origin="1900-01-01")); \ lt$year*12 + lt$mon } # compute a month difference as a difference between two monnb'sR> mondf <- function(d1, d2) { monnb(d2) - monnb(d1) }# take it for a spinR> mondf(as.Date("2008-01-01"), Sys.Date())[1] 24R> Seems about right. One could wrap this into some simple class structure. Or leave it as a hack :) Edit: Also seems to work with your examples from the Mathworks: R> mondf("2000-05-31", "2000-06-30")[1] 1R> mondf(c("2002-03-31", "2002-04-30", "2002-05-31"), "2002-06-30")[1] 3 2 1R> Adding the EndOfMonth flag is left as an exercise to the reader :) Edit 2: Maybe difftime leaves it out as there is no reliable way to express fractional difference which would be consistent with the difftime behavior for other units.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1995933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205459/']}
jdg_70618
stackexchange
llm_judgeable_groundtruth_similarity
13937
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that $$\sum_{\substack{x,y \in \mathbb N \\ ax-by \ne 0 }}\frac1{|ax-by|xy}$$ converges, where $a, b \in \mathbb N$ This 2-D problem can be proved by an integral test. I'm looking for some other proofs that can be easily generalized to higher dimensional cases like below, Prove that $$\sum_{\substack{x_1,x_2, \cdots, x_d \in \mathbb N \\ \bf a \cdot \bf x \ne 0 }}\frac1{|{\bf a} \cdot {\bf x}|x_1 x_2 \cdots x_d}$$ converges, with ${\bf a} \in \mathbb Z^d$, and $\forall \; 1 \le i \le d, a_i \ne 0$. Now provide the response and nothing else.
For abelian groups, the ring End(A) is very important. As far as non-abelian groups A go, End(A) is not even (usually considered) a group. "Adding" homomorphisms doesn't work in the non-abelian case. If you define (f+g)(x) = f(x) + g(x), then (f+g)(x+y) = f(x+y) + g(x+y) = f(x) + f(y) + g(x) + g(y), but (f+g)(x) + (f+g)(y) = f(x) + g(x) + f(y) + g(y). To conclude that: f(y) + g(x) = g(x) + f(y) are equal, you use that + is commutative, that A is abelian. More precisely, if you take f=g to be the identity endomorphism, then f+g is an endomorphism iff A is abelian. "Composing" homomorphisms doesn't work to form a group, since they are not invertible. Aut(A), the group of invertible endomorphisms, does form a group. Aut(A) does not determine if a group is abelian or not: 4×2 and the dihedral group of order 8 have isomorphic automorphism groups. Instead of a ring, End(A) sits inside the "near-ring" of self-maps. See the wikipedia article on nearring for an explanation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/13937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4649/']}
jdg_70619
stackexchange
llm_judgeable_groundtruth_similarity
29954407
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 the title said, I can't quite understand why (true && {}) gives me {}, but the reverse is not the same. Edit: As a followup, since I'm using a boolean operator, why does this expression not give me a boolean when evaluated? Now provide the response and nothing else.
The expression operands to && are evaluated left to right. The value of the && expression is the value of the subexpression last evaluated. In your case, that'll be the right-most expression in both cases. So, with (true && {}) , the && operator first evaluates true . It's not falsy, so it then evaluates {} and returns that expression result. With ({} && true) it does the same things backwards, so the second expression evaluated is true .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29954407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4746361/']}
jdg_70620
stackexchange
llm_judgeable_groundtruth_similarity
59423646
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list and I want to put a condition on it. for example, I want to have items from list lst that value greater than 10: var lst = [{"value":5 , "name":"test1"}, {"value":12 , "name":"test2"}, {"value":8 , "name":"test3"}, {"value":23 , "name":"test4"}];/*output: value greater than 10 => [{"value":12 , "name":"test2"}, {"value":23 , "name":"test4"}]*/ Now provide the response and nothing else.
You can either use the where function on iterables to filter its elements, then convert the resulting iterable back to a list, or use the list literal syntax, or a combination of the two where you "spread" the result of where : var list = [ ... ];var filtered1 = list.where((e) => e["value"] > 10).toList();var filtered2 = [for (var e in list) if (e["value"] > 10) e];var filtered3 = [... list.where((e) => e["value"] > 10)];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59423646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8484965/']}
jdg_70621
stackexchange
llm_judgeable_groundtruth_similarity
42029347
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 create a new SceneKit node when the user taps the screen, and have it appear directly in front of the camera at a set distance. For testing, this will be a SCNText reads reads "you tapped here". It should also be at right angles to the line of sight - that is, "face on" to the camera. So, given the self.camera.orientation SCNVector4 (or similar), how can I: produce the SCNVector3 that puts the node in "front" of the camera at a given distance? produce the SCNVector4 (or SCNQuaternion) that orients the node so it is "facing" the camera? I suspect that the answer to (2) is that it's the same as the `self.camera.orientation? But (1) has me a little lost. I see a number of similar questions, like this one , but no answers. Now provide the response and nothing else.
(Swift 4) Hey, you can use this simpler function if you want to put the object a certain position relative to another node (e.g. the camera node) and also in the same orientation as the reference node: func updatePositionAndOrientationOf(_ node: SCNNode, withPosition position: SCNVector3, relativeTo referenceNode: SCNNode) { let referenceNodeTransform = matrix_float4x4(referenceNode.transform) // Setup a translation matrix with the desired position var translationMatrix = matrix_identity_float4x4 translationMatrix.columns.3.x = position.x translationMatrix.columns.3.y = position.y translationMatrix.columns.3.z = position.z // Combine the configured translation matrix with the referenceNode's transform to get the desired position AND orientation let updatedTransform = matrix_multiply(referenceNodeTransform, translationMatrix) node.transform = SCNMatrix4(updatedTransform)} If you'd like to put 'node' 2m right in front of a certain 'cameraNode', you'd call it like: let position = SCNVector3(x: 0, y: 0, z: -2)updatePositionAndOrientationOf(node, withPosition: position, relativeTo: cameraNode) Edit: Getting the camera node To get the camera node, it depends if you're using SceneKit, ARKit, or other framework. Below are examples for ARKit and SceneKit. With ARKit, you have ARSCNView to render the 3D objects of an SCNScene overlapping the camera content. You can get the camera node from ARSCNView's pointOfView property: let cameraNode = sceneView.pointOfView For SceneKit, you have an SCNView that renders the 3D objects of an SCNScene. You can create camera nodes and position them wherever you want, so you'd do something like: let scnScene = SCNScene()// (Configure scnScene here if necessary)scnView.scene = scnScenelet cameraNode = SCNNode()cameraNode.camera = SCNCamera()cameraNode.position = SCNVector3(0, 5, 10) // For examplescnScene.rootNode.addChildNode(cameraNode) Once a camera node has been setup, you can access the current camera in the same way as ARKit: let cameraNode = scnView.pointOfView
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42029347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1469457/']}
jdg_70622
stackexchange
llm_judgeable_groundtruth_similarity
29372559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: lstsq tries to solve Ax=b minimizing |b - Ax| . Both scipy and numpy provide a linalg.lstsq function with a very similar interface. The documentation does not mention which kind of algorithm is used, neither for scipy.linalg.lstsq nor for numpy.linalg.lstsq , but it seems to do pretty much the same. The implementation seems to be different for scipy.linalg.lstsq and numpy.linalg.lstsq . Both seem to use LAPACK, both algorithms seem to use a SVD. Where is the difference? Which one should I use? Note: do not confuse linalg.lstsq with scipy.optimize.leastsq which can solve also non-linear optimization problems. Now provide the response and nothing else.
If I read the source code right (Numpy 1.8.2, Scipy 0.14.1), numpy.linalg.lstsq() uses the LAPACK routine xGELSD and scipy.linalg.lstsq() uses xGELSS . The LAPACK Manual Sec. 2.4 states The subroutine xGELSD is significantly faster than its older counterpart xGELSS, especially for large problems, but may require somewhat more workspace depending on the matrix dimensions. That means that Numpy is faster but uses more memory. Update August 2017: Scipy now uses xGELSD by default https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29372559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/859591/']}
jdg_70623
stackexchange
llm_judgeable_groundtruth_similarity
3561334
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 $f:[a,b] \to \mathbb{R}$ be a continous, convex function. (By convex, I mean $f(\lambda x+(1- \lambda)y) \leq \lambda f(x)+(1- \lambda)f(y)$ for any choice of $x,y \in [a,b]$ and $\lambda \in [0,1]).$ Q: Is $f$ Lipschitz? If not, what would be a counterexample? I know a theorem that says a convex function on $(a,b)$ has to be Lipschitz on each $[c,d]$ . However, with no extra assumptions, the Lipschitz constant might change. Will continuity ensure that there's one Lipschitz constant that works for everything? Now provide the response and nothing else.
As a convex function, $f$ has a left and right derivative in every point of $(a, b)$ , and these are monotonically increasing. But these (one-sided) derivatives can approach $-\infty$ for $x \to a$ or $+\infty$ for $x \to b$ , and then $f$ is not Lipschitz continuous on $[a, b]$ . An example is $f(x) = 1 - \sqrt{x}$ on $[0, 1]$ . It is convex, but the derivative approaches $-\infty$ for $x \to 0$ , so that it is not Lipschitz continuous.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3561334', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/524916/']}
jdg_70624
stackexchange
llm_judgeable_groundtruth_similarity
257722
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $k \subset L$ be two algebraically closed fields of characteristic $0$. Let $U \subset \mathbb P^n_k$ be a smooth quasi-projective variety and let $U_L$ denote the base change of $U$ to $Spec (L)$. Does anyone have a reference for why the map on etale fundamental groups $\pi_1(U_L) \rightarrow \pi_1(U)$ is an isomorphism? Ultimately, I'm interested in the case that $U$ is normal, but I have a fairly easy argument to deduce that from the case that $U$ is smooth. Brian Conrad has also suggested a promising, though involved, avenue of attack using that topological $\pi_1$ is finitely generated. However since this seems like something that should be known, I was curious whether anyone knows of a reference (or perhaps a very short proof). Here are some further remarks: It's fairly clear that the map is a surjection, and it is known to be an isomorphism if $U$ is projective (even in characteristic $p$). However, if $U$ is quasi-projective, the map need not be an isomorphism in characteristic $p$ (for example, it fails to be an isomorphism for $\mathbb A^1$, due to Artin Schreier covers). I suspect the isomorphism still holds true without the smoothness hypothesis on U, and true for prime to p parts of the etale fundamental group in characteristic p, but I really only want to apply this when U is smooth (or normal) and $k$ is a subfield of $\mathbb C$. Now provide the response and nothing else.
This is an expansion of my comments above. You do not need resolution of singularities or SGA 4. The key step is "elimination oframification" or "Abhyankar's Lemma". This is proved in Append. 1 of Exposé XIII of SGA 1. Here is the link in the StacksProject. Abhankar's Lemma, Stacks Project Tag 0BRM http://stacks.math.columbia.edu/tag/0BRM Here is the setup for Abhyankar's Lemma. Let $A$ be aDVR that contains a characteristic $0$ field, let $A\subset B$ be aninjective, local homomorphism of DVRs with ramification index $e$, i.e.,$\mathfrak{m}_B^{e+1}\subset \mathfrak{m}_AB \subset \mathfrak{m}_B^e$, let$K_1/\text{Frac}(A)$ be a finite field extension, let $L_1/\text{Frac}(B)$be a compositum of $K_1/\text{Frac}(A)$ and$\text{Frac}(B)/\text{Frac}(A)$, let $A\subset A_1$, resp. $B\subset B_1$,be the integral closure of $A$ in $K_1$, resp. of $B$ in $L_1$. Let$\mathfrak{n}_A\subset A_1$ be a maximal ideal that contains $\mathfrak{m}_AA_1$, and let $\mathfrak{n}_B\subset B_1$ be any maximal ideal that contains$\mathfrak{m}_B B_1 + \mathfrak{n}_A B_1$. Abhyankar's Lemma. if the ramification index $e$ of $A\subset B$ divides the ramification indexof $A\to (A_1)_{\mathfrak{n}_A}$, then $(A_1)_{\mathfrak{n}_A}\subset(B_1)_{\mathfrak{n}_B}$ is formally smooth, i.e., the ramification indexequals $1$. Nota bene. In characteristic $0$ this follows easily from the CohenStructure Theorem, etc. In positive characteristic, Abhyankar's lemma saysmore, because (1) the tensor product $\text{Frac}(B)\otimes_{\text{Frac}(A)}K_1$ may be nonreduced, and (2) under the assumption that the the residuefield extension $A/\mathfrak{m}_A \to B/\mathfrak{m}_B$ is separable, weneed to also prove that the residue field extension of$(A_1)_{\mathfrak{n}_A} \to (B_1)_{\mathfrak{n}_B}$ is separable. Thisrequires a further assumption that $e$ is prime to $p$. When $e$ is notprime to $p$, Abhyankar's Lemma has counterexamples, but the result thatsometimes does the job is Krasner's Lemma, Stacks Project Tag 0BU9: http://stacks.math.columbia.edu/tag/0BU9 Let $K$ be a field (not necessarily characteristic $0$), let$X_K$ be a projective, connected $K$-scheme, and let $x_0\in X_K$ be a $K$-rational point. For every $K$-scheme $T$, an étale cover of $X_T$ trivialized over $x_0$ is a finite, étale morphism $g_T:Z_T\to X_T$ of some degree $d$ together with an ordered $n$-tuple of $T$-morphisms $(s_i:T\to Z_T)_{i=1,\dots,d}$ such that the union of the images of the sections $s_i$ equals $Z_T\times_{X_K} \text{Spec}\kappa(x_0)$. Rigidity in the Projective Case. For every $K$-scheme $T$, every étale cover of $X_T$ trivialized over $x_0$ is isomorphic to the base change of an étale cover of $X_K$ trivialized over $x_0$, and that trivialized étale cover is unique up to unique isomorphism. This is, essentially, proved in Section 1 of Exposé X of SGA 1. The key point is rigidity of trivialized étale covers in the proper case. Descent for Affine Curves. Now assume further that $K$ is a characteristic $0$ field that contains all roots of unity. Assume that $X_K$ is a smooth, projective, connected curve over $K$. Let$Y_K\subset X_K$ be aproper closed subset, i.e., a finite set of closed points. Denote$X_K\setminus Y_K$ by $U_K$, and assume that the $K$-point $x_0$ is contained in $U_K$. Fix an integer $d$.Let$f_K:\widetilde{X}_K\to X_K$ be a finite surjective morphism of some degree$n$ with $\widetilde{X}_K$ a smooth, projective curve such that (i)$f_K^{*}(x_0)$ is a set of $n$ distinct $K$-rational points of$\widetilde{X}_K,$ and such that for every closed point $y\in Y_K,$ forevery closed point $\widetilde{y}\in \widetilde{X}_K$ with$f(\widetilde{y})=y$, the ramification index of $\mathcal{O}_{X_K,y}\to\mathcal{O}_{\widetilde{X}_K,\widetilde{y}}$ is divisible by $e$ for every$e\leq d$. For instance, begin with a finite morphism $g:X_K\to\mathbb{P}^1_K$ that is smooth at every point of $Y_K$, such that $g(x_0)$equals $[1,1]$, and such that $Y_K\subsetf^{-1}(\underline{0}+\underline{\infty})$, and define $\widetilde{X}_K$ tobe the normalization of the fiber product of $g$ and the morphism$\mathbb{P}^1_K\to \mathbb{P}^1_K$ by $[z_0,z_1]\mapsto[z_0^{d!},z_1^{d!}]$. For a field extension $L/K$, the ramification hypothesis on$f_L:\widetilde{X}_L\to X_L$ over $Y_L$ is still valid. For every finitesurjective morphism $W_L\to X_L$ of degree $d$, for every closed point $w$of $W_L$ that maps to $Y_L$, the ramification index $e$ at $w$ divides $d!$.Thus, by Abhyankar's Lemma, the normalization $\widetilde{W}_L$ of$W_L\times_{X_L} \widetilde{X}_L$ is étale over $\widetilde{X}_L$ atevery closed point lying over $Y_L$. Thus, if $W_L\to X_L$ is assumed to beétale away from $Y_L$ then $\widetilde{W}_L\to \widetilde{X}_L$ iseverywhere étale of finite degree $d$. Assume further that the fiber of $W_L$ over $x_0$ is a set of $d$ distinct $L$-rational points. Then also the fiber of $\widetilde{W}_L$ is a set of distinct $L$-rational points. By the projective descent result above, there exists a finite, étale morphism $\widetilde{W}_K\to\widetilde{X}_K$ whose fiber over $x_0$ is a set of distinct $K$-rational points and whose base change equals $\widetilde{W}_L$. Thus, $W_L$ isan intermediate extension of the base change to $L$ of the extension$\widetilde{W}_K\to X_K$. In particular, for the fiber $\widetilde{W}_K \times_{X_K} \text{Spec}\kappa(x_0)$ over $x_0$, the degree $n$ morphism $\widetilde{W}_L \to W_L$ defines a partition $\Pi$ of the fiber into $d$ subsets of size $n$. Descent for $W_L$. There exists a unique irreducible component $W_K$ of the relative Hilbert scheme $\text{Hilb}^n_{\widetilde{W}_K/X_K} \to X_K$ whose fiber over $x_0$ parameterizes the partition $\Pi$ above. The base change of $W_K\to X_K$ to $L$ is isomorphic to $W_L\to X_L$. In conclusion, for the opensubset $U_K=X_K\setminus Y_K$, for every finite étale morphism$V_L\to U_L$, there exists a finite étale morphism $V_K\to U_K$ whosebase change to $L$ equals $V_L\to U_L$. Descent in Arbitrary Dimension. Now let $k$ be a characteristic $0$ field containing all roots of unity, and let $U_k$ be a normal, quasi-projective variety of dimension $r\geq 1$ together with a specified $k$-rational point $u_0$ in the smooth locus. I claim that there exists a blowing up $\nu_k:U'_k\to U_k$ at finitely many points including $u_0$ such that $U'_k$ is normal, and there exists a flat morphism $\pi:U'_k\to \mathbb{P}^{r-1}_k$ such that the exceptionial divisor $E_0$ over $u_0$ is the image of a rational section of $\pi$. The easiest way to get this is to embed $U_k$ into a projective space $\mathbb{P}^{r+s}_k$, choose a linear $\mathbb{P}^s_k\subset \mathbb{P}^{r+s}_k$ that intersects $U'_k$ transversally in finitely many points including $u_0$, and then let $\pi$ be the restriction to $U_k$ of the linear projection away from $\mathbb{P}^s_k$. Now let $K$ be the fraction field $k(\mathbb{P}^{r-1}_k)$ of $\mathbb{P}^{r-1}_k$, and let $U_K$ be the generic fiber of $\pi$. Let $x_0$ be the $K$-rational point corresponding to the exceptional divisor $E_0$. For every field extension $\ell/k$, for every finite étale morphism $V_\ell\to U_\ell$ whose fiber over $u_0$ is a set of distinct $\ell$-rational points, the fiber product with $\nu_\ell:U'_\ell\to U_\ell$ is a finite étale morphism to $U'_\ell$ that is trivialized over $E_0$. Thus, setting $L=k(\mathbb{P}^{r-1}_\ell)$, we obtain a finite étale morphism $V_L\to U_L$ whose fiber over $x_0$ is a set of distinct $L$-rational points. Applying the curve case, this descends the generic fiber of $V_\ell\to U_\ell$ to a variety $V_K$ over $K=k(\mathbb{P}^{r-1}_k)$. Finally, we can construct $V_k\to U_k$ as the integral closure of $U_k$ in the fraction field of the $V_K$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/257722', 'https://mathoverflow.net', 'https://mathoverflow.net/users/75970/']}
jdg_70625
stackexchange
llm_judgeable_groundtruth_similarity
3011248
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 stack three DIVs vertically and have just the middle div scroll vertically? I don't want to use pixel heights, though, because the DIVs are inside of a dialog box that is resizeable. Something like this (pardon my lousy ASCII art): +-----------+| Header |+-----------+| ^|| ||| Scroll ||| ||| v|+-----------+| Footer |+-----------+ The goal is to have the header and and footer fixed and, as the dialog grows, the middle div would grow vertically. Maybe I'm just being stupid, but I've been fighting this for the last few hours and can't seem to get it right. The three DIVs probably need to be inside "another" DIV but when I do that, and set the height to 100%, it grows as the middle DIV grows. Again, it's probably something silly I'm not accounting for. I've also tried using a TABLE to no avail. Thanks for any help. Now provide the response and nothing else.
This should work <div id="header" style="position:absolute; top:0px; left:0px; height:50px;overflow:hidden;"></div><div id="content" style="position:absolute; top:50px; bottom:50px; left:0px; overflow:auto;"></div><div id="footer" style="position:absolute; bottom:0px; height:50px; left:0px; overflow:hidden;"></div> Edited - For fixed position header and footer in modal dialog <div id="wrapper" style="position:relative; overflow:hidden; height:100%; width:100%;"> <div id="header" style="position:absolute; top:0px; left:0px; height:50px;overflow:hidden;"> </div> <div id="content" style="position:absolute; top:50px; bottom:50px; left:0px; overflow:auto;"> </div> <div id="footer" style="position:absolute; bottom:0px; height:50px; left:0px; overflow:hidden;"> </div></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3011248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459783/']}
jdg_70626
stackexchange
llm_judgeable_groundtruth_similarity
178129
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The objective is to secure my database data from server theft, i.e. the server is at a business office location with normal premises lock and burglar alarm, but because the data is personal healthcare data I want to ensure that if the server was stolen the data would be unavailable as encrypted. I'm exploring installing mySQL on a mounted Truecrypt encrypted volume. It all works fine, and when I power off, or just cruelly pull the plug the encrypted drive disappears. This seems a load easier than encrypting data to the database, and I understand that if there is a security hole in the web app , or a user gets physical access to a plugged in server the data is compromised, but as a sanity check , is there any good reason not to do this? @James I'm thinking in a theft scenario, its not going to be powered down nicely and so is likely to crash any DB transactions running. But then if someone steals the server I'm going to need to rely on my off site backup anyway. @tomjedrz, its kind of all sensitive, individual personal and address details linked to medical referrals/records. Would be as bad in our field as losing credit card data, but means that almost everything in the database would need encryption... so figured better to run the whole DB in an encrypted partition. If encrypt data in the tables there's got to be a key somewhere on the server I'm presuming, which seems more of a risk if the box walks. At the moment the app is configured to drop a dump of data (weekly full and then deltas only hourly using rdiff) into a directory also on the Truecrypt disk. I have an off site box running WS_FTP Pro scheduled to connect by FTPs and synch down the backup, again into a Truecrypt mounted partition. Now provide the response and nothing else.
We've been running mySQL on a volume secured by Truecrypt whole-disk encryption ever since they added it as a feature. Before that, we kept the data on a separate volume encrypted by TC. It has been humming away on the same box for over 6 years, and has been remarkably robust and tolerant to things like power-off, RAID degradation (hardware controller w/ RAID 1) and hardware failure. The performance hit for us has been negligible ( some would even argue TrueCrypt-encrypted disks perform better, but I wouldn't go that far) whether in an encrypted laptop or a server. The bottom line from our standpoint (we're also in healthcare) is that disk encryption is just one layer of security in our arsenal, but potentially an important one if physical security is ever compromised. There certainly are lots of scenarios where data could be stolen from a running system with an encrypted drive, but it mitigates the threat of data loss from simple theft, which could be more likely than lots of the other risks that you'd still want to mitigate against. For that reason, we encrypt all of our servers -- TrueCrypt for Windows, encrypted LVM for GNU/Linux.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/178129', 'https://serverfault.com', 'https://serverfault.com/users/37871/']}
jdg_70627
stackexchange
llm_judgeable_groundtruth_similarity
23220
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 am trying to learn about Green's functions as part of my graduate studies and have a rather basic question about them: In my maths textbooks and a lot of places online, the basic Greens function G for a linear differential operator L is stated as $$L G = \delta (x-x')$$ which is all well and good. I am now reading Economou's text on GF in Quantum Physics where he goes to define Green's functions as solutions of inhomogenous DE of the type: $$[z - L(r)]G(r,r';z) = \delta (r-r')$$ Where $z = \lambda + is$ and L is a time independent, linear, hermitian differential operator that has eigenfunctions $\phi_n (r)$ $$ L(r) \phi_n (r) = \lambda_n \phi_n (r)$$ Where these $\lambda_n$ are the eigenvalues of L. Where does this z come from in the second equation and what is the link between this and the first one? Edit: see my post below for a new couple of questions. Now provide the response and nothing else.
$z$ is the frequency form the Fourier transform of the time-axis, it appears when you solve the time-dependent Schrodinger equation: $$\left (i \frac{\partial}{\partial t} - L(x) \right ) G(x,t; x't')= \delta (x-x') \delta(t-t')$$ For time-independent $L$, $G$ is a function of difference $t-t'$ only, so you write: $$G(x;x'; z) = \int_{-\infty}^{+\infty} e^{i z (t-t')} G(x,t; x't') d t$$. For the retarded Green function, $G^{R}(x,t; x,t')=0$ if $t<t'$ and the integral converges if $\rm{Im} \, z >0$. For the advanced Green function $G^{A}(x,t; x,t')=0$ if $t>t'$ and the integral converges for $\rm{Im} \, z =s <0$. Thus the resolvent $G(x;x';z)$ conveniently encodes both : $$G^{R/A}(x,t; x',t') = \lim_{s \to \pm 0} \frac{1}{2\pi} \int e^{-i z(t-t')} G(x;x';z) d z$$with $+$ sign for the retarded, and $-$ sign for the advanced Green function. For finite systems $G(z)$ is analytic on the whole plane except the discrete set of singularities on the real axis. For an infinite system there is a cut on the real axis corresponding to the continuous part of the spectrum. Substituting the inverse transform into the equation gives:$$\left ( z - L(x) \right ) G(x;x';z) = \delta (x-x')$$ as in the Economou text.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/23220', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8457/']}
jdg_70628
stackexchange
llm_judgeable_groundtruth_similarity
44143110
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are a lot of resources for people who want to visualize package dependencies, but I'm interested specifically in visualizing functions within a package and their dependencies on one another. There are tools like miniCRAN for graphing package dependencies, but is there anything available to graph function dependencies within a package? For example, suppose I only have two functions in my package. func1 <- function(n) return(LETTERS[n])func2 <- function(n) return(func1(n%%26+1)) Then I would just want a graph with two labeled nodes and an edge connecting them, depicting the dependency of func2 on func1 . I would think there are a lot of packages out there that have really hairy functional dependencies that such a utility could help in understanding/organizing/refactoring/etc. Thanks. Now provide the response and nothing else.
I think a better option (built on top of the mvbutil package's foodweb functions) is the DependenciesGraph package built by datastorm-open on Github on top of their more general visNetwork package. DependenciesGraph : an R package for dependencies visualization between packages and functions In my example, I have been visualizing my own package for maintenance and development and have been very pleased with the results. library(DependenciesGraph)library(QualtricsTools) # A package I'm developingdeps <- funDependencies("package:QualtricsTools", "generate_split_coded_comments")plot(deps) The output is a web server (either viewed in RStudio's viewer or in a separate browser) that allows you to choose specific functions through a drop down or by clicking on them, to zoom in and out, to drag them around, and so forth. To me, this is much nicer than using base R to plot the output of the foodweb function because often it is difficult to get the text to look nice displayed on top of each node, all the edges are jarringly colored differently in a foodweb plot, and it doesn't appear to me that the base R plot functions are doing very much to ensure that the layout of the plot is readable or clear. A comparison against mvbutil's foodweb: library(mvbutils)library(QualtricsTools) deps <- foodweb(where="package:QualtricsTools", prune='make_split_coded_comments')plot(deps) (Sorry there's a discrepancy in the names, they really are the same function, I just happened to have renamed the function between making these two plots).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44143110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3161979/']}
jdg_70629
stackexchange
llm_judgeable_groundtruth_similarity
239031
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: Given SeedRandom[3];n = 5;mat = RandomReal[{-4, 4}, {n, n}];adjMat[matrix_, lB_, uB_] := Partition[Boole[lB <= # <= uB] & /@ Flatten[matrix], Length[matrix]] I generate an adjacency matrix based on lB = -2 and uB = 1 : adjMat[mat, -2, 1](*output*){{1, 0, 1, 0, 0}, {1, 1, 0, 1, 0}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 0}} This output is what I aimed to find. However, I am not particularly happy with the adjMat[...] function as it first converts mat to a list and then reconstructs the desired adjacency matrix using Partition . Can we make this adjMat[...] function work with matrix input (without flattening) rather than a list? Any improvement is welcome. Now provide the response and nothing else.
ClearAll[adjMat2]adjMat2[matrix_, lB_, uB_] := Map[Boole[lB <= # <= uB] &, matrix, {-1}]adjMat2[mat, -2, 1] // MatrixForm ClearAll[adjMat3]adjMat3[matrix_, lB_, uB_] := UnitStep[matrix - lB] UnitStep[uB - matrix]adjMat3[mat, -2, 1] // MatrixForm And, for fun, PrecedesTilde = Boole @* Map[Thread] @* Thread @* LessEqual;-2 ≾ mat ≾ 1 {{1, 0, 1, 0, 0}, {1, 1, 0, 1, 0}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 0}} MatrixForm @ %
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/239031', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/60365/']}
jdg_70630
stackexchange
llm_judgeable_groundtruth_similarity
19122575
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why do I have to write std::cout and not also std::<< in a line of code like this: #include <iostream>int main() { std::cout << "Hello, world!"; return 0;} cout comes from std library, and isn't << usually used to do bits shifting? So, why don't I have to write the scope operator :: also before << , since it is used also with another meaning? How the compiler knows that after std::cout , << means another thing? Now provide the response and nothing else.
First, the compiler will look at the types to the left and right of << . std::cout is of type std::ostream , the string literal is of type array of 15 const char . As the left is of class type, it will search for a function named operator<< . The question is, where will it look? The lookup for this name operator<< is a so-called unqualified lookup, because the function name isn't qualified like std::operator<< . Unqualified lookup for function names invokes argument-dependent lookup. The argument-dependent lookup will search in the classes and namespaces associated with the argument types. When you include <iostream> , a free function of the signature template<typename traits>std::basic_ostream<char, traits>& operator<<(std::basic_ostream<char, traits>&, const char*); has been declared in namespace std . This namespace is associated with the type of std::cout , therefore this function will be found. std::ostream is just a typedef for std::basic_ostream<char, std::char_traits<char>> , and the array of 15 const char can be converted implicitly to a char const* (pointing to the first element of the array). Therefore, this function can be called with the two argument types. There are other overloads of operator<< , but the function I mentioned above is the best match for the argument types and the one selected in this case. A simple example of argument-dependent lookup: namespace my_namespace{ struct X {}; void find_me(X) {}}int main(){ my_namespace::X x; find_me(x); // finds my_namespace::find_me because of the argument type} N.B. As this function is a operator, the actual lookup is a bit more complex. It is looked up via qualified lookup in the scope of the first argument (if that's of class type), i.e. as a member function. Additionally , unqualified lookup is performed, but ignoring all member functions. The result is slightly different, because unqualified lookup is actually like a two-step procedure, where argument-dependent lookup is the second step. If the first step finds a member function, the second step is not performed, i.e. argument-dependent lookup is not used. Compare: namespace my_namespace{ struct X { void find_me(X, int) {} void search(); }; void find_me(X, double) {} void X::search() { find_me(*this, 2.5); // only finds X::find_me(int) // pure unqualified lookup (1st step) finds the member function // argument-dependent lookup is not performed }} to: namespace my_namespace{ struct X { void operator<<(int) {} void search(); }; void operator<<(X, double) {} void X::search() { *this << 2.5; // find both because both steps are always performed // and overload resolution selects the free function }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19122575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090403/']}
jdg_70631
stackexchange
llm_judgeable_groundtruth_similarity
31796332
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 insert a python dictionary as a json into my postgresql database (via python and psycopg2). I have: thedictionary = {'price money': '$1', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'}cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1, 'http://www.google.com', '$20', thedictionary, 'red', '8.5x11')) And it gives the error message: cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%d, %s, %s, %d, %s, %s)", (1, ' http://www.google.com ', '$20', thedictionary, 'red', '8.5x11')) psycopg2.ProgrammingError: can't adapt type 'dict' I am not sure how to proceed from here.I cannot find anything on the internet about how to do this exact kind of thing and I am very new to psycopg2. Now provide the response and nothing else.
cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%s, %s, %s, %s, %s, %s)", (1, 'http://www.google.com', '$20', json.dumps(thedictionary), 'red', '8.5x11')) That will solve your problem. However, you really should be storing keys and values in their own separate columns. To retrieve the dictionary, do: cur.execute('select charecteristics from product where store_id = 1')dictionary = json.loads(cur.fetchone()[0])
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31796332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3312595/']}
jdg_70632
stackexchange
llm_judgeable_groundtruth_similarity
4939382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have my config setup to handle a bunch of GET requests which render pixels that work fine to handle analytics and parse query strings for logging. With an additional third party data stream, I need to handle a POST request to a given url that has JSON in an expected loggable format inside of it's request body. I don't want to use a secondary server with proxy_pass and just want to log the whole response into an associated log file like what it does with GET requests. A snippet of some code that I'm using looks like the following: GET request (which works great): location ^~ /rl.gif { set $rl_lcid $arg_lcid; if ($http_cookie ~* "lcid=(.*\S)") { set $rl_lcid $cookie_lcid; } empty_gif; log_format my_tracking '{ "guid" : "$rl_lcid", "data" : "$arg__rlcdnsegs" }'; access_log /mnt/logs/nginx/my.access.log my_tracking; rewrite ^(.*)$ http://my/url?id=$cookie_lcid? redirect;} Here is kinda what I am trying to do:POST request (which does not work): location /bk { log_format bk_tracking $request_body; access_log /mnt/logs/nginx/bk.access.log bk_tracking;} Curling curl http://myurl/bk -d name=example gives me a 404 page not found. Then I tried: location /bk.gif { empty_gif; log_format bk_tracking $request_body; access_log /mnt/logs/nginx/bk.access.log bk_tracking;} Curling curl http://myurl/bk.gif -d name=example gives me a 405 Not Allowed . My current version is nginx/0.7.62 . Any help in the right direction is very much appreciated! Thanks! UPDATE So now my post looks like this: location /bk { if ($request_method != POST) { return 405; } proxy_pass $scheme://127.0.0.1:$server_port/dummy; log_format my_tracking $request_body; access_log /mnt/logs/nginx/my.access.log my_tracking;}location /dummy { set $test 0; } It is logging the post data correctly, but returns a 404 on the requesters end. If I change the above code to return a 200 like so: location /bk { if ($request_method != POST) { return 405; } proxy_pass $scheme://127.0.0.1:$server_port/dummy; log_format my_tracking $request_body; access_log /mnt/logs/nginx/my.access.log my_tracking; return 200;}location /dummy { set $test 0; } Then it return the 200 correctly, but no longer records the post data. ANOTHER UPDATE Kinda found a working solution. Hopefully this can help other on their way. Now provide the response and nothing else.
This solution works like a charm: http { log_format postdata $request_body; server { location = /post.php { access_log /var/log/nginx/postdata.log postdata; fastcgi_pass php_cgi; } }} I think the trick is making nginx believe that you will call a CGI script. Edit 2022-03-15: there is some discussion on where log_format should be set. The documentation clearly says that it needs to be in the http context: http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format If you put log_format in the server context, nginx will fail to load the config: nginx: [emerg] "log_format" directive is not allowed here in <path>:<line> (tested with nginx 1.20 on ubuntu 18.04)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4939382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/519311/']}
jdg_70633
stackexchange
llm_judgeable_groundtruth_similarity
1462649
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's a dead-simple webpage that leaks memory in IE8 using jQuery (I detect memory leaks by watching the memory usage of my iexplore.exe process grow over time in the Windows Task Manager): <html><head> <title>Test Page</title> <script type="text/javascript" src="jquery.js"></script></head><body><script type="text/javascript"> function resetContent() { $("#content div").remove(); for(var i=0; i<10000; i++) { $("#content").append("<div>Hello World!</div>"); } setTimeout(resetTable, 2000); } $(resetContent);</script><div id="content"></div></body></html> Apparently even when calling the jQuery.remove() function I still experience some memory leakage. I can write my own remove function that experiences no memory leak as follows: $.fn.removeWithoutLeaking = function() { this.each(function(i,e){ if( e.parentNode ) e.parentNode.removeChild(e); });}; This works just fine and doesn't leak any memory. So why does jQuery leak memory? I created another remove function based on jQuery.remove() and this does indeed cause a leak: $.fn.removeWithLeakage = function() { this.each(function(i,e) { $("*", e).add([e]).each(function(){ $.event.remove(this); $.removeData(this); }); if (e.parentNode) e.parentNode.removeChild(e); });}; Interestingly, the memory leak seems to be caused by the each call which jQuery includes to prevent memory leaks from events and data associated with the DOM elements being deleted. When I call the removeWithoutLeaking function then my memory stays constant over time, but when I call removeWithLeakage instead then it just keeps growing. My question is, what about that each call $("*", e).add([e]).each(function(){ $.event.remove(this); $.removeData(this);}); could possibly be causing the memory leak? EDIT: Fixed typo in code which, upon retesting, proved to have no effect on the results. FURTHER EDIT: I have filed a bug report with the jQuery project, since this does seem to be a jQuery bug: http://dev.jquery.com/ticket/5285 Now provide the response and nothing else.
I thought David might be onto something with the alleged removeChild leak, but I can't reproduce it in IE8... it may well happen in earlier browsers, but that's not what we have here. If I manually removeChild the divs there is no leak; if I alter jQuery to use outerHTML= '' (or move-to-bin followed by bin.innerHTML) instead of removeChild there is still a leak. In a process of elimination I started hacking at bits of remove in jQuery. line 1244 in 1.3.2: //jQuery.event.remove(this);jQuery.removeData(this); Commenting out that line resulted in no leak. So, let's look at event.remove, it calls data('events') to see if there are any events attached to the element. What is data doing? // Compute a unique ID for the elementif ( !id ) id = elem[ expando ] = ++uuid; Oh. So it's adding one of jQuery's uuid-to-data-lookup entry hack properties for every element it even tries to read data on, which includes every single descendent of an element you're removing! How silly. I can short-circuit that by putting this line just before it: // Don't create ID/lookup if we're only reading non-present dataif (!id && data===undefined) return undefined; which appears to fix the leak for this case in IE8. Can't guarantee it won't break something else in the maze that is jQuery, but logically it makes sense. As far as I can work out, the leak is simply the jQuery.cache Object (which is the data store, not a really a cache as such) getting bigger and bigger as a new key is added for every removed element. Although removeData should be removing those cache entries OK, IE does not appear to recover the space when you delete a key from an Object. (Either way, this is an example of the sort of jQuery behaviour I don't appreciate. It is doing far too much under the hood for what should be a trivially simple operation... some of which is pretty questionable stuff. The whole thing with the expando and what jQuery does to innerHTML via regex to prevent that showing as an attribute in IE is just broken and ugly. And the habit of making the getter and setter the same function is confusing and, here, results in the bug.) [Weirdly, leaving the leaktest for extended periods of time ended up occasionally giving totally spurious errors in jquery.js before the memory actually ran out... there was something like ‘unexpected command’, and I noted a ‘nodeName is null or not an object’ at line 667, which as far as I can see shouldn't even have been run, let alone that there is a check there for nodeName being null! IE is not giving me much confidence here...]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1462649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1694/']}
jdg_70634
stackexchange
llm_judgeable_groundtruth_similarity
21029999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Curious what the right way to approach this is: var Hello = React.createClass({getInitialState: function() { return {total: 0, input1:0, input2:0};},render: function() { return ( <div>{this.state.total}<br/> <input type="text" value={this.state.input1} onChange={this.handleChange} /> <input type="text" value={this.state.input2} onChange={this.handleChange} /> </div> );},handleChange: function(e){ this.setState({ ??? : e.target.value}); t = this.state.input1 + this.state.input2; this.setState({total: t});}});React.renderComponent(<Hello />, document.getElementById('content')); Obviously you could create separate handleChange functions to handle each different input, but that's not very nice. Similarly you could create a component just for an individual input, but I wanted to see if there's a way to do it like this. Now provide the response and nothing else.
I suggest sticking to standard HTML attributes like name on input Elements to identify your inputs. Also, you don't need to keep "total" as a separate value in state because it is composable by adding other values in your state: var Hello = React.createClass({ getInitialState: function() { return {input1: 0, input2: 0}; }, render: function() { const total = this.state.input1 + this.state.input2; return ( <div>{total}<br/> <input type="text" value={this.state.input1} name="input1" onChange={this.handleChange} /> <input type="text" value={this.state.input2} name="input2" onChange={this.handleChange} /> </div> ); }, handleChange: function(e) { this.setState({[e.target.name]: e.target.value}); }});React.renderComponent(<Hello />, document.getElementById('content'));
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21029999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297824/']}
jdg_70635
stackexchange
llm_judgeable_groundtruth_similarity
44787552
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If a topic has 4 partitions, and a publisher sends a message to the topic, will that same message be replicate across all four partitions or only one? Now provide the response and nothing else.
Partitioning and replication are two different things. Partitioning is for scalability. A topic is partitioned in one or more partitions distributed on different brokers so that more consumers can connect to these brokers in order to receive messages sent to the same topic but from different partitions. Increasing partitions increases scalability and the possibility to have more consumers to get messages from the same topic. Answering your question, each message sent to a topic comes into only one partition (of the topic itself). Replication is for fault-tolerance. You can specify a replication factor on topic creation and it means that every partition for that topic is replicated more times on different brokers. One replica is the "leader" where producer sends and consumer gets messages; other replicas are "follower" which have copies of messages from the "leader" replica. If the broker which handles the "leader" replica goes down, one of the "follower" becomes leader.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44787552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3231690/']}
jdg_70636
stackexchange
llm_judgeable_groundtruth_similarity
21359777
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I add our remote repository as upstream and try to fetch it , it fails as below : $ git fetch upstream remote: Counting objects: 11901, done. remote: aborting due to possible repository corruption on the remote side. error: pack-objects died of signal 9 error: git upload-pack: git-pack-objects died with error. fatal: git upload-pack: aborting due to possible repository corruption on the re mote side. fatal: protocol error: bad pack header I understand that it fails due to having huge files in the repository( which we do have) , but why does it Not fail when I clone the same repository? Because I am able to clone the repository successfully. Shouldn't The same objects be packed at the time of a clone request? Now provide the response and nothing else.
To expand a bit on VonC's answer ... First, it may help to note that signal 9 refers to SIGKILL and tends to occur because the remote in question is a Linux host and the process is being destroyed by the Linux "OOM killer" (although some non-Linux systems behave similarly). Next, let's talk about objects and pack-files. A git "object" is one of the four types of items that are found in a git repository: a "blob" (a file); a "tree" (a list of blobs, their modes, and their names-as-stored-in-a-directory: i.e., what will become a directory or folder on when a commit is unpacked); a "commit" (which gives the commit author, message, and top level tree among other data); and a "tag" (an annotated tag). Objects can be stored as "loose objects", with one object in a file all by itself; but these can take up a lot of disk space, so they can instead be "packed", many objects into one file with extra compression added. Making a pack out of a lot of loose objects, doing this compression, is (or at least can be) a cpu- and memory-intensive operation. The amount of memory required depends on the number of objects and their underlying sizes: large files take more memory. Many large files take a whole lot of memory. Next, as VonC noted, git clone skips the attempt to use "thin" packs (well, normally anyway). This means the server just delivers the pack-files it already has. This is a "memory-cheap" operation: the files already exist and the server need only deliver them. On the other hand, git fetch tries, if it can, to avoid sending a lot of data that the client already has. Using a "smart" protocol, the client and server engage in a sort of conversation, which you can think of as going something like this: "I have object A, which needs B and C; do you have B and C? I also have D, E, and F." "I have B but I need C, and I have D and E; please send me A, C, and F." Thus informed, the server extracts the "interesting" / "wanted" objects out of the original packs, and then attempts to compress them into a new (but "thin") pack. This means the server will invoke git-pack-objects . If the server is low on memory (with "low" being relative to the amount that git-pack-objects is going to need), it's likely to invoke the "OOM killer". Since git-pack-objects is memory-intensive, that process is a likely candidate for the "OOM killer" to kill. You then see, on your client end, a message about git-pack-objects dying from signal 9 ( SIGKILL ). (Of course it's possible the server's OOM killer kills something else entirely, such as the bug database server. :-) )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21359777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/895429/']}
jdg_70637
stackexchange
llm_judgeable_groundtruth_similarity
43130834
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 destructure an array of length 2, but I get a typescript error: [ts] Tuple type '[string]' with length '1' cannot be assignedto tuple with length '2'. let output = {status: false}; if(execute.permission) { let message: [string] = execute.params; if(message.length >= 2) { // Destructuring follows [output['position'], output['message']] = message; } } How do I tell typescript, that the array could possiblly be of length 2? Now provide the response and nothing else.
You've not declared message as an array; you've declared it as a tuple ( [string] ) and tuples have a fixed number of elements. (See the Tuple section in the Basic Types documentation.) You could declare it as a tuple that has two string elements ( [string, string] ), but given that you are testing message.length >= 2 it seems likely you intended to declare it as a string array ( string[] ): let output = {status: false};if(execute.permission) { let message: string[] = execute.params; if(message.length >= 2) { // Destructuring follows [output['position'], output['message']] = message; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43130834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648138/']}
jdg_70638
stackexchange
llm_judgeable_groundtruth_similarity
202488
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: Non-Turing complete languages offer a great advantage over Turing-complete languages as they are much more analyzable and, thus, offer much broader optimization possibilities. Yet they are barely used and Turing-completeness is actually sold as a good feature. Are there any mainstream non-Turing-complete languages available today that are made for general-purpose programming? Now provide the response and nothing else.
There are no mainstream multi-purpose non Turing complete languages today. There are, however, several non Turing complete domain specific languages. ANSI SQL, regular expressions, data languages (HTML, CSS, JSON, etc), and s-expressions are some notable examples. There isn't really a benefit for multi-purpose non Turing complete languages. The "much more analyzable" aspect, which I'm assuming is a nod to Rice's theorem, does apply but it doesn't make much sense for languages that target several different application domains, other requirements take precedence. The flexibility of Turing completeness is a lot more important than its complexity. Programming languages, as every other piece of software, are all about trade offs. For domain specific languages, on the other hand, it might just be the other way around. If you aren't building "one language to rule them all", you are free to implement only the features that make sense for the very specific purpose of your language. And more often than not, Turing completeness is not one of them.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/202488', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/54384/']}
jdg_70639
stackexchange
llm_judgeable_groundtruth_similarity
7015486
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 writing a macro which goes through a document and tries to parse it by Style. Right now, anything in the designated style is copied onto the immediate window. Is there a way to automate the macro further to move the text from the immediate window into a txt file? Otherwise, anyone using the macro would not be able to see the text unless they opened up VBA, correct? Now provide the response and nothing else.
Here's my suggestion: write to the immediate window AND to a file at the same time. Examples below. Why make the information first transit in the immediate window, and only then write it to a file from there? That just sounds perversely and uselessly difficult! Dim s As StringDim n As Integern = FreeFile()Open "C:\test.txt" For Output As #ns = "Hello, world!"Debug.Print s ' write to immediatePrint #n, s ' write to files = "Long time no see."Debug.Print sWrite #n, s ' other way of writing to fileClose #nDim FSO As Scripting.FileSystemObjectSet FSO = New Scripting.FileSystemObjectDim txs As Scripting.TextStreamSet txs = FSO.CreateTextFile("C:\test2.txt")s = "I like chickpeas."Debug.Print s ' still writing to immediatetxs.WriteLine s ' third way of writing to filetxs.CloseSet txs = NothingSet FSO = Nothing Note that this last bit of code requires a reference to be set: Tools > References > checkmark at Microsoft Scripting Runtime.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7015486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799810/']}
jdg_70640