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
46095870
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 build a relatively long string (an SVG if that matters) and return it from a function. What is the best way to build such a string in Elixir? In other languages I'd use something like a StringBuilder class. Is there an equivalent thing in Elixir? You can append strings with the <> operator, but isn't that just a list append? It seems like doing a lot of those would get really inefficient. Now provide the response and nothing else.
Elixir Strings (called Binaries in Erlang) are represented as a contiguous sequence of bytes in memory, not a Linked List of bytes/characters, if that's what you mean by "list". They are immutable and a naive implementation of appending two binaries will be O(n+m) if the strings are of length n and m , but the Erlang VM optimizes the use case of building a large string: if you have two strings, a and b , and a has free memory after its allocation, and you concatenate them ( a <> b ), the VM only copies b and reuses the old value of a . This optimization will for obvious reasons not be applied if you later concatenate another string c to a , but this optimization itself is enough to make the task of building a large binary as efficient as in languages with mutable strings. This optimization is explained in detail here . Here's a demo of this optimization in action. In the first example, I'm creating a 10,000,000 byte string by appending to a base value. In the second example, I'm creating a 500,000 byte string by prepending to a base value, which takes over 10x more time than appending 10,000,000 bytes. In a naive implementation, both would take the same amount of time. {time, _} = :timer.tc(fn -> Enum.reduce(1..10_000_000, "", fn _, acc -> acc <> "." end)end)IO.inspect time{time, _} = :timer.tc(fn -> Enum.reduce(1..500_000, "", fn _, acc -> "." <> acc end)end)IO.inspect time 6836217807815 In short, you should be fine building large string as long as you're only appending the value. If you're going to write the resulting string to a socket or stream or similar, you might be able to do it significantly faster by creating iolists instead of a flat string. More info about those here and here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46095870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17693/']}
jdg_73841
stackexchange
llm_judgeable_groundtruth_similarity
62011541
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 app on Rails 5.2 and it was previously hosted on DigitalOcean, but I need to host it on heroku. I've been reading that heroku can't read Credentials.yml of because it's on gitignore and of course I don't want it public. So my key variables are like this (and example with redis): host: Rails.application.credentials.redis_host, password: Rails.application.credentials.redis_password Heroku can't read this. So my question is what is the best approach to change that in to heroku ENV variables? Do I need to edit all my current keys (there about 340) to ENV['SOMEKEY']? I'll appreciate you help! Now provide the response and nothing else.
Create credentials.yml and master key: rails credentials:edit Edit credentails: EDITOR=vim rails credentials:edit WORKING WITH VIM: For inserting Press i //Do required editing For exiting Press Esc :wq //for exiting and saving :q! //for exiting without saving EXAMPLE OF HOW CREDENTIALS.YML can look: development: github: client: acascascsacascascasc secret: vdsvsvg34g34gproduction: github: client: 34g3rvv secret: erberb43 FIND A CREDENTIAL: rails cRails.application.credentials.dig(:aws, :access_key_id) or if an env variable is used Rails.application.credentials[Rails.env.to_sym][:aws][:access_key_id] The credentials.yml file should NOT be in gitignore. The master key that decrypts the credentials SHOULD be in gitignore. To set your master key in production: heroku config:set RAILS_MASTER_KEY=123456789 or heroku config:set RAILS_MASTER_KEY=`cat config/master.key` That's all you need to know about credentials in Ruby on Rails. Good luck :) Update: I've created a screencast covering the topic :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62011541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13495668/']}
jdg_73842
stackexchange
llm_judgeable_groundtruth_similarity
22235580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: library(ggplot2)library(cumplyr)library(scales)library(RColorBrewer)myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))x = 1:5y = 1:5pts = cartesian_product(c('x','y'))d1 = cbind(pts, runif(nrow(pts),min=0,max=1), 1)d2 = cbind(pts, runif(nrow(pts),min=0,max=4), 2)colnames(d1) = colnames(d2) = c("x","y","val","k")d = rbind(d1,d2)p1 <- ggplot(d1)p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))p1 <- p1 + scale_fill_gradientn(colours = myPalette(4))p1p2 <- ggplot(d2, aes(x = x, y = y, fill = val))p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) p2 <- p2 + scale_fill_gradientn(colours = myPalette(4))p2 And this leads to the two plots below. My question is, using this same type of color scheme, how do I get both plots to use the same scale for value? E.g. p1 should be much more uniform than p2. p1: p2: Now provide the response and nothing else.
Use limit in scale_gradientn : p1 <- ggplot(as.data.frame(d1))p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))p2 <- ggplot(as.data.frame(d2), aes(x = x, y = y, fill = val))p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) library(gridExtra)p1 <- p1 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))p2 <- p2 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))grid.arrange(p1, p2) The grid.arrange stuff is just to avoid me having to copy/paste two pictures.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22235580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318976/']}
jdg_73843
stackexchange
llm_judgeable_groundtruth_similarity
38354
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm aware that keras serves as a high-level interface to TensorFlow. But it seems to me that keras can do many functionalities on its own (data input, model creation, training, evaluation). Furthermore, some of TensorFlow's functionality can be ported directly to keras (e.g. it is possible to use a tf metric or loss function in keras). My question is, what does TensorFlow offer that can't be reproduced in keras? Now provide the response and nothing else.
Deep Learning frameworks operate at 2 levels of abstraction: Lower Level : This is where frameworks like Tensorflow, MXNet, Theano, and PyTorch sit. This is the level where mathematical operations like Generalized Matrix-Matrix multiplication and Neural Network primitives like Convolutional operations are implemented. Higher Level : This is where frameworks like Keras sit. At this Level, the lower level primitives are used to implement Neural Network abstraction like Layers and models. Generally, at this level other helpful APIs like model saving and model training are also implemented. You cannot compare Keras and TensorFlow because they sit on different levels of abstraction. I also want to take this opportunity to share my experience of using Keras: I do not agree that Keras is only useful for basic Deep Learning work. Keras is a beautifully written API. The functional nature of the API helps you completely and gets out of your way for more exotic applications. Keras does not block access to lower level frameworks. Keras results in much more readable and succinct code. Keras model Serialization/Deserialization APIs, callbacks, and data streaming using Python generators is very mature. Keras has been declared the official high level abstraction for TensorFlow.
{}
{'log_upvote_score': 5, 'links': ['https://datascience.stackexchange.com/questions/38354', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/59193/']}
jdg_73844
stackexchange
llm_judgeable_groundtruth_similarity
35710346
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 process that loops through two lists, one being relatively large while the other being significantly smaller. Example: larger_list = list(range(15000))smaller_list = list(range(2500))for ll in larger_list: for sl in smaller_list: pass I scaled the sized down of the lists to test performance, and I noticed there is a decent difference between which list is looped through first. import timeitlarger_list = list(range(150))smaller_list = list(range(25))def large_then_small(): for ll in larger_list: for sl in smaller_list: passdef small_then_large(): for sl in smaller_list: for ll in larger_list: passprint('Larger -> Smaller: {}'.format(timeit.timeit(large_then_small)))print('Smaller -> Larger: {}'.format(timeit.timeit(small_then_large)))>>> Larger -> Smaller: 114.884992572>>> Smaller -> Larger: 98.7751009799 At first glance, they look identical - however there is 16 second difference between the two functions. Why is that? Now provide the response and nothing else.
When you disassemble one of your functions you get: >>> dis.dis(small_then_large) 2 0 SETUP_LOOP 31 (to 34) 3 LOAD_GLOBAL 0 (smaller_list) 6 GET_ITER >> 7 FOR_ITER 23 (to 33) 10 STORE_FAST 0 (sl) 3 13 SETUP_LOOP 14 (to 30) 16 LOAD_GLOBAL 1 (larger_list) 19 GET_ITER >> 20 FOR_ITER 6 (to 29) 23 STORE_FAST 1 (ll) 4 26 JUMP_ABSOLUTE 20 >> 29 POP_BLOCK >> 30 JUMP_ABSOLUTE 7 >> 33 POP_BLOCK >> 34 LOAD_CONST 0 (None) 37 RETURN_VALUE>>> Looking at address 29 & 30, it looks like these will execute every time the inner loop ends. The two loops look basically the same, but these two instructions are executed each time the inner loop exits. Having the smaller number on the inside would cause these to be executed more often, hence increasing the time (vs the larger number on the inner loop).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35710346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1040092/']}
jdg_73845
stackexchange
llm_judgeable_groundtruth_similarity
623549
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'd like to start / stop a piece of software running on an in-car computer depending on the 12V_IGN rail going on resp. off. This happens when the ignition switch goes in / resp. out of position RUN. See these two scans from the original service manual. The computer corresponds to the radio on the schematics: During my dry tests, I simply used a switch (connecting the IGN pin with GND), a pull-up resistor, and a CD4093B Schmitt trigger: The output of the trigger goes to a level shifter because the computer expects +3.3 V on its GPIO inputs. Now I'd like to know whether I will still need a pull-up / pull-down resistor when using the 12V_IGN rail of my car as input, or I can attach the IGN input pin directly to the rail. UPDATE: In the service manual, the power junction block stands for the permanent (aka standby) +12V rail, and the wire labeled BRN in scan #2 is 12V_IGN, as it is only hot when the ignition switch is in position RUN. Now provide the response and nothing else.
The CD4093, and many other chips as well, will be wiped out of existence by transients in short order if you connect their inputs directly to any DC power circuit in the car. Same goes for supply voltages: you have to regulate them down. The “12V” in the car can temporarily become +/-50V, with shorter spikes going even higher. Even the voltage regulators you’re using need to be able to take such transients. You need at the very least a current limiting series resistor. Say four 250k resistors in series to minimize their capacitance. No need for a pull-down: the loads attached to the V_IGN line do that job already. No need for a pull-up either. You don’t need the separate CMOS Schmitt trigger nor a special level shifter. In any case, leaving CMOS inputs floating should never be done - in case you’ll be designing other CMOS logic circuits. You can scale the voltage down to 5V or 3.3V using a resistive divider. Schmitt inputs on MCUs will handle that fine. The divider’s Thevenin resistance should be between 100k and 1M. The higher the better usually, since the inputs are CMOS and thus like open circuits at DC. The upper resistor connecting the input pin to the ignition voltage should be split into 2, 3 or 4 series connected resistors to lower the parasitic series capacitance.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/623549', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/193570/']}
jdg_73846
stackexchange
llm_judgeable_groundtruth_similarity
58030067
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my flutter project, I have a container with some icons and text below them. I want this entire container to be fixed at bottom of the screen without using bottom navigation bar like the below image- So, I need an entire example to fix that container at bottom and keep my other components inside body with a scroll view. Now provide the response and nothing else.
Ok,Here you go.... return Scaffold( appBar: AppBar( title: Text("Header"), ), body: Column( children: <Widget>[ Expanded( child: Container( alignment: Alignment.center, child: Text("Hello"), ), ), Container( height: 50, width: double.maxFinite, decoration: BoxDecoration( color: Colors.deepOrange, borderRadius: BorderRadius.vertical(top: Radius.circular(20.0)) ), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ IconButton(icon: Icon(Icons.arrow_forward), onPressed: (){},), IconButton(icon: Icon(Icons.arrow_downward), onPressed: (){},), IconButton(icon: Icon(Icons.arrow_left), onPressed: (){},), IconButton(icon: Icon(Icons.arrow_upward), onPressed: (){},), ], ), ) ], ), );
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58030067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10764147/']}
jdg_73847
stackexchange
llm_judgeable_groundtruth_similarity
2999528
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We are using Java2D to resize photos uploaded to our website, but we run into an issue (a seemingly old one, cf.: http://forums.sun.com/thread.jspa?threadID=5425569 ) - a few particular JPEGs raise a CMMException when we try to ImageIO.read() an InputStream containing their binary data: java.awt.color.CMMException: Invalid image format at sun.awt.color.CMM.checkStatus(CMM.java:131) at sun.awt.color.ICC_Transform.<init>(ICC_Transform.java:89) at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:516) at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1114) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1082) at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:897) at javax.imageio.ImageIO.read(ImageIO.java:1422) at javax.imageio.ImageIO.read(ImageIO.java:1326) ... (snipped the remainder of the stack trace, which is our ImageIO.read() call, servlet code and such) We narrowed it down to photos taken on specific cameras, and I selected a photo that triggers this error: http://img214.imageshack.us/img214/5121/estacaosp.jpg . We noticed that this only happens with Sun's JVM (on Linux and Mac, just tested it on 1.6.0_20) - a test machine with OpenJDK reads the same photos without a hitch, possibly due to a different implementation of the JPEG reader. Unfortunately, we are unable to switch JVMs in production, nor to use native-dependent solutions such as ImageMagick ( http://www.imagemagick.org/ ). Considering that, my question is: Does a replacement for ImageIOs JPEG reader which can handle photos such as the linked one exist? If not, is there another 100% pure Java photo resizing solution which we can use? Thank you! Now provide the response and nothing else.
One possibly useful library for you could be the Java Advanced Imaging Library ( JAI ) Using this library can be quite a bit more complicated than using ImageIO but in a quick test I just ran, it did open and display the problem image file you linked. public static void main(String[] args) { RenderedImage image = JAI.create("fileload", "estacaosp.jpg"); float scale=(float) 0.5; ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add(scale); pb.add(scale); pb.add(1.0F); pb.add(1.0F); pb.add(new InterpolationNearest() );// ;InterpolationBilinear()); image = JAI.create("scale", pb); // Create an instance of DisplayJAI. DisplayJAI srcdj = new DisplayJAI(image); JScrollPane srcScrollPaneImage = new JScrollPane(srcdj);// Use a label to display the image JFrame frame = new JFrame(); frame.getContentPane().add(srcScrollPaneImage, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } After running this code the image seems to load fine. It is then resized by 50% using the ParamaterBlock And finally if you wish to save the file you can just call : String filename2 = new String ("tofile.jpg"); String format = new String ("JPEG"); RenderedOp op = JAI.create ("filestore", image, filename2, format); I hope this helps you out. Best of luck.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2999528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64635/']}
jdg_73848
stackexchange
llm_judgeable_groundtruth_similarity
150016
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: We have a cube and we are coloring its edges. There are three colors available. We say that the two colorings are the same if one can obtain a second by turning cube and permuting colors. Find the number of different colorings. Any ideas? I've found Pólya enumeration theorem ,but it's difficult to understand for me, also this approach does not take into account the permutation of colors... Now provide the response and nothing else.
As I started working on this using Burnside's lemma , I might as well show what I've got. It is easy to make a mistake here. Marko Riedel cast a serious doubt on the result. Lo and behold! It turned out that I had made an error in calculating that fraction. Because the erroneous sum still produced an integer I didn't catch it myself. As described in loc.cit the 24 rotations of the cube split into 5 conjugacy classes. For each class we need to know what kind of orbits a representative in that class (or rather, the cyclic group generated by the representative) has among the edges. We also need to knowthe cardinality of the class. $A$ : The class of the identity mapping. Its action on the edges has 12 singleton orbits, and $|A|=1$ . $B$ : The class of 90 degree rotations. Its action partitions the edges into 3 orbits with 4 edges in each orbit. $|B|=6.$ $C$ : The class of 180 degree rotations about an axis connecting the midpoints of an opposite pair of faces of the cube (the squares of elements of class $B$ ). The edges are partitioned into 6 pairs. $|C|=3.$ $D$ : The class of 120 degree rotations about an axis connecting two opposite vertices. The edges are partitioned to 4 orbits, each with 3 edges. $|D|=8.$ $E$ : The class of 180 degree rotations about an axis connecting the midpoints of two parallel but opposite edges. The edges are partitioned into 7 orbits: 2 singletons (the ones intersecting the axis) and 5 pairs. $|E|=6.$ The group of color permutations is isomorphic to $S_3$ and has three conjugacy classes: $a$ = the class of the identity mapping, $b$ = the class of three 2-cycles (this time swapping two colors and leaving the third color as it is), $c$ = the class of two 3-cycles. The cartesian product of order $24\cdot6=144$ then acts on the set $X$ of colorings. The following table lists the number of fixed points in $X$ that an element of the listed conjugacy class has. $$\begin{array}{c|c|ccc|c|c}\text{class}&\text{size}&|X^g|&&\text{class}&\text{size}&|X^g|\\\hlineAa&1&3^{12}&&Cc&6&0\\Ab&3&1&&Da&8&3^4\\Ac&2&0&&Db&24&1\\Ba&6&3^3&&Dc&16&3^4\\Bb&18&3^3&&Ea&6&3^7\\Bc&12&0&&Eb&18&3^5\\Ca&3&3^6&&Ec&12&0\\Cb&9&3^6&&&&\end{array}$$ Feeding these numbers into the formula of Burnside's lemma tells that the number of orbits (=the number of distinguishable colorings under the prescribed rules) is $$|X/G|=\frac{1\cdot3^{12}+3\cdot1+6\cdot3^3+18\cdot3^3+3\cdot3^6+9\cdot3^6+8\cdot3^4+24\cdot1+16\cdot3^4+6\cdot3^7+18\cdot3^5}{144}=3891.$$ How did I come up with these numbers. The details vary a bit case-by-case. As somewhat typical examples consider: The class $Ab$ : Here the edges stay at the same place, but two of the colors are interchanged. A coloring is a fixed point of this operation only if it is monochromatic (of the non-interchanged color). Thus the elements in this class have exactly one fixed point. The class $Ba$ : Here we want to calculate the number of colorings that remain unchanged, when we rotate the cube by 90 degrees, and don't do any repainting. For this to happen it is necessary and sufficient that any of the three groups of four edges permuted among themselves by the rotation must share the same color. We have the liberty of choosing the colors for all the orbits independently. Therefore there are $3^3$ such colorings. The class $Bb$ : Here the 3 groups of 4 edges undergo some repainting in addition to the 90 degree rotation. If the three colors are R,Y,G, and we are to repaint every yellow edge green, and every green edge yellow, then for each orbit the possible colorings are RRRR, YGYG and GYGY. In the latter two cases repainting cancels the effect of the rotation. So we have 3 choice for the three groups of 4 edges, and a total of $3^3$ coloringsfixed under a group action of this type. The class $Bc$ : Here we can assume a color replacement scheme $Y\mapsto R\mapsto G\mapsto Y$ . This permutation of order 3 just doesn't mesh with the rotation of order 4, so no colorings are fixed points for this operation. The class $Dc$ : Let's study the same color replacement scheme as with class $Bc$ . The 12 edges are partitioned into 4 groups of 3 edges. The coloring of such a group has to be either $RGY$ , $GYR$ or $YRG$ for the repainting to cancel the effect of the rotation. But the choices for the four orbits are independent from each other, so we get a total of $3^4$ colorings that are fixed under an operation of this type. The class $Eb$ : Assume color replacement scheme $R\mapsto R$ , $Y\mapsto G\mapsto Y$ . For a coloring to be a fixed point, the two edges that are rotated in place, must both be red. But for the 5 pairs of edgese that interchange their locations, the possible colorings are $RR$ , $YG$ and $GY$ for the same reasons as with class $Bb$ . If you have trouble filling in the rest of the table, @ping me!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/150016', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25661/']}
jdg_73849
stackexchange
llm_judgeable_groundtruth_similarity
211645
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If n defines number of sets, what is the number of all possible relations between them? For example, when n = 2:1) A can intersect with B2) A and B can be disjoint3) A can be subset of B4) B can be subset of A that leaves us with 4 possible relations. Now with the n = 3 it gets tricker (A can intersect with B, but not C or B can be subsect of C and intersect with A there etc). Wondering if there's any formula that can be made to calculate such possible relations. Working on this problem for last couple of days, read about Venn diagrams, Karnaugh map, but still can't figure that one out. Any help is appreciated! Now provide the response and nothing else.
Let $[n]=\{1,\dots,n\}$, and consider sets $A_1,\dots,A_n$. For each non-empty $S\subseteq[n]$ let $$U_S=\bigcap_{k\in S}A_k\setminus\bigcup_{k\in[n]\setminus S}A_k\;;$$ $U_S$ is the set of $x$ that belong to $A_k$ if and only if $k\in S$. To get a clearer picture of this, consider first the case $n=2$. Then $U_{\{1\}}=A_1\setminus A_2$, $U_{\{2\}}=A_2\setminus A_1$, and $A_{\{1,2\}}=A_1\cap A_2$. These are the three regions of a Venn diagram for two sets that are inside at least one of the two sets. A Venn diagram for three sets has eight regions, and you should check that the seven that are in at least one of the three sets are precisely the seven sets $U_S$ such that $\varnothing\ne S\subseteq[3]$. The relationships amongst the sets $A_1,\dots,A_n$ are completely determined by which of the sets $U_S$ are empty and which are not. Some of these are pretty uninteresting: for instance, if $U_S=\varnothing$ for every non-empty $S\subseteq[n]$, then $A_1=\ldots=A_n=\varnothing$. However, if you’re willing to accept that the emptiness or not of each of the sets $A_k$ is part of their relationship, then we can count the possibilities quite easily: $[n]$ has $2^n-1$ non-empty subsets $S$, so $\{U_S:\varnothing\ne S\subseteq[n]\}$ is a family of $2^n-1$ sets. This family has $2^{2^n-1}$ subfamilies, so there are $2^{2^n-1}$ different ways to choose which of the sets $U_S$ are to be empty. In this sense, then, there are $2^{2^n-1}$ possible relationships amongst $n$ sets.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/211645', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44476/']}
jdg_73850
stackexchange
llm_judgeable_groundtruth_similarity
46263963
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 playing with the Dataset API in Tensorflow v1.3 . It's great.It is possible to map a dataset with a function as described here . I am interested to know how can I pass a function which has an additional argument, for example arg1 : def _parse_function(example_proto, arg1): features = {"image": tf.FixedLenFeature((), tf.string, default_value=""), "label": tf.FixedLenFeature((), tf.int32, default_value=0)} parsed_features = tf.parse_single_example(example_proto, features) return parsed_features["image"], parsed_features["label"] Of course, dataset = dataset.map(_parse_function) will not work since there is no way to pass in arg1 . Now provide the response and nothing else.
Here is an example using a lambda expression to wrap the function to which we want to pass an argument: import tensorflow as tfdef fun(x, arg): return x * argmy_arg = tf.constant(2, dtype=tf.int64)ds = tf.data.Dataset.range(5)ds = ds.map(lambda x: fun(x, my_arg)) In the above, the signature of the function provided to map must match the contents of our dataset. So we have to write our lambda expression to match that. Here it is simple, as there is only one element contained in the dataset, the x that contains elements in the range from 0 to 4. If necessary, you can pass in an arbitrary number of external arguments from outside the dataset: ds = ds.map(lambda x: my_other_fun(x, arg1, arg2, arg3) , and so on. To verify that the above works, we can observe that the mapping indeed multiplies each dataset element by two: iterator = ds.make_initializable_iterator()next_x = iterator.get_next()with tf.Session() as sess: sess.run(iterator.initializer) while True: try: print(sess.run(next_x)) except tf.errors.OutOfRangeError: break The output: 02468
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46263963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3052875/']}
jdg_73851
stackexchange
llm_judgeable_groundtruth_similarity
29517715
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 carry this into my .map() loop? It seems to disappear. :-( I'm creating a "dynamic form" where the user can specify multiple lines of input for his form. I want to iterate over all items in state.items[] and build form input fields for them. E.g the form starts with 'field' and 'autocomplete_from. The user can then click add a new line to get more rows in his form. 102 render: function() {103 return (104 <div>105 {this.state.items.map(function(object, i){106 return (107 <div>109 <FieldName/>110 <strong> State.autocomplete_from: {this.state.autocomplete_from} </strong> // ^^^ // Uncaught TypeError: Cannot read property 'state' of undefined120 <button onClick={this.newFieldEntry}>Create a new field</button>121 <button onClick={this.saveAndContinue}>Save and Continue</button>122 </div>123 );124 })}125 </div>126 ); Now provide the response and nothing else.
In .map this does not refer to your component., there are several ways how you can solve this issue Save this to variable render: function() { var _this = this; return ( <div> {this.state.items.map(function(object, i){ return ( <div> <FieldName/> <strong> State.autocomplete_from: {_this.state.autocomplete_from} </strong> <button onClick={this.newFieldEntry}>Create a new field</button> <button onClick={this.saveAndContinue}>Save and Continue</button> </div> ); })} </div> );} Set this for .map callback( if you can't use ES2015 features, this variant is prefered ) this.state.items.map(function (object, i) { // ....}, this); use arrow function this.state.items.map((object, i) => { // ....}) use .bind this.state.items.map(function(object, i) { // ....}.bind(this))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29517715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375721/']}
jdg_73852
stackexchange
llm_judgeable_groundtruth_similarity
41779374
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have a class defined like class A {protected: ~A(){ }}; then I can dynamically allocate the individual as well as array of objects like A* ptr1 = new A;A* ptr2 = new A[10]; However when I define the constructor for this class class A {public: A(){}protected: ~A(){ }}; then I can create individual objects with A* ptr = new A; but when I try to dynamically allocate the array of object with A* ptr = new A[10]; compiler(gcc-5.1 and Visual Studio 2015) starts complaining that A::~A() is inaccessible. Can anyone explain about:- 1- Why is the difference in behavior with constructor being defined and not defined. 2- When the constructor is defined why I am allowed to create individual object and not array of object. Now provide the response and nothing else.
Rejecting an array- new with a protected destructor is correct, as per C++11, §5.3.4 ¶17: If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function (12.5), and the constructor (12.1). If the new expression creates an array of objects of class type, access and ambiguity control are done for the destructor (12.4). (emphasis added; almost exactly the same wording is used in C++03, §5.3.4 ¶16; C++14 moves some stuff around, but that doesn't seem to change the core of the issue - see @Baum mit Augen 's answer) That comes from the fact that new[] succeeds only if only all the elements have been constructed, and wants to avoid leaking objects in case one of the costructor calls fails; thus, if it manages to construct - say - the first 9 objects but the 10th fails with an exception, it has to destruct the first 9 before propagating the exception. Notice that this restriction logically wouldn't be required if the constructor was declared as noexcept , but still the standard doesn't seem to have any exception in this regard. So, here gcc is technically wrong in the first case, which, as far as the standard is concerned, should be rejected as well, although I'd argue that "morally" gcc does the right thing (as in practice there's no way that the default constructor of A can ever throw).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41779374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4699294/']}
jdg_73853
stackexchange
llm_judgeable_groundtruth_similarity
579864
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Recently, Amazon announced new instance types for RDS . Currently, we are running db.m1.large , and it looks like the new db.m3.large is comparable but cheaper. Before moving these over, I wanted to double check with you guys that there are no hidden "gotchas" I'm not seeing. Are there any reasons not to move our instances to the new, cheaper, faster instance type? Now provide the response and nothing else.
The only real cons I can see are: lack of PIOPS optimisation for the db.m3.large (where you would have guaranteed bandwidth connecting you to EBS and PIOPS volumes) smaller (albeit faster) instance/ephemeral storage for the m3.large (32GB SSD vs 2x 480GB HDD), and to be honest I'm not sure instance storage is relevant for RDS instances And that's it. In return for these cons, you receive faster CPUs and lower prices. I have already moved a standard m1.large instance running CentOS+MySQL slave (i.e. an EC2 instance, not an RDS instance) to an m3.large. The idle CPU floor dropped from around 6-7% to 1.5-2%, and peak loads are reduced from around 85-90% to 45-50%, simply by relaunching as an m3.large.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/579864', 'https://serverfault.com', 'https://serverfault.com/users/113900/']}
jdg_73854
stackexchange
llm_judgeable_groundtruth_similarity
13350877
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 the same type of table view controllers in my app many times and would like to create a more generic table view controller which I can use over and over again. These table view controllers are quite simple and show only the contents of an array, put a check mark to the selected table view cell and return the index of the selected table view cell to the calling view controller after the Done button in the toolbar has been tapped. Currently I create each one of these table view controllers directly in Storyboard and instantiate them by using segues. Would it be possible to do this in code only (without using Storyboard or xibs)? What would be the best way to instantiate and push them onto the navigation controller stack (each one will be shown in a view controller). Now provide the response and nothing else.
You have to be precise here. You can calculate the visible rectangular region given the camera's field-of-view, camera.fov , and a given distance, dist , from the camera. Since the object presumably has depth, you have to pick one plane through the mesh, and do the calculation at that distance. Here is how to calculate the visible height and width for a given distance dist from the camera. var vFOV = THREE.MathUtils.degToRad( camera.fov ); // convert vertical fov to radiansvar height = 2 * Math.tan( vFOV / 2 ) * dist; // visible heightvar width = height * camera.aspect; // visible width three.js r.117
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13350877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1214667/']}
jdg_73855
stackexchange
llm_judgeable_groundtruth_similarity
10055
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My question is regarding the algebraic formulation for packing problems in graphs. Taking an example, suppose I am interested in the problem of finding if there is a packing of k edge disjoint triangles in a given input (undirected) graph. I am aware of techniques that approach this problem combinatorially. Is there a way to frame this problem algebraically? Also, in context of graph theory, are algebraic methods less powerful when compared to combinatorial methods? Or is there any particular intuition that governs which approach is more effective in certain problems? I apologize if my question sounds too general. The purpose of this question is to try and form an understanding of algebraic vs combinatorial methods in the context of graph theory. Now provide the response and nothing else.
It is possible to prove the fixed-parameter tractability of various graph-theoretical problems (e.g., finding a path of length k or finding k disjoint triangles) using algebraic techniques by reducing the problem to questions about certain polynomials. See for example the following very readable paper by Ryan Williams: http://arxiv.org/abs/0807.3026v3 and some other related papers: http://www.cs.cmu.edu/~jkoutis/papers/MultilinearDetection.pdf http://doi.ieeecomputersociety.org/10.1109/FOCS.2010.24 http://arxiv.org/abs/0912.2371 About your meta question: as the formulation of graph-theoretical problems is usually "combinatorial," it is not surprising to me that most of the natural approaches are "combinatorial" rather than "algebraic." The "algebraic" approaches work only if the problem has some unexpected connection with algebra, which is probably quite rare for natural "combinatorial" problems. In the above-mentioned papers, such a connection is discovered, allowing us to solve the problem using algebraic techniques. Interestingly, for these problems the algebraic algorithms are faster (have better bounds) than the combinatorial ones.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/10055', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/3816/']}
jdg_73856
stackexchange
llm_judgeable_groundtruth_similarity
3022046
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 access 32-bit registers in C ? If it is, how ? And if not, then is there any way to embed Assembly code in C ? I`m using the MinGW compiler, by the way.Thanks in advance! Now provide the response and nothing else.
If you want to only read the register, you can simply: register int ecx asm("ecx"); Obviously it's tied to instantiation. Another way is using inline assembly. For example: asm("movl %%ecx, %0;" : "=r" (value) : ); This stores the ecx value into the variable value . I've already posted a similar answer here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3022046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362766/']}
jdg_73857
stackexchange
llm_judgeable_groundtruth_similarity
80791
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: Theory: The speed of light changes when it enters or exits the solar system due to a difference in medium (dark matter possibly). Potential problem 1: refraction If there was a speed change at the edge of the solar system, refraction would occur. This would manifest in ways similar to the sunset effect . Solution: the sunset refraction occurs because the angle against the edge of the atmosphere is extreme. No effect is noticed at high noon. Earth's proximity to the edge of the solar system, in contrast, makes it's angle nearly perpendicular in all directions. Wouldn't this negate any sunset effect? Sub-solution: My research on refraction seems to indicate that what I'll call the "distinction level" of the edge of the mediums has an effect on the level of refraction. So that, if the edge were not solid, but rather tapered, the refraction is reduced. SO, what would be effect on light entering our solar system if the light were severely slowed--let's say by a factor of 1,000,000 times, to what it is now. What, if any, refractive effects would be observed? How much would these effects change if the tapering of the edge were severe?--Could any refractive effect be overcome by tapering? Another question, what would be the effect of the light coming from Alpha Centauri if it's system had a similar medium transition at it's edge? How would it be noticable? This picture illustrates my thoughts: Now provide the response and nothing else.
Tapering makes no difference in Snell's law. If you have a refractive index profile n(z) [approximately independent of x and y], and you know the angle of the light at z1, then you can figure out the angle at another point z2 using Snell's law -- and the angle only depends on n(z1) and n(z2), not n(z) for any other z. It doesn't matter how smooth or sharp n(z) changes. (The profile and smoothness does affect the reflection and transmission amplitudes, but it does not affect the angle.) The atmosphere is a good example -- the refractive index changes very smoothly from earth to outer space, as the air gets thinner and thinner, but there is still a sunset effect ... and moreover, you can calculate the sunset effect without knowing anything about the refractive index profile of the atmosphere. You only need to know the refractive index on the ground and the refractive index in space. Therefore, if the refractive index changed at the edge of the solar system, we would see stars in weird, distorted positions, and the distortions would change over the course of the year, as the earth moved relative to the edge of the solar system. (Yes, I know the earth is kinda near the center of the solar sytem, but it still moves to some extent.) The relative positions of stars are measured to extraordinarily high accuracy, so if there were a refractive index change, it would be easily seen, unless the refractive index change were extremely small. I haven't gone through the calculation of exactly how small the refractive index has to be to be undetectable. Certainly a change of 1,000,000 can be ruled out! -- ADDENDUM -- Here's a more specific way to think about whether it's astronomically observable. Just to be clear, let's do both 1:10^6 and 10^6:1 index contrast. If the index is 1 inside the solar system and 10^6 outside... (Light travels slow in the interstellar medium.) Then whatever direction we look, the rays exit the solar system more-or-less normal to the shell at the "edge of the solar system", by Snell's law. No matter where earth is, we see all the stars in almost exactly the positions they would be if we projected them onto the shell . (It would look like the ancient idea of a celestial sphere.) Then the question becomes: Can we observe the parallax of an object at the edge of the solar system? The answer is: Yes, very very easily. We can observe the parallax of stars far beyond the solar system, and we can observe that faraway galaxies have a parallax that's much smaller than that. So we can rule this possibility out. If the index is 10^6 inside the solar system and 1 outside... (Light travels fast in the interstellar medium.) Then almost any direction we look will have total internal reflection at the edge of the solar system -- we won't see any stars at all, maybe we'll even see a reflection of the sun -- except for the direction where we are looking almost exactly dead-on normal to the imaginary shell at the edge of the solar system. In that direction, there will be a little angular window where we will see all of the stars in every direction squeezed together. I think we can rule this out too!
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/80791', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11226/']}
jdg_73858
stackexchange
llm_judgeable_groundtruth_similarity
8416990
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 shortcut in Shell/Bash that can rename all the files in a folder based on a regex or some other criteria. What I am looking for here is in my folder documents, that has let's say a 100 text files with the following naming convention: <longdocumentidentifier>-doc-<counter>.txt. I need to rename all the files with the above given convention to just: doc-<counter>.txt Is there a one-liner that can help me with the above? Now provide the response and nothing else.
I would suggest something like this: for i in *-doc-*.txt; do mv "$i" "${i/*-doc-/doc-}"; done ${i/*-doc-/doc-} replaces the first occurrence of *-doc- with doc- . If you need to do more than one replacement (see comment number 1), you need to use the ${var//Pattern/Replacement} variant. If you need to replace the beginning of the name you need to use ${var/#Pattern/Replacement} , if you need to replace the end (ie: the extension) you need to use the ${var/%Pattern/Replacement} form. See Shell Parameter Expansion for more details. This expansion is bash specific.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8416990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207072/']}
jdg_73859
stackexchange
llm_judgeable_groundtruth_similarity
17043393
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 looking at the numpy.savetxt , and am stuck at the fmt option. I tried looking at here and also the reference in the link below all the letters that can be used for the fmt option sort give me a general sense of what is going on. What I do not understand is if the % symbol is required and in an example given here how should I interpret the 10.5 number? If "f" is about setting the floating point, then how come is it 10.5 (then again, I might not know how floating points are set...). Now provide the response and nothing else.
Knowing that np.savetxt only works for 1D or 2D arrays, the general idea is: when fmt is a single formatting string it applies to all elements in the array (1D or 2D input array) when fmt is a sequence of formatting strings, it applies to each column of the 2D input array I'm presenting here some examples using the following input array: import numpy as npa = np.array([[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]]) 1) Setting floating point precision: np.savetxt('tmp.txt', a, fmt='%1.3f') 11.000 12.000 13.000 14.00021.000 22.000 23.000 24.00031.000 32.000 33.000 34.000 2) Adding characters to right-justify. With spaces: np.savetxt('tmp.txt', a, fmt='% 4d') 11 12 13 14 21 22 23 24 31 32 33 34 With zeros: np.savetxt('tmp.txt', a, fmt='%04d') 0011 0012 0013 00140021 0022 0023 00240031 0032 0033 0034 3) Adding characters to left-justify (use of " - "). With spaces: np.savetxt('tmp.txt', a, fmt='%-4d') 11 12 13 14 21 22 23 24 31 32 33 34 4) When fmt is a sequence of formatting strings, each row of a 2D input array is processed according to fmt : fmt as a sequence in a single formatting string fmt = '%1.1f + %1.1f / (%1.1f * %1.1f)'np.savetxt('tmp.txt', a, fmt=fmt)11.0 + 12.0 / (13.0 * 14.0)21.0 + 22.0 / (23.0 * 24.0)31.0 + 32.0 / (33.0 * 34.0) fmt as an iterator of formatting strings : fmt = '%d', '%1.1f', '%1.9f', '%1.9f'np.savetxt('tmp.txt', a, fmt=fmt)11 12.0 13.000000000 14.00000000021 22.0 23.000000000 24.00000000031 32.0 33.000000000 34.000000000
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17043393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2460137/']}
jdg_73860
stackexchange
llm_judgeable_groundtruth_similarity
4893706
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 awesome an accidental feature as this is, it makes for a lousy way to "shuffle" an array of "cards". The fact that I'm getting the same number tells me I've having some problem in picking separate seeds each time. Am I using srand48 or the time(NULL) call improperly? Is there some underlying logic flaw I'm missing? Is there just not enough time inbetween iterations for the value of time() to be different? The code is being run on Linux. void shuffle(){ int i_rnd; /* Integer random number, range 0..100 */ int i_rnd2; card tempCard; /*temporary card to facillitate swapping*/ int i = 0; /*can't use a FOR loop 'cause we're not using c99 standard*/ while(i < 1000) { srand48( (unsigned) time( NULL ) ); /* Seed the random number generator */ i_rnd = (int) ( drand48() * 100); i_rnd = i_rnd%52; // return a random number 0-51 i_rnd2 = (int) ( drand48() * 100); i_rnd2 = i_rnd2%52; // return a random number 0-51 /*we have two random numbers, now exchange the two objects with the / picked array indices */ tempCard = cardDeck[i_rnd]; cardDeck[i_rnd]=cardDeck[i_rnd2]; cardDeck[i_rnd2]=tempCard; //swap complete. increment counter so we can eventually get out of the while i++; }return;} Now provide the response and nothing else.
You need to seed the pseudorandom number generator once , not every time you use it. Many (most?) pseudorandom number generators (PRNG) are deterministic given a certain seed value. If time() returns the same value each time your loop executes, you seed the PRNG with the same value just before you use it each time, so when you query it for random numbers it returns the same values.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4893706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/355682/']}
jdg_73861
stackexchange
llm_judgeable_groundtruth_similarity
1404137
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm attempting to solve the following equation (eventually with Lambert's W Function having checked the solution on Wolfram Alpha): $$100n^2 = 2^n$$ I got as far as follows but I am unsure how to progress: $$\ln100 + 2\ln(n) = n\ln2$$ Any suggestions would be much appreciated. Now provide the response and nothing else.
To use Lambert W you may proceed this way :\begin{align}100\,n^2 &= 2^n\\(10\,n)^2 &= e^{n\log 2}\\10\,n &= \pm e^{n\log 2/2}\\\left(-\,n \log 2/2\right) e^{-n\log 2/2}&= \mp (\log 2)/{20}\\-\,n \log 2/2&=W\left(\mp (\log 2)/20\right)\\\end{align}The negative argument (see wikipedia ) will be between $-\dfrac 1e$ and $0$ and return you two solutions : $-\frac{2}{\log 2}W_{-1}\left(-\frac{\log 2}{20}\right)\approx 14.324727837\quad$ and $-\frac{2}{\log 2}W\left(-\frac{\log 2}{20}\right)\approx 0.1036578164$ while the positive argument will return simply $-\frac{2}{\log 2}W\left(\frac{\log 2}{20}\right)\approx -0.0967040343267$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1404137', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29317/']}
jdg_73862
stackexchange
llm_judgeable_groundtruth_similarity
9577471
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building a MP3 player for iOS that plays audio files hosted on the web. I want to offer the ability to play the files offline so I have the files downloading using ASIHTTP but I am cannot seem to find info on initiallzing AVPlayer with a mp3 in the app documents directory. Has anyone done this before? Is it even possible? *I posted an answer below that shows how to use the iOS AvPlayer for both local and http files. Hope this helps! Now provide the response and nothing else.
I decided to answer my own question because I felt like there is very little documentation on how to use the Apple provided AVPlayer for both local and stream (over http) files. To help understand the solution, I put together a sample project on GitHub in Objective-C and Swift The code below is Objective-C but you can download my Swift example to see that. It is very similar! What I found is that the two ways of setting up the files are almost identical except for how you instantiate your NSURL for the Asset > PlayerItem > AVPlayer chain. Here is an outline of the core methods .h file (partial code) -(IBAction) BtnGoClick:(id)sender;-(IBAction) BtnGoLocalClick:(id)sender;-(IBAction) BtnPlay:(id)sender;-(IBAction) BtnPause:(id)sender;-(void) setupAVPlayerForURL: (NSURL*) url; .m file (partial code) -(IBAction) BtnGoClick:(id)sender { NSURL *url = [[NSURL alloc] initWithString:@""]; [self setupAVPlayerForURL:url];}-(IBAction) BtnGoLocalClick:(id)sender { // - - - Pull media from documents folder //NSString* saveFileName = @"MyAudio.mp3"; //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //NSString *documentsDirectory = [paths objectAtIndex:0]; //NSString *path = [documentsDirectory stringByAppendingPathComponent:saveFileName]; // - - - // - - - Pull media from resources folder NSString *path = [[NSBundle mainBundle] pathForResource:@"MyAudio" ofType:@"mp3"]; // - - - NSURL *url = [[NSURL alloc] initFileURLWithPath: path]; [self setupAVPlayerForURL:url];}-(void) setupAVPlayerForURL: (NSURL*) url { AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil]; AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset]; player = [AVPlayer playerWithPlayerItem:anItem]; [player addObserver:self forKeyPath:@"status" options:0 context:nil];}- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object == player && [keyPath isEqualToString:@"status"]) { if (player.status == AVPlayerStatusFailed) { NSLog(@"AVPlayer Failed"); } else if (player.status == AVPlayerStatusReadyToPlay) { NSLog(@"AVPlayer Ready to Play"); } else if (player.status == AVPlayerItemStatusUnknown) { NSLog(@"AVPlayer Unknown"); } }}-(IBAction) BtnPlay:(id)sender { [player play];}-(IBAction) BtnPause:(id)sender { [player pause];} Check out the Objective-C source code for a working example of this. Hope this helps! -Update 12/7/2015 I now have a Swift example of the source code you can view here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9577471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363561/']}
jdg_73863
stackexchange
llm_judgeable_groundtruth_similarity
55510
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 quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time. int globalgarbage;unsigned int anumber = 42; But what about static ones defined within a function? void doSomething(){ static bool globalish = true; // ...} When is the space for globalish allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething() is first called? Now provide the response and nothing else.
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2. include <iostream>#include <string>using namespace std;class test{public: test(const char *name) : _name(name) { cout << _name << " created" << endl; } ~test() { cout << _name << " destroyed" << endl; } string _name;};test t("global variable");void f(){ static test t("static variable"); test t2("Local variable"); cout << "Function executed" << endl;}int main(){ test t("local to main"); cout << "Program start" << endl; f(); cout << "Program end" << endl; return 0;} The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output: global variable createdlocal to main createdProgram startstatic variable createdLocal variable createdFunction executedLocal variable destroyedProgram endlocal to main destroyedstatic variable destroyedglobal variable destroyed
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/55510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4790/']}
jdg_73864
stackexchange
llm_judgeable_groundtruth_similarity
4060613
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 inherited a codebase :) Under src/test/java/ there's a file that I need to run (I need to run its public static void main(String[] args) , not a @Test method within it). The closest I have got is: mvn -e exec:java -Dexec.mainClass="com.me.packagex.RunFile" -Dexec.classpathScope="test" but that then fails, and it appears to be because RunFile wants to use classes that exist under src/main/java/com/me/packagex/ (notice, /main/, not /test/). The files under there are in the same package as RunFile, i.e. 'package com.me.packagex;'. If I remove the -Dexec.classpathScope="test" then it can't find RunFile at all. It's as if I need to give it two scopes, but it doesn't accept "test,compile". The person I've inherited this from (dearly departed) used to run it from Eclipse. I need a way to run it from the command-line. I hope this is clearly explained. tyvm, This is promising. Pascal, I've tried your example and that doesn't work for me. Although now I look at it - it's not finding Demo, rather than not finding Dog. Apache Maven 2.2.1 (rdebian-1)Java version: 1.6.0_18Java home: /usr/lib/jvm/java-6-openjdk/jreDefault locale: en_GB, platform encoding: UTF-8OS name: "linux" version: "2.6.32-25-generic" arch: "i386" Family: "unix"$ mvn -e exec:java -Dexec.mainClass="com.stackoverflow.Demo" -Dexec.classpathScope="test"[ERROR] BUILD ERROR[INFO] ------------------------------------------------------------------------[INFO] An exception occured while executing the Java class. com.stackoverflow.Demo[INFO] ------------------------------------------------------------------------[INFO] Traceorg.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. com.stackoverflow.Demo at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375)Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. com.stackoverflow.Demo at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) ... 17 moreCaused by: java.lang.ClassNotFoundException: com.stackoverflow.Demo at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:284) at java.lang.Thread.run(Thread.java:619) Now provide the response and nothing else.
(...) I hope this is clearly explained. Not bad but I can't reproduce. I created a project: $ mvn archetype:generate -DgroupId=com.stackoverflow \ -DartifactId=Q4060613 \ -Dversion=1.0-SNAPSHOT \ -DarchetypeArtifactId=maven-archetype-quickstart Then cd ed into it and created a Dog class (under src/main/java ): $ cd Q4060613$ cat > src/main/java/com/stackoverflow/Dog.javapackage com.stackoverflow;public class Dog { public String bark() { return "woof!"; }} and created a Demo class (under src/test/java ): $ cat > src/test/java/com/stackoverflow/Demo.java package com.stackoverflow;public class Demo { public static void main(String[] args) { System.out.println(new Dog().bark()); }} After compiling the source code, running the command you provided works as expected: $ mvn test...$ mvn exec:java -Dexec.mainClass="com.stackoverflow.Demo" -Dexec.classpathScope="test"[INFO] Scanning for projects......[INFO] --- exec-maven-plugin:1.2:java (default-cli) @ Q4060613 --- woof! [INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------... Something else must be wrong.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4060613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492389/']}
jdg_73865
stackexchange
llm_judgeable_groundtruth_similarity
31064
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've read this similar question and it has some very good information. Can a site that has personal information about you be accessed by another site to determine who you are/where you are? For example if I log into Facebook (let's pretend it has my real name and location) then I go to another website (for example a forum and post something bad about the government), even though my IP is hidden could anyone find out that I made the comment on the forum based on the fact I had logged into Facebook in the same browser session which has my personal info? The VPN service I use protects itself using shared IP addresses, how does this affect privacy? What steps can I take to mitigate such a threat, if one exists? Now provide the response and nothing else.
Connecting thorugh a VPN does not provide anonymity. It just provides a different IP address. Any way in which you could otherwise be traced you still be traced. If you want your VPN-redirected traffic to not be at all associated with your non-VPN-redirected traffic, then your best solution is to keep completely separate profiles for each use. The most complete way to do so is with two separate computers; the second most complete way is by using a separate OS on the same computer (also not that bad), and the third way is to separate out the browsers (not ideal, but less friction). And then, of course, never do anything within the one profile that you do with the other. No shared accounts, no shared logins, no shared usage patterns, no shared anything. Don't even visit the sames sites. Often when people's anonymous personae are tracked down (e.g. by a repressive government, etc.) and tied to a real-world person, it's by discovering patters in behavior, speech, timing, or other such side-channel details, or one one persona makes some reference to the other, or by both sharing some common offline characteristic (like the sound of your voice if someone talks to you). The more a given identity does, the more difficult it becomes for that identity to remain secret. The only safety (if there is any at all) is in keeping the anonymous persona sparse and very rarely encountered. It's an extraordinarily dangerous line to tread, so do so with the utmost caution. Also, and here's a technical detail you don't want to forget: If a "content of interest" is seen by the government coming form a specific IP address, and YOU are seen connecting to a VPN at that same address... well then your secret is not so secret. If your only protection is a VPN, then you're not particularly protected.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/31064', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10714/']}
jdg_73866
stackexchange
llm_judgeable_groundtruth_similarity
8223197
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 see that my ModelState.Values[x].Errors is correctly populated with the two validation errors for a single property. If I use a @Html.ValidationSummary() in my view, it correctly displays both errors.... albeit at the top of the page, and not next to the offending input. Using @Html.ValidationMessageFor(model => model.MyProperty) displays the first error only for that property! How do I show both errors, next to the appropriate input? Now provide the response and nothing else.
One solution is to implement your own extension method on HtmlHelper that does something different to the default ValidationMessageFor behavior. The sample @Html.ValidationMessagesFor method below will concatenate multiple error messages that have been added to the ModelState during server-side validation (only). public static MvcHtmlString ValidationMessagesFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null){ var propertyName = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName; var modelState = htmlHelper.ViewData.ModelState; // If we have multiple (server-side) validation errors, collect and present them. if (modelState.ContainsKey(propertyName) && modelState[propertyName].Errors.Count > 1) { var msgs = new StringBuilder(); foreach (ModelError error in modelState[propertyName].Errors) { msgs.AppendLine(error.ErrorMessage); } // Return standard ValidationMessageFor, overriding the message with our concatenated list of messages. return htmlHelper.ValidationMessageFor(expression, msgs.ToString(), htmlAttributes as IDictionary<string, object> ?? htmlAttributes); } // Revert to default behaviour. return htmlHelper.ValidationMessageFor(expression, null, htmlAttributes as IDictionary<string, object> ?? htmlAttributes);} This is useful if you have custom business validation you're applying across a collection belonging to your model (for example, cross-checking totals), or checking the model as a whole. An example using this, where a collection of Order.LineItems are validated server-side: @using MyHtmlHelperExtensions // namespace containing ValidationMessagesFor@using (Html.BeginForm()){ @Html.LabelFor(m => m.LineItems) <ul> @Html.EditorFor(m => m.LineItems) </ul> @Html.ValidationMessagesFor(m => m.LineItems)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8223197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/483655/']}
jdg_73867
stackexchange
llm_judgeable_groundtruth_similarity
2378984
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to find when:$$(1+x)^y (1-x)^z$$is smaller than 1, given $0<x<1$, $0<y<1$, and $0<z<1$ A sufficient condition is $z\geq y$, but I cannot find a necessary and sufficient condition. Now provide the response and nothing else.
If there are three integer solutions, they add to $0$ and so are $a$,$b$ and $c=-a-b$. Then$$-24=ab+ac+bc=ab-(a+b)^2=-a^2-ab-b^2.$$You need to prove that $24$ is not represented over the integersby the quadratic form $a^2+ab+b^2$. Maybe you could complete the square...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2378984', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468785/']}
jdg_73868
stackexchange
llm_judgeable_groundtruth_similarity
8817377
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 layout with multiple ImageView s, some of those images need to have the same onClickListener.I would like my code to be flexible and to be able to get a collection of those View s, iterate and add the listeners at run-time. Is there a method like findViewById that will return a collection of View s rather than just a single one? Now provide the response and nothing else.
I've finally wrote this method ( Updated thanks to @SuitUp (corrected username)): private static ArrayList<View> getViewsByTag(ViewGroup root, String tag){ ArrayList<View> views = new ArrayList<View>(); final int childCount = root.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = root.getChildAt(i); if (child instanceof ViewGroup) { views.addAll(getViewsByTag((ViewGroup) child, tag)); } final Object tagObj = child.getTag(); if (tagObj != null && tagObj.equals(tag)) { views.add(child); } } return views;} It will return all views that have android:tag="TAG_NAME" attribute. Enjoy ;)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8817377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1115237/']}
jdg_73869
stackexchange
llm_judgeable_groundtruth_similarity
411
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider directed graphs. We call a node $v$ superstar if and only if no other node can be reached from it, but all other nodes have an edge to $v$. Formally: $\qquad \displaystyle $v$ \text{ superstar } :\Longleftrightarrow \mathrm{outdeg}(v) = 0 \land \mathrm{indeg}(v) = n-1$ with $n$ the number of nodes in the graph. For example, in the below graph, the unfilled node is a superstar (and the other nodes are not). [ source ] How can you identify all superstars in a directed graphs in $\mathcal{O}(n)$ time? A suitable graph representation can be chosen from the usual candidates ; please refrain from using representations that move the problem's complexity to preprocessing. No assumptions regarding density can be made. We don't assume the graph contains a superstar; if there is none, the algorithm should recognize it. Notation : $\mathrm{outdeg}$ is a node's number of outgoing edges, $\mathrm{indeg}$ similar for incoming edges. Now provide the response and nothing else.
We can eliminate all but one of the vertices by checking for the existence of $n-1$ edges because we can eliminate one possibility for each edge we check. In particular, if there is an edge going from $x$ to $y$, we eliminate $x$ and move on to $y$ (as another vertex can be reached from it); if not, we eliminate $y$ (as it cannot be reached from $x$). Once we reach the last vertex, whichever vertex is not eliminated should be compared with each other vertex (ensure the superstar condition is upheld: there is an edge incoming but not outgoing) until it is eliminated or confirmed as the superstar. Some pseudocode: vertex superstar(graph g) current vertex = first # Go through each vertex for each subsequent vertex in g ("next") # If there's an edge from this to the next, we eliminate this one [move to the new one]. # If not, we just stay here. if edge exists from current to next candidate = next end if end for # Now we are on the final remaining candidate, check whether it satisfies the requirements. # just a rename for clarity candidate = current for each other vertex in g if edge from current to other exists return null else if no edge from other to current return null end if end for return candidateend superstar Let's walk through an example to illustrate the method. Take this array, with the source vertex on the top and destination on the side. 1 indicates an edge: $$\begin{array}{r|c c c c|r} & 1 & 2 & 3 & 4 \\\hline1 & - & 1 & 0 & 1 \\2 & 1 & - & 0 & 1 \\3 & 1 & 1 & - & 1 \\4 & 1 & 1 & 0 & - \\\end{array}$$ I'll grey out the vertices we have ruled out as potential superstars.I'll use green and red to indicate the edges we are looking at when they do and do not contain the edge we're looking for, and blue to indicate where we have already looked. We start by looking at vertices 1 and 2. $$\begin{array}{r|c c c c} & 1 & 2 & 3 & 4 \\\hline1 & - & \color{green}{1} & 0 & 1 \\2 & 1 & - & 0 & 1 \\3 & 1 & 1 & - & 1 \\4 & 1 & 1 & 0 & - \\\end{array}$$The green number shows there is anedge from 2 to 1, so we eliminate 2 and look for an edge from 3 to 1: $$\begin{array}{r|c c c c} & 1 & \color{grey}{2} & 3 & 4 \\\hline1 & - & \color{blue}{1} & \color{red}{0} & 1 \\\color{grey}{2} & 1 & - & 0 & 1 \\3 & 1 & 1 & - & 1 \\4 & 1 & 1 & 0 & - \\\end{array}$$ We see there is no such edge, so we eliminate 1 and take 3 as our currentvertex. Recall that we have eliminated 2 already, so see whether there is an edge from 4 to 3: $$\begin{array}{r|c c c c} & \color{grey}{1} & \color{grey}{2} & 3 & 4 \\\hline\color{grey}{1} & - & \color{blue}{1} & \color{blue}{0} & 1 \\\color{grey}{2} & 1 & - & 0 & 1 \\3 & 1 & 1 & - & \color{green}{1} \\4 & 1 & 1 & 0 & - \\\end{array}$$ There is an edge from 4 to 3, so we eliminate 4. At this point we haveeliminated all but one of the vertices (3), so check out its edges and see whether it qualifies: $$\begin{array}{r|c c c c} & \color{grey}{1} & \color{grey}{2} & 3 & \color{grey}{4} \\\hline\color{grey}{1} & - & \color{blue}{1} & \color{red}{0} & 1 \\\color{grey}{2} & 1 & - & 0 & 1 \\3 & \color{green}{1} & 1 & - & \color{blue}{1} \\\color{grey}{4} & 1 & 1 & 0 & - \\\end{array}$$ There is an edge from 1 to 3 but not the reverse, so 3 is still a candidate. $$\begin{array}{r|c c c c} & \color{grey}{1} & \color{grey}{2} & 3 & \color{grey}{4} \\\hline\color{grey}{1} & - & \color{blue}{1} & \color{blue}{0} & 1 \\\color{grey}{2} & 1 & - & \color{red}{0} & 1 \\3 & \color{blue}{1} & \color{green}{1} & - & \color{blue}{1} \\\color{grey}{4} & 1 & 1 & 0 & - \\\end{array}$$ There is also an edge from 2 to 3 but not the reverse, so 3 is still a candidate. $$\begin{array}{r|c c c c} & \color{grey}{1} & \color{grey}{2} & 3 & \color{grey}{4} \\\hline\color{grey}{1} & - & \color{blue}{1} & \color{blue}{0} & 1 \\\color{grey}{2} & 1 & - & \color{blue}{0} & 1 \\3 & \color{blue}{1} & \color{blue}{1} & - & \color{green}{1} \\\color{grey}{4} & 1 & 1 & \color{red}{0} & - \\\end{array}$$ There is an edge from 4 to 3 but not 3 to 4; that completes our check of 3's edges and we have found that it is, in fact, a superstar. Since we eliminate one vertex as a possible superstar on each of the first$n-1$ edge checks, the best case is that the $n$th check eliminates thefinal vertex for a complexity of $n$. In the worst case (the last orsecond-to-last vertex is a superstar, or the final check disqualifies it), after the first $n-1$ comparisons we compare the candidatewith $2\times(n-1)$ more vertices, for a worst case complexity of $3n-3$ ($O(n)$). So, this algorithm is$\Theta(n)$.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/411', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/98/']}
jdg_73870
stackexchange
llm_judgeable_groundtruth_similarity
56011
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It was Faltings who first proved in 1983 the Mordell conjecture, that a curve of genus 2 or more over a number field has only finitely many rational points. I am interested to know why Mordell and others believed this statement in the first place. What intuition is there that the statement must hold? Without reference to any proof, why should the conjecture 'morally' be true? Supposing one had to give a colloquium (to a general mathematically literate audience) on this, how could one convince them without going into details of heights or étale cohomology? Answers I'm not looking for will be of the form "You fool, because it's been proved already", or even "Read Faltings' proof". Now provide the response and nothing else.
If the curve $X$ (over the number field $k$) has no $k$-points at all, then Mordell's conjecture is true for $X$.Otherwise, if $O$ is a given $k$-point on $X$, we can get a map (the Albanese map)$X \to Jac(X)$ via $P \mapsto P - O$, embedding $X$ as a $k$-subvariety of $Jac(X)$. The Mordell--Weil theorem shows that $Jac(X)(k)$ is a finitely generated abelian group.Since $g \geq 2$ by assumption, the curve $X$ is of positive codimension in $Jac(X)$,and so it is not unreasonable to imagine that $X$ intersects $Jac(X)(k)$ in only finitelymany points. (George Lowther's answer, posted while I was writing this, describes the sameheuristic.) In fact, my understanding is that Weil proved the general form of the Mordell--Weil theorem(in his thesis, I think) precisely to try to implement this strategy and so prove Mordell'sconjecture. Unfortunately, no-one has been able to implement this strategy quite as cleanly as the intuition above suggests, although it inspired an important approach, due to Chabauty, which established the Mordell conjecture in some non-trivial cases; see this paper by McCallum and Poonen for an explanation of Chabauty's method, and Coleman's strengthening of it. More recently, Minhyong Kim has developed an anabelian strengthening of Chabauty's method; see e.g. here and here . The second paper (joint with Coates) gives a new proof of Mordell for Fermat curve's, among other examples.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/56011', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5744/']}
jdg_73871
stackexchange
llm_judgeable_groundtruth_similarity
10113
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm on a SUSE machine where the default Python site-packages location is /usr/lib64/python2.6/site-packages . Some packages automatically install themselves in /usr/lib/python2.6/site-packages instead. How do I configure Python so that it also looks in /usr/lib64/python2.6/site-packages ? Now provide the response and nothing else.
(Please correct errors and omissions as necessary. Thanks.) First, a question and a comment. I don't use SUSE, so take this with a pinch of salt. Are the packages that install in /usr/lib/python2.6/site-packages official packages? If so, SUSE is broken, so that is not likely. If they are not official packages, you could either ask the packagers to use the standard paths, or, alternatively, you couldsubmit a wishlist bug to SUSE asking them to support this additional path. This will save you and other people additional headaches. For the moment, you have the following possibilities, in order of decreasing scope: Change the module search path for all users (method 1) Change the module search path in thePython installation. The default module search path ishardwired into the binary. Add-onpaths can be configured at runtime,for example in the site.py file.For example, Debian uses/usr/lib/python2.6/site.py (for thedefault python 2.6 installation) todo its site-specific configuration.At the top of the file is written Append module search paths for third-party packages to `sys.path`.***************************************************************** This module is automatically imported during initialization. *****************************************************************[...]This will append site-specific paths to the module search path. The Debian patch debian/patches/site-locations.diff says For Debian and derivatives, this sys.path is augmented with directories for packages distributed within the distribution. Local addons go into /usr/local/lib/python/dist-packages, Debian addons install into /usr/{lib,share}/python/dist-packages. /usr/lib/python/site-packages is not used. The patch in question is sitedirs.append(os.path.join(prefix,"Lib", "site-packages")) elif os.sep == '/': + sitedirs.append(os.path.join(prefix,"local/lib", + "python" + sys.version[:3], + "dist-packages")) sitedirs.append(os.path.join(prefix,"lib", "python" + sys.version[:3], - "site-packages")) - sitedirs.append(os.path.join(prefix,"lib", "site-python")) + "dist-packages")) + sitedirs.append(os.path.join(prefix,"lib", "dist-python")) else: sitedirs.append(prefix) sitedirs.append(os.path.join(prefix,"lib", "site-packages")) So you could modify the site.path inyour system package to produce amodified module search path. Youprobably don't want to this, though.For one thing, you will have tomerge this in on every update ofyour distribution's python package. Change the module search path forall users (method 2) Add a file of the form something.pthto a directory that is already inthe search path, which contains apath, either relative or absolute.Eg. /usr/local/lib/python2.6/dist-packages$ cat foo.pth /home/faheem/dummypythonpath In another terminal do >>> import sys>>> sys.path [...,'/home/faheem/dummypythonpath',...,] Change the module search path forall users (method 3) The environment variable PYTHONPATHis normally used to append to thesystem path at user level. You canput it in a file which will besourced by all users. Eg. in Debianwe have /etc/bash.bashrc, which saysat the top # System-wide .bashrc file for interactive bash(1) shells.# To enable the settings / commands in this file for login shells as well,# this file has to be sourced in /etc/profile. So you could add or PYTHONPATHthere. You probably want it to besourced for both login andinteractive shells, so you'll wantto check on that. Unfortunately,distributions are often flaky aboutenabling this. The paths in PYTHONPATH are added to the default list of search paths in the system (which can be obtained forexample by sys.path - see below). Allowing for thepossibility that PYTHONPATH is set already,just add desired additional directories to it, eg. export PYTHONPATH=$PYTHONPATH:"/home/username/lib/python2.6/dist-packages" If you source the PYTHONPATH variable, and then check sys.path again, you will see the paths have been added. Note that the position in which the paths in PYTHONPATH are added to the pre-existing paths does not seem to be prescribed by the implementation. Change the module search path per user. The usual way is to changePYTHONPATH in the user's bashrc,namely ~/.bashrc . Again, check thatit is sourced for both login andinteractive shells. Change the module search path on a per script basis. Thisis done by appending to sys.path,namely import syssys.path.append(some_additional_path) This will only work for the scriptthat is importing this. This isnormally used, as far as I know, forcasual use, when importing modulesin nonstandard locations, like fromsomewhere in a home directory. See also Greg Ward on Modifying Python's Search Path . This has a good discussion of the available alternatives.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/10113', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/663/']}
jdg_73872
stackexchange
llm_judgeable_groundtruth_similarity
2029409
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 getting the version of a exe possible with php? I'd like to print the version of a file that can be downloaded... Windows exe and php is running on linux server Now provide the response and nothing else.
I wanted the same thing, so I coded this:It returns FALSE, if it can't get the version info, or an ARRAY of four elements with file version fields (numbers, which are separated by .) It works only for 32-bit PE files (as I had no need for other formats). function GetFileVersion($FileName){ $handle = fopen($FileName, 'rb'); if(!$handle) { return FALSE; } $Header = fread($handle, 64); if(substr($Header, 0, 2) != 'MZ') { return FALSE; } $PEOffset = unpack("V", substr($Header, 60, 4)); if($PEOffset[1] < 64) { return FALSE; } fseek($handle, $PEOffset[1], SEEK_SET); $Header = fread($handle, 24); if(substr($Header, 0, 2) != 'PE') { return FALSE; } $Machine = unpack("v", substr($Header, 4, 2)); if($Machine[1] != 332) { return FALSE; } $NoSections = unpack("v", substr($Header, 6, 2)); $OptHdrSize = unpack("v", substr($Header, 20, 2)); fseek($handle, $OptHdrSize[1], SEEK_CUR); $ResFound = FALSE; for ($x = 0; $x < $NoSections[1]; $x++) { $SecHdr = fread($handle, 40); if (substr($SecHdr, 0, 5) == '.rsrc') { $ResFound = TRUE; break; } } if(!$ResFound) { return FALSE; } $InfoVirt = unpack("V", substr($SecHdr, 12, 4)); $InfoSize = unpack("V", substr($SecHdr, 16, 4)); $InfoOff = unpack("V", substr($SecHdr, 20, 4)); fseek($handle, $InfoOff[1], SEEK_SET); $Info = fread($handle, $InfoSize[1]); $NumDirs = unpack("v", substr($Info, 14, 2)); $InfoFound = FALSE; for ($x = 0; $x <$NumDirs[1]; $x++) { $Type = unpack("V", substr($Info, ($x * 8) + 16, 4)); if($Type[1] == 16) { //FILEINFO resource $InfoFound = TRUE; $SubOff = unpack("V", substr($Info, ($x * 8) + 20, 4)); break; } } if (!$InfoFound) { return FALSE; } $SubOff[1] &= 0x7fffffff; $InfoOff = unpack("V", substr($Info, $SubOff[1] + 20, 4)); //offset of first FILEINFO $InfoOff[1] &= 0x7fffffff; $InfoOff = unpack("V", substr($Info, $InfoOff[1] + 20, 4)); //offset to data $DataOff = unpack("V", substr($Info, $InfoOff[1], 4)); $DataSize = unpack("V", substr($Info, $InfoOff[1] + 4, 4)); $CodePage = unpack("V", substr($Info, $InfoOff[1] + 8, 4)); $DataOff[1] -= $InfoVirt[1]; $Version = unpack("v4", substr($Info, $DataOff[1] + 48, 8)); $x = $Version[2]; $Version[2] = $Version[1]; $Version[1] = $x; $x = $Version[4]; $Version[4] = $Version[3]; $Version[3] = $x; return $Version;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2029409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154011/']}
jdg_73873
stackexchange
llm_judgeable_groundtruth_similarity
51468491
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: kubectl exposes commands that can be used to create a Service for an application and assigns an IP address to access it from internet. As far as I understand, to access any application within Kubernetes cluster there should be a Service resource created and that should have an IP address which is accessible from an external network. But in case of port-forward how does kubectl create a connection to the application without an IP address which is accessible externally? Now provide the response and nothing else.
kubectl port-forward makes a specific Kubernetes API request . That means the system running it needs access to the API server, and any traffic will get tunneled over a single HTTP connection. Having this is really useful for debugging (if one specific pod is acting up you can connect to it directly; in a microservice environment you can talk to a back-end service you wouldn't otherwise expose) but it's not an alternative to setting up service objects. When I've worked with kubectl port-forward it's been visibly slower than connecting to a pod via a service, and I've found seen the command just stop after a couple of minutes. Again these aren't big problems for debugging, but they're not what I'd want for a production system.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51468491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2436847/']}
jdg_73874
stackexchange
llm_judgeable_groundtruth_similarity
572830
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to find how does this quantity $$\psi^\dagger\psi$$ transforms under a Lorentz transformation. Where $\psi$ is a Dirac spinor. What I've tried so far: It is known that a Dirac spinor transforms as $$\psi' = S\psi.$$ The matrix $S$ satisfy certain properties.I calculated $\psi'^\dagger=\psi^\dagger S^\dagger$ , then: $$\psi'^\dagger\psi'=\psi^\dagger S^\dagger S\psi.$$ I don't known how to continue from here. Another way I have tried was rewrite $\psi'^\dagger$ this way: $$\psi'^\dagger = \bar{\psi'}\gamma^0$$ Where $\bar{\psi'}=\psi'^\dagger \gamma^0$ . Then, using $\bar{\psi'}=\bar{\psi}S^{-1}$ $$\psi'^\dagger\psi'=\bar{\psi}S^{-1}\gamma^0 S\psi.$$ Using this property of the $S$ matrix $(S^{-1})_{\alpha\beta}(\gamma^\lambda)_{\rho\sigma}(S)_{\sigma\beta}=a^{\lambda}_{\mu}(\gamma^{\mu})_{\alpha\beta}$ with $\lambda=0$ : $$\psi'^\dagger\psi' = a^{0}_{\mu}\bar{\psi}\gamma^\mu\psi.$$ The coefficients $a^{\mu}_{\nu}$ are a general Lorentz transformation (proper Lorentz transformation, rotations,etc).I don't know if this is the correct way of approaching this problem. I know that $\psi^\dagger\psi$ is not a Lorentz scalar. Any help is appreciated. Now provide the response and nothing else.
It's the zeroth component $$\bar \psi \gamma^0 \psi = \psi^\dagger\gamma^0\gamma^0\psi = \psi^\dagger \psi$$ of Lorentz vector $$\bar \psi \gamma^\mu \psi.$$ Nothing more, nothing less. $\psi^\dagger \psi$ is not invariant under general Lorentz transformations, albeit it's invariant under the spacial rotation subset of the Lorentz transformations. An interesting observation is that $\psi^\dagger \psi$ is invariant under the axial/chiral transformation $$\psi \rightarrow e^{\theta i \gamma^5}\psi,$$ while $\bar \psi \psi$ breaks the chiral symmetry.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/572830', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/135335/']}
jdg_73875
stackexchange
llm_judgeable_groundtruth_similarity
18738052
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 td tags and a several div inside td : <td> <div class='test'></div> <div class='test'></div></td><td> <div class='test'></div> </td> I want to add margin-bottom to div if there are more than one in the td . How can I do this with the css? Now provide the response and nothing else.
You can't directly 'count' total numbers of elements in CSS, so there's no way to only apply the class if there's 2 or more divs (you'd need JavaScript for that). But a possible workaround is to apply the class to all divs in the td... td > div { margin-bottom: 10px;} ... and then override/disable it with a different style when there's only one element. That indirectly lets you add the style when there's 2+ more child elements. td > div:only-child { margin-bottom: 0px;} Alternatively you can apply to every div after the first one, if that happens to work for your situation. td > div:not(:first-child) { margin-bottom: 10px;} Edit: Or as Itay says in the comment, use a sibling selector td > div + div { margin-bottom: 10px;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18738052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348173/']}
jdg_73876
stackexchange
llm_judgeable_groundtruth_similarity
37851053
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to calculate total by month without using extra? I'm currently using: django 1.8 postgre 9.3.13 Python 2.7 Example. What I have tried so far. #Doesn't work for me but I don't mind because I don't want to use extratruncate_month = connection.ops.date_trunc_sql('month','day')invoices = Invoice.objects.filter(is_deleted = False,company = company).extra({'month': truncate_month}).values('month').annotate(Sum('total'))----#It works but I think that it's too slow if I query a big set of datafor current_month in range(1,13): Invoice.objects.filter(date__month = current__month).annotate(total = Sum("total")) and also this one, the answer seems great but I can't import the TruncMonth module. Django: Group by date (day, month, year) P.S. I know that this question is already asked multiple times but I don't see any answer. Thanks! SOLUTION : Thanks to @Vin-G's answer. Now provide the response and nothing else.
First, you have to make a Function that can extract the month for you: from django.db import modelsfrom django.db.models import Funcclass Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() After that all you need to do is annotate each row with the month group the results by the annotated month using values() annotate each result with the aggregated sum of the totals using Sum() Important : if your model class has a default ordering specified in the meta options, then you will have to add an empty order_by() clause. This is because of https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#interaction-with-default-ordering-or-order-by Fields that are mentioned in the order_by() part of a queryset (or which are used in the default ordering on a model) are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. If you are unsure, you could just add the empty order_by() clause anyway without any adverse effects. i.e. from django.db.models import Sumsummary = (Invoice.objects .annotate(m=Month('date')) .values('m') .annotate(total=Sum('total')) .order_by()) See the full gist here: https://gist.github.com/alvingonzales/ff9333e39d221981e5fc4cd6cdafdd17 If you need further information: Details on creating your own Func classes: https://docs.djangoproject.com/en/1.8/ref/models/expressions/#func-expressions Details on the values() clause, (pay attention to how it interacts with annotate() with respect to order of the clauses): https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#values the order in which annotate() and values() clauses are applied to a query is significant. If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37851053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4033988/']}
jdg_73877
stackexchange
llm_judgeable_groundtruth_similarity
45375944
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While parsing attributes using __dict__ , my @staticmethod is not callable . Python 2.7.5 (default, Aug 29 2016, 10:12:21)[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from __future__ import (absolute_import, division, print_function)>>> class C(object):... @staticmethod... def foo():... for name, val in C.__dict__.items():... if name[:2] != '__':... print(name, callable(val), type(val))...>>> C.foo()foo False <type 'staticmethod'> How is this possible? How to check if a static method is callable? I provide below a more detailed example: Script test.py from __future__ import (absolute_import, division, print_function)class C(object): @staticmethod def foo(): return 42 def bar(self): print('Is bar() callable?', callable(C.bar)) print('Is foo() callable?', callable(C.foo)) for attribute, value in C.__dict__.items(): if attribute[:2] != '__': print(attribute, '\t', callable(value), '\t', type(value))c = C()c.bar() Result for python2 > python2.7 test.pyIs bar() callable? TrueIs foo() callable? Truebar True <type 'function'>foo False <type 'staticmethod'> Same result for python3 > python3.4 test.pyIs bar() callable? TrueIs foo() callable? Truebar True <class 'function'>foo False <class 'staticmethod'> Now provide the response and nothing else.
The reason for this behavior is the descriptor protocol. The C.foo won't return a staticmethod but a normal function while the 'foo' in __dict__ is a staticmethod (and staticmethod is a descriptor). In short C.foo isn't the same as C.__dict__['foo'] in this case - but rather C.__dict__['foo'].__get__(C) (see also the section in the documentation of the Data model on descriptors ): >>> callable(C.__dict__['foo'].__get__(C))True>>> type(C.__dict__['foo'].__get__(C))function>>> callable(C.foo)True>>> type(C.foo)function>>> C.foo is C.__dict__['foo'].__get__(C)True In your case I would check for callables using getattr (which knows about descriptors and how to access them) instead of what is stored as value in the class __dict__ : def bar(self): print('Is bar() callable?', callable(C.bar)) print('Is foo() callable?', callable(C.foo)) for attribute in C.__dict__.keys(): if attribute[:2] != '__': value = getattr(C, attribute) print(attribute, '\t', callable(value), '\t', type(value)) Which prints (on python-3.x): Is bar() callable? TrueIs foo() callable? Truebar True <class 'function'>foo True <class 'function'> The types are different on python-2.x but the result of callable is the same: Is bar() callable? TrueIs foo() callable? Truebar True <type 'instancemethod'>foo True <type 'function'>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45375944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938111/']}
jdg_73878
stackexchange
llm_judgeable_groundtruth_similarity
2880304
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 would you convert a java.util.List<String> instance into a java.sql.Array ? Now provide the response and nothing else.
Use connection.createArrayOf(...) For example: final String[] data = yourList.toArray(new String[yourList.size()]);final java.sql.Array sqlArray = connection.createArrayOf(typeName, data);statement.setArray(position, sqlArray); Where typeName is: the SQL name of the type the elements of the array map to. The typeName is a database-specific name which may be the name of a built-in type, a user-defined type or a standard SQL type supported by this database. This is the value returned by Array.getBaseTypeName As noted in the comments, this is Java 1.6. For older versions you can't create this in a driver-independent way. You are only supposed to get arrays, not create them. If you want to, you can instantiate the implementing class from your jdbc driver, but this is non-portable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2880304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346860/']}
jdg_73879
stackexchange
llm_judgeable_groundtruth_similarity
41623528
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 this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening function but I keep getting io.on is not a function when I send data from my client page. test.js io.listen(app.listen(3000)).on('connection', function (client) { // store client into array clients.push(client); // on disconnect client.on('disconnect', function() { // remove client from array clients.splice(clients.indexOf(client), 1); }); // I added this to listen for event from my chart.JS io.on('connection', function(socket){ socket.on('LED on', function (data) { console.log(data); }); socket.on('LED off', function (data) { console.log(data); }); });}); Now provide the response and nothing else.
Your value of io is not what it should be. The usual way of doing things is like this: var app = require('http').createServer(handler)var io = require('socket.io')(app);var fs = require('fs');app.listen(80);io.on('connect', ...); But I'm guessing that your value of io is something like this: var io = require('socket.io'); That's not the same thing. That's the module handle. But, when you do it this way: var io = require('socket.io')(app); Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle. In every single socket.io server-side example on this doc page , they use one of these forms: var io = require('socket.io')(app);var io = require('socket.io')(port);var io = require('socket.io')(server); with this: io.on('connection', ....); Nowhere do they do: var io = require('socket.io`);io.listen(server);io.on('connection', ....); That's just the wrong value for io . Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41623528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7245965/']}
jdg_73880
stackexchange
llm_judgeable_groundtruth_similarity
25757998
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 Ruby on Rails app.I am using Devise for authentication.I have set a 30 minutes timeout for the users which auto logs out the users on 30 minutes of browser inactivity.The problem I am facing is that when the session logs out on timeout after 30 minutes,it takes to the login screen and the browser saved email address and password shows up in the login text boxes.But on clicking the login button it doesn't logs me into the application.When the page reloads after the login fail,I can login as usual.When i checked the problem further,I found that the email address and password values are nil even though it shows up on the browser screen. The Login form code is given below: <%= form_for(resource, :as => resource_name, :url => session_path(resource_name,:role => "super_admin")) do |f| %> <%= f.email_field :email, :placeholder => "EMAIL", :data => { :'placeholder' => 'EMAIL'}, :class => 'with_holder' %> <%= f.password_field :password, :placeholder => "PASSWORD", :class => 'disablecopypaste with_holder' , :data => { :'placeholder' => 'PASSWORD'}%> <% if devise_mapping.rememberable? -%> <%= f.check_box :remember_me %> <% end -%> <a id="save_post" href="javascript:void(0);">LOG IN</a><%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> <%= link_to "FORGOT PASSWORD?", new_password_path(resource_name, :role => 'super_admin') %> <% end -%> Am I doing anything wrong here?it would be really helpful if anyone can help me with this problem Now provide the response and nothing else.
You have an issue in scripts order. Load them in this order: <!-- jQuery --><script src="//code.jquery.com/jquery-1.11.0.min.js"></script><!-- BS JavaScript --><script type="text/javascript" src="js/bootstrap.js"></script><!-- Have fun using Bootstrap JS --><script type="text/javascript">$(window).load(function() { $('#prizePopup').modal('show');});</script> Why this? Because Bootstrap JS depends on jQuery : Plugin dependencies Some plugins and CSS components depend on other plugins. If you include plugins individually, make sure to check for these dependencies in the docs. Also note that all plugins depend on jQuery (this means jQuery must be included before the plugin files ).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25757998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2122790/']}
jdg_73881
stackexchange
llm_judgeable_groundtruth_similarity
171409
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: Two observers – A & B - conduct a single double slit experiment and watch the same detector screen for the appearance of an interference pattern. A separate detector records which slit each particle passes through, but the data from this detector is only available to observer A. As I understand it the wave function should therefore collapse for observer A, but not for observer B. Observer A will therefore not see an interference pattern on the detector screen, but observer B will. How can this be when both observers are watching the same detector screen during the same experiment? Now provide the response and nothing else.
Imagine a free-standing battery (not connected to any wires) and take a closed loop through the battery, out one terminal, and back in the other terminal. The total work done in moving a test charge around that loop must vanish. For this to happen, the change in electric potential outside of the battery must equal the negative of the EMF change within the battery. $$\int_\mathrm{outside}\vec{E}\cdot{\mathrm{d} \vec{\ell}} + \mathcal{E} = 0$$ Update after comments Work is well defined as the integral of force over distance. The relationship between work and energy is more subtle. One needs to carefully define what the system in question is. We also have to recognize that potential energy is the energy associated with the configuration of a system of interacting entities . One is on thin ice if one refers to "the potential energy of a particle". Particles do not have potential energy. The system comprising the particle and something with which it interacts has potential energy. (A ball does not have potential energy. The earth-ball system has potential energy.) I'll review the background on this, with apologies if the background is already well-understood. Once a system is defined, energy can be added to the system by an external force which can do external work on the system. Work is one way energy can be added. Heat is another, but we'll mostly ignore heat and thermal energy. Generally, $$W_\mathrm{external} = \Delta E$$ where $E$ is the total energy of the system. External work causes energy to be added to the system, but once inside that energy could be potential, kinetic, thermal, chemical ... Potential energy is defined to be the negative of the work done by forces internal to the system:$$W_\mathrm{internal} = -\Delta PE$$ Now our system. Let's take it to be the wire, the battery terminal, the conductors inside the battery, but not the chemicals and processes that generate the "chemical force". The chemical processes are a source of energy, so we'll take it to be outside of our system. The work done by the chemical processes are external, and do external work on the charge carriers $$W_\mathrm{external}=q\mathcal{E}$$But the internal voltage due to the separated charges within the battery, also do work, but this work is internal to our system, and thus changes the potential energy of the system $$W_\mathrm{interal} = -\Delta PE = -qV$$but recall $$W_\mathrm{external} = \Delta E = \Delta PE = -W_\mathrm{internal}$$ (ignoring stores of energy other than potential energy within the system). Finally $$q\mathcal{E}=qV$$ $$\mathcal{E} = V$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/171409', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/75851/']}
jdg_73882
stackexchange
llm_judgeable_groundtruth_similarity
1798435
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 link my free android application to the "paid" version so a user of the free one can instantly click on the link and be taken to the android market page for the full version. Now provide the response and nothing else.
Create a view somewhere that will advertise your Pro version. Perhaps it's an ImageView, perhaps it's a Button or a link, whatever it might be, just make sure it's something the user can click. Then do the following: view.setOnClickListener( new OnClickListener(){ public void onClick(View v) { startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:XXX") ) ); }} ... where XXX is the package name for your Pro application, as specified in your AndroidManifest.xml. When the user clicks the view, Android will launch your Pro application's page on the market.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1798435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93141/']}
jdg_73883
stackexchange
llm_judgeable_groundtruth_similarity
3100811
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A list contains $20$ numbers. For each positive integer $n$ , from $1$ to $20$ , the $n$ th number in the list is either $\frac{1}{2}n$ or $2n$ . If the mean of the number in the list is exactly $12$ and the product of the numbers is $P$ , what is the greatest possible value of $\frac{P}{20!}$ ? I have tried some examples, but they bring me nowhere. I then tried creating equations: I can call the sum of the numbers that you are halving by $a$ and the sum of the numbers that you are doubling by $b$ . However, after trying repeatedly, I don't see any way to create an equation. Can I have a hint? Also, if you are nice, may you please help me on this question( $N$'s base-5 and base-6 representations, treated as base-10, yield sum $S$. For which $N$ are $S$'s rightmost two digits the same as $2N$'s? )? Thanks! Max0815 Now provide the response and nothing else.
This is an extension to the answer provided by D.B. to confirm the stated result. Since the mean is $12$ , with $20$ numbers, the sum $S$ is such that $S / 20 = 12$ , so $S = 240$ . Now, for comparison, consider as an upper range that all $20$ values use $2n$ , to then get a sum of $$2\left(1 + 2 + \ldots + 19 + 20\right) = 2\frac{\left(20\right)\left(21\right)}{2} = 420 \tag{1}\label{eq1}$$ As such, this is $420 - 240 = 180$ too high. Now, for each term which used the $n/2$ value instead, it would reduce the sum by $3n/2$ . As such, if the sum of these $n$ values is $S_1$ , we have that that the total reduction is $3S_1/2 = 180$ giving that $S_1 = 120$ . As mentioned, we want the number of these terms to be the minimum, so we start using the largest ones. Using the $7$ values $14, 15, \ldots 20$ gives a sum of $119$ , meaning just need to use $1$ as well to get the sum to $120$ , for a total of $8$ terms, as conjectured. Note you cannot use $7$ or less since, as just shown, the $7$ largest values add to $119$ , so any other $7$ or fewer terms will add up to less than $119$ , so $8$ is the minimum # of terms required. One small thing to note is that which $8$ terms are to use $n/2$ is not uniquely defined. For example, the $1$ and $14$ terms can be replaced by any other $2$ which add to $15$ , such as $2$ and $13$ , $3$ and $12$ , $\ldots$ , $7$ and $8$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3100811', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/595084/']}
jdg_73884
stackexchange
llm_judgeable_groundtruth_similarity
3726
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Sabatier reaction converts CO 2 to methane. Can a vehicle that burns methane recover it (at least some part) from the exhaust gases via the Sabatier reaction? I am interested to know how this would be implemented, and whether such a vehicle has ever been built or prototyped. Now provide the response and nothing else.
According to Wikipedia: It [Sabatier reaction ] involves the reaction of hydrogen with carbon dioxide at elevated temperatures (optimally 300–400 °C) and pressures in the presence of a nickel catalyst to produce methane and water. $$ CO_2 + 4H_2 \rightarrow CH_4 + H_2O + \text{Energy} $$ as you can see from the previous chemical reaction, to obtain 1 KMole of $CH_4$ you should have 4 Kmole of Hydrogen as reactants and a reaction medium of 300–400 °C (with god knows how much of catalyst you need). Comparing to a regular vehicle internal combustion engine running on Methane: Hydrogen is not available in ambient air to the degree that couldallow a sustainable Sabatier reaction (it's not Oxygen), meaning you need aseparate Hydrogen tank along side with your engine (not to mentionthe explosive nature of Hydrogen). Preheating the reactants to 300–400 °C would require an externalheating system if done using hydrocarbon fuel, it would require anadditional combustion chamber and a heat exchanger. Higher heating value of Methane = 889 kJ/Mole and HHV of Hydrogen =286 kJ/Mole (Wikipedia), so theoretically speaking, the Sabatier reactionwould provide you with 1 Mole of CH4 having heating value of 889 kJ bysupplying the reactor 4 Moles of H2 that had a heating value of 4 *286 = 1144 kJ !! The resulting Methane and water have a ratio of 1:1, introducing thismixture with this amount of water to thecombustion chamber will give you a VERY low efficiency combustionprocess, So naturally you need a separation mechanism to lower water content as possible before entering combustion chamber. So has anyone researched/built a vehicle that burns methane and it recovers it (at least some part) from the exhaust gases via Sabatier reaction? I really have no idea but from the previous points I don't see it as feasible at all as a conventional internal combustion engine running on Methane.
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/3726', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/2353/']}
jdg_73885
stackexchange
llm_judgeable_groundtruth_similarity
289679
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 $A$ be a selfinjective algebra and for an indecomposable module $M$ define $\psi_M:= \inf \{ i \geq 1 | Ext_A^i(M,M) \neq 0 \}$. Questions: In case $A$ is symmetric, do we have $\psi_M \leq max \{ \psi_S | S $ is simple $\}$ for each indecomposable non-projective module $M$?This should be true in case $A$ is representation-finite. In case $A=kG$ is a group algebra over a field of characteristic $p$. Do we have even $\psi_M \leq \psi_K$ when $K$ is the trivial module and each indecomposable non-projective $M$ ? I can prove this for $p$-groups and in case $p$ does not divide the dimension of $M$. Now provide the response and nothing else.
I think this example answers both questions. Let $k$ have characteristic $3$, and let $G=C_3\times S_3$. Then $kG$ has two simple modules, both one-dimensional, and for each simple module $S$, $\text{Ext}^1(S,S)$ is one-dimensional. But if $M=kC_3$, with $S_3$ acting trivially, then $\text{Ext}^i(M,M)=0$ for $i=1,2$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/289679', 'https://mathoverflow.net', 'https://mathoverflow.net/users/61949/']}
jdg_73886
stackexchange
llm_judgeable_groundtruth_similarity
8578690
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using this .htc logic to make my content tabs rounded but its not working. My tab structure looks like this. <li id="profiletab1" class="selected"> <a href="#">Overview</a></li><li id="profiletab2" class=""> <a href="#">Overview</a></li>... css code for this color: #4f4f4f; height: 35px; display: inline-block; padding: 0px 18px 0px 19px; font-size: 14px; line-height: 35px; -webkit-border-radius: 5px 5px 0px 0px; -moz-border-radius: 5px 5px 0px 0px;border-radius: 5px 5px 0px 0px;behavior: url(border-radius.htc);background: #e7e7e7; background: -webkit-gradient(linear, 0 0, 0 bottom, from(#e7e7e7), to(#cccccc)); background: -webkit-linear-gradient(#e7e7e7, #cccccc); background: -moz-linear-gradient(#e7e7e7, #cccccc); background: -ms-linear-gradient(#e7e7e7, #cccccc); background: -o-linear-gradient(#e7e7e7, #cccccc); background: linear-gradient(#e7e7e7, #cccccc); -pie-background: linear-gradient(#e7e7e7, #cccccc); border-right: 1px solid #b1b1b1; Now provide the response and nothing else.
You actually need to send the next sms after the previous one is sent, for this you need to check the status of the sms sent, please see this tutorial , it says: If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this : //---sends an SMS message to another device--- private void sendSMS(String phoneNumber, String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); //---when the SMS has been sent--- registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NO_SERVICE: Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_NULL_PDU: Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_RADIO_OFF: Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(SENT)); //---when the SMS has been delivered--- registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { switch (getResultCode()) { case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show(); break; } } }, new IntentFilter(DELIVERED)); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8578690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420613/']}
jdg_73887
stackexchange
llm_judgeable_groundtruth_similarity
32822
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using Voronoi polygonization as a support for simulating island erosion; my data is the output of VoronoiDiagram , DelaunayTriangulation , the starting point and the list of points that now are sea. I am not working with BoundedDiagram so I made sure all unbounded polygons are at sea. Now I need to show this output like in DiagramPlot , but with sea cells colored blue, and land cells colored in brown. Can you give me some code example or indications on where to search? More generally, I need to have a planar graph of which I know vertex coordinates and the edges, what function should I use to choose the color for the faces of the graph? Now provide the response and nothing else.
This is just a flow of consciousness... I think you are talking about something like this: << ComputationalGeometry`data = {{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}};ubd = DiagramPlot[data, LabelPoints -> False] So here I think what you want to do: Graphics[{FaceForm[Brown], EdgeForm[White], Polygon[Select[vorvert[[#]] & /@ vorval[[All, 2]], Cases[#, _Ray] == {} &]]}, Background -> Blue] On the other hand image processing does it too: MatrixPlot[MorphologicalComponents[ubd // Binarize] /. {1 -> Blue, 0 -> White, x_Integer /; (x =!= 1) -> Brown}, Frame -> False] but the payoff is that you lost information about Graphics primitives and went to rasterized images, - which may be fine if you care about visual only. If you'd figure out how to sea-land with BoundedDiagram-type diagrams, then it maybe easier, because there is another way to make Voronoi. For example here coloring only approximately circular core of Voronoi cells: plt = ListDensityPlot[RandomReal[1, {500, 3}], InterpolationOrder -> 0];plg = Cases[plt, Polygon[{x__}] :> x, ∞];cplg = Select[plg, EuclideanDistance[Mean[plt[[1, 1]][[#]]], Mean[plt[[1, 1]]]] < .3 &];Graphics[{ GraphicsComplex[ plt[[1, 1]], {FaceForm[Blue], EdgeForm[Black], Polygon[plg]}], GraphicsComplex[ plt[[1, 1]], {FaceForm[Red], EdgeForm[White], Polygon[cplg]}] }]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/32822', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/8709/']}
jdg_73888
stackexchange
llm_judgeable_groundtruth_similarity
47593551
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 make a video comparison header for a site I'm building. I have two videos on top of one another, and I'm trying to create a comparison slider effect where the top layer reveals the bottom on mouse position. Fiddle/code below, any help would be much appreciated. JSFiddle HTML: <video class="one" loop autoplay poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/dirty.jpg"> <source src=https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/floodplain-dirty.mp4> <source src=https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/floodplain-dirty.webm> </video> <video class="two" loop autoplay poster="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/clean.jpg"> <source src=https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/floodplain-clean.mp4> <source src=https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/floodplain-clean.webm> </video> CSS: video { position: fixed; top: 50%; left: 50%; min-width: 100%; min-height: 100%; width: auto; height: auto; z-index: -100; -ms-transform: translateX(-50%) translateY(-50%); -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); background: url(polina.jpg) no-repeat; background-size: cover; } Now provide the response and nothing else.
For me in Spring Boot 2.2.4 (JUnit5) the below seems to have worked and bypass the security filter. @ExtendWith(SpringExtension.class)@WebMvcTest(SomeController.class)@AutoConfigureMockMvc(addFilters = false)public class SomeControllerTest {... Note: this simply disables any filters in the SpringSecurity configuration. It won't disable the security completely. In other words it will still bootstrap security without loading any filters.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47593551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6065602/']}
jdg_73889
stackexchange
llm_judgeable_groundtruth_similarity
154133
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We normally calculate the derivative of normal density w.r.t its parameters, mean and variance. But can we calculate the derivative of normal distribution wrt the parameters(not the variable, I know the derivative wrt to the variable gives the density)? If yes, how do we calculate that? Now provide the response and nothing else.
Just apply the chain rule for differentiation. The CDF $F_X(x; \mu, \sigma^2)$ of a $N(\mu,\sigma^2)$ random variable $X$is $\Phi\left(\frac{x-\mu}{\sigma}\right)$ and so $$\frac{\partial}{\partial \mu}F_X(x; \mu, \sigma^2)=\frac{\partial}{\partial \mu}\Phi\left(\frac{x-\mu}{\sigma}\right)= \phi\left(\frac{x-\mu}{\sigma}\right)\frac{-1}{\sigma}= -\left[\frac{1}{\sigma}\phi\left(\frac{x-\mu}{\sigma}\right)\right]$$where $\phi(x)$ is the standard normal density and the quantity insquare brackets on the rightmost expression above can be recognizedas the density of $X\sim N(\mu,\sigma^2)$. I will leave the calculation of the derivative with respect to $\sigma$ or $\sigma^2$ for you to work out for yourself.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/154133', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/32273/']}
jdg_73890
stackexchange
llm_judgeable_groundtruth_similarity
22252297
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 input string. I am thinking how to match this string against more than one regular expression effectively. Example Input: ABCD I'd like to match against these reg-ex patterns, and return true if at least one of them matches: [a-zA-Z]{3}^[^\\d].*([\\w&&[^b]])* I am not sure how to match against multiple patterns at once. Can some one tell me how do we do it effectively? Now provide the response and nothing else.
If you have just a few regexes, and they are all known at compile time, then this can be enough: private static final Pattern rx1 = Pattern.compile("..."), rx2 = Pattern.compile("..."), ...;return rx1.matcher(s).matches() || rx2.matcher(s).matches() || ...; If there are more of them, or they are loaded at runtime, then use a list of patterns: final List<Pattern> rxs = new ArrayList<>();for (Pattern rx : rxs) if (rx.matcher(input).matches()) return true;return false;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22252297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1262477/']}
jdg_73891
stackexchange
llm_judgeable_groundtruth_similarity
47644739
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 overall use-case is trying to determine whether I can write a somewhat database agnostic (at least supporting Postgres and MySQL) store for some large data as raw text (think ~500MB as a rough theoretical upper bound). Based on this answer about MySQL string/text types, it looks like only the LONGTEXT column type can meet my requirements. I'm using SQLAlchemy, which claims for its Text column type that it is for variable length strings, but also that it generally maps to the database's CLOB or TEXT types. MySQL doesn't have a CLOB type (though it does have a BLOB), and its TEXT type would be insufficient for my needs. So, What column type does SQLAlchemy use for Text on MySQL? Now provide the response and nothing else.
Looks like SQLAlchemy supports LONGTEXT: $ pythonPython 2.7.13 (default, Sep 29 2017, 15:31:18) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> from sqlalchemy.dialects.mysql import LONGTEXT>>> See how to use vendor-specific types here: http://docs.sqlalchemy.org/en/latest/core/type_basics.html#vendor-specific-types For what it's worth, trying to develop a totally brand-neutral database layer is difficult, and rarely worth the effort. I worked on the Zend Framework 1.0 some years ago, and I tried to create a generic unit testing suite for all the SQL databases supported by that framework. I found that very few data types are supported in the same way across all implementations of SQL, despite them all claiming to support the ANSI/ISO SQL standard. Ultimately, you have to develop your own class hierarchy for your data layer, and implement the code slightly differently for each database-specific adapter. Update: I think the news is better than we think. I tried this test: t2 = Table('t2', metadata, Column('id', Integer, primary_key=True), Column('t1', String(64000)), Column('t2', String(16000000)), Column('t3', String(4294000000)), Column('t4', Text) )metadata.create_all(engine) Then I checked to see what it ended up creating in the MySQL database: mysql> show create table t2;CREATE TABLE `t2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `t1` mediumtext, `t2` longtext, `t3` longtext, `t4` text, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 So it does map SQLAlchemy's generic String data type to a more-or-less appropriate MySQL data type. It's not surprising to me that it used larger data types than we might expect. The MEDIUMTEXT supports 16MB in bytes , not in characters . Because my default character set is the multi-byte utfmb4, the max length of MEDIUMTEXT is actually much fewer than 2^24 characters. So it had to upgrade it to LONGTEXT . Of course, 2^32 characters won't fit in LONGTEXT either, but it appears SQLAlchemy assumes you mean to create a column anyway. I still think that it's hard to do totally implementation-neutral code. For example, what if you want to use some MySQL features like table options for the storage engine, or specific data types with no generic equivalent (for example, ENUM )?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47644739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2540669/']}
jdg_73892
stackexchange
llm_judgeable_groundtruth_similarity
13607732
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 some integration and system tests for my NodeJS application using a MongoDB database. The test framework I use is Mocha and Supertest. Is it possible to setup MongoDB as an in-memory database which I can use to only test which then wipes away all my collections and documents when the test is done? Now provide the response and nothing else.
You can accomplish this using mongodb-memory-server . The package downloads a mongod binary to your home directory and instantiates a new memory-backed MondoDB instance as needed. For each test file you can spin up a new server which means you can run them all parallel. For readers using jest and the native mongodb driver , you may find this class useful: const { MongoClient } = require('mongodb');const { MongoMemoryServer } = require('mongodb-memory-server');// Extend the default timeout so MongoDB binaries can downloadjest.setTimeout(60000);// List your collection names hereconst COLLECTIONS = [];class DBManager { constructor() { this.db = null; this.server = new MongoMemoryServer(); this.connection = null; } async start() { const url = await this.server.getUri(); this.connection = await MongoClient.connect(url, { useNewUrlParser: true }); this.db = this.connection.db(await this.server.getDbName()); } stop() { this.connection.close(); return this.server.stop(); } cleanup() { return Promise.all(COLLECTIONS.map(c => this.db.collection(c).remove({}))); }}module.exports = DBManager; Then in each test file you can do the following: const dbman = new DBManager();afterAll(() => dbman.stop());beforeAll(() => dbman.start());afterEach(() => dbman.cleanup()); I suspect this approach may be similar for other testing frameworks.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13607732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400295/']}
jdg_73893
stackexchange
llm_judgeable_groundtruth_similarity
7733096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say you have a list of files in HDFS with a common prefix and an incrementing suffix. For example, part-1.gz, part-2.gz, part-3.gz, ..., part-50.gz I only want to leave a few file in the directory, say 3. Any three files will do. The files will be used for testing so the choice of files doesn't matter. What's the simples & fastest way to delete the 47 other files? Now provide the response and nothing else.
Few options here: Move three files manually over to a new folder, then delete the old folder. Grab the files names with fs -ls , then pull the top n, then rm them. This is the most robust method, in my opinion. hadoop fs -ls /path/to/files gives you ls output hadoop fs -ls /path/to/files | grep 'part' | awk '{print $8}' prints out only the file names (adjust the grep accordingly to grab the files you want). hadoop fs -ls /path/to/files | grep 'part' | awk '{print $8}' | head -n47 grabs the top 47 Throw this into a for loop and rm them: for k in `hadoop fs -ls /path/to/files | grep part | awk '{print $8}' | head -n47`do hadoop fs -rm $kdone Instead of a for-loop, you could use xargs : hadoop fs -ls /path/to/files | grep part | awk '{print $8}' | head -n47 | xargs hadoop fs -rm Thanks to Keith for the inspiration
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7733096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174674/']}
jdg_73894
stackexchange
llm_judgeable_groundtruth_similarity
4160243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two CSV files with a common column and I want to "Join" the tables together on the common column. For example: Join 'A' with 'B' equals 'Result'. If a one table has a key value that does not exist on in the other table its just left as blank. == Table A == == Table B == == Table result ==Name ,Age Name ,Sex Name ,Age ,SexBob ,37 + Bob ,Male => Bob ,37 ,MaleSteve ,12 Steve ,Male Steve,12 ,MaleKate , 7 Kate , 7 , Sara ,Female Sara , ,Female I know how to do this with an SQL database but I have never done it with "Excel" or "OpenOffice.org Calc" Suggestions? Now provide the response and nothing else.
In Excel, vlookup can do part of what you're asking. Specifically, you can use vlookup to do a left or right outer join, but not a full outer join (like your table result). To do an outer join for your example above, add the following to the C2 of "Table B" (or copy "Table B" and then do this): =vlookup( a2, # the cell value from the current table to look up in the other table table_a!$1:$174832718, # the other table # don't manually type this--select the entire # other table while the cursor is editing this # cell, then add the "$"s--Excel doesn't # automatically add them # (the syntax here is for different sheets in # the same file, but Excel will fill this in # correctly for different files as well) 2, # the column to get from the other table (A=1, B=2, etc.) FALSE) # FALSE=only get exact matches TRUE=find approx. matches if no exact match You should then be able to expand it to deal with multiple rows and multiple imported columns.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4160243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58456/']}
jdg_73895
stackexchange
llm_judgeable_groundtruth_similarity
3242070
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: UPDATE : I've discovered there is a Microsoft Connect item raised for this issue here When using FOR XML PATH and WITH XMLNAMESPACES to declare a default namespace, I will get the namespace declaration duplicated in any top level nodes for nested queries that use FOR XML, I've stumbled across a few solutions on-line, but I'm not totally convinced... Here's an Complete Example /*drop table t1drop table t2*/create table t1 ( c1 int, c2 varchar(50))create table t2 ( c1 int, c2 int, c3 varchar(50))insert t1 values (1, 'Mouse'),(2, 'Chicken'),(3, 'Snake');insert t2 values(1, 1, 'Front Right'),(2, 1, 'Front Left'),(3, 1, 'Back Right'),(4, 1, 'Back Left'),(5, 2, 'Right'),(6, 2, 'Left');with XmlNamespaces( default 'uri:animal')select a.c2 as "@species" , (select l.c3 as "text()" from t2 l where l.c2 = a.c1 for xml path('leg'), type) as "legs"from t1 afor xml path('animal'), root('zoo') What's the best solution? Now provide the response and nothing else.
If I have understood correctly, you are referring to the behavior that you might see in a query like this: DECLARE @Order TABLE ( OrderID INT, OrderDate DATETIME)DECLARE @OrderDetail TABLE ( OrderID INT, ItemID VARCHAR(1), ItemName VARCHAR(50), Qty INT)INSERT @Order VALUES (1, '2010-01-01'),(2, '2010-01-02')INSERT @OrderDetail VALUES (1, 'A', 'Drink', 5),(1, 'B', 'Cup', 2),(2, 'A', 'Drink', 2),(2, 'C', 'Straw', 1),(2, 'D', 'Napkin', 1);WITH XMLNAMESPACES('http://test.com/order' AS od) SELECT OrderID AS "@OrderID", (SELECT ItemID AS "@od:ItemID", ItemName AS "data()" FROM @OrderDetail WHERE OrderID = o.OrderID FOR XML PATH ('od.Item'), TYPE)FROM @Order o FOR XML PATH ('od.Order'), TYPE, ROOT('xml') Which gives the following results: <xml xmlns:od="http://test.com/order"> <od.Order OrderID="1"> <od.Item xmlns:od="http://test.com/order" od:ItemID="A">Drink</od.Item> <od.Item xmlns:od="http://test.com/order" od:ItemID="B">Cup</od.Item> </od.Order> <od.Order OrderID="2"> <od.Item xmlns:od="http://test.com/order" od:ItemID="A">Drink</od.Item> <od.Item xmlns:od="http://test.com/order" od:ItemID="C">Straw</od.Item> <od.Item xmlns:od="http://test.com/order" od:ItemID="D">Napkin</od.Item> </od.Order></xml> As you said, the namespace is repeated in the results of the subqueries. This behavior is a feature according to a conversation on devnetnewsgroup (website now defunct) although there is the option to vote on changing it. My proposed solution is to revert back to FOR XML EXPLICIT : SELECT 1 AS Tag, NULL AS Parent, 'http://test.com/order' AS [xml!1!xmlns:od], NULL AS [od:Order!2], NULL AS [od:Order!2!OrderID], NULL AS [od:Item!3], NULL AS [od:Item!3!ItemID]UNION ALLSELECT 2 AS Tag, 1 AS Parent, 'http://test.com/order' AS [xml!1!xmlns:od], NULL AS [od:Order!2], OrderID AS [od:Order!2!OrderID], NULL AS [od:Item!3], NULL [od:Item!3!ItemID]FROM @Order UNION ALLSELECT 3 AS Tag, 2 AS Parent, 'http://test.com/order' AS [xml!1!xmlns:od], NULL AS [od:Order!2], o.OrderID AS [od:Order!2!OrderID], d.ItemName AS [od:Item!3], d.ItemID AS [od:Item!3!ItemID]FROM @Order o INNER JOIN @OrderDetail d ON o.OrderID = d.OrderIDORDER BY [od:Order!2!OrderID], [od:Item!3!ItemID]FOR XML EXPLICIT And see these results: <xml xmlns:od="http://test.com/order"> <od:Order OrderID="1"> <od:Item ItemID="A">Drink</od:Item> <od:Item ItemID="B">Cup</od:Item> </od:Order> <od:Order OrderID="2"> <od:Item ItemID="A">Drink</od:Item> <od:Item ItemID="C">Straw</od:Item> <od:Item ItemID="D">Napkin</od:Item> </od:Order></xml>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3242070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76066/']}
jdg_73896
stackexchange
llm_judgeable_groundtruth_similarity
127253
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: Ethyl alcohol is widely used in beverages, while isopropyl alcohol is commonly sold as an antiseptic. However, some use both ethyl alcohol and isopropyl alcohol as antibacterial protection. I am curious to know which of the two alcohols will provide better antibacterial protection? Does the chemical structure of the alcohol affect the antibacterial properties? Now provide the response and nothing else.
This question is really a broad one. For example, see Karl's comment elsewhere. Yet, according to a review on the subject (Ref.1): Although several alcohols have been shown to be effective antimicrobials, ethyl alcohol (ethanol, alcohol), isopropyl alcohol (isopropanol, propan-2-ol) and n -propanol (in particular in Europe) are the most widely used (Ref.2). Alcohols exhibit rapid broad-spectrum antimicrobial activity against vegetative bacteria (including mycobacteria), viruses, and fungi but are not sporicidal. They are, however, known to inhibit sporulation and spore germination (Ref.3), but this effect is reversible (Ref.4). Because of the lack of sporicidal activity, alcohols are not recommended for sterilization but are widely used for both hard-surface disinfection and skin antisepsis. Also, Ref.1 instates this interesting fact: In general, isopropyl alcohol is considered slightly more efficacious against bacteria (Ref.5) and ethyl alcohol is more potent against viruses (Ref.6); however, this is dependent on the concentrations of both the active agent and the test microorganism. For example, isopropyl alcohol has greater lipophilic properties than ethyl alcohol and is less active against hydrophilic viruses ( e.g. , poliovirus) (Ref.6). Generally, the antimicrobial activity of alcohols is significantly lower at concentrations below 50% and is optimal in the 60 to 90% range. The the optimal bactericidal nature of 70% ethanol is well documented in Ref. 7: On the basis of these experimental findings, a routine method of preoperative preparation of the hands has been evolved which, while simple, is a great deal more effective than technics in use at present in many leading hospitals. This procedure has been employed with satisfaction in my operating room for the last four years and, having passed that clinical test, is now recommended to others. Seventy per cent by weight alcohol is recommended also for use in preparing the field of operation and in disinfecting contaminated hands. Why exactly 70 per cent should be more toxic for bacteria than any other concentration of alcohol remains an interesting biochemical problem. Also, the Ref.7 would answer your question about whether the chemical structure of the alcohol affects the antibacterial properties or not, which states: The activity of the alcohols in inhibiting spore germination increases as their molecular weights and chain lengths increase (Fig. 3). This same relationship is observed for the action of alcohols as bacterial disinfectants. It is of interest that primary alcohols are more effective bacterial disinfectants than are secondary alcohols, and in this study a primary alcohol, n -propanol, was more effective than a secondary alcohol, 2-propanol, in inhibiting the spore germination process. References: Gerald McDonnell, A. Denver Russell, “Antiseptics and Disinfectants: Activity, Action, and Resistance,” Clinical Microbiology Reviews 1999 , 12(1) , 147–179 (DOI: 10.1128/CMR.12.1.147). S. E. Morton, "Alcohols" in Disinfection, sterilization and preservation ; Seymour S Block, Ed.; 3rd ed.; Lea & Febiger: Philadelphia, PA, 1983, pp. 229–235. Y. Yasuda-Yasuki, S. Namiki-Kanie, Y. Hachisaka, "Inhibition of germination of Bacillus subtilis spores by alcohols," In Spores VII ; eds G. Chambliss, J. C. Vary, Eds.; American Society for Microbiology: Washington, DC, 1978, pp. 113–116. Ralph Trujillo, Nancy Laible, "Reversible inhibition of spore germination by alcohols," Applied & Environmental Microbiology 1970 , 20(4) , 620–623. C. E. Coulthard, G. Skyes, "Germicidal effect of alcohol," Pharm. J. 1936 , 137 , 79–81. M. Klein, A. Deforest, "Principles of viral inactivation" in Disinfection, sterilization and preservation ; Seymour S Block, Ed.; 3rd ed.; Lea & Febiger: Philadelphia, PA, 1983, pp. 422–434. Philip B. Price, “Ethyl alcohol as a germicide,” Archives of Surgery 1939 , 38(3) , 528–542 (doi:10.1001/archsurg.1939.01200090135010).
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/127253', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/87310/']}
jdg_73897
stackexchange
llm_judgeable_groundtruth_similarity
34188161
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's always a large empty white space below my footer. How do I ensure that the page ends at the end of the footer? Now provide the response and nothing else.
There are three solutions to this problem In all of the following examples I've included an extremely basic HTML-template by only using three divs: header, content and footer. All the options are minified but should work fine on more advanced websites. Using the background-color Set for both the body and footer the same background-color. body { margin: 0px; font-family: Arial; line-height: 20px; background-color: red;}#header { height: 20px; background: #222; color: white;}#content { background: gray; height: 200px;}#footer { height: 20px; background: red; /*Same as body, you could also use transparent */ color: white;} <div id="header"> Header</div><div id="content"> Content</div><div id="footer"> Footer</div> Using a sticky footer Use a sticky footer that is fixed at the bottom of the browser window. (I wouldn't recommend this option, because many users don't like sticky footers. You could however use a sticky header) body { margin: 0px; font-family: Arial; line-height: 20px;}#header { height: 20px; background: #222; color: white;}#content { height: 2000px;}#footer { position: fixed; width: 100%; bottom: 0; left: 0; height: 20px; background: #222; color: white;} <div id="header"> Header</div><div id="content"> Content</div><div id="footer"> Footer</div> Using a minimum-height for the content Set a minimum-height for the content div that equals the browser windows height minus the height of the header and footer. (This is my personal favorite because it works cross-browser and is responsive on all screens) body { margin: 0px; font-family: Arial; line-height: 20px;}#header { height: 20px; background: #222; color: white;}#content { min-height: calc(100vh - 40px);}#footer { height: 20px; background: #222; color: white;} <div id="header"> Header</div><div id="content"> Content</div><div id="footer"> Footer</div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34188161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5578142/']}
jdg_73898
stackexchange
llm_judgeable_groundtruth_similarity
49872111
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 script which I need to deactivate for safari (desktop only) due to compatibility issues. The script must be in the body and cant be in a linked .js file. I have tried to add a if statement in order to amend "Cburl" of the script so if safari is detected and a bad url is given so the script will not load. Original <script type="text/javascript"> var cbuser = { name: '', email: '', message: '' }, access_token = '3354777755', cburl = '//www.domain.com/help/'; document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>');</script> With safari detection: <script type="text/javascript"> var safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); //check if safari var cbuser = { name: '', email: '', message: '' }, access_token = '3354777755', if(!safari){ cburl = '//www.domain.com/nohelp/'; document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>'); } else { cburl = '//www.domain.com/help/'; document.write('<script type="text/javascript" src="' + cburl + 'assets/help/js/script.js"></' + 'script>'); }</script> Is there a fault with the way im detecting safari? Now provide the response and nothing else.
I used to check if the user is using safari with this. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); Then you can stop the script doing this: if(isSafari){ alert('Is safari'); //Do something} else { alert('Is other browser'); // Do something} Here is a fiddle so you can play with it. Here is a snippet for your specific case. I changed the document.write to windows.location in order to make it work. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(isSafari) { var cbuser = { name: '', email: '', message: '' }; var access_token = '7654345676'; window.location = "https://www.example.com/notSafari";} else { var cbuser = { name: '', email: '', message: '' }; var access_token = 'Z2SxfM5dRzKsm3Auhbi4'; window.location = 'https://www.example.com';} Just change the ´ https://www.example.com ´ to your URLs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49872111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9657006/']}
jdg_73899
stackexchange
llm_judgeable_groundtruth_similarity
1581
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been thinking about this one, but I can't seem to find what causes this difference. All fishes that I've seen have their tail fin positioned vertical: But all the marine mammals I know have their tail positioned horizontal: Why is there this difference? Is it because it's mammals compared to fish? Or could fish as well have horizontal tail fins? Now provide the response and nothing else.
While fish tend to move from side to side (lateral undulation) for which a vertical tail makes sense, the land ancestors of marine mammals had their limbs under them and so their spines were already adapted to up and down movement (dorsoventral undulation). When these animals moved to marine environments, they continued up and down movement in their swimming, for which a horizontal tail makes sense. ( The wikipedia article on fins gives some more detail, and links to this webpage on Berkeley.edu . A paper by Thewissen et al. suggests that for cetaceans, dorsoventral undulation as a swimming strategy came first, and the horizontal tail evolved later. More detail: In a third example beyond fishes and marine mammals, the icthyosaurs and other aquatic reptiles developed vertical tails, even though like marine mammals they evolved from four-footed land animals. This may be because the legs/spines/gaits of land reptiles differ from those of land mammals , so that the earliest icthyosaurs swam with lateral undulation, as reflected in their spinal modifications . This blog post by Brian Switek gives a really superb run-down on the issue, with figures and citations. I'll quote this part which deals with the dorsoventral undulation theory: ...mammals and their relatives were carrying their legs underneath their bodies and not out to the sides since the late Permian, and so the motion of their spine adapted to move in an up-and-down motion rather than side-to-side like many living reptiles and amphibians. Thus Pakicetus[the pre-cetacean land mammal] would not have evolved a tail for side-to-side motion like icthyosaurs or sharks because they would have had to entirely change the way their spinal column was set up first. Switek goes on to to talk about exceptions in some marine mammals: At this point some of you might raise the point that living pinnipeds like seals and sea lions move in a side-to-side motion underwater. That may be true on a superficial level, but pinnipeds primarily use their modified limbs (hindlimbs in seals and forelimbs in sea lions) to move through the water; they aren’t relying on propulsion from a large fluke or caudal fin providing most of the propulsion with the front fins/limbs providing lift and allowing for change in direction. This diversity of strategies in living marine mammals suggests differing situations encountered by differing ancestors with their own suites of characteristics, but in the case of whales it seems that their ancestors were best fitted to move by undulating their spinal column and using their limbs to provide some extra propulsion/direction.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/1581', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/611/']}
jdg_73900
stackexchange
llm_judgeable_groundtruth_similarity
6880884
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Been messing about with python, as usual it throws my rigid static typed Object Oriented world in to a bit of a mess. Python supports duck typing, has no usable concept of interface based programming (as in C# interfaces) and allows Global variables. With all these goodies is there really any point to a dependency injection container or does the Python run-time become the container. I understand the point to these containers in static typed OO languages such as Java and C# but where would such a thing fit into the nutty world of python (I love it)? I have always suspected that Dependency injection as a design pattern was a bad smell that has been created by everything must be a class "Nazi thinking" that is c# and Java, would i be correct or is there something I am missing? So far I think I can cover factories, Singletons, Multi-instance objects, just by using Globals. I also suspect that the Aspect stuff is covered too, although I am still thinking about this. The Duck Typing is the thing that is getting me at the moment, so used to defining interfaces then basing classes on these interfaces and letting the static stuff cover my stupidity that I feel that without static typing, containers are a bit useless. edit I think I won't be using Dependency Injector frameworks/containers when using python. There really isn't any point. After thinking and reading the responses so far, the argument is made clear that without static type definitions the promises made are so loose that why bother at all. Duck typing is what it is, and the only promise can be made through documentation. As long as the reference comes into the class Method / function through a signiture parameter, and not coming through the ether of the programming environment, then I think I will be safe. Alarming though is the fact that I can not enforce my will on others through my over bearing design practices as I have done in Java and C#. Do I care......nah :) Now provide the response and nothing else.
has no usable concept of interface based programming (as in C# interfaces) Just because the compiler can't check that you're using the interface correctly doesn't mean there's "no usable concept of interfaces". You document an interface, and write unit tests. As for globals, it's not like public static methods and fields on C# or Java classes are really any different. Consider how java.lang.Math works, for example. Now consider the fact that java.lang.Math isn't a Singleton. They did that for a good reason. With all these goodies is there really any point to a dependency injection container I doubt it, but then I never really saw the point of them in C# or Java, either. Dependency injection is a programming technique , in my view. And there's really not that much to it, either. I have always suspected that Dependency injection as a design pattern was a bad smell that has been created by everything must be a class "Nazi thinking" No, it isn't. Dependency injection is a good idea a lot of the time. You don't need a class to inject dependencies into, either. Every time you pass something to a free function as a parameter, instead of having the function call another function to get the information, you're basically doing the same thing: inversion of control. Python also lets you treat modules similarly to classes in a lot of ways (certainly more ways than Java and C# do). There are problems that can be solved by passing modules as parameters to functions. :) So far I think I can cover factories, Singletons, Multi-instance objects, just by using Globals. Singletons are the bad smell, if anything. In nearly every case, in my extensive experience, they exist because someone thought it would be Bad(TM) on principle to have a global, without really thinking through the possible options, or why they wanted that kind of access to a single shared object, or even why globals are "Bad(TM) on principle" in the first place. You could make a global function in Python that acts as a factory. However, I would say it's more Pythonic to do any of the following: a) first, make really, really, really sure you can't just do what you want with __init__ . I mean, in a dynamically typed language, you can do a heck of a lot that way. b) If __init__ won't cut it, try using __new__ to control the behaviour. In Python, classes are objects themselves, which are callable. By default, calling them instantiates the class. With __new__ , you can hook into that. c) Use a decorator applied to the class. Here is an example that makes a Singleton (just because): def _singleton(cls): instance = cls() result = lambda: instance result.__doc__ = cls.__doc__ return result@_singletonclass example(object): pass The way this works: when you decorate the class, _singleton() is called, with the class being passed in. An instance is constructed and cached, and _singleton() returns an anonymous function that will return the instance when called. To complete the charade, the class's documentation is attached to the anonymous function. Then Python rebinds the class' name in the global scope to the returned anonymous function. So when you call it, you get the same instance of the class, every time. Now, this can still be worked around, of course (you can do something like example().__class__() to get another instance), but it's much more clear that you're doing something wrong than if you simply ignored a factory function in order to use the constructor normally. Plus, it means the calling code actually acts as if it were calling the constructor normally :) The Duck Typing is the thing that is getting me at the moment, so used to defining interfaces then basing classes on these interfaces and letting the static stuff cover my stupidity that I feel that without static typing, containers are a bit useless. You need to shift your thinking: stop worrying about what the thing you've been passed is , and worry about whether it can do what you want it to do . That's how duck typing works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6880884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/280391/']}
jdg_73901
stackexchange
llm_judgeable_groundtruth_similarity
34546142
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Disclaimer: I have followed Google's own Node.js quickstart guide and successfully connect and use the gmail.users.labels.list() functionality. I have checked for questions/answers here, like this one (that is not using the Node.js API I am asking about), or this one (similar to this one ) which apparently is the same problem I have but the solution does not work. My problem: When using Google's Node.js API I get a error trying to send a email. The error is: { "code": 403, "errors": [{ "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" }]} My setup: fs.readFile(secretlocation, function processClientSecrets(err, content) { if (err) { console.log('Error loading client secret file: ' + err); return; } authorize(JSON.parse(content), sendMessage);});function sendMessage(auth) { var raw = makeBody('[email protected]', '[email protected]', 'subject', 'message test'); gmail.users.messages.send({ auth: auth, userId: 'me', message: { raw: raw } }, function(err, response) { res.send(err || response) });} The function processClientSecrets is from the Google guide i mentioned above. It reads my .json file that has my access_token and refresh_token . The makeBody function is a to make a encoded body message. In the config variabels I have also: var SCOPES = [ 'https://mail.google.com/', 'https://www.googleapis.com/auth/gmail.modify', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.send']; Why it should work: the authorization process works for the gmail.users.labels.list() method. the message body I'm testing works if I test it at Google's test page . My question: Is my setup wrong? Have there been changes in the API? What am I missing? Now provide the response and nothing else.
Ok, so I found the problem(s). Problem #1 While following the Node.js quickstart guide the example in that tutorial has var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']; And when I got the .json that looks like: { "access_token": "xxx_a_long_secret_string_i_hided_xxx", "token_type": "Bearer", "refresh_token": "xxx_a_token_i_hided_xxx", "expiry_date": 1451721044161} those tokens where produced taking into account only the auth/gmail.readonly scope in the tutorial code. So I deleted the first .json , added the scopes from my final scope array (i posted in the question) and ran the tutorial setup again, receiving a new token. Problem #2 In the object passed to the API I was sending: { auth: auth, userId: 'me', message: { raw: raw }} but that is wrong, message key should be called resource . Final setup: This is what I added to the tutorial's code: function makeBody(to, from, subject, message) { var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n", "MIME-Version: 1.0\n", "Content-Transfer-Encoding: 7bit\n", "to: ", to, "\n", "from: ", from, "\n", "subject: ", subject, "\n\n", message ].join(''); var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_'); return encodedMail;}function sendMessage(auth) { var raw = makeBody('[email protected]', '[email protected]', 'test subject', 'test message'); gmail.users.messages.send({ auth: auth, userId: 'me', resource: { raw: raw } }, function(err, response) { res.send(err || response) });} And call everything with: fs.readFile(secretlocation, function processClientSecrets(err, content) { if (err) { console.log('Error loading client secret file: ' + err); return; } // Authorize a client with the loaded credentials, then call the // Gmail API. authorize(JSON.parse(content), sendMessage);});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34546142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2256325/']}
jdg_73902
stackexchange
llm_judgeable_groundtruth_similarity
912070
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose you have a vector function of space: $\vec{E}(x,y,z)=Ex(x,y,z)\hat{x}+Ey(x,y,z)\hat{y}+Ez(x,y,z)\hat{z}$. Suppose now you want to rotate the whole vector function by using a unitary rotation matrix $\mathbf{R}(\theta)$ but you still want to describe it in terms of the original coordinates. That is, a bunch of little arrows are firmly connected to some type of frame and you keep your head steady and rotate the frame with your hands. What will it look like now? I claim that it can be done in the following way: The rotated vector field, $\vec{E}_r(x,y,z)$, is given by $$\vec{E}_r(x,y,z)=\mathbf{R(\theta)}\vec{E}\left ( \left [ \begin{array}{ccc}1 \\0 \\0 \end{array} \right ]\cdot \mathbf{R}^T(\theta)\vec{r}, \left [ \begin{array}{ccc}0 \\1 \\0 \end{array} \right ]\cdot \mathbf{R}^T(\theta) \vec{r},\left [ \begin{array}{ccc}0 \\0 \\1 \end{array} \right ]\cdot \mathbf{R}^T(\theta) \vec{r} \right ),$$where $\vec{r}$ = $\left ( \begin{array}{ccc}x \\y \\z \end{array} \right )$, $T$ indicates a matrix transpose, and $\cdot$ indicates a dot product. My question: Is this correct? It seems good enough in two dimensions. Suppose $\vec{E}(x,y)=x\hat{x}+\hat{y}$: Using the rotation matrix $\mathbf{R}(\theta)=\left( \begin{array}{ccc}\cos\theta & \sin\theta \\-\sin\theta & \cos\theta \end{array} \right)$, with $\theta=\pi/2$ gives This looks correct. It is as though I just took the image and rotated it 90 degrees clockwise. I checked it in three dimensions for some specific cases but nothing rigorous. I have not been able to find a reference regarding the rotation of vector fields. Consider a specific case of a rotation of a vector field around the x axis by 180 degrees. Given that $\vec{E}$ is as described at the top, this would mean $\vec{E}_r(x,y,z)=Ex(x,-y,-z)\hat{x}-Ey(x,-y,-z)\hat{y}-Ez(x,-y,-z)\hat{z}$. Again, is this correct? Now provide the response and nothing else.
It looks correct to me. One way to see this is to realize that $$R^T(\theta) = R(\theta)^{-1}$$ So your formula says that to find the value at $(x, y, z)$, we should first rotate $(x, y, z)$ by $-\theta$, and then find the projection of the resulting vector onto the (original) $x-$, $y-$, and $z-$axes, i.e., find the coordinates in the original domain of the vector field. [Those are your three dot products]. We then find the vector that's "attached there" in the original vector field (that's the application of "E") and rotate that into the new coordinates (that's the $R(\theta)$). So yes, it's fine. If you're willing to write $E$ as a function of a single 3-component vector rather than a function of three separate arguments, then this all simplifies a good deal: $$E_\text{new}(\mathbf v) = R \cdot E( R^{-1}(\mathbf v)),$$at which point my description above can be read much more easily. In particular, this version (with no "thetas") works in any dimension, for any rotation matrix $R$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/912070', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/140363/']}
jdg_73903
stackexchange
llm_judgeable_groundtruth_similarity
116315
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to perform Mann-Whitney test on a real data set using scipy. I extracted an example where the problem occurs. It seems that the function tiecorrect returns negative value which is the source of problem in my opinion. Here is my case import scipy.statsx = [1.] * 163 + [2.] * 81 + [3.] * 40 + [4.] * 6 + [5.] * 2y = [1.] * 1007 + [2.] * 362 + [3.] * 99 + [4.] * 27 + [5.] * 13 # real-world exampleprint scipy.stats.mannwhitneyu(x,y) I have successfully performed the MW test on the same case using SPSS and R but I would like to figure out how to do with in scipy. Now provide the response and nothing else.
Let's take a step back from the Dirichlet distribution and multinomial distribution and consider a slightly simpler set of models. The binomial distribution describes the number of "successes" $y$ one expects to observe in a number of trials $n$. The binomial model has several key properties: The binomial model is dichotomous. Each event in a binomial modelhas a probability of "success" $\theta$. The trials in a binomial model are independent: previous successes neither increase nordecrease the probability of future successes. This is all well and good when all of our data are subject to some kind of rigorous controls, so that we know that across all of our observations, the $\theta$ for each "batch" of trials is the same. But more realistically, we have reason to believe that $\theta$ for trial $y_i$ is different than for trial $y_j$. One way to accomplish this is to treat each $\theta$ as if it were drawn separately from a beta distribution. The beta distribution has several useful properties It is a probability distribution of probabilities: that is, it has support on the unit interval It is conjugate to the binomial model, which simplifies computations (I have intentionally omitted an extended discussion of conjugacy in this post and how that can simplify the process of drawing values from these distributions because I feel that is only tangentially related to your question.) One method to draw values from a beta-binomial model is the following set of steps: Draw a value $\tilde{\theta}$ from the beta distribution. Draw a value $y$ from the binomial distribution with $\theta=\tilde{\theta}$. This covers the simple case of a dichotomous, binary outcome. But you've asked about Dirichlet distributions. Happily, the Dirichlet distribution is actually the same thing as a beta distribution when the dimension is 2. In higher dimensions, it is analogous to the beta distribution. Likewise, the multinomial distribution is the higher-dimensional analogue to the binomial distribution. In the case of a dichotomous outcome, the binomial distribution is the multinational outcome. Drawing values from a multinomial distribution with a Dirichlet distribution over the probabilities of outcomes is accomplished in a very similar way: Draw a vector of probabilities from the Dirichlet distribution. Use that vector of probabilities to draw a vector of outcomes from the multinomial distribution.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/116315', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1215/']}
jdg_73904
stackexchange
llm_judgeable_groundtruth_similarity
23786609
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background We use Amazon S3 in our project as a storage for files uploaded by clients. For technical reasons, we upload a file to S3 with a temporary name , then process its contents and rename the file after it has been processed. Problem The 'rename' operation fails time after time with 404 (key not found) error, although the file being renamed had been uploaded successfully. Amazon docs mention this problem: Amazon S3 achieves high availability by replicating data across multiple servers within Amazon's data centers. If a PUT request is successful, your data is safely stored. However, information about the changes must replicate across Amazon S3, which can take some time , and so you might observe the following behaviors: We implemented a kind of polling as workaround : retry the 'rename' operation until it succeeds. The polling stops after 20 seconds. This workaround works in most cases: the file gets replicated within few seconds. But sometimes — very rarely — 20 seconds are not enough; the replication in S3 takes more time. Questions What is the maximum time you observed between a successful PUT operation and complete replication on Amazon S3? Does Amazon S3 offer a way to 'bypass' replication? (Query 'master' directly?) Now provide the response and nothing else.
Update: this answer uses some older terminology, which i have left in place, for the most part. AWS has changed the friendly name of "US-Standard" to be more consistent with the naming of other regions, but its regional endpoint for IPv4 still has the unusual name s3-external-1.amazonaws.com . The us-east-1 region of S3 has an IPv4/IPv6 "dual stack" endpoint that follows the standard convention of s3.dualstack.us-east-1.amazonaws.com and if you are IPv6 enabled, this endpoint seems operationally-equivalent to s3-external-1 as discussed below. The documented references to geographic routing of requests for this region seem to have largely disappeared, without much comment, but anecdotal evidence suggests that the following information is still relevant to that region. Q. Wasn’t there a US Standard region? We renamed the US Standard Region to US East (Northern Virginia) Region to be consistent with AWS regional naming conventions. — https://aws.amazon.com/s3/faqs/#regions Buckets using the S3 Transfer Acceleration feature use a global-style endpoint of ${bucketname}.s3-accelerate.amazonaws.com and it is not yet evident how this endpoint behaves with regard to us-east-1 buckets and eventual consistency, though it stands to reason that other regions should not be affected by this feature, if enabled. This feature improves transfer throughput for users who are more distant from the bucket by routing requests to the same S3 endpoints but proxying through the AWS "Edge Network," the same system that powers CloudFront. It is, essentially, a self-configuring path through CloudFront but without caching enabled. The acceleration comes from optimized network stacks and keeping the traffic on the managed AWS network for much of its path across the Internet. As such, this feature should have no impact on consistency, if you enable and use it on a bucket... but, as I mentioned, how it interacts with us-east-1 buckets is not yet known. The US-Standard (us-east-1) region is the oldest, and presumably largest, region of S3, and does play by some different rules than the other, newer regions. An important and relevant difference is the consistency model. Amazon S3 buckets in [all regions except US Standard] provide read-after-write consistency for PUTS of new objects and eventual consistency for overwrite PUTS and DELETES. Amazon S3 buckets in the US Standard region provide eventual consistency. http://aws.amazon.com/s3/faqs/ This is why I assumed you were using US Standard. The behavior you described is consistent with that design constraint. You should be able to verify that this doesn't happen with a test bucket in another region... but, because data transfer from EC2 to S3 within the same region is free and very low latency, using a bucket in a different region may not be practical. There is another option that is worth trying, has to do with the inner-workings of US-Standard. US Standard is in fact geographically-distributed between Virginia and Oregon, and requests to "s3.amazonaws.com" are selectively routed via DNS to one location or another. This routing is largely a black box, but Amazon has exposed a workaround. You can force your requests to be routed only to Northern Virginia by changing your endpoint from "s3.amazonaws.com" to "s3-external-1.amazonaws.com" ... http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region ... this is speculation on my part, but your issue may be exacerbated by geographic routing of your requests, and forcing them to "s3-external-1" (which, to be clear, is still US-Standard), might improve or eliminate your issue. Update: The advice above has officially risen above speculation, but I'll leave it for historical reference. About a year I wrote the above, Amazon indeed announced that US-Standard does offer read-after-write consistency on new object creation, but only when the s3-external-1 endpoint is used. They explain it as though it's a new behavior, and that may be the case... but it also may simply be a change in the behavior the platform officially supports. Either way: Starting [2015-06-19], the US Standard Region now supports read-after-write consistency for new objects added to Amazon S3 using the Northern Virginia endpoint (s3-external-1.amazonaws.com). With this change, all Amazon S3 Regions now support read-after-write consistency. Read-after-write consistency allows you to retrieve objects immediately after creation in Amazon S3. Prior to this change, Amazon S3 buckets in the US Standard Region provided eventual consistency for newly created objects, which meant that some small set of objects might not have been available to read immediately after new object upload. These occasional delays could complicate data processing workflows where applications need to read objects immediately after creating the objects. Please note that in US Standard Region, this consistency change applies to the Northern Virginia endpoint (s3-external-1.amazonaws.com). Customers using the global endpoint (s3.amazonaws.com) should switch to using the Northern Virginia endpoint (s3-external-1.amazonaws.com) in order to leverage the benefits of this read-after-write consistency in the US Standard Region. [emphasis added] https://forums.aws.amazon.com/ann.jspa?annID=3112 If you are uploading a large number of files (hundreds per second), you might also be overwhelming S3's sharding mechanism. For very high numbers of uploads per second, it's important that your keys ("filenames") not be lexically sequential. Depending on how Amazon handles DNS, you may also want to try another alternate variant of addressing your bucket if your code can handle it. Buckets in US-Standard can be addressed either with http://mybucket.s3.amazonaws.com/key ... or http://s3.amazonaws.com/mybucket/key ... and the internal implementation of these two could, at least in theory, be different in a way that changes the behavior in a way that would be relevant to your issue.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23786609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2170192/']}
jdg_73905
stackexchange
llm_judgeable_groundtruth_similarity
21584541
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: struct books{ char name[100]; float price; int pages;}; Declaring a structure Without creating an object of a structure , does the structure occupies space in memory for its DATA MEMBERS ? Now provide the response and nothing else.
The definition of a struct is normally not part of the binary in C. It only exists in your source code. When the compiler sees references to your struct (typically for allocation or deallocation of space for an instance of this struct, access to its fields through an object variable, etc), it consults your struct definition in order to understand what the correct numbers are for that data type (it mainly wants to calculate data type sizes and field offsets). When all this is done, the struct definition itself is forgotten and only the numbers are kept in the program, wherever they were actually used. Therefore, if you don't reference your struct at all, then no traces of it should be present.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21584541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3240722/']}
jdg_73906
stackexchange
llm_judgeable_groundtruth_similarity
10503666
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: preresult is an OrderedDict() . I want to save the first 100 elements in it. Or keep preresult but delete everything other than the first 100 elements. The structure is like this stats = {'a': {'email1':4, 'email2':3}, 'the': {'email1':2, 'email3':4}, 'or': {'email1':2, 'email3':1}} Will islice work for it? Mine tells itertool.islice does not have items Now provide the response and nothing else.
Here's a simple solution using itertools : >>> import collections>>> from itertools import islice>>> preresult = collections.OrderedDict(zip(range(200), range(200)))>>> list(islice(preresult, 100))[-10:][90, 91, 92, 93, 94, 95, 96, 97, 98, 99] This returns only keys. If you want items, use iteritems (or just items in Python 3): >>> list(islice(preresult.iteritems(), 100))[-10:][(90, 90), (91, 91), (92, 92), (93, 93), (94, 94), (95, 95), (96, 96), (97, 97), (98, 98), (99, 99)]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10503666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1325302/']}
jdg_73907
stackexchange
llm_judgeable_groundtruth_similarity
80596
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: In computer security, what does provable security mean? I read the Provable Security article on Wikipedia, and I was able to grasp the basics. I would like to see this described in more detail, using, for example, the provability of RSA encryption. Some queries: Is RSA provable? For small p and q , it is not secure. Can we say it is provable security? What is the best provable public key encryption algorithm? Now provide the response and nothing else.
You can define a system as provably secure if the security of the system ultimately relies upon a mechanism or rule which has some logical or mathematical proof. For example, we can logically say that given a + b = c , it isn't possible to know the value of the other two values if you only know one, e.g. c=40 could mean a=20, b=20 , or a=10, b=30 , or a=-100, b=140 , or an infinite number of other possibilities. This means that it's very, very hard to work out the values of a and b from just knowing c . If you can build a security system upon this premise, you have a provably secure system. This concept is extended, in the case of RSA, to factorisation of semiprimes. Semiprimes are numbers which can be represented as the product of two primes, i.e. n = p * q . Given only n , it is relatively computationally difficult to work out the values of p and q . For example, it is trivial to multiply the primes 1009 and 6121 in a calculator to get 6176089, but it's much harder to guess which primes I used to get an answer of 27116399. I, as a legitimate user, can trivially multiply the primes, but you, as an attacker, must do some difficult work to guess which primes I used. The way I would phrase it for RSA is as follows: RSA relies upon the semiprime factorisation problem for security. Semiprime factorisation is a known-hard problem (specifically, no general solution exists which can factor semiprimes in polynomial time or better) and as such requires significant computational work to resolve. RSA therefore has the property that, assuming you pick a large enough pair of primes (and adhere to some other RSA-specific requirements, such as not making them too close), it will be computationally infeasible for an adversary to break RSA given most common threat models. An important factor here is that the problem scales. If your threat model includes threat actors with significant resources, you can scale your prime sizes to make their work much harder, at the cost of increased computation time on your own system.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/80596', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/43517/']}
jdg_73908
stackexchange
llm_judgeable_groundtruth_similarity
23702532
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Grails 2.4 is now using the Asset Pipeline for managing and processing static assets in Grails applications instead of the Resources system. This is pretty new and there isn't much doc about it on the internet yet. My question is, how to correctly handle 3rd party libraries? For instance, the select2 ( http://ivaynberg.github.io/select2/ ) library comes with all its .css, .js, image files in a single flat folder. Should I copy the different file types in to their corresponding assets/javascripts/ , assets/stylesheets/ , etc. subfolders? What to do with files that don't really have an obvious location like the .json, text, or doc files? Should I create a vendors/select2/ folder? Where, in assets/ or in web-app/ ? And then, how should I load all the necessary files from my GSPs? This lib will also be needed only in a form view, and therefore shouldn't be loaded unless it's needed. Now provide the response and nothing else.
Baxxabit's answer led me to my solution. I've been struggling with much the same thing, but wanting to make the most of the pipeline so that I can use the less-asset-pipeline plugin. Using bootstrap as an example, I created a vendor folder as a peer of the standard assets folders and then dropped the bootstrap files under there. application.js: //This is a javascript file with its top level require directives//= require jquery//= require bootstrap-3.1.1/javascript/bootstrap//= require_tree views//= require_self... and application.css: /**= require_self*= require main*= require mobile*= require bootstrap-3.1.1/stylesheets/bootstrap*= encoding UTF-8*/ To override the boostrap customization I can simply drop a customized variables.less file into ./grails-app/assets/vendor/bootstrap-3.1.1/stylesheets/variables.less. The first folder under assets is ignored when it comes to overriding files, thereafter the path needs to match whatever you put under vendor. This gives me this sort of hierarchy: grails-app/assets/├── images...├── javascripts│   └── application.js├── stylesheets│   ├── application.css│   ├── bootstrap-3.1.1│   │   └── stylesheets│   │   └── variables.less│   ├── errors.css│   ├── main.css│   └── mobile.css└── vendor └── bootstrap-3.1.1 ├── javascript │   ├── bootstrap.js │   └── bootstrap.min.js └── stylesheets ├── alerts.less... ├── variables.less └── wells.less I like the result. I've got the distributed package cleanly delineated and relatively easily upgradable, and I've got my changes to that package separated off into a clearly identifiable customization file. I've put an example using the sass-asset-pipeline plugin at https://github.com/ggascoigne/grails-pipeline-scss .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23702532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267398/']}
jdg_73909
stackexchange
llm_judgeable_groundtruth_similarity
250259
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 run some Python code in the external code cell as following: The above Python code produced the result (as shown with red [1] in the screenshot), which is a list of squart of i. Then, I want to analyze the result within Mathematica environment. Out of my expectation, the result shown as not defined (as shown with red [2] in the screenshot). My Question How can I export the output result of Python to Mathematica computational enviroment? (So that I can further analyze the data in Mathematica) Now provide the response and nothing else.
Even if the session was still open External code cell will be open after executing, you can't use the same variable name you'd defined in the external session, inside Mathematica. Let me introduce you to ExternalValue . (* start a python session *)session = StartExternalSession["Python"];(* run your code using the defined session *)ExternalEvaluate[session, "import mathresult=[math.sqrt(i) for i in range(10)]"];(* get the value from the session *)ExternalValue[session, "result"](*Out: {0., 1., 1.41421, 1.73205, 2., 2.23607, 2.44949, 2.64575, 2.82843, 3.} *)(* terminate the session *)DeleteObject[session] Also, you can use this workaround but it has its limitations: result = ExternalEvaluate["Python", "import math[math.sqrt(i) for i in range(10)]"];result(*Out: {0., 1., 1.41421, 1.73205, 2., 2.23607, 2.44949, 2.64575, 2.82843, 3.} *) Note that if you use the print statement in python, this workaround doesn't work. result value will be Null . Update 1 You can stay in the External code cell : result = ExternalValue[ExternalEvaluate`GetDefaultExternalSession["Python"], "result"]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/250259', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30507/']}
jdg_73910
stackexchange
llm_judgeable_groundtruth_similarity
13261794
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Spring security for authenticating users. I created a custom authentication provider and now I am wondering how I can get error messages from the provider into my form. This is the authenticate() method in my custom authentication provider: @Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException { UserProfile profile = userProfileService.findByEmail(authentication.getPrincipal().toString()); if(profile == null){ throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal())); } String suppliedPasswordHash = DigestUtils.shaHex(authentication.getCredentials().toString()); if(!profile.getPasswordHash().equals(suppliedPasswordHash)){ throw new BadCredentialsException("Invalid credentials"); } UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(profile, null, profile.getAuthorities()); return token;} This is my form: <form name='f' action="<c:url value='j_spring_security_check' />" method='POST'><div id="data-entry-form"> <div class="form-entry"> <label><spring:message code="login.form.label.email"/></label> <input type='text' name='j_username' value=''> </div> <div class="form-entry"> <label><spring:message code="login.form.label.password"/></label> <input type='password' name='j_password'/> </div> <div class="form-entry"> <input type="submit" value="Verzenden"/> </div></div> How would I get error messages into my form? From the moment I press the login button, Spring takes over, so the only method I could generate error messages in would be the authenticate() method... Now provide the response and nothing else.
3 Steps of the safest way (we don't rely on the LAST_EXCEPTION): Specify error page (for example "login-error") in configuration for your custom authentication provider httpSecurity.authorizeRequests().antMatchers("/css/**", "/js/**", "/img/**").permitAll().anyRequest().fullyAuthenticated().and().formLogin().loginPage("/login").permitAll().failureUrl("/login-error").and().logout().permitAll() Create controller for url /login-error that returns view of your custom login page (for example "login") with the next code: @Controllerpublic class LoginController { @GetMapping("/login-error") public String login(HttpServletRequest request, Model model) { HttpSession session = request.getSession(false); String errorMessage = null; if (session != null) { AuthenticationException ex = (AuthenticationException) session .getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); if (ex != null) { errorMessage = ex.getMessage(); } } model.addAttribute("errorMessage", errorMessage); return "login"; }} Get the error message into your page finally (ThymeLeaf tags for example): <!--/*@thymesVar id="errorMessage" type="java.lang.String"*/--><div class="alert" th:if="${errorMessage}" th:text="${errorMessage}"></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13261794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1032791/']}
jdg_73911
stackexchange
llm_judgeable_groundtruth_similarity
32915
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to this article , Canada would be breaking at least three UN treaties once it legalized marijuana in October. But why didn't the Canadian government just leave the treaties beforehand? It seems like a painless process with no repercussions, and they could join back any time they wanted if necessary. Now provide the response and nothing else.
Probably because Uruguay didn't do it either and apparently without consequences : While Canada appears set to violate these international agreements, the [International Narcotics Control] board has limited powers when it comes to forcing signatories to comply. Gélinas-Faucher said that the agency can ask countries which signed these agreements to discontinue their drug trade with Canada, since the agreements govern trade in legal drugs as well. And another country could sue Canada before the International Court of Justice. Those scenarios, however, are considered unlikely. Uruguay, which also legalized cannabis, has not been subjected to similar reprisals. And here's what happened in that case , basically Uruguay argued that human rights trump drug enforcement: Uruguay has forged ahead with cannabis regulation despite repeated criticisms from the International Narcotics Control Board (INCB), as in the Board’s report for 2016, which states: The Board notes the continued implementation by the Government of Uruguay of measures aimed at creating a regulated market for the non-medical use of cannabis. While this policy has not yet been fully implemented, the Board wishes to reiterate its position that such legislation is contrary to the provisions of the international drug control conventions, particularly to the measures set out in article 4, paragraph (c), of the 1961 Convention as amended, according to which States parties are obliged to ‘limit exclusively to medical and scientific purposes the production, manufacture, export, import, distribution of, trade in, use and possession of drugs.’ In opting for regulation notwithstanding such criticisms, Uruguay has argued that its policy is fully in line with the original objectives that the UN drug control treaties emphasized but have subsequently failed to achieve: namely, the protection of the health and welfare of humankind. While there can be little doubt that, as the INCB has pointed out, Uruguay is contravening its obligations under the 1961 Single Convention to limit cannabis exclusively to medical and scientific purposes, Uruguay has sought to side step the question of drug treaty non-compliance by placing its new law in the context of the country’s adherence to its more foundational obligations under international law. Uruguayan authorities have specifically argued that the creation of a regulated market for adult use of cannabis is driven by health and security imperatives and is therefore an issue of human rights. As such, officials point to wider UN human rights obligations that need to be respected, specifically appealing to the precedence of human rights principles over drug control obligations within the UN system as a whole. In the event of a conflict between human rights obligations and drug control requirements, they argue, Uruguay is bound to give priority to its human rights obligations. The argument for the priority of human rights obligations in matters of drug control is not a new one for Uruguay. In 2008, Uruguay sponsored a resolution at the Commission on Narcotic Drugs (the UN’s central policy making body on the issue) to ensure the promotion of human rights in the implementation of the international drug control treaties. Uruguay’s argument that human rights protections take precedence over drug control requirements finds support in the 2010 report to the UN General Assembly by the UN Special Rapporteur on the Right to Health, which signaled: “When the goals and approaches of the international drug control regime and international human rights regime conflict, it is clear that human rights obligations should prevail.” In 2015, Uruguay co-sponsored a resolution calling upon the UN High Commissioner for Human Rights (OHCHR) to prepare a report ‘on the impact of the world drug problem on the enjoyment of human rights.’ In its contribution to OHCHR preparations, Uruguay laid out its stance regarding the primacy of human rights: We reaffirm the importance of ensuring the human rights system, underscoring that human rights are universal, intrinsic, interdependent and inalienable, and that is the obligation of States to guarantee their priority over other international agreements, emphasizing the international drug control conventions. Uruguay’s ability to move forward with a policy clearly beyond the bounds of the UN drug treaties owes to a combination of factors. First, Uruguayan authorities foresaw the international criticism their move would likely trigger, and fashioned an argument based on human rights obligations that was consistent with the country’s international reputation, and that was coherent with the country’s rationale for revising its cannabis law in the first place. Second, as a practical matter, the UN drug control treaty bodies, including the INCB, do not have the kind of enforcement authority or practical political power that would be necessary to prevent Uruguay from moving ahead with implementation of its new law. Countries such as the United States have historically wielded their political influence and power to encourage full implementation of the drug treaties. However, with Uruguay’s law entering its fifth year since passage, there has not been a concerted U.S. government effort to punish Uruguay bilaterally or in an international arena, suggesting that Uruguay’s reforms will not be stymied because of international pressures. In this regard, Uruguay has taken advantage of felicitous timing, with its law’s passage having come in the midst of a major shift toward cannabis regulation within the United States. After the November 2012 ballot initiatives to legalize cannabis in the states of Colorado and Washington, U.S. President Barack Obama’s administration adopted a policy of conditional accommodation of state-level cannabis legalization, contained in Justice Department enforcement guidance known as the “Cole Memo.” This accommodation provided Uruguay a political cushion internationally, just as the Uruguayan parliament was preparing to approve the country’s cannabis reform. In the wake of the Colorado and Washington ballot initiatives, the U.S. federal government was suddenly in an awkward spot. The United States was the key architect and for decades the chief enforcer of the UN drug treaties, including vigorous enforcement of the global prohibition on non-medical uses of cannabis. To oppose Uruguay’s new law or even pressure Uruguay to revise or annul it—as it is easy to imagine previous administrations attempting to do so—would open the United States to charges of hypocrisy. Indeed, regarding non-medical cannabis, the INCB has also repeatedly noted that the United States is “not in conformity” with the drug treaties, and has underscored that the “strict prohibition of non-medical use set out in the 1961 Convention” applies fully to countries with federal structures of government. In other words, if “sub-national Governments have taken measures towards legalizing and regulating the non-medical use of cannabis, despite federal law to the contrary”—as is quite evidently the situation today in the United States—then such developments are “in violation of the international drug control legal framework.” In this new context, the United States has kept its criticisms of Uruguay’s cannabis law soft and perfunctory. Under President Donald Trump, U.S. Attorney General Jeff Sessions has made clear his animus toward legal cannabis. In January 2018, Sessions rescinded the Cole Memo, heightening concerns over how federal enforcement powers will be wielded. But Sessions’ bid to turn back the clock on cannabis legalization is considered unlikely to succeed; cannabis reforming states are not expected to be reverse course, even if the Trump administration expends significant political capital in an effort to compel them. This leaves the U.S. federal government in the same awkward situation that began in November 2012 when the voters of Colorado and Washington State approved their ballot initiatives: unable to undo the states’ reforms, and therefore out of compliance with the drug treaties it has long championed. For the foreseeable future, the United States is unlikely to be in a position to oppose efforts to legalize and regulate cannabis, such as that now underway in Uruguay. It looks like Canada is taking a somewhat similar line (to Uruguay's)... Witnesses appearing before your Committee all agreed that if Bill C-45 is passed, Canada would be in violation of the 1961 Single Convention, the 1971 Convention on Psychotropic Substances, and the 1988 Anti-Trafficking Convention. Your Committee heard from the Minister of Foreign Affairs at the end of its hearings. In her testimony, the Minister “recognize[d] that [the] proposed approach of legalizing, [regulating], and strictly restricting cannabis will result in Canada contravening certain obligations […] under the three UN drug conventions: the Single Convention on Narcotics Drugs from 1961, the 1971 Convention on Psychotropic Substances and the 1988 United Nation Convention Against Illicit Traffic in Narcotic Drugs and Psychotropic Substances.” Even as Bill C-45 will violate certain international obligations related to cannabis, the Minister of Foreign Affairs noted that Canada’s policy regarding international drug control remains consistent with the overarching goal of the three conventions , namely to protect the health and welfare of society. Moreover, while GAC officials in earlier testimony characterized the contravention of the international drug conventions as technical , the Minister of Foreign Affairs stated before your Committee that “the issue of the conventions is an important one, and [the government] need[s] to be clear about it.” [...] She informed your Committee that government officials have been discussing Canada’s intention to legalize recreational cannabis with G7 countries as well as a dozen others. In particular, she noted that Canada was re-elected to the Commission on Narcotic Drugs (CND) in a contested election in March 2017, after having announced its intention to legalize recreational cannabis. In answering questions put to her about how Canada intends to reconcile its views on the importance of a rules-based international order with Bill C-45’s violation of international treaties, the Minister pointed out the need for Canada to be open about being in contravention , to preserve the health and safety of Canadians, as well as to work with international partners. And yes, INCB also protested against Canada in similar terms as against Uruguay; I'll spare you the quote. Their position will probably have no effect. The Canadian discussions also covered various solutions. One was to re-accede with a reservation like Bolivia: Your Committee heard about the experience of Bolivia. According to Mr. Jelsma, in January 2012, Bolivia withdrew from the 1961 Single Convention after failing to obtain a reservation from the criminalization provisions of the treaty for the traditional use of the coca leaf, which is protected in the Bolivian constitution. A year later, the country was able to obtain a reservation and re-acceded to the treaty. Another suggestion was a convention between the cannabis-legalizating countries: Some witnesses discussed the option of inter se modification and the role Canada could play in its pursuit. Your Committee was informed that the inter se option would entail the negotiation of a side agreement on cannabis among like-minded countries that are parties to the three drug control conventions. It would also maintain “a clear commitment to the original treaty aim to promote the health and welfare of human kind, and to the original treaty obligations vis-à-vis countries that are not party to the inter se agreement.” This option is provided for in Article 41 of the Vienna Convention on the Law of Treaties. And there's some Canadian precedent for going that route: Professor de Mestral pointed to Canada’s experience with the 1970 Arctic Waters Pollution Prevention Act, which asserts the Government of Canada’s jurisdiction over the navigation of international shipping through Arctic waters. He noted that the Act generated an “extremely negative” reaction on the part of the international community, including several protests from allies, as it was in apparent contravention of international law governing freedom of the seas. In drawing conclusions about this experience, Professor de Mestral noted: We built a consensus, the third Convention on the Law of the Sea gave us a platform where we were able to make our arguments successfully that change was needed. But clearly in the face of protests, Canada simply said, “We will not go to the international court on this issue. We believe we are right. We believe that change has to be made to international law, and we’re prepared to do it with like-minded states. I guess that may be what Canada will have to do.” However, with regard to cannabis, the Canadian government [for now] seems undecided what [else] to do, beyond openly admitting its [technical] non-compliance.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/32915', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7434/']}
jdg_73912
stackexchange
llm_judgeable_groundtruth_similarity
6232633
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting timeouts using the Entity Framework (EF) when using a function import that takes over 30 seconds to complete. I tried the following and have not been able to resolve this issue: I added Default Command Timeout=300000 to the connection string in the App.Config file in the project that has the EDMX file as suggested here . This is what my connection string looks like: <add name="MyEntityConnectionString" connectionString="metadata=res://*/MyEntities.csdl|res://*/MyEntities.ssdl| res://*/MyEntities.msl; provider=System.Data.SqlClient;provider connection string=&quot; Data Source=trekdevbox;Initial Catalog=StarTrekDatabase; Persist Security Info=True;User ID=JamesTKirk;Password=IsFriendsWithSpock; MultipleActiveResultSets=True;Default Command Timeout=300000;&quot;" providerName="System.Data.EntityClient" /> I tried setting the CommandTimeout in my repository directly like so: private TrekEntities context = new TrekEntities();public IEnumerable<TrekMatches> GetKirksFriends(){ this.context.CommandTimeout = 180; return this.context.GetKirksFriends();} What else can I do to get the EF from timing out? This only happens for very large datasets. Everything works fine with small datasets. Here is one of the errors I'm getting: System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. OK - I got this working and it's silly what happened. I had both the connection string with Default Command Timeout=300000 and the CommandTimeout set to 180. When I removed the Default Command Timeout from the connection string, it worked. So the answer is to manually set the CommandTimeout in your repository on your context object like so: this.context.CommandTimeout = 180; Apparently setting the timeout settings in the connection string has no effect on it. Now provide the response and nothing else.
There is a known bug with specifying default command timeout within the EF connection string. http://bugs.mysql.com/bug.php?id=56806 Remove the value from the connection string and set it on the data context object itself. This will work if you remove the conflicting value from the connection string. Entity Framework Core 1.0: this.context.Database.SetCommandTimeout(180); Entity Framework 6: this.context.Database.CommandTimeout = 180; Entity Framework 5: ((IObjectContextAdapter)this.context).ObjectContext.CommandTimeout = 180; Entity Framework 4 and below: this.context.CommandTimeout = 180;
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6232633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705132/']}
jdg_73913
stackexchange
llm_judgeable_groundtruth_similarity
46139099
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A UILabel has a Dynamic Type: Automatically Adjusts Font check-box in the Attributes Inspector in Interface Builder. Is there an equivalent in Interface Builder for automatically adjusting the font size of a UIButton, or does this have to be handled in code? I'm using Xcode 9.0 beta 6, targeting iOS 11. Now provide the response and nothing else.
Apparently there isn't, but it's not very hard to fix. You can make an extension on UIButton with an @IBInspectable property: extension UIButton { @IBInspectable var adjustsFontForContentSizeCategory: Bool { set { self.titleLabel?.adjustsFontForContentSizeCategory = newValue } get { return self.titleLabel?.adjustsFontForContentSizeCategory ?? false } }} Now you can simply turn it on for every UIButton (or any of its subclasses).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46139099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8586894/']}
jdg_73914
stackexchange
llm_judgeable_groundtruth_similarity
132423
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: Lets say I have a java class called DirectAction some of the methods in the class have the word "action" or "Action" What is the grep command to get the names of all the methods who have "Action" or "action" and write it to an external file? Example: public class DirectAction extends ERXDirectAction {/** * * @param aRequest */public DirectAction(WORequest aRequest) {}// ============================================================================================// ACTIONS/** * Default Action * */@docDirectActionpublic WOActionResults defaultAction() {}/** * @return goes to login page for student */@docDirectActionpublic WOActionResults studentAction() { ); return nextPage;}/** * @return goes to Admin login page */@docDirectActionpublic WOActionResults adminAction() { return nextPage;}/** * @return calls the AdminAction */@docDirectActionpublic WOActionResults staffAction() { return adminAction();} } I want to get only the below output. public class DirectAction extends ERXDirectActionpublic DirectAction(WORequest aRequest)public WOActionResults defaultAction()public WOActionResults studentAction()public WOActionResults adminAction()public WOActionResults staffAction() NOTE: the only word that is common in all these methods is "Action" or "action" Also please use only grep if possible :) Now provide the response and nothing else.
If you want to return only the matching text (instead of the whole line), you need the -o flag grep -o 'public .*[a|A]ction.*)' or with extended regular expressions grep -Eo 'public .*[aA]ction.*\)' file Or, extended for any lines beginning with pub(lic), pri(vate) or pro(tected) grep -Eo '^(pub|pri|pro).*[aA]ction.*\)' file
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/132423', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/68738/']}
jdg_73915
stackexchange
llm_judgeable_groundtruth_similarity
208645
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In group theory the number of Sylow $p$-subgroups of a finite group $G$, is of the form $kp+1$. So it is interesting to discuss about the divisors of this form. As I checked it seems that for an odd prime $p$, there is not any divisor $a$ of $p^4+1$, where $1<a<p^4+1$ and $a=kp+1$, for some $k>0$.Could you help me about this question? If it is true how we can prove it? Also when I checked the same fact for $p^8+1$, we get many counterexamples. What is the difference between $4$ and $8$? Now provide the response and nothing else.
There's none indeed. Lemma : if $1<m<n$ are coprime integers then $mn+1$ does not divide $n^4+1$. First observe that for any $m,n$, of $mn+1$ divides $n^4+1$, then it divides $n^4m^4+m^4=((nm)^4-1)+1+m^4$, and since $mn+1$ clearly divides $((nm)^4-1)$, we deduce that it also divides $1+m^4$. To prove the lemma, assume the contrary. As we have just seen, $mn+1$ divides $m^4+1$ as well. Write $(m^4+1)/(mn+1)=k$, and $k=(\ell m+r)$ with $0\le r\le m-1$. Then $m^4+1=(\ell m+r)((mn+1)=mN'+r$, so $r=1$. So $(\ell m+1)$ divides $m^4+1$. Then $m$ and $\ell$ are coprime: indeed, we have $(m\ell +1)(mn+1)=m^4+1$, so $\ell(mn+1)-m^3=-n$. If a prime $p$ were dividing both $m$ and $\ell$ then it would also divide $n$, contradicting that $m$ and $n$ are coprime, so $m$ and $\ell$ are indeed coprime. We have $\ell<n$ because otherwise$$m^4+1=(mn+1)(m\ell+1)\ge (mn+1)^2> (m^2+1)^2>m^4+1.$$ So we found a new pair $(m,\ell)$ with $\max(m,\ell)<n$, with $m\ell+1$ dividing both $m^4+1$ and $\ell^4+1$. So, assuming that $n$ is minimal, we're done unless $\ell=1$. This happens if $m+1$ divides $m^4+1$, and since $m+1$ divides $m^4-1$ as well, if this occurs then $m+1=2$, contradicting $m>1$. (Note: without the coprime assumption the conclusion fails, as $(m,n)=(m,m^3)$ for $m\ge 2$, e.g. $(m,n)=(2,8)$, satisfies $mn+1|n^4+1$.) Proposition If $p$ is prime then $p^4+1$ has no divisor of the form $kp+1$ except $1$ and $p^4+1$. Proof: write $p^4+1=(kp+1)(k'p+\ell)$ with $0\le\ell\le p-1$; then $\ell=1$. So exchanging $k$ and $k'$ if necessary we can suppose $k\le k'$. If by contradiction $k$ is divisible by $p$ then $k'\ge k\ge p$, so $p^4+1\ge (p^2+1)^2>p^4+1$, contradiction. So $k$ and $p$ are coprime, and the lemma yields a contradiction.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/208645', 'https://mathoverflow.net', 'https://mathoverflow.net/users/31045/']}
jdg_73916
stackexchange
llm_judgeable_groundtruth_similarity
155248
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: Using the GeoServer option, it is possible to load map tiles from external services. Which services are compatible with GeoServer ? How can I find such services? Does GeoServer follow a standard that has a name that I can google for? The documentation shows a few examples: GeoGraphics[{Entity["AdministrativeDivision", {"California", "UnitedStates"}]}, GeoServer -> "http://a.tile.openstreetmap.org/`1`/`2`/`3`.png"] Now provide the response and nothing else.
The keywords to search for are "tile server" and "XYZ URL". I was able to find several services compatible with this format. There is a list, complete with previews here: https://leaflet-extras.github.io/leaflet-providers/preview/ (Found through GIS.SE ) The {x} , {y} and {z} placeholders in the URL correspond to `1` , `2` and `3` in Mathematica. MapBox is another great source for base maps, as shown by @C.E. in his answer. Here are a few examples that do not require API keys: From https://basemap.nationalmap.gov/ , USGS[map :"HydroCached" | "ImageryOnly" | "ImageryTopo" |"ShadedReliefOnly" | "Topo"] := "https://basemap.nationalmap.gov/arcgis/rest/services/USGS" <> map <> "/MapServer/tile/`1`/`3`/`2`" From https://carto.com/location-data-services/basemaps/ , carto[style : "light_all" | "dark_all" | "light_nolabels" | "light_only_labels" |"dark_nolabels" | "dark_only_labels"] := "https://cartodb-basemaps-1.global.ssl.fastly.net/" <> style <> "/`1`/`2`/`3`.png" From http://maps.stamen.com/ , stamenBase[style_, format_] := "http://tile.stamen.com/" <> style <> "/`1`/`2`/`3`." <> formatstamen[style : "toner"] := stamenBase[style, "png"]stamen[style : "watercolor" | "terrain"] := stamenBase[style, "jpg"] Demo: GeoGraphics[Entity["AdministrativeDivision", {"California", "UnitedStates"}], GeoServer -> #] & /@ {USGS["Topo"], carto["light_all"], stamen["terrain"]} These are just quick and dirty examples. In some cases it may be beneficial or necessary to set the "Tileset" suboption of GeoServer (see under Details in doc page). Tile servers can also be used with the interactive DynamicGeoGraphics : DynamicGeoGraphics[Entity["City", {"Lyon", "RhoneAlpes", "France"}], GeoServer -> stamen["toner"]]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/155248', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12/']}
jdg_73917
stackexchange
llm_judgeable_groundtruth_similarity
399168
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 heard from someone that axial gap /pancake motors (lynch or etek) are better for servo control (speed and position) than standard radial flux DC motors. Both motors are brushed type. I don't really understand the physics behind this claim , although I know how each one operate. So can anyone please state if it is really better, equal or worse motor technology for servo drive, and why? Now provide the response and nothing else.
One advantage i can think of is that the low inductance of axial-flux motors means that they have low electrical time constants, allowing current to flow very quickly into the armature for virtually instant torque production , which should translate to fast acceleration and deceleration which maybe desirable for high performance servo control.. BUT: However they are not widely used probably because of their higher price and manufacturing challenges explained in magnax motors white paper : WP- High Efficiency Axial Flux Machines - whitepaper v1.7 The pancake motor also might suffer from several problems: 1-High interia due to their shape which might not be desirable for rapid movments. more details in : motor-sizing-calculations (source:orientalmotor.com) 2-low inductance cause problems in torque loop: motor-inductance-effects-on-servo-drives (source is doc.ingeniamc.com) Quote1: "Motor inductance, or more appropriately electrical time constant value affect the servo drives in many ways. While high inductance values may limit the system bandwidth, low inductance values can lead to control loop instabilities, inaccuracies in current readings, increased power losses and other problems. These issues are especially critical in high speed brushed motors with very low friction and fast dynamics.The problem is more notorious with brushed DC motors" Since The current ripple can be expressed as : Quote 2: "At low loads, positive motor currents can be read as negative due to current ripple. This leads to unstable current loops that become uncontrollable!"
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/399168', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/81645/']}
jdg_73918
stackexchange
llm_judgeable_groundtruth_similarity
2813817
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As the title states, I am unsure of how to construct an uncountable antichain in the power set $\mathcal{P}(\mathbb{N})$. Recall that an antichain is a set $\mathcal{A}\subset\mathcal{P}(\mathbb{N})$ where each element of $\mathcal{A}$ is not a subset of another element of $\mathcal{A}$. It seems that everything I attempt requires me to assign a property to the "$n$-th set" but that already makes it countable... Now provide the response and nothing else.
Enumerate the (countably many) vertices of the infinite rooted binary tree by $\mathbb{N}$. Then each infinite path of this tree will induce an infinite subset of $\mathbb{N}$. Moreover, two such subsets are not comparable with respect to inclusion (and indeed, the intersection of two such subsets will be finite since two distinct infinite paths in this tree have only finitely many common edges.) Now try to count how many infinite paths there are in the infinite rooted binary tree.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2813817', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/407845/']}
jdg_73919
stackexchange
llm_judgeable_groundtruth_similarity
50206002
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 planning to create a merchant table, which will have store locations of the merchant. Most merchants are small businesses and they only have a few stores. However, there is the odd multi-chain/franchise who may have hundreds of locations. What would be my solution if I want to put include location attributes within the merchant table? If I have to split it into multiple tables, how do I achieve that? Thank you! EDIT: How about splitting the table. To cater for the majority, say up to 5 locations I can place them inside the same table. But beyond 5, it will spill over to a normalised table with an indicator on the main table to say there are more than 5 locations. Any thoughts on how to achieve that? Now provide the response and nothing else.
You have a couple of options depending on your access patterns: Compress the data and store the binary object in DynamoDB. Store basic details in DynamoDB along with a link to S3 for the larger things. There's no transactional support across DynamoDB and S3 so there's a chance your data could become inconsistent. Rather than embed location attributes, you could normalise your tables and put that data in a separate table with the equivalent of a foreign key to your merchant table. But, you may then need two queries to retrieve data for each merchant, which would count towards your throughput costs. Catering for a spill-over table would have to be handled in the application code rather than at the database level: if (store_count > 5) then execute another query to retrieve more data If you don't need the performance and scalability of DynamoDB, perhaps RDS is a better solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50206002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9525104/']}
jdg_73920
stackexchange
llm_judgeable_groundtruth_similarity
14844407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my code the background-position-y doesn't work. In Chrome it's ok, but not working in Firefox. Anyone have any solution? Now provide the response and nothing else.
If your position-x is 0, there's no other solution than writing : background-position: 0 100px; background-position-x is a non-standard implementation coming from IE. Chrome did copy it, but sadly not firefox... However this solution may not be perfect if you have separate sprites on a big background, with rows and cols meaning different things... (for example different logos on each row, selected/hovered on right, plain on left)In that case, I'd suggest to separate the big picture in separate images, or write the different combinations in the CSS... Depending on the number of sprites, one or the other could be the best choice.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14844407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2060899/']}
jdg_73921
stackexchange
llm_judgeable_groundtruth_similarity
5633821
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two columns in a MySQL table: DateOfService (datetime) BirthDate (date) I want to run a MySQL query that will provide date difference between these two fields in months. How can I do this in a MySQL select query? Thanks. Now provide the response and nothing else.
Have a look at the TIMESTAMPDIFF() function in MySQL. What this allows you to do is pass in two TIMESTAMP or DATETIME values (or even DATE as MySQL will auto-convert) as well as the unit of time you want to base your difference on. You can specify MONTH as the unit in the first parameter: SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-04')-- 0 SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-05')-- 1 SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-15')-- 1 SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-12-16')-- 7 It basically gets the number of months elapsed from the first date in the parameter list. This solution accounts for the varying amount of days in each month (28,30,31) as well as leap years. If you want decimal precision in the number of months elapsed, it's a little more complicated, but here is how you can do it: SELECT TIMESTAMPDIFF(MONTH, startdate, enddate) + DATEDIFF( enddate, startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) MONTH ) / DATEDIFF( startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) + 1 MONTH, startdate + INTERVAL TIMESTAMPDIFF(MONTH, startdate, enddate) MONTH ) Where startdate and enddate are your date parameters, whether it be from two date columns in a table or as input parameters from a script: Examples: With startdate = '2012-05-05' AND enddate = '2012-05-27':-- Outputs: 0.7097 With startdate = '2012-05-05' AND enddate = '2012-06-13':-- Outputs: 1.2667 With startdate = '2012-02-27' AND enddate = '2012-06-02':-- Outputs: 3.1935
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5633821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300118/']}
jdg_73922
stackexchange
llm_judgeable_groundtruth_similarity
5153696
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple class as below class A {protected: int x;}; class B : public A {public: int y; void sety(int d) { y = d; } int gety() { return y; }}; int main() { B obj; obj.sety(10); cout << obj.gety(); getch();} How can I set the value of the protected instance variable A::x from an instance of the derived class B without creating an instance of class A . EDIT: Can we access the value of A::x using the object of B? Like obj.x ? Now provide the response and nothing else.
B is an A , so creating an instance of B is creating an instance of A . That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things: class A{protected: int x;};class B : public A{public: int y; int gety() const { return y; } void sety(int d) { y = d; } int getx() const { return x; } void setx(int d) { x = d; }};int main(){ B obj; // compiles cleanly because B::sety/gety are public obj.sety(10); std::cout << obj.gety() << '\n'; // compiles cleanly because B::setx/getx are public, even though // they touch A::x which is protected obj.setx(42); std::cout << obj.getx() << '\n'; // compiles cleanly because B::y is public obj.y = 20; std::cout << obj.y << '\n'; // compilation errors because A::x is protected obj.x = 84; std::cout << obj.x << '\n';} obj can access A::x just as an instance of A could, because obj is implicitly an instance of A .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5153696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134713/']}
jdg_73923
stackexchange
llm_judgeable_groundtruth_similarity
24035
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: Rotten potatoes have a distinctive unpleasant odour, and I can't find any definitive answer as to what the chemical involved is. I was thinking it might be Butyric acid, from the fermentation of the starch, but according to Wikipedia : Butyric acid is present in, and is the main distinctive smell of, human vomit. And those puppies don't smell like vomit. They're more like rotting flesh – the reason I'm asking is that I've spent half the day looking for a dead animal that the cat brought in or something, only to discover that the horrible smell was coming from the potato box. Now provide the response and nothing else.
My first guess was that it was putrescine and other polyamines---but the smell of putrefying potatoes actually comes from methyl mercaptan, dimethyl sulfide, and dimethyl trisulfide. Check it: Source: A. Kamiya, Y. Ose, Study on offensive odor (Report IV): A Consideration of Putrefaction and Offensive Odor of Solid Waste , Journal of Japan Society of Air Pollution, 18(5), 1983, pp 453-463. Notice that the headspace composition changes quite a bit with time. Most of the headspace chromatography studies I found dealt with early detection of disease organisms in infected potatoes, rather than potatoes in full putrefaction mode. You'll also find many references to solanine poisoning from potatoes; solanine is a toxic glycoalkaloid , is nonvolatile, and has nothing at all to do with the foul smell and toxic gas produced by putrid potatoes. Methyl mercaptan ($\rm CH_3SH$) has an odor described as "rotting cabbage" by ATDSR; it's one of the major contributors to the smell of farts (oh, sorry, "flatus" if we're being polite). It has an odor detection threshold as low as 1 ppb. Dimethyl sulfide ($\rm (CH_3)_2S$) is responsible for the smell of the sea (in low concentrations); it too has a cabbagy smell. Dimethyl trisulfide ($\rm CH_3SSSCH_3$) is present in relatively smaller amounts but it has an even stronger odor. The detection threshold is around 1 part per trillion, and it is apparently a strong insect attractant. The gases produced by rotting potatoes are quite toxic (see Rotting potatoes in basement kill four members of Russian family ). (To keep the notes below in context, in my original answer I said that a plot point in "The Walking Dead" was that zombies couldn't smell delicious humans if they were wearing coats smeared with rotting flesh. I suggested that when the zombie apocalypse arrives, packing your pockets with putrid potatoes might work, too. Now I'm not so sure. Can zombies distinguish between polyamines and sulfur compounds? Perhaps they're stench connoisseurs.)
{}
{'log_upvote_score': 6, 'links': ['https://chemistry.stackexchange.com/questions/24035', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/12923/']}
jdg_73924
stackexchange
llm_judgeable_groundtruth_similarity
8283213
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 just started learning F#. I wonder how can I determine whether the argument of a function is a tuple? let tuple = (1, 2)let notTuple = 3let isTuple t = // returns 'true' if t is a tuple, 'false' otherwiseprintfn "%b" isTuple tuple // trueprintfn "%b" isTuple notTuple // false Now provide the response and nothing else.
FSharpType.IsTuple [MSDN] does this. let isTuple value = match box value with | null -> false | _ -> FSharpType.IsTuple(value.GetType())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8283213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1067514/']}
jdg_73925
stackexchange
llm_judgeable_groundtruth_similarity
8821476
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 NSIS script that is working well for a large application. I have read many threads all over the web, but cannot get a clear answer to the following: is it possible to install an application using NSIS which, when launched (regardless of the type of user) automatically is run as administrator? If this is possible how can it be achieved? Note: I am already imposing that the NSIS package must be run as admin using RequestExecutionLevel admin I have tried writing the UAC requirement to the applications registry entry using this method but I could not get the RUNASADMIN command to compile as it is not in the required format for NSIS. Now provide the response and nothing else.
To ensure that the installer is running as administrator usually I recommend this little example: Outfile RequireAdmin.exeRequestExecutionLevel admin ;Require admin rights on NT6+ (When UAC is turned on)!include LogicLib.nshFunction .onInitUserInfo::GetAccountTypepop $0${If} $0 != "admin" ;Require admin rights on NT4+ MessageBox mb_iconstop "Administrator rights required!" SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED Quit${EndIf}FunctionEndPage InstFileSectionSectionEnd The installed application should perform similar steps if it always needs to run as admin, for a Win32 app that would be: Add a requestedExecutionLevel element to the manifest with the level attribute set to requireAdministrator Call IsUserAnAdmin or CheckTokenMembership to make sure you really are admin. If by "automatically is run as administrator" you mean bypass the UAC elevation, then no that is not really possible, the whole point of UAC is to allow the user to confirm/deny privileged operations! Some applications get around this by installing a NT service that performs whatever operation they require on behalf of the application. I would not recommend this because it fills the users machine up with services and could weaken the security of the system if the service is not coded correctly. If you did not write the application you are installing then your options are a bit more limited. If the application does not have a manifest at all you could use a external ( myapp.exe.manifest ) manifest. Setting the RUNASADMIN string under the AppCompatFlags key is not really something the installer should be doing, those compatibility options are supposed to be controlled by the user, not applications. The forum thread you linked to also tell you about two ways to set the SLDF_RUNAS_USER flag on a shortcut, this will not ensure that the application is started as admin in all situations, only when the application is started from the shortcut but it might be your only option if you cannot change the application itself...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8821476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/626442/']}
jdg_73926
stackexchange
llm_judgeable_groundtruth_similarity
1857630
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 $\mathcal{A}$ be a non (necessarily) unital commutative Banach algebra, and let $$ M_{\mathcal{A}} = \{ \phi:\mathcal{A} \to \mathbb{C} : \phi \mbox{ is multiplicative and not trivial}\} $$and$$ \mathrm{Max}(\mathcal{A})=\{ I \lhd \mathcal{A} : I \mbox{ maximal} \}.$$If $\mathcal{A}$ is unital, it is well known that there is a bijection between $M_{\mathcal{A}}$ and $\mathrm{Max}(\mathcal{A})$ sending each functional to its kernel (the inverse is given by the quotient and the Gelfand-Mazur theorem). My question is, is this still a bijection in the non-unital case? I'm aware that if $\mathcal{A}$ is a commutative C*-algebra it is still a bijection. Also that the restriction gives a bijection from $M_{\tilde{\mathcal{A}}} \setminus \{ \pi:\tilde{\mathcal{A}} \to \mathbb{C} \}$ to $M_{\mathcal{A}}$; but this fact don't seem enough to conclude the result. I haven't been able to find a source for this. Thanks in advance. Now provide the response and nothing else.
The kernels of nonzero homomorphisms to $\mathbb C$ are modular ideals, terminology that might help you find more references. Without any further restriction on the algebras, using the zero product is a way to provide trivial counterexamples. E.g., take $\mathbb C$ with the $0$ product, which has maximal ideal $\{0\}$ and no nonzero homomorphisms to $\mathbb C$. Googling led me to the following maybe more interesting example, Example 1.3 in this Feinstein and Somerset article : Take $C[0,1]$ with its usual Banach space structure but with multiplication $(f\diamond g)(t) = f(t)g(t)t$. Then the ideal of functions vanishing at $0$ is maximal but not the kernel of a nonzero homomorphism to $\mathbb C$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1857630', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79036/']}
jdg_73927
stackexchange
llm_judgeable_groundtruth_similarity
20263195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a vaadin TextArea as a rough console. The user can enter commands which should be executed when he presses the enter key. Is there a way to specify this with a listener on the TextArea? The closest thing I found is to use: TextArea textArea = new TextArea();textArea.addTextChangeListener(this);textArea.setTextChangeEventMode(TextChangeEventMode.EAGER); And handle the text change event: @Overridepublic void textChange(TextChangeEvent event) { System.out.println(event.getText());} This is however triggered as soon as text has been entered in the TextArea. I would like to be notified only when the enter key has been pressed. Now provide the response and nothing else.
You cannot listen to shortcut keys on the textarea itself, but a simple solution would be to add a submit button and use enter as it's shortcut: Button b = new Button("submit", new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // handle your event }});layout.addComponent(b);b.setClickShortcut(KeyCode.ENTER); You can hide the button itself if you don't wish it: b.setVisible(false); Another solution would be to use ShortcutActions and Handlers as described in here: https://vaadin.com/book/-/page/advanced.shortcuts.html But in either case you have to take into account that listening to enter key will cause a conflict when using a TextArea component because you also need to use the same key to get to the next line in the TextArea.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20263195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/826938/']}
jdg_73928
stackexchange
llm_judgeable_groundtruth_similarity
2829423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say that I have a JDBC ResultSet, and I call the getLong() or getshort() method. For which of the following SQL types {SMALLINT, INT, BIGINT} should I get long, and for which types should I get an error? In other words, if I have an INT and I want a SMALLINT (A short), would I get it, or would I get an error? Similarly, if I have an INT and want a BIGINT (a long), would I get it, or would I get an error? The Javadocs (listed below) say nothing. public long getLong(int columnIndex) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a long in the Java programming language. Parameters: columnIndex - the first column is 1, the second is 2, ... Returns: the column value; if the value is SQL NULL, the value returned is 0 Throws: SQLException - if a database access error occurs Now provide the response and nothing else.
From the Retrieving Values from Result Sets section of the Java tutorials: JDBC allows a lot of latitude as far as which getXXX methods you can use to retrieve the different SQL types. For example, the method getInt can be used to retrieve any of the numeric or character types. The data it retrieves will be converted to an int; that is, if the SQL type is VARCHAR , JDBC will attempt to parse an integer out of the VARCHAR. The method getInt is recommended for retrieving only SQL INTEGER types, however, and it cannot be used for the SQL types BINARY, VARBINARY, LONGVARBINARY, DATE , TIME, or TIMESTAMP. I'm interpreting that to mean that the data will be coerced. It should work just fine if it's an upcast, but I'd expect potential loss of precision (naturally) if, for example, you're reading a LONG value using getInt() . I'd expect an Exception to be thrown if you try to read text using getInt() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2829423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23072/']}
jdg_73929
stackexchange
llm_judgeable_groundtruth_similarity
62836374
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 just implemented a global search in my website and I started having issues with React-Router. It is not updating the view if the url changes parameters. For example, navigating from /users/454545 to /teams/555555 works as expected. However, navigating from /teams/111111 to teams/222222 changes the url but the component is still /teams/111111 . Here is my code fo the Search Input field. const SearchResult = ({ id, url, selectResult, text, type }) => ( <Row key={id} onClick={() => selectResult(url)} width='100%' padding='5px 15px 5px 15px' style={{cursor: 'pointer'}}> <Column alignItems='flex-start' style={{width: '100%'}}> <Label textAlign='left' color='#ffffff'>{text}</Label> </Column> <Column style={{width: '100%'}}> <Label textAlign='right' color='#ffffff'>{type}</Label> </Column> </Row>)const SearchInput = (props) => { const { isSearching, name, onChange, onClear, results } = props; return ( <Section width='100%' style={{display: 'flex', position: 'relative'}}> <Wrapper height={props.height} margin={props.margin}> <i className="fas fa-search" style={{color: 'white'}} /> <input id='search_input' placeholder={'Search for a team, circuit, or user'} name={name} onChange={onChange} style={{outline: 'none', backgroundColor: 'transparent', borderColor: 'transparent', color: '#ffffff', width: '100%'}} /> {onClear && !isSearching && <i onClick={onClear} className="fas fa-times-circle" style={{color: '#50E3C2'}} />} {isSearching && <Spinner viewBox="0 0 50 50" style={{marginBottom: '0px', height: '50px', width: '50px'}}> <circle className="path" cx="25" cy="25" r="10" fill="none" strokeWidth="4" /> </Spinner> } </Wrapper> {results && <Section backgroundColor='#00121A' border='1px solid #004464' style={{maxHeight: '400px', position: 'absolute', top: '100%', left: '0px', width: '97%', overflowY: 'scroll'}}> <Section backgroundColor='#00121A' style={{display: 'flex', flexDirection: 'column', padding: '15px 0px 0px 0px', justifyContent: 'center', alignItems: 'center', width: '100%'}}> {results.length === 0 && <Text padding='0px 0px 15px 0px' color='#ffffff' fontSize='16px'>We didn't find anything...</Text>} {results.length !== 0 && results.map(r => <SearchResult selectResult={props.selectResult} id={r._id} url={r.url} text={r.text} type={r.type} />)} </Section> </Section>} </Section> )}export default SearchInput; The parent component is a nav bar which looks something like this. I've slimmed it down for readability. import React, { useState, useEffect } from 'react';import { connect } from 'react-redux';import SearchInput from '../shared/inputs/SearchInput';const TopNav = (props) => { const [search, setSearch] = useState(null); const [searchResults, setSearchResults] = useState(null); const debouncedSearchTerm = useDebounce(search, 300); const [isSearching, setIsSearching] = useState(false); function clearSearch() { document.getElementById('search_input').value = ''; setSearchResults(null); } function searchChange(e) { if (!e.target.value) return setSearchResults(null); setSearch(e.target.value); setIsSearching(true); } async function updateQuery(query) { const data = { search: query } const results = await api.search.query(data); setSearchResults(results); setIsSearching(false); } function selectResult(url) { props.history.push(url); setSearchResults(null); } function useDebounce(value, delay) { // State and setters for debounced value const [debouncedValue, setDebouncedValue] = useState(value); useEffect( () => { // Update debounced value after delay const handler = setTimeout(() => { setDebouncedValue(value); }, delay); // Cancel the timeout if value changes (also on delay change or unmount) // This is how we prevent debounced value from updating if value is changed ... // .. within the delay period. Timeout gets cleared and restarted. return () => { clearTimeout(handler); }; }, [value, delay] // Only re-call effect if value or delay changes ); return debouncedValue; } useEffect(() => { if (debouncedSearchTerm) { updateQuery(debouncedSearchTerm); } else { setSearchResults(null); } }, [user, debouncedSearchTerm]) return ( <ContentContainer style={{boxShadow: '0 0px 0px 0 #000000', position: 'fixed', zIndex: 1000}} backgroundColor='#00121A' borderRadius='0px' width='100%'> <Section style={{display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50px'}} width='1200px'> <SearchInput height={'30px'} margin='0px 20px 0px 0px' isSearching={isSearching} selectResult={selectResult} onChange={searchChange} onClear={clearSearch} results={searchResults} /> </Section> </ContentContainer> )}function mapStateToProps(state) { return { user: state.user.data, notifs: state.notifs }}export default connect(mapStateToProps, { logout, fetchNotifs, updateNotifs })(TopNav); Tl;DR Using react-router for site navigation. Doesn't update component if navigating from /teams/111111 to /teams/222222 but does update if navigating from /users/111111 to /teams/222222 . Any and all help appreciated! Now provide the response and nothing else.
When a URL's path changes, the current Component is unmounted and the new component pointed by the new URL is mounted. However, when a URL's param changes, since the old and new URL path points to the same component, no unmount-remount takes place; only the already mounted component receives new props. One can make use of these new props to fetch new data and render updated UI. Suppose your param id is parameter . With hooks: useEffect(() => { // ... write code to get new data using new prop, also update your state}, [props.match.params.parameter]); With class components: componentDidUpdate(prevProps){ if(this.props.match.params.parameter!== prevProps.match.params.parameter){ // ... write code to get new data using new prop, also update your state }} Use KEY: Another approach could be to use the unique key prop. Passing a new key will force acomponent to remount. <Route path="/teams/:parameter" render={(props) => ( <Team key={props.match.params.parameter} {...props} />)} />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62836374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5012993/']}
jdg_73930
stackexchange
llm_judgeable_groundtruth_similarity
7503276
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 read from an ncx file (i.e. xml file) using XElement: XElement foundNode = ncx.Descendants("navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault(); As a result, foundNode is null because ncx.Descendants("navPoint") returns an empty enumeration. But the data is there: <?xml version='1.0' encoding='utf-8'?><ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en"> <head> <meta content="8eab2efe-d584-478a-8c73-1304d2ae98fa" name="dtb:uid"/> <meta content="3" name="dtb:depth"/> <meta content="calibre (0.8.12)" name="dtb:generator"/> <meta content="0" name="dtb:totalPageCount"/> <meta content="0" name="dtb:maxPageNumber"/> </head> <docTitle> <text>Fine</text> </docTitle> <navMap> <navPoint class="chapter" id="27665f37-ecf5-4934-a044-4f77152e54d9" playOrder="1"> <navLabel> <text>I. BLIND</text> </navLabel> <content src="Fine_split_003.html"/> Could you please explain what is wrong here? Thanks. Now provide the response and nothing else.
You need to take namespace in XML into account: XDocument ncx = XDocument.Load("file.xml");XNamespace df = ncx.Root.Name.Namespace;XElement foundNode = ncx.Descendants(df + "navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7503276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/643692/']}
jdg_73931
stackexchange
llm_judgeable_groundtruth_similarity
102448
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a bash script that creates 5 files with the extension ".P" and write a line of "something" into them. "P" represents a number and it's the PID of the process that creates the file. How can you do that?I am creating my file and writing into it like this: echo "something" > file_name Now provide the response and nothing else.
If you want to know the PID of the currently running bash session (which may very well be the one running your shell script and nothing else), you can use either $$ or ${BASHPID} . They are similar but subtly different; quoting the GNU bash 4.2 man page, "Shell variables" section: BASHPID Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized. You may also find ${PPID} helpful; it holds the process ID of the parent process of the current bash session. If you want to go any further than that, you'll have to write some code to walk the process tree, and that will almost certainly be OS-dependent. Try echo "something" > file_name.$$ in your shell for an example. And if you are doing anything serious, please always quote anything involving environment variables that you didn't set to a known safe value yourself. If what you want is the PID of the process that originally created a file, as indicated in the title, I doubt that's possible (although it would depend on exactly which OS you're running). It just wouldn't be a useful piece of information to store in the general case, as PIDs are both reused as well as normally more or less random. On a busy multi-user system, they for all intents and purposes will be random for any given user.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/102448', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/53006/']}
jdg_73932
stackexchange
llm_judgeable_groundtruth_similarity
45829838
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 find the solution to this and can't understand what I'm doing wrong. On my Linux server I have run the following command: ssh-keygen -t rsa This generated an id_rsa and id_rsa.pub file. I then copied them both locally and attempted to run the following code: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('myserver', username='myuser', key_filename='id_rsa') sftp = ssh.open_sftp() sftp.chdir('/path/to/file') sftp.get(file, os.path.join(tmp_dir, '{0}.existing-{1}'.format('myfile', current_datetime)))except Exception, err: logging.debug(err) logging.info('Error connecting to Host') I get the following error in my log: 2017-08-22 22:41:54,486 Switch to new keys ...2017-08-22 22:41:54,502 Adding ssh-ed25519 host key for myserver.domain.com: 51ac2fe875499371256dd8c5a132f3942017-08-22 22:41:54,502 Trying key 7688e32d30edb2c94bfe39be9897004f from id_rsa2017-08-22 22:41:54,532 userauth is OK2017-08-22 22:41:54,549 Authentication (publickey) failed.2017-08-22 22:41:54,563 not a valid OPENSSH private key file2017-08-22 22:41:54,563 Error connecting to Host2017-08-22 22:41:54,657 EOF in transport thread am I missing something? It is a valid OPENSSH private key file. edit - if I use the id_rsa.pub I get the following: 2017-08-22 22:58:09,631 Kex agreed: ecdh-sha2-nistp2562017-08-22 22:58:09,631 HostKey agreed: ssh-ed255192017-08-22 22:58:09,631 Cipher agreed: aes128-ctr2017-08-22 22:58:09,631 MAC agreed: hmac-sha2-2562017-08-22 22:58:09,631 Compression agreed: none2017-08-22 22:58:09,694 kex engine KexNistp256 specified hash_algo <built-in function openssl_sha256>2017-08-22 22:58:09,710 Switch to new keys ...2017-08-22 22:58:09,726 Adding ssh-ed25519 host key for myserver.domain.com: 51ac2fe875499371256dd8c5a132f3942017-08-22 22:58:09,726 not a valid OPENSSH private key file2017-08-22 22:58:09,726 Error connecting to Host2017-08-22 22:58:09,819 EOF in transport thread Why? Now provide the response and nothing else.
I have a Paramiko RSA key authentication setup running. Here is a summary of what I did: run ssh-keygen -t rsa to generate the id_rsa and id_rsa.pub files copy contents of id_rsa.pub into ~/.ssh/authorized_keys (on thetarget system) copy the id_rsa (private) keyfile onto the client machine (on the target I have mode 755 on .ssh/ and 644 on authorized_keys) The following code runs a login using Paramiko: import loggingimport paramikologger = paramiko.util.logging.getLogger()hdlr = logging.FileHandler('app.log')formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')hdlr.setFormatter(formatter)logger.addHandler(hdlr)logger.setLevel(logging.INFO)try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) k = paramiko.RSAKey.from_private_key_file('id_rsa') ssh.connect('160.100.28.216', username='edwards', pkey = k) sftp = ssh.open_sftp() sftp.chdir('/home/edwards')except Exception, err: logging.debug(err) logging.info('Error connecting to Host') The following is seen in the app.log file: 2017-08-23 16:52:33,154 INFO Connected (version 2.0, client OpenSSH_6.6.1) 2017-08-23 16:52:46,926 INFO Authentication (publickey) successful! 2017-08-23 16:52:47,203 INFO [chan 0] Opened sftp connection (server version 3) (NB: The Paramiko client is using the private key file.) This is all on Python 2.7.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45829838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2977876/']}
jdg_73933
stackexchange
llm_judgeable_groundtruth_similarity
37258
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to set up a custom toolchain where the browser (Firefox or, preferrably, Chrome) is often/frequently/constantly forced to refresh from the commandline. (The idea is to instantly see the visual changes in the html/webapp I'm editing in an adjacent Emacs frame - without having to constantly tab to the browser to do a manual refresh.) The closest I've come so far is to run google-chrome FILE_PATH . However this opens a new tab every time. Are there other approaches? Now provide the response and nothing else.
Something to play with It uses xdotool , which lets you script windows/desktop actions. If you supply the name of the browser as an argument, it'll find and reload the current page. You can set a default browser, so you don't need to supply one each time, and you can change whether you send a CTRL-R to reload, or SHIFT-CTRL-R to reload without cache. It should flip to your browser, reload the page, then flip back to whatever window you called this from. I use this often by putting browser in background, with editor window set to 'ON-TOP' so it's always visible, hot-key this script, or call it from your editor, and it'll return your focus when it's done. I'm a vim user, and I could see making an autocommand to automatically trigger this script whenever a given file was written, so the browser would refresh when appropriate, I know you can do the same. #!/bin/bash## L Nix <[email protected]># reload browser window## whether to use SHIFT+CTRL+R to force reload without cacheRELOAD_KEYS="CTRL+R"#RELOAD_KEYS="SHIFT+CTRL+R"## set to whatever's given as argumentBROWSER=$1## if was empty, default set to name of browser, firefox/chrome/opera/etc..if [ -z "${BROWSER}" ]; then BROWSER=firefoxfi## get which window is active right nowMYWINDOW=$(xdotool getactivewindow)## bring up the browserxdotool search --name ${BROWSER} windowactivate --sync# send the page-reload keys (C-R) or (S-C-R)xdotool search --name ${BROWSER} key --clearmodifiers ${RELOAD_KEYS}## sometimes the focus doesn't work, so follow up with activatexdotool windowfocus --sync ${MYWINDOW}xdotool windowactivate --sync ${MYWINDOW}#
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/37258', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/18092/']}
jdg_73934
stackexchange
llm_judgeable_groundtruth_similarity
36629
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question arose when I thought that on Normal Days , at least I have observed bright sun while going outside, going to office, in park etc. for less than a second. It happens almost daily. Not deliberately but that's how things work I guess. Similar example is playing cricket. Many times sun comes in the way of ball in the air and again I have a glimpse of sun. To me, it is very common as I've seen in international cricket matches on TV. On the other hand, in case of the days of Solar Eclipse , on one or two occasions, when the sun wasn't very bright due to clouds, I've deliberately observed the partial eclipse just for a glimpse, just to confirm it's actually cut . And I confirmed it. (How fast it was? It was not like I stood still and observed the sun for less than a second and then closed eyes. It was like this: I started moving my head and sight from earth surface and in a faster way moved my head towards sun and without any break, stopped at safe location on earth again where there was no sun) . And it did literally no harm to me. So my doubt is: Why there's so much theories that you must not stare sun even for less than a second or even a glimpse by mistake? If you see news on eclipse day, you'll see full news about this. But on any other normal day, no such news. Is there something special, something more bright on solar eclipse day? Will it damage eyes? Now provide the response and nothing else.
Glancing at a partial solar eclipse is about as dangerous as glancing at the Sun on any other day. If you look at the Sun a few minutes after sunrise or a few minutes before sunset, when the Sun's altitude is low, the light is filtered through a lot of air, and most of the ultraviolet is scattered, so it's a lot less dangerous than looking at the Sun in the middle of the day. However, during an eclipse, people tend to look at the Sun for more than just a few minutes, and that's not healthy for the eyes. The big danger of looking at a solar eclipse without proper protection occurs when it's a total (or nearly total) eclipse. When the eclipse is near totality, the sky is dark, so your pupils dilate, letting in more light. But the light rays coming from that small sliver of Sun are just as bright as normal, and have the same proportion of UV (ultraviolet) as full sunlight. Those UV rays can cause a lot of damage to the retina very quickly, and that damage can be permanent.
{}
{'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/36629', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/30361/']}
jdg_73935
stackexchange
llm_judgeable_groundtruth_similarity
3297
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are tons of NP-complete problems around and sources collecting them, e.g. see the book by Garey and Johnson. I would be interested to see a list of NEXP-complete problems as well. Is there one available? As I assume there isn't, I open this question (is this supposed to be a community wiki? I don't know about this stuff). Ideally the list should cover the different "types" of NEXP-complete problems, perhaps with some healthy redundancy to get the big picture, but without repeating itself too much. For example, it is good to have two or three different succinct versions of the same NP-complete problem as examples, if the succinct encodings come in slightly different forms. Not a dozen. A clean way to add the redundancy is by adding clauses of the form "Also NEXP-complete if BLAH". Clauses of the form "Remains NEXP-complete if the input graph has degree at most BLAH" are also welcome. Finally, let me add a personal preference. I am most of all interested in complete problems of "algebraic" flavor, if there are any. For example, my favorite #P-complete problem is the permanent for its algebraic flavor. I hope the equality NEXP = MIP can also provide some nice algebraic NEXP-complete problem that I am not aware of. Now provide the response and nothing else.
For some NP-complete problems, there's a SUCCINCT variant that's NEXP-complete. An example is SUCCINCT HAMILTON PATH: A Boolean circuit with 2 n inputs and one output represents a graph on 2 n vertices. To determine if there is an edge between vertices i and j , encode i and j in n bits each, and feed their concatenation to the circuit: there is an edge between these vertices iff the output of the circuit is true. Given such a circuit, is there a Hamilton path in the graph represented by the circuit? Similarly, there's SUCCINCT 3SAT, SUCCINCT KNAPSACK, etc. Reference Hana Galperin, and Avi Wigderson (1983), "Succinct representations of graphs", Information and Control 56:3, pp. 183–198.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/3297', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1509/']}
jdg_73936
stackexchange
llm_judgeable_groundtruth_similarity
1453171
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 looking at an algorithm that can map between characters with diacritics ( tilde , circumflex , caret , umlaut , caron ) and their "simple" character. For example: ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> ná --> aä --> aấ --> aṏ --> o Etc. I want to do this in Java, although I suspect it should be something Unicode-y and should be doable reasonably easily in any language. Purpose: to allow easily search for words with diacritical marks. For example, if I have a database of tennis players, and Björn_Borg is entered, I will also keep Bjorn_Borg so I can find it if someone enters Bjorn and not Björn. Now provide the response and nothing else.
I have done this recently in Java: public static final Pattern DIACRITICS_AND_FRIENDS = Pattern.compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");private static String stripDiacritics(String str) { str = Normalizer.normalize(str, Normalizer.Form.NFD); str = DIACRITICS_AND_FRIENDS.matcher(str).replaceAll(""); return str;} This will do as you specified: stripDiacritics("Björn") = Bjorn but it will fail on for example Białystok, because the ł character is not diacritic. If you want to have a full-blown string simplifier, you will need a second cleanup round, for some more special characters that are not diacritics. Is this map, I have included the most common special characters that appear in our customer names. It is not a complete list, but it will give you the idea how to do extend it. The immutableMap is just a simple class from google-collections. public class StringSimplifier { public static final char DEFAULT_REPLACE_CHAR = '-'; public static final String DEFAULT_REPLACE = String.valueOf(DEFAULT_REPLACE_CHAR); private static final ImmutableMap<String, String> NONDIACRITICS = ImmutableMap.<String, String>builder() //Remove crap strings with no sematics .put(".", "") .put("\"", "") .put("'", "") //Keep relevant characters as seperation .put(" ", DEFAULT_REPLACE) .put("]", DEFAULT_REPLACE) .put("[", DEFAULT_REPLACE) .put(")", DEFAULT_REPLACE) .put("(", DEFAULT_REPLACE) .put("=", DEFAULT_REPLACE) .put("!", DEFAULT_REPLACE) .put("/", DEFAULT_REPLACE) .put("\\", DEFAULT_REPLACE) .put("&", DEFAULT_REPLACE) .put(",", DEFAULT_REPLACE) .put("?", DEFAULT_REPLACE) .put("°", DEFAULT_REPLACE) //Remove ?? is diacritic? .put("|", DEFAULT_REPLACE) .put("<", DEFAULT_REPLACE) .put(">", DEFAULT_REPLACE) .put(";", DEFAULT_REPLACE) .put(":", DEFAULT_REPLACE) .put("_", DEFAULT_REPLACE) .put("#", DEFAULT_REPLACE) .put("~", DEFAULT_REPLACE) .put("+", DEFAULT_REPLACE) .put("*", DEFAULT_REPLACE) //Replace non-diacritics as their equivalent characters .put("\u0141", "l") // BiaLystock .put("\u0142", "l") // Bialystock .put("ß", "ss") .put("æ", "ae") .put("ø", "o") .put("©", "c") .put("\u00D0", "d") // All Ð ð from http://de.wikipedia.org/wiki/%C3%90 .put("\u00F0", "d") .put("\u0110", "d") .put("\u0111", "d") .put("\u0189", "d") .put("\u0256", "d") .put("\u00DE", "th") // thorn Þ .put("\u00FE", "th") // thorn þ .build(); public static String simplifiedString(String orig) { String str = orig; if (str == null) { return null; } str = stripDiacritics(str); str = stripNonDiacritics(str); if (str.length() == 0) { // Ugly special case to work around non-existing empty strings // in Oracle. Store original crapstring as simplified. // It would return an empty string if Oracle could store it. return orig; } return str.toLowerCase(); } private static String stripNonDiacritics(String orig) { StringBuilder ret = new StringBuilder String lastchar = null; for (int i = 0; i < orig.length(); i++) { String source = orig.substring(i, i + 1); String replace = NONDIACRITICS.get(source); String toReplace = replace == null ? String.valueOf(source) : replace; if (DEFAULT_REPLACE.equals(lastchar) && DEFAULT_REPLACE.equals(toReplace)) { toReplace = ""; } else { lastchar = toReplace; } ret.append(toReplace); } if (ret.length() > 0 && DEFAULT_REPLACE_CHAR == ret.charAt(ret.length() - 1)) { ret.deleteCharAt(ret.length() - 1); } return ret.toString(); } /* Special regular expression character ranges relevant for simplification -> see http://docstore.mik.ua/orelly/perl/prog3/ch05_04.htm InCombiningDiacriticalMarks: special marks that are part of "normal" ä, ö, î etc.. IsSk: Symbol, Modifier see http://www.fileformat.info/info/unicode/category/Sk/list.htm IsLm: Letter, Modifier see http://www.fileformat.info/info/unicode/category/Lm/list.htm */ public static final Pattern DIACRITICS_AND_FRIENDS = Pattern.compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+"); private static String stripDiacritics(String str) { str = Normalizer.normalize(str, Normalizer.Form.NFD); str = DIACRITICS_AND_FRIENDS.matcher(str).replaceAll(""); return str; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1453171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63051/']}
jdg_73937
stackexchange
llm_judgeable_groundtruth_similarity
54041246
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to java 8, I would like to optimise my code bellow: public Response create() { try{ ... } catch (Exception e) { codeA; } finally { codeB; }}public Response update() { try{ ... } catch (Exception e) { codeA; } finally { codeB; }} I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code. } catch (Exception e) { codeA;} finally { codeB;} Now provide the response and nothing else.
Depends what you do in the ... . You could do something like this: private Response method(Supplier<Response> supplier) { try{ return supplier.get(); } catch (Exception e) { codeA; } finally { codeB; }} and invoke like: public Response create() { return method(() -> { ... for create }); }public Response update() { return method(() -> { ... for update }); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54041246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10867841/']}
jdg_73938
stackexchange
llm_judgeable_groundtruth_similarity
17395718
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 bunch of links in my app. I added rel='external' target='_blank' to all of them. In the Ripple emulator, or in a regular desktop browser, this works great. But on my Android (JB 4.2.2) it opens the link in the same window. Hitting "back" takes me back to the app, but everything is screwed and the app does not work as planned (script events do not react), until physically reloaded. How do I ensure that a link opens in the device's browser? Do I need to use a Cordova plugin? (I'm using Cordova 2.9.0, jQuery 1.10.1, jQuery Mobile 1.3.1) Now provide the response and nothing else.
This has been really fickle with Cordova/PhoneGap in the last few releases, I believe because of the InAppBrowser work which might be a solution for you. What is working for us to launch in the external browser is: window.open("http://myurl.com", '_system'); In our case, we want to find all external links and launch them in Safari/Chrome (and keep internal links in our Angular router). This probably isn't the most elegant solution, but we are doing this right now by capturing input events on the links and taking over the behavior like so: $(document).on('mousedown','a', function(e) { e.preventDefault(); var elem = $(this); var url = elem.attr('href'); if (url.indexOf('http://') !== -1) { window.open(url, '_system'); } }); I hope that helps you a bit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17395718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19856/']}
jdg_73939
stackexchange
llm_judgeable_groundtruth_similarity
412053
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 was asked on an exam whether the Schrodinger equation can be used to describe planetary motion and my answer was "No, because the solutions are wavefunctions which give probabilities but everything can be exactly measured for large objects." Then I read this article which suggested it should be possible. What would the Hamiltonian be, and how do we get definite results instead of probabilities? Now provide the response and nothing else.
Yes, you can construct classical orbits from the Schrodinger equation, as long as you take the right limit. For example, consider the hydrogen atom. While the lower energy levels, like the $1s$ or $2p$ look nothing like classical orbits, you may construct wavefunctions that do by superposing solutions with high $n$ appropriately. Such solutions obey the Schrodinger equation with Hamiltonian $H = p^2/2m - e^2/r$, but have a sharp peak, which orbits the nucleus in a circular or elliptical trajectory. For very high $n$ the peak can get extremely sharp, so the position is definite for all practical purposes. Heuristically this works because, given a state that is a superposition of states with different $\ell$'s and $m$'s but the same $n$, the coefficients of the $|n, \ell, m \rangle$ states inside are essentially a discrete Fourier transform of the position space wavefunction, with $O(n^2)$ entries. For higher $n$, you can use this to build sharper and sharper peaks. This reasoning is not even necessary; we know it has to work because everything is quantum, so there must be a way to reproduce classical results within quantum mechanics. By treating a planet as a single particle, the same reasoning holds. However, as pointed out by other answers, this isn't the full story, because a planet is much more complicated than an electron. In fact this complication is essential, because if a planet and star were single particles in perfectly empty space, there's no particular reason the planet would end up in one of these classical-looking states with a sharply peaked position. For a real planet this is a consequence of decoherence: superpositions that don't have sharply peaked positions are not stable against interaction with the environment. That's how the classical world emerges. I should also note that the link you gave is not an example of this. That article is about an astrophysical quantity that happens to be described by an equation with the same form as the Schrodinger equation, but absolutely nothing quantum is going on. It's just a coincidence, which arises because there aren't that many different low-order PDEs. If there is any reason at all, it's simply that we look for simple equations on both microscopic and macroscopic scales.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/412053', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/186417/']}
jdg_73940