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
|
14842
|
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:
Please, take a look at the chart below. As you can see the first period the volatility is high and the second is low. How can I check if the volatility is stationary (homogeneous) during the entire period? The plot represents the residuals of a simple linear regression.
Now provide the response and nothing else.
|
A simple method , useful both for exploration and hypothesis testing, takes the Durbin Watson statistic and the semivariogram as its point of departure: denoting the sequence of residuals by $e_t$ (with $t$ the "index" of the plot), compute $$\gamma(t) = \frac{1}{2}(e_{t+1}-e_t)^2.$$ The data (as presented in the question) result in this plot: (The residual values have been uniformly rescaled compared to what is shown on the vertical axis in the original plot. This does not affect the subsequent analysis.) Typically there will be scatter, as shown here. To visualize this better, smooth it : This plot is on a square root scale (let's call this the "dispersion") to dampen the extreme oscillations. The wiggly blue lines are a modest smooth (medians of 3 followed by a lag-13 moving average). The solid red line is an aggressive smooth of that. (Here, it's a Gaussian convolution; in general, though, I would recommend a Lowess smooth of $\sqrt{\gamma(t)}$.) Together, these lines trace out detailed fluctuations in dispersion and intermediate-range trends, respectively. The yellow and green thresholds, shown for reference, delimit (a) the lowest smoothed dispersion in the first 225 indexes and (b) the mean smoothed dispersion from index 226 onwards. I chose the changepoint of 225 by inspection. Clearly almost all the smoothed dispersion values above 6 occurred during the first 225 indexes. From index=225 to index=350 or so, the smoothed dispersions decrease and then stay constant around 2.7. The change in dispersion is now visually obvious. For most purposes--where the change is so clear and strong--that's all one needs. But this approach lends itself to formal testing, too . To identify a point where the dispersion changed, and to estimate the uncertainty of that point, apply a sequential online changepoint procedure to the sequence $(\gamma(t))$. An even more straightforward check, when you suspect there has been just one major change in volatility, is to use regression to check the dispersion for a trend. If one exists, you can reject the null hypothesis of homogeneous volatility.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/14842', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5405/']}
|
jdg_377241
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51529814
|
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 finally gave up and wrote a for loop to initialize a simple array of objects where each object has an incremented counter ( id ) as an attribute of the object. In other words, I just want: var sampleData = [{id: 1},{id: 2},...]; I was hoping for a compact syntax I could just put on my return statement. let sampleData = [];for (var p = 0; p < 25; p++){ sampleData.push({id: p});}return { data: sampleData, isLoading: true};
Now provide the response and nothing else.
|
Array.from() is a nice way to do this. You can pass a {length: somlength} object or some other array-like object and a function that defines each item. The first argument (calling it _ just to indicate it's not used) to that function would be the item from an array we passed in (but we only passed in a length so it doesn't mean much), the second i is the index, which is used for your id : let sampleData = Array.from({length: 10}, (_, id) => ({id}))console.log(sampleData)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51529814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9101619/']}
|
jdg_377242
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6657479
|
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 I have a sprite. Its axis-aligned bounding box (AABB) is easy to find since I know the width and height. Say I rotate it 45 degrees, I don't think the AABB would be big enough to cover it, so I need a new AABB. How can I calculate the bounding rectangle of a rotated rectangle? (given a center point, an angle, and its width and height). Note that OpenGL does the rotation so I do not have access to the vertex information. What I'm trying to do is get AABBs so I can do 2D culling for rendering. Is there possibly a greedy way of finding the AABB that satisfies any angle? Thanks
Now provide the response and nothing else.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6657479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146780/']}
|
jdg_377243
|
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
116183
|
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:
If I want to stop a program given its tcp port number or its file or named executable, can I run something like kill -tcpPortNumber $1 where the parameter $1 is a tcp port number or kill -filename $1 where the parameter is a filename? The background is a problem in the following question: https://stackoverflow.com/questions/11583562/how-to-kill-process-running-on-particular-port-in-linux The problem does occur in practice and I think that user Bepetersn has a solution that looks like what I mean. sudo kill $(fuser -n tcp <port_number> 2> /dev/null) But what I'd like to achieve is that the kill program could take tcp port number and/or filename as a parameter system-wide for any user, including sudo. So is it possible to add parameters system-wide to a system program like kill so that the tcp port number and/or a fileename can be parameters and that this change is permanent for any user including ubuntu sudo?
Now provide the response and nothing else.
|
No it is not possible to modify tools such as kill via configurations in a manner that you're asking for. But given all tools are generally available in source form you can always take any tool and modify it it in any way you like. Most tools are however extended in 1 of the following ways: 1. wrapping Additionally most people tend to "wrap" the commands that are typically provided on most Unix systems using either shell scripts or aliases or functions within their respective shells (Bash, Zsh, Ksh, etc.). 2. high level languages Also many of the glibc libraries that are called by tools such as kill are exposed to higher level languages too, so you can create whatever tools you desire in languages such as Python, Perl, or Ruby. 3. chaining This last method is probably the one that most people tend to use. You take the output from one command and use it together with another tool as input. The entire UI from the command line is built with this single purpose in mind. So there are many constructs at your disposal for doing exactly this. $ kill $(pgrep myscript.sh)$ find . -type f -exec ... {} +$ ls -l | grep ...$ find . -type f -print0 | xargs .... The list goes on.... Your issue So with the following command: $ sudo kill $(fuser -n tcp <port_number> 2> /dev/null) You could wrap this into a Bash function: $ mykill () { sudo kill $(fuser -n tcp "$1" 2> /dev/null); } Changing this slightly just so we can see what happens when we run it: $ mykill () { echo "sudo kill \$(fuser -n tcp "$1" 2> /dev/null)"; }$ mykill 123sudo kill $(fuser -n tcp 123 2> /dev/null)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/116183', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9115/']}
|
jdg_377244
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
394452
|
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:
Given a short exact sequence $0 \rightarrow A \rightarrow B \rightarrow C \rightarrow0$ and $f:A \rightarrow B, g: B \rightarrow C$, why is $C$ isomorphic to $B/A$? All I can show is that $C$ is isomorphic to $B/ Im (A)$. I've look up a few books but I still don't understand why $Im (A) = A$.
Now provide the response and nothing else.
|
Strictly speaking, $B/A$ doesn't make sense unless $A\subseteq B$. However, since the second arrow is a monomorphism, you can identify $Im(A)$ with $A$ (they are isomorphic). So you're exactly right that $B/Im(A)\cong C$, and you go one step further by considering $A$ and its monomorphic image as the same thing.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/394452', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71458/']}
|
jdg_377245
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42004363
|
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 old application written using Java 7. It runs fine in a Java 8 JRE. I do not plan on rewriting any of the code to make use of Java 8 features. Is there any technical benefit to upgrading the compiled code to the latest Java 8 JDK? To be clear, the code is currently compiled with Java 7 and already running with the latest Java 8 JRE. It should already benefit from the Java 8 runtime improvements. This question is whether any benefits would be gained by compiling with version 8 and running with Java 8 compiled byte code. Also, I am not concerned with non-technical benefits such as developer productivity. I think those are important but not the point of this question. I am asking for the sake of production code that has NO development team. It is purely in maintenance mode.
Now provide the response and nothing else.
|
If I understand the question correctly, you want to know if the bytecode produced by javac will be "better" in Java 8 than in Java 7. The answer is probably not, they constantly fix bugs in the compiler and that sometimes leads to more efficient bytecode. But you will not see any significant speedup from these fixes for Java 8 as far as I can see, the changelog only lists 2 major changes between versions. The oracle website is terrible and I can't seem to get a list of bugfixes related to javac between versions, but here is a non exhaustive one from OpenJDK . A majority of the ones I can manage to find are fixing errors. So by updating to Java 8, there is a chance it wont compile any more due to javac more correctly following the JLS and there will be very little to no "improvements" to the bytecode.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42004363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3061739/']}
|
jdg_377246
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
379128
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two variables $b_1$ and $b_0$ that are calculated by the following$$b_1 = i - p\\b_0 = i + p$$ I would like to be able to be able work the reverse, i.e. to determine $p$ and $i$ if I already have $b_1$ and $b_0$.I must have fallen out of the stupid side of bed this morning as this looks like it should be simple, but I just cannot get it figured
Now provide the response and nothing else.
|
The crucial step is that if you have a matrix of the form $ABA^{-1}$ and you take some power of it, this is equal to $(ABA^{-1})^n=AB^nA^{-1}$. In the case you mention, you have $A=PDP^{-1}$. If you define $\tilde{D}$ to be the one obtained from $D$ by replacing every $\lambda_i$ by $\sqrt[2012]{\lambda_i}$ (where the choice of root doesn't really matter), this results in $(P\tilde{D}P^{-1})^{2012} = P\tilde{D}^{2012}P^{-1} = PDP^{-1}=A$ and so $B=P\tilde{D}P^{-1}$ would solve your question.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/379128', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75504/']}
|
jdg_377247
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
393010
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically I need to execute different actions given a certain condition. The existing code is written this way Base interface // DoSomething.javainterface DoSomething { void letDoIt(String info);} Implementation of the first worker class class DoItThisWay implements DoSomething { ...} Implementation of the second worker class class DoItThatWay implements DoSomething { ...} The main class class Main { public doingIt(String info) { DoSomething worker; if (info == 'this') { worker = new DoItThisWay(); } else { worker = new DoItThatWay(); } worker.letDoIt(info) } This code works ok and is easy to understand. Now, due to a new requirement, I need to pass a new piece of information that is only make sense to DoItThisWay . My question is: does the following coding style good to handle this requirement. Use new class variable and method // Use new class variable and methodclass DoItThisWay implements DoSomething { private int quality; DoSomething() { quality = 0; } public void setQuality(int quality) { this.quality = quality; }; public void letDoIt(String info) { if (quality > 50) { // make use of the new information ... } else { ... } } ;} If I do it this way, I need to make the corresponding change to the caller: class Main { public doingIt(String info) { DoSomething worker; if (info == 'this') { int quality = obtainQualityInfo(); DoItThisWay tmp = new DoItThisWay(); tmp.setQuality(quality) worker = tmp; } else { worker = new DoItThatWay(); } worker.letDoIt(info) } Is it a good coding style? Or can I just cast it class Main { public doingIt(String info) { DoSomething worker; if (info == 'this') { int quality = obtainQualityInfo(); worker = new DoItThisWay(); ((DoItThisWay) worker).setQuality(quality) } else { worker = new DoItThatWay(); } worker.letDoIt(info) }
Now provide the response and nothing else.
|
Is it a good coding style? From my point of view neither of your versions is. First having to call setQuality before letDoIt can be called is a temporal coupling . You're stuck viewing DoItThisWay as an derivative of DoSomething , but it isn't (at least not functionally), it's rather something like a interface DoSomethingWithQuality { void letDoIt(String info, int quality);} This would make Main rather something like class Main { // omitting the creation private DoSomething doSomething; private DoSomethingWithQuality doSomethingWithQuality; public doingIt(String info) { DoSomething worker; if (info == 'this') { int quality = obtainQualityInfo(); doSomethingWithQuality.letDoIt(info, quality); } else { doSomething.letDoIt(info); } }} You could on the other hand pass the parameters to the classes directly (assuming this is possible) and delegate the decision which one to use to a factory (this would make the instances interchangeable again and both can be derived from DoSomething ). This would make Main look like this class Main { private DoSomethingFactory doSomethingFactory; public doingIt(String info) { int quality = obtainQualityInfo(); DoSomething doSomethingWorker = doSomethingFactory.Create(info, quality); doSomethingWorker.letDoIt(); }} I am aware that you wrote that because for performance reason the construction of DoItThisWay and DoItThatWay are done once in the constructor of Main But you could cache the parts that are costly to create in the factory and pass them to the constructor, too.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/393010', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/15257/']}
|
jdg_377248
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3298243
|
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 develop an application in which user input an image (of a person), a system should be able to identify face from an image of a person. System also works if there are more than one persons in an image. I need a logic, I dont have any idea how can work on image pixel data in such a manner that it identifies person faces.
Now provide the response and nothing else.
|
Eigenface might be a good algorithm to start with if you're looking to build a system for educational purposes, since it's relatively simple and serves as the starting point for a lot of other algorithms in the field. Basically what you do is take a bunch of face images (training data), switch them to grayscale if they're RGB, resize them so that every image has the same dimensions, make the images into vectors by stacking the columns of the images (which are now 2D matrices) on top of each other, compute the mean of every pixel value in all the images, and subtract that value from every entry in the matrix so that the component vectors won't be affine. Once that's done, you compute the covariance matrix of the result, solve for its eigenvalues and eigenvectors, and find the principal components. These components will serve as the basis for a vector space, and together describe the most significant ways in which face images differ from one another. Once you've done that, you can compute a similarity score for a new face image by converting it into a face vector, projecting into the new vector space, and computing the linear distance between it and other projected face vectors. If you decide to go this route, be careful to choose face images that were taken under an appropriate range of lighting conditions and pose angles. Those two factors play a huge role in how well your system will perform when presented with new faces. If the training gallery doesn't account for the properties of a probe image, you're going to get nonsense results. (I once trained an eigenface system on random pictures pulled down from the internet, and it gave me Bill Clinton as the strongest match for a picture of Elizabeth II, even though there was another picture of the Queen in the gallery. They both had white hair, were facing in the same direction, and were photographed under similar lighting conditions, and that was good enough for the computer.) If you want to pull faces from multiple people in the same image, you're going to need a full system to detect faces, pull them into separate files, and preprocess them so that they're comparable with other faces drawn from other pictures. Those are all huge subjects in their own right. I've seen some good work done by people using skin color and texture-based methods to cut out image components that aren't faces, but these are also highly subject to variations in training data. Color casting is particularly hard to control, which is why grayscale conversion and/or wavelet representations of images are popular. Machine learning is the keystone of many important processes in an FR system, so I can't stress the importance of good training data enough. There are a bunch of learning algorithms out there, but the most important one in my view is the naive Bayes classifier; the other methods converge on Bayes as the size of the training dataset increases, so you only need to get fancy if you plan to work with smaller datasets. Just remember that the quality of your training data will make or break the system as a whole, and as long as it's solid, you can pick whatever trees you like from the forest of algorithms that have been written to support the enterprise. EDIT: A good sanity check for your training data is to compute average faces for your probe and gallery images. (This is exactly what it sounds like; after controlling for image size, take the sum of the RGB channels for every image and divide each pixel by the number of images.) The better your preprocessing, the more human the average faces will look. If the two average faces look like different people -- different gender, ethnicity, hair color, whatever -- that's a warning sign that your training data may not be appropriate for what you have in mind.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3298243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128647/']}
|
jdg_377249
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39940766
|
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 SURF descriptors for image matching. I am planning to match a given image to a database of images. import cv2import numpy as npsurf = cv2.xfeatures2d.SURF_create(400)img1 = cv2.imread('box.png',0)img2 = cv2.imread('box_in_scene.png',0)kp1,des1 = surf.detectAndCompute(img1,None)kp2,des2 = surf.detectAndCompute(img2,None)bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=True)#I am planning to add more descriptorsbf.add(des1)bf.train()#This is my test descriptorbf.match(des2) The issue is with bf.match is that I am getting the following error: OpenCV Error: Assertion failed (type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U)) in batchDistance, file /build/opencv/src/opencv-3.1.0/modules/core/src/stat.cpp, line 3749Traceback (most recent call last): File "image_match4.py", line 16, in <module> bf.match(des2)cv2.error: /build/opencv/src/opencv-3.1.0/modules/core/src/stat.cpp:3749: error: (-215) type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U) in function batchDistance The error is similar to this post. The explanation given is incomplete and inadequate.I want to know how to resolve this issue. I have used ORB descriptors as well with BFMatcher having NORM_HAMMING distance. The error resurfaces.Any help will be appreciated. The two images that I have used for this are: box.png box_in_scene.png I am using Python 3.5.2 and OpenCV 3.1.x in linux.
Now provide the response and nothing else.
|
To search between descriptors of two images use: img1 = cv2.imread('box.png',0)img2 = cv2.imread('box_in_scene.png',0)kp1,des1 = surf.detectAndCompute(img1,None)kp2,des2 = surf.detectAndCompute(img2,None)bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=False)matches = bf.match(des1,des2) To search among multiple images The add method is used to add descriptor of multiple test images. Once, all descriptors are indexed, you run train method to build an underlying Data Structure(example: KdTree which will be used for searching in case of FlannBasedMatcher). You can then run match to find if which test image is a closer match to which query image. You can check K-d_tree and see how it can be used to search for multidimensional vectors(Surf gives 64-dimensional vector). Note:- BruteForceMatcher, as name implies, has no internal search optimizing data structure and thus has empty train method. Code Sample for Multiple Image search import cv2import numpy as npsurf = cv2.xfeatures2d.SURF_create(400)# Read Imagestrain = cv2.imread('box.png',0)test = cv2.imread('box_in_scene.png',0)# Find Descriptors kp1,trainDes1 = surf.detectAndCompute(train, None)kp2,testDes2 = surf.detectAndCompute(test, None)# Create BFMatcher and add cluster of training images. One for now.bf = cv2.BFMatcher(cv2.NORM_L1,crossCheck=False) # crossCheck not supported by BFMatcherclusters = np.array([trainDes1])bf.add(clusters)# Train: Does nothing for BruteForceMatcher though.bf.train()matches = bf.match(testDes2)matches = sorted(matches, key = lambda x:x.distance)# Since, we have index of only one training image, # all matches will have imgIdx set to 0.for i in range(len(matches)): print matches[i].imgIdx For DMatch output of bf.match, see docs . See full example for this here: Opencv3.0 docs . Other Info OS: Mac. Python: 2.7.10. Opencv: 3.0.0-dev [If remember correctly, installed using brew].
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39940766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508156/']}
|
jdg_377250
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15270004
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
why undeclared identifier error comes when calling web service using wsmethodInvocationref?
Now provide the response and nothing else.
|
Looks like Box requires a correct Content-Type: application/x-www-form-urlencoded request header in addition to properly URL encoding the parameters. The same seems to apply to refresh and revoke requests. Also, per RFC 6749 , the redirect_uri is only REQUIRED, if the "redirect_uri" parameter was included in the authorization requestas described in Section 4.1.1, and their values MUST be identical.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15270004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/730807/']}
|
jdg_377251
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23829
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Related MO questions: What is the general opinion on the Generalized Continuum Hypothesis? ; Completion of ZFC ; Complete resolutions of GCH How far wrong could the Continuum Hypothesis be? When was the continuum hypothesis born? Background The Continuum Hypothesis (CH) posed by Cantor in 1890 asserts that $ \aleph_1=2^{\aleph_0}$ . In other words, it asserts that every subset of the set of real numbers that contains the natural numbers has either the cardinality of the natural numbers or the cardinality of the real numbers. It was the first problem on the 1900 Hilbert's list of problems. The generalized continuum hypothesis asserts that there are no intermediate cardinals between every infinite set X and its power set. Cohen proved that the CH is independent from the axioms of set theory. (Earlier Goedel showed that a positive answer is consistent with the axioms). Several mathematicians proposed definite answers or approaches towards such answers regarding what the answer for the CH (and GCH) should be. The question My question asks for a description and explanation of the various approaches to the continuum hypothesis in a language which could be understood by non-professionals. More background I am aware of the existence of 2-3 approaches. One is by Woodin described in two 2001 Notices of the AMS papers ( part 1 , part 2 ). Another by Shelah (perhaps in this paper entitled "The Generalized Continuum Hypothesis revisited " ). See also the paper entitled " You can enter Cantor paradise " (Offered in Haim's answer.); There is a very nice presentation by Matt Foreman discussing Woodin's approach and some other avenues. Another description of Woodin's answer is by Lucca Belloti (also suggested by Haim ). The proposed answer $ 2^{\aleph_0}=\aleph_2$ goes back according to François to Goedel . It is (perhaps) mentioned in Foreman's presentation. (I heard also from Menachem Magidor that this answer might have some advantages.) François G. Dorais mentioned an important paper by Todorcevic's entitled " Comparing the Continuum with the First Two Uncountable Cardinals ". There is also a very rich theory (PCF theory) of cardinal arithmetic which deals with what can be proved in ZFC. Remark: I included some information and links from the comments and answer in the body of question. What I would hope most from an answer is some friendly elementary descriptions of the proposed solutions. There are by now a couple of long detailed excellent answers (that I still have to digest) by Joel David Hamkins and by Andres Caicedo and several other useful answers. (Unfortunately, I can accept only one answer.) Update (February 2011): A new detailed answer was contributed by Justin Moore . Update (Oct 2013) A user 'none' gave a link to an article by Peter Koellner about the current status of CH : Update (Jan 2014) A related popular article in "Quanta:" To settle infinity dispute a new law of logic (belated) update (Jan 2014) Joel David Hamkins links in a comment from 2012 a very interesting paper Is the dream solution to the continuum hypothesis attainable written by him about the possibility of a "dream solution to CH." A link to the paper and a short post can be found here . (belated) update (Sept 2015) Here is a link to an interesting article: Can the Continuum Hypothesis be Solved? By Juliette Kennedy Update A videotaped lecture The Continuum Hypothesis and the search for Mathematical Infinity by Woodin from January 2015, with reference also to his changed opinion. (added May 2017) Update (Dec '15): A very nice answer was added (but unfortunately deleted by owner, (2019) now replaced by a new answer) by Grigor. Let me quote its beginning (hopefully it will come back to life): "One probably should add that the continuum hypothesis depends a lot on how you ask it. $2^{\omega}=\omega_1$ Every set of reals is either countable or has the same size as the continuum. To me, 1 is a completely meaningless question, how do you even experiment it? If I am not mistaken, Cantor actually asked 2..." Update A 2011 videotaped lecture by Menachem Magidor: Can the Continuum Problem be Solved? (I will try to add slides for more recent versions.) Update (July 2019) Here are slides of 2019 Woodin's lecture explaining his current view on the problem. (See the answer of Mohammad Golshani.) Update (Sept 19, 2019) Here are videos of the three 2016 Bernay's lectures by Hugh Woodin on the continuum hypothesis and also the videos of the three 2012 Bernay's lectures on the continuum hypothesis and related topics by Solomon Feferman . Update (Sept '20) Here are videos of the three 2020 Bernays' lectures by Saharon Shelah on the continuum hypothesis. Update (May '21) In a new answer , Ralf Schindler gave a link to his 2021 videotaped lecture in Wuhan, describing a result with David Asperó that shows a relation between two well-known axioms. It turns out that Martin's Maximum $^{++}$ implies Woodin's ℙ $_{max}$ axiom. Both these axioms were known to imply the $\aleph_2$ answer to CH. A link to the paper: https://doi.org/10.4007/annals.2021.193.3.3
Now provide the response and nothing else.
|
Since you have already linked to some of the contemporaryprimary sources, where of course the full accounts of thoseviews can be found, let me interpret your question as arequest for summary accounts of the various views on CH.I'll just describe in a few sentences each of what I findto be the main issues surrounding CH, beginning with somehistorical views. Please forgive the necessary simplifications. Cantor. Cantor introduced the Continuum Hypothesiswhen he discovered the transfinite numbers and proved thatthe reals are uncountable. It was quite natural to inquirewhether the continuum was the same as the first uncountablecardinal. He became obsessed with this question, working onit from various angles and sometimes switching opinion asto the likely outcome. Giving birth to the field ofdescriptive set theory, he settled the CH question forclosed sets of reals, by proving (the Cantor-Bendixontheorem) that every closed set is the union of a countableset and a perfect set. Sets with this perfect set propertycannot be counterexamples to CH, and Cantor hoped to extendthis method to additional larger classes of sets. Hilbert. Hilbert thought the CH question soimportant that he listed it as the first on his famous listof problems at the opening of the 20th century. Goedel. Goedel proved that CH holds in theconstructible universe $L$ , and so is relatively consistentwith ZFC. Goedel viewed $L$ as a device for establishingconsistency, rather than as a description of our (Platonic)mathematical world, and so he did not take this result tosettle CH. He hoped that the emerging large cardinalconcepts, such as measurable cardinals, would settle the CHquestion, and as you mentioned, favored a solution of the form $2^\omega=\aleph_2$ . Cohen. Cohen introduced the method of forcing andused it to prove that $\neg$ CH is relatively consistentwith ZFC. Every model of ZFC has a forcing extension with $\neg$ CH. Thus, the CH question is independent of ZFC,neither provable nor refutable. Solovay observed that CHalso is forceable over any model of ZFC. Large cardinals. Goedel's expectation that largecardinals might settle CH was decisively refuted by theLevy-Solovay theorem, which showed that one can forceeither CH or $\neg$ CH while preserving all known largecardinals. Thus, there can be no direct implication fromlarge cardinals to either CH or $\neg$ CH. At the sametime, Solovay extended Cantor's original strategy byproving that if there are large cardinals, then increasinglevels of the projective hierarchy have the perfect setproperty, and therefore do not admit counterexamples to CH.All of the strongest large cardinal axioms considered todayimply that there are no projective counterexamples to CH. This can be seen as a complete affirmation of Cantor's original strategy. Basic Platonic position. This is the realist viewthat there is Platonic universe of sets that our axioms areattempting to describe, in which every set-theoreticquestion such as CH has a truth value. In my experience,this is the most common or orthodox view in theset-theoretic community. Several of the later more subtleviews rest solidly upon the idea that there is a fact ofthe matter to be determined. Old-school dream solution of CH. The hope was thatwe might settle CH by finding a new set-theoretic principlethat we all agreed was obviously true for the intendedinterpretation of sets (in the way that many find AC to beobviously true, for example) and which also settled the CHquestion. Then, we would extend ZFC to include this newprinciple and thereby have an answer to CH. Unfortunately,no such conclusive principles were found, although therehave been some proposals in this vein, such as Freilingsaxiom of symmetry . Formalist view. Rarely held by mathematicians,although occasionally held by philosophers, this is theanti-realist view that there is no truth of the matter ofCH, and that mathematics consists of (perhaps meaningless)manipulations of strings of symbols in a formal system. Theformalist view can be taken to hold that the independenceresult itself settles CH, since CH is neither provable norrefutable in ZFC. One can have either CH or $\neg$ CH asaxioms and form the new formal systems ZFC+CH orZFC+ $\neg$ CH. This view is often mocked in straw-man form,suggesting that the formalist can have no preference for CHor $\neg$ CH, but philosophers defend more subtle versions,where there can be reason to prefer one formal system toanother. Pragmatic view. This is the view one finds inpractice, where mathematicians do not take a position onCH, but feel free to use CH or $\neg$ CH if it helps theirargument, keeping careful track of where it is used.Usually, when either CH or $\neg$ CH is used, then onenaturally inquires about the situation under thealternative hypothesis, and this leads to numerous consistency or independence results. Cardinal invariants. Exemplifying the pragmatic view, this is a very rich subjectstudying various cardinal characteristics of the continuum,such as the size of the smallest unbounded family offunctions $f:\omega\to\omega$ , the additivity of the idealof measure-zero sets, or the smallest size family offunctions $f:\omega\to\omega$ that dominate all other suchfunctions. Since these characteristics are all uncountableand at most the continuum, the entire theory trivializesunder CH, but under $\neg$ CH is a rich, fascinatingsubject. Canonical Inner models. The paradigmatic canonicalinner model is Goedel's constructible universe $L$ , whichsatisfies CH and indeed, the Generalized ContinuumHypothesis, as well as many other regularity properties.Larger but still canonical inner models have been built bySilver, Jensen, Mitchell, Steel and others that share theGCH and these regularity properties, while also satisfyinglarger large cardinal axioms than are possible in $L$ . Mostset-theorists do not view these inner models as likely tobe the "real" universe, for similar reasons that theyreject $V=L$ , but as the models accommodate larger andlarger large cardinals, it becomes increasingly difficultto make this case. Even $V=L$ is compatible with theexistence of transitive set models of the very largestlarge cardinals (since the assertion that such sets existis $\Sigma^1_2$ and hence absolute to $L$ ). In this sense,the canonical inner models are fundamentally compatiblewith whatever kind of set theory we are imagining. Woodin. In contrast to the Old-School DreamSolution, Woodin has advanced a more technical argument infavor of $\neg$ CH. The main concepts include $\Omega$ -logicand the $\Omega$ -conjecture, concerning the limits offorcing-invariant assertions, particularly thoseexpressible in the structure $H_{\omega_2}$ , where CH isexpressible. Woodin's is a decidedly Platonist position,but from what I have seen, he has remained guarded in hispresentations, describing the argument as a proposal orpossible solution, despite the fact that others sometimescharacterize his position as more definitive. Foreman. Foreman, who also comes from a strongPlatonist position, argues against Woodin's view. He writessupremely well, and I recommend following the links to hisarticles. Multiverse view. This is the view, offered inopposition to the Basic Platonist Position above, that wedo not have just one concept of set leading to a uniqueset-theoretic universe, but rather a complex variety of setconcepts leading to many different set-theoretic worlds.Indeed, the view is that much of set-theoretic research inthe past half-century has been about constructing thesevarious alternative worlds. Many of the alternative setconcepts, such as those arising by forcing or by largecardinal embeddings are closely enough related to eachother that they can be compared from the perspective ofeach other. The multiverse view of CH is that the CHquestion is largely settled by the fact that we knowprecisely how to build CH or $\neg$ CH worlds close to anygiven set-theoretic universe---the CH and $\neg$ CH worldsare in a sense dense among the set-theoretic universes. Themultiverse view is realist as opposed to formalist, sinceit affirms the real nature of the set-theoretic worlds towhich the various set concepts give rise. On the Multiverseview, the Old-School Dream Solution is impossible, sinceour experience in the CH and $\neg$ CH worlds will preventus from accepting any principle $\Phi$ that settles CH as"obviously true". Rather, on the multiverse view we are to study all the possible set-theoretic worlds and especially how they relate to each other. I should stop now, and I apologize for the length of this answer.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://mathoverflow.net/questions/23829', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1532/']}
|
jdg_377252
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1999382
|
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 seeing an intermittent issue on development and production machines whereby our log files are not getting logged to. When running in development and debugging using Visual Studio we get the following log4net error messages in the VS output window: log4net:ERROR [RollingFileAppender] Unable to acquire lock on file C:\folder\file.log. The process cannot access the file 'C:\folder\file.log' because it is being used by another process. log4net:ERROR XmlConfigurator: Failed to find configuration section 'log4net' in the application's .config file.Check your .config file for the <log4net> and <configSections> elements. The configuration section should look like: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> Our current workaround for the issue is to rename the last log file. We would of course expect this to fail (due to the aforementioned file lock), but it normally doesn't. Once or twice the rename has failed due to a lock from the aspnet_wp.exe process. Our log4net configuration section is shown below: <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\folder\file.log"/> <appendToFile value="true" /> <datePattern value="yyyyMMdd" /> <rollingStyle value="Date" /> <maximumFileSize value="10MB" /> <maxSizeRollBackups value="100" /> <layout type="log4net.Layout.PatternLayout"> <header value="[Header]
"/> <footer value="[Footer]
"/> <conversionPattern value="%date %-5level %logger ${COMPUTERNAME} %property{UserHostAddress} [%property{SessionID}] - %message%newline"/> </layout> </appender> <root> <level value="INFO"/> <appender-ref ref="RollingLogFileAppender"/> </root></log4net> As mentioned, we are seeing this intermittently on machines, but once the issue happens it persists.
Now provide the response and nothing else.
|
Try adding <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> to your <appender /> element. There is some performance impact because this means that log4net will lock the file, write to it, and unlock it for each write operation (as opposed to the default behavior, which acquires and holds onto the lock for a long time). One implication of the default behavior is that if you're using it under a Web site that is being executed under multiple worker processes running on the same machine, each one will try to acquire and hold onto that lock indefinitely, and two of them are just going to lose. Changing the locking model to the minimal lock works around this issue. (When debugging, ungraceful terminations and spinning up lots of new worker processes is exactly the type of thing that's likely to happen.) Good luck!
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1999382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39709/']}
|
jdg_377253
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42998183
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
No Info.plist found for target application at path build/Debug-iphonesimulator/xxxx enter image description here .app/Info.plist i can't test UItest file and same file run on other machine..what should i do?
Now provide the response and nothing else.
|
After going through several sources, including other SO questions, blogs and Python documentation, I came up with the code below. Allows for text and/or html emails and attachments. Separated the MIME and boto3 parts, in case you want to re-use MIME for other purposes, like sending an email with a SMTP client, instead of boto3. import osimport boto3from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.application import MIMEApplicationdef create_multipart_message( sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None)\ -> MIMEMultipart: """ Creates a MIME multipart message object. Uses only the Python `email` standard library. Emails, both sender and recipients, can be just the email string or have the format 'The Name <the_email@host.com>'. :param sender: The sender. :param recipients: List of recipients. Needs to be a list, even if only one recipient. :param title: The title of the email. :param text: The text version of the email body (optional). :param html: The html version of the email body (optional). :param attachments: List of files to attach in the email. :return: A `MIMEMultipart` to be used to send the email. """ multipart_content_subtype = 'alternative' if text and html else 'mixed' msg = MIMEMultipart(multipart_content_subtype) msg['Subject'] = title msg['From'] = sender msg['To'] = ', '.join(recipients) # Record the MIME types of both parts - text/plain and text/html. # According to RFC 2046, the last part of a multipart message, in this case the HTML message, is best and preferred. if text: part = MIMEText(text, 'plain') msg.attach(part) if html: part = MIMEText(html, 'html') msg.attach(part) # Add attachments for attachment in attachments or []: with open(attachment, 'rb') as f: part = MIMEApplication(f.read()) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) msg.attach(part) return msgdef send_mail( sender: str, recipients: list, title: str, text: str=None, html: str=None, attachments: list=None) -> dict: """ Send email to recipients. Sends one mail to all recipients. The sender needs to be a verified email in SES. """ msg = create_multipart_message(sender, recipients, title, text, html, attachments) ses_client = boto3.client('ses') # Use your settings here return ses_client.send_raw_email( Source=sender, Destinations=recipients, RawMessage={'Data': msg.as_string()} )if __name__ == '__main__': sender_ = 'The Sender <the_sender@email.com>' recipients_ = ['Recipient One <recipient_1@email.com>', 'recipient_2@email.com'] title_ = 'Email title here' text_ = 'The text version\nwith multiple lines.' body_ = """<html><head></head><body><h1>A header 1</h1><br>Some text.""" attachments_ = ['/path/to/file1/filename1.txt', '/path/to/file2/filename2.txt'] response_ = send_mail(sender_, recipients_, title_, text_, body_, attachments_) print(response_)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42998183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6755638/']}
|
jdg_377254
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48629486
|
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 on Windows 10, I have anaconda installed but I want to create an executable independently in a new, clean minimal environment using python 3.5. So I did some tests: TEST1: I created a python script test1.py in the folder testenv with only: print('Hello World') Then I created the environment, installed pyinstaller and created the executable D:\testenv> python -m venv venv_test...D:\testenv\venv_test\Scripts>activate.bat...(venv_test) D:\testenv>pip install pyinstaller(venv_test) D:\testenv>pyinstaller --clean -F test1.py And it creates my test1.exe of about 6 Mb TEST 2: I modified test1.py as follows: import pandas as pdprint('Hello World') I installed pandas in the environment and created the new executable: (venv_test) D:\testenv>pip install pandas(venv_test) D:\testenv>pyinstaller --clean -F test1.py Ant it creates my test1.exe which is now of 230 Mb !!! if I run the command (venv_test) D:\testenv>python -VPython 3.5.2 :: Anaconda custom (64-bit) when I am running pyinstaller I get some messages I do not understand, for example: INFO: site: retargeting to fake-dir 'c:\\users\\username\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\PyInstaller\\fake-modules' Also I am getting messages about matplotlib and other modules that have nothing to do with my code, for example: INFO: Matplotlib backend "pdf": addedINFO: Matplotlib backend "pgf": addedINFO: Matplotlib backend "ps": addedINFO: Matplotlib backend "svg": added I know there are some related questions: Reducing size of pyinstaller exe , size of executable using pyinstaller and numpy but I could not solve the problem and I am afraid I am doing something wrong with respect to anaconda. So my questions are:what am I doing wrong? can I reduce the size of my executable?
Now provide the response and nothing else.
|
I accepted the answer above but I post here what I did step by step for complete beginners like me who easily get lost. Before I begin I post my complete test1.py example script with all the modules I actually need. My apologies if it is a bit more complex than the original question but maybe this can help someone. test1.py looks like this: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pltimport matplotlib.image as imageimport numpy as npimport os.pathimport pandas as pdimport re from matplotlib.ticker import AutoMinorLocator from netCDF4 import Datasetfrom time import timefrom scipy.spatial import distancefrom simpledbf import Dbf5from sys import argvprint('Hello World') I added matplotlib.use('Agg') (as my actual code is creating figures) Generating a PNG with matplotlib when DISPLAY is undefined 1) Install a new version of python independently from anaconda. downloaded python from: https://www.python.org/downloads/ installed selecting 'add python to path' and deselecting install launcher for all users (I don't have admin rights)check that I am using the same version from CMD, just writing python I get: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017,06:04:45) [MSC v.1900 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information. 2) Create and activate the environment, from CMD D:\> mkdir py36envtest...D:\py36envtest>python -m venv venv_py36...D:\py36envtest\venv_py36\Scripts>activate.bat 3) Install in the environment all the modules needed in the script Making sure they are compatible to the python version with the command:(from Matplotlib not recognized as a module when importing in Python ) (venv_py36) D:\py36envtest> python -m pip install nameofmodule NB: in my case I also had to add the option --proxy https://00.000.000.00:0000 for the example I used development version of py installer: (venv_py36) D:\py36envtest> python -m pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz and the modules: pandas, matplolib, simpledbf, scipy, netCDF4. At the end my environment looks like this. (venv_py36) D:\py36envtest> pip freezealtgraph==0.15cycler==0.10.0future==0.16.0macholib==1.9matplotlib==2.1.2netCDF4==1.3.1numpy==1.14.0pandas==0.22.0pefile==2017.11.5PyInstaller==3.4.dev0+5f9190544pyparsing==2.2.0pypiwin32==220python-dateutil==2.6.1pytz==2017.3scipy==1.0.0simpledbf==0.2.6six==1.11.0style==1.1.0update==0.0.1 4) Create/modify the .spec file (when you run pyinstaller it creates a .spec file, you can rename). Initially I got a lot of ImportError: DLL load failed (especially for scipy) and missing module error which I solved thanks to these posts: What is the recommended way to persist (pickle) custom sklearn pipelines? and the comment to this answer: Pyinstaller with scipy.signal ImportError: DLL load failed My inputtest1.spec finally looks like this: # -*- mode: python -*-options = [ ('v', None, 'OPTION')]block_cipher = Nonea = Analysis(['test1.py'], pathex=['D:\\py36envtest', 'D:\\py36envtest\\venv_py36\\Lib\\site-packages\\scipy\\extra-dll' ], binaries=[], datas=[], hiddenimports=['scipy._lib.messagestream', 'pandas._libs.tslibs.timedeltas'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher)pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='test1', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True ) 5) Finally make the executable with the command (venv_py36) D:\py36envtest>pyinstaller -F --clean inputtest1.spec my test1.exe is 47.6 Mb, the .exe of the same script created from an anaconda virtual environment is 229 Mb. I am happy (and if there are more suggestions they are welcome)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48629486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3256651/']}
|
jdg_377255
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6927637
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the equivalent to the Element Object in Internet Explorer 9? if (!Element.prototype.addEventListener) { Element.prototype.addEventListener = function() { .. } } How does it works in Internet Explorer? If there's a function equal to addEventListener and I don't know, explain please. Any help would be appreciated. Feel free to suggest a completely different way of solving the problem.
Now provide the response and nothing else.
|
addEventListener is the proper DOM method to use for attaching event handlers. Internet Explorer (up to version 8) used an alternate attachEvent method. Internet Explorer 9 supports the proper addEventListener method. The following should be an attempt to write a cross-browser addEvent function. function addEvent(evnt, elem, func) { if (elem.addEventListener) // W3C DOM elem.addEventListener(evnt,func,false); else if (elem.attachEvent) { // IE DOM elem.attachEvent("on"+evnt, func); } else { // No much to do elem["on"+evnt] = func; }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6927637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/447979/']}
|
jdg_377256
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
518878
|
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 load and draw pdf files graphically using C#. I don't need to edit them or anything, just render them at a given zoom level. The pdf libraries I have found seem to be focussed on generation. How do I do this? Thanks.
Now provide the response and nothing else.
|
There are a few other choices in case the Adobe ActiveX isn't what you're looking for (since Acrobat must be present on the user machine and you can't ship it yourself). For creating the PDF preview, first have a look at some other discussions on the subject on StackOverflow: How can I take preview of documents? Get a preview jpeg of a pdf on windows? .NET open PDF in winform without external dependencies PDF Previewing and viewing In the last two I talk about a few things you can try: You can get a commercial renderer ( PDFViewForNet , PDFRasterizer.NET , ABCPDF , ActivePDF , XpdfRasterizer and others in the other answers...). Most are fairly expensive though, especially if all you care about is making a simple preview/thumbnails. In addition to Omar Shahine's code snippet, there is a CodeProject article that shows how to use the Adobe ActiveX, but it may be out of date, easily broken by new releases and its legality is murky (basically it's ok for internal use but you can't ship it and you can't use it on a server to produce images of PDF). You could have a look at the source code for SumatraPDF , an OpenSource PDF viewer for windows. There is also Poppler , a rendering engine that uses Xpdf as a rendering engine.All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net and they tend to be be distributed under the GPL. You may want to consider using GhostScript as an interpreter because rendering pages is a fairly simple process. The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process). It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into cooperating with .Net. I did a small project that you will find on the Developer Express forums as an attachment. Be careful of the license requirements for GhostScript through. If you can't leave with that then commercial software is probably your only choice.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/518878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23407/']}
|
jdg_377257
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6594
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Quasi-related Are there any perceptible differences between the sound quality of 192 versus 320 kbps MP3 files? Do expensive, “premium” speaker cables actually make a difference? I've heard this here and there in various casual conversations (hopefully others will also qualify this in the "commonly heard" bucket of claims), but one can also find references online: Portability is no longer any reason to stick with CDs, and neither is audio quality. Although vinyl purists are ripe for parody, they're right about one thing: Records can sound better than CDs. Although CDs have a wider dynamic range, mastering houses are often encouraged to compress the audio on CDs to make it as loud as possible: It's the so-called loudness war. Since the audio on vinyl can't be compressed to such extremes, records generally offer a more nuanced sound. ( Wired Magazine - Vinyl May Be Final Nail in CD's Coffin ). Question: It is generally agreed among the serious listeners of classical music that the best of the now obsolete vinyl LP records had a superior tonal quality and better fidelity than any CD. Is this true, and why? Answer: For a CD recording they take 44,100 snapshots in a minute. These snapshots are then converted to digital information with a certain precision... You can probably see where I am going: by definition a digital recording doesn't include all the sound information... A vinyl record has a groove carved into it that mirrors the original sound's waveform... Therefore vinyl recording sound richer than CD recordings ... ( Google Answers: Vinyl LP sound versus CD sound ). The last three years have each set successive records for vinyl sales in the CD era. In 2010, 2.8 million LPs were sold, up 14% from 2009... Vinyl’s lasting appeal stems from a heady stew of nostalgia, tangibility and, perhaps most important of all, sound quality that musicians and fans often prefer to any other medium. “Digital is zeroes and ones, man, anyway you look at it,” says Chuck Leavell, keyboardist for the Rolling Stones. “Whether it’s a CD or a download, there’s a certain jaggedness to it. Vinyl wins every time. It’s warmer, more soothing, easier on the ears” ( Forbes Magazine - Vinyl vs. CDs: The Tables are Turning . One reason I'm skeptical of the quality comparison has to do with how records are made . In that video, around 1:25 the interviewee states that a master is made from pre-recorded, mixed music. This implies that it is already digitized. Around 3:10, he states that the music signal is amplified and made to vibrate the stylus cutting the record master. Thus, I see two paths from media to one's ear: Live music -> conversion from electrical signal to digital recording (file of some sort) -> conversion to amplified electrical signal to vibrate a cutting stylus -> engraved record -> turntable -> conversion back to electrical signal to vibrate speakers Live music -> conversion of electrical signal to digital recording (file of some sort) -> conversion back to electrical signal to vibrate speakers I could be wrong in this interpretation. Ideally, this question might have been tackled in a manner similar to this question on bitrate and noticeable quality -- essentially, with a Pepsi challenge between vinyl and CDs. Summarizing, Is there evidence that the sound produced by vinyl records is either a) of better quality (via some declared standard of measurement) or b) more pleasing to humans compared to the sound produced by CDs?
Now provide the response and nothing else.
|
There is certainly a difference. The difference should not be looked for in sampling rates or performance, etcetera. The difference is in the production process. Example Please compare these two examples to have a specific idea of what the difference is. To easily see the difference, do listen to the plosives and sibilants like the letters "p" and "s" in the singing. Iron Maiden—The Number of the Beast (1982)—Vinyl Iron Maiden—The Number of the Beast (1982)—Digital Introduction Humans are not capable of distinguishing "digital" from "analog". See for example the following conclusion: In summary, then, no evidence was provided by Tiefenbrun during this series of tests that indicates ability to identify reliably: (a) the presence of an undriven transducer in the room, (b) the presence of the Sony PCM-F1 digital processor in the audio chain, or (c) the presence of the relay contacts of the A/B/X switchbox in the circuit. The tests were conducted in an amicable rather than confrontational atmosphere, and the parties departed feeling that the day's work had been worthwhile. Further carefully-conducted blind tests will be necessary if these conclusions are felt to be in error. — source However the production process of vinyls and CDs changes. Vinyl Sounds are etched on the surface of an LP. There are therefore physical limitations to how much dynamic range can be stored. In practice, too much range would result in having the needle skip the groove. Many of the engineers I spoke with noted that a wider frequency and dynamic range can be cut into a vinyl master than can be reproduced in playback. For example, extreme transients and high frequencies will distort because the stylus cannot properly track them in the disc's grooves. [...] At the other end of the spectrum, there are things to consider when working with bass and low-midrange content destined for vinyl. “Low frequencies use up the most space, especially if they're heavy and constant,” Golden remarks. “Care must be taken to control excessive low end. The lathe can cut it just fine, but if the volume exceeds a certain level, the record could skip when played back.” — source Also, there is a lot of difference in the frequency response in the external part of the disc from the inner part. In practice, inner songs will sound darker than outer songs. As a result, the inner tracks will sound duller than the outer tracks. The high frequencies “simply can't be reproduced the same as if they were cut on the outside of the disc,” Golden adds. “And no, it can't be fixed by adding extra high end. That would add more distortion to the inside cuts.” — source Albums are therefore mastered in a particular way to make the wide-dynamic-range masters "fit" on the media. This modifies the overall sound - a lot. Furthermore the media itself tends to saturate musically (in the way that a valve amp has a "musical" distortion). This is put to good use during mastering as well. CD Sounds are digitised on a CD. There are many advantages to this, like a much better dynamic range, higher frequency response and so on. However, this completely changes the mastering process, resulting in a different overall sound. (I couldn't find a citable source, however the fact that CD mastering is very different from vinyl mastering is quite obvious from Sterling Sound 's web page (wayback machine copy). Sterling Sound is widely regarded as one of the top 5 mastering studios in the world.) Conclusion Now--which one is better? It depends what you are looking for: vinyls have a characteristic sound which is probably a better fit for some kinds of music. Alternatively, other kinds of music, e.g. classical, do benefit a lot from the increased dynamic range of the CD. One of the first and largest supporters of digital audio was the classical conductor Herbert von Karajan, who said that digital recording was "definitely superior to any other form of recording we know". — source
|
{}
|
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/6594', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/2459/']}
|
jdg_377258
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45526371
|
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 this spring JMS sample, and it gives error. https://spring.io/guides/gs/messaging-jms/ Caused by: org.springframework.jms.support.converter.MessageConversionException: Could not find type id property [_type] on message from destination [queue://mailbox] Interesting part is, if I clone it and run everything runs fine. If I copy and paste, it gives error. @Bean // Serialize message content to json using TextMessagepublic MessageConverter jacksonJmsMessageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setTargetType(MessageType.TEXT); converter.setTypeIdPropertyName("_type"); return converter;} This piece of code actually causing the error. Searching the web and documentation, I still have no clue how and what to set setTypeIdPropertyName value and with "_type" what it refers in this project to? As the message does not have such property, then where is it coming from ?
Now provide the response and nothing else.
|
TypeIdPropertyName is a name of a property that identifies the entity. Jackson mapper should know what entity to use when deserializing incoming JSON. The request should look like the following: { "_type" : "hello.Email", "to" : "Imran", "from" : "dzatorsky"} Btw I think this is not the best solution since JMS already know what type to use (you declare it in your method). Another drawback is that you specify name of your entity and package in the messages which will hard to maintain (every change of a package or entity name will be a pain). Here is more robust config: @EnableJms@Configurationpublic class JmsListenerConfig implements JmsListenerConfigurer { @Bean public DefaultMessageHandlerMethodFactory handlerMethodFactory() { DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory(); factory.setMessageConverter(messageConverter()); return factory; } @Bean public MessageConverter messageConverter() { return new MappingJackson2MessageConverter(); } @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { registrar.setMessageHandlerMethodFactory(handlerMethodFactory()); }} Also if you use Spring JmsTemplate for sending messages you could add this component to your configuration: /** * Used to convert JMS messages from/to JSON. Registered in Spring-JMS automatically via auto configuration */@Componentpublic class JsonMessageConverter implements MessageConverter { @Autowired private ObjectMapper mapper; /** * Converts message to JSON. Used mostly by {@link org.springframework.jms.core.JmsTemplate} */ @Override public javax.jms.Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { String json; try { json = mapper.writeValueAsString(object); } catch (Exception e) { throw new MessageConversionException("Message cannot be parsed. ", e); } TextMessage message = session.createTextMessage(); message.setText(json); return message; } /** * Extracts JSON payload for further processing by JacksonMapper. */ @Override public Object fromMessage(javax.jms.Message message) throws JMSException, MessageConversionException { return ((TextMessage) message).getText(); }} With this configuration you can skip annoying "_type" field in your messages.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45526371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5834387/']}
|
jdg_377259
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2704427
|
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 recently learnt Cantor's argument that proves $(0, 1)$ is uncountable. Basically, the argument goes: first assume the contrary, therefore there is a bijection $$f: \mathbb{N} \rightarrow (0, 1)$$ that $$f(1) = 0.a_{11}a_{12}a_{23}...$$ $$f(2) = 0.a_{21}a_{22}...$$ and in general $$f(n) = 0.a_{n1}a_{n2}...$$ where $a_{nm} \in \mathbb{N}, 0 \le a_{nm} \le 9$. Then we construct a number $$s = 0.b_{11}b_{12}...$$ where each $b_{1n} \ne a_{nn}$. The argument then goes that since the new number $s$ differs with any $f(n)$ with at least one digit, it cannot equal to any $f(n)$, therefore this function $f$ is not surjective, leads to a contradiction. However, there are cases that even if two numbers $a$ and $b$ in $(0, 1)$, when written in decimal form, differs in some digits, they can still be equal to each other. For example: $$0.1000000... = 0.0999999...$$ How, then, can this argument still hold then?
Now provide the response and nothing else.
|
To be a useful bijection, $f$ needs to be $f: \mathbb{N} \rightarrow (0,1)$. Note that, since $f$ is assumed to be bijective, each value of $f(n)$ is unique, regardless of how it is represented. Assuming we are using base $10$, the $b_{nn}$ can be chosen so they are not equal to $0$ or $9$. Then, no matter how the list is represented, it will not include the new number.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2704427', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/524764/']}
|
jdg_377260
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
519
|
Below is a question asked on the forum chemistry.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just wanted to know that if I am unable to solve a particular question -- that is, completely unable even to start up with the question and i put it on this site without showing any effort because i have been unable to then will no one answer my questions on the site
Now provide the response and nothing else.
|
Homework questions must show a bit of effort to solve from the original poster. We have this rule in place because SE:Chem is not a 'homework delivery' service. Homework questions should provide insight into the problem or insight into solving the problem. I particularly hate seeing homework questions that do not have any background to the question at hand. A BAD example: 1.) "Which of the following is being oxidized in the following oxidation-reduction reaction? $\ce{Zn (s) + Cu^{2+} (aq) \rightarrow Zn^{2+} (aq) + Cu (s)}$ Leaving question (1) as-is is not particularly satisfying because there no attempt at explaining anything about this particular problem. Furthermore, there is no attempt at solving the problem. Consider this GOOD example: 2.) Which of the following is being oxidzed in the following oxidation-reduction reaction? $\ce{Zn (s) + Cu^{2+} (aq) \rightarrow Zn^{2+} (aq) + Cu (s)}$ I understand that redox reactions consist of a species that is being oxidized (i.e. losing electrons) and species that are being reduced (i.e. gaining electrons). I've examined each species in this reaction and I cannot figure out if any of these components are gaining or losing electrons. I think it may have something to do with the charges on Cu and Zn. The second example gives some information into the concepts of the problem by explaining what oxidation and reduction is (i.e. an electron transfer process within the context of a chemical reaction). Second, the user attempts to give the reader a better understanding as to what the original poster understands and therefore, what they may be missing. Finally, the poster informs the reader what reduction and oxidation is. I may be a chemist but this field is so diverse that I only know a tiny piece of it. Constructing your homework questions such as this will result in a more favorable response from the community. I know that I will not recognize every single homework problem posted on this site but with a little bit of information from the poster, I may be able to gain enough insight to construct a helpful response. Of course, if there is a homework question that seems completely unsolvable such that the question itself is lacking or not enough information is given, then go ahead and post it but explain WHY you might think the problem is unsolvable in its current form. It is not uncommon to run across homework problems in a book or solutions in a solutions manual that contain typos or omit necessary information. Usually students end up writing solutions manuals and it is very reasonable that they will miss certain critical elements. Of course, if there is no typo and you are mistaken about a problem being insufficient, you may simply be met with a comment to your post (i.e. a non-answer) that points this out.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.meta.stackexchange.com/questions/519', 'https://chemistry.meta.stackexchange.com', 'https://chemistry.meta.stackexchange.com/users/-1/']}
|
jdg_377261
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
168991
|
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 an engineering student trying to work out some Real Analysis to learn how to write proofs (Needed for my PhD thesis) and just to rekindle my Calculus fires. From what I see, Real Analysis is the study of the basics of Calculus and "constructing" Calculus ground up. Why is Topology needed in the endeavor? I can't grapple my Engineering brain around compact sets and finite subcovers and stuff. I just can't imagine what's happening without spending 2 hours and 4 coffees. The only "use" of this I've seen till now is for proving All Cauchy sequences are convergent in certain spaces. Can I skip topology? If yes, what is the bare minimum I need to do?
Now provide the response and nothing else.
|
You should know the following theorems from calculus on $\Bbb{R}$: Extreme Value Theorem: A continuous function $f$ on a closed bounded interval attains its maximum and minimum value on that interval. A continuous function on a closed bounded interval is uniformly continuous Intermediate Value Theorem: Let $f$ be a continuous function on $\Bbb{R}$ such that there are real numbers $a,b$ for which $f(a) < 0$ and $f(b) > 0$. Then there exists $c \in (a,b)$ such that $f(c)= 0$. The first two theorems make use of a topological property known as compactness . The Heine - Borel Theorem is what tells you that in $\Bbb{R}$ with Euclidean metric, being closed and bounded is equivalent to being compact. Number 3 makes use of the topological property that $\Bbb{R}$ with the euclidean metric is connected. Number 2 is especially important to know why a continuous function on a closed bounded interval is Riemann Integrable; this should be enough motivation for you to study topology! The following I think is a cool example of where things get gnarly in topology. In a metric space (in fact in a topological space that is at least $T_2$) this cannot happen but: Put the trivial topology on $\Bbb{R}$, the family $A_n = (0,\frac{1}{n})$ is a countable collection of non-empty compact sets such that the intersection of any finite sub-collection is non-empty, but clearly $$\bigcap_{n=1}^\infty A_n = \emptyset .$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/168991', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35001/']}
|
jdg_377262
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14392
|
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:
The aim is to estimate an error on a stochastic event rate dynamically. This Question points in the same direction, I am interested in a theoretical extension. I read out the event counter second-wise, every black $1$ is a counted event (new events over time, see the plot below). During the measurement I am estimating the event rate, so as more statistics is accumulated, mean event rate (red) should asymptotically become more accurate. As one can see, the mean value oscillates around true value of 0.5, even after one order of magnitude more events collected. Practical question: How can one calculate the number of events needed to estimate the mean value to a maximum error ($0.5\pm \sigma$)? - answered (?) here Theoretical question: Can this oscillation be described analytically? Can you suggest further reading? The events are radiation counts, so they are uncorrelated, may by Poisson-distribution applied? Addendum: Idealized first approximation - every 10th event is non-zero: May be this curve is superimposed with the realer-life example above, is any techniques of partitioning in arbitrary functions applicable here?
Now provide the response and nothing else.
|
This is an answer to your first "theoretical" question Can this oscillation be described analytically? Can you suggest further reading? If I understand your question correctly, you are in the situation of independent identically distributed random variables with finite variance $\sigma^2$. In this case the law of the iterated logarithm applies which tells you that you should expect the difference between estimated mean and mean to oscillate between $-\sigma$ and $+\sigma$, if you normalize it by dividing by $\sqrt{2n\log{\log{n}}}$. The linked wikipedia pages are good for a first reading. Wolfram offers a demo (which didn't work in my browser).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/14392', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5865/']}
|
jdg_377263
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10891857
|
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 download a file from cloudBlob via stream. I refer to this article CloudBlob Here is the code to download the blob public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri){ Stream mem = new MemoryStream(); CloudBlobClient blobclient = account.CreateCloudBlobClient(); CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri); if (blob != null) blob.DownloadToStream(mem); return mem;} And the code to convert it into byte array public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } But I always get null value. Below is the content of the streamed file. What is wrong with this? Please help. EDIT Setting the Position to 0 inside ReadFully method is not allowed, so I put it inside DownloadBlobAsStream This should work now: public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri){ Stream mem = new MemoryStream(); CloudBlobClient blobclient = account.CreateCloudBlobClient(); CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri); if (blob != null) blob.DownloadToStream(mem); mem.Position = 0; return mem;}
Now provide the response and nothing else.
|
Your problem is that your input stream pointer is set to end of the steam (See the screen shot, Length and Position both shows same value) that's why when you read it you always get null. You would need to set to input stream pointer to 0 using Stream.Position = 0 as below: public static byte[] ReadFully(Stream input){ byte[] buffer = new byte[16 * 1024]; input.Position = 0; // Add this line to set the input stream position to 0 using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10891857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015790/']}
|
jdg_377264
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3757393
|
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 for solution for : Given a array and a number P , find two numbers in array whose product equals P. Looking for solution better than O(n*2) . I am okay with using extra space or other datastructure .Any help is appreciated ?
Now provide the response and nothing else.
|
Make a pass through the array, and add the elements to a Hashtable. For each element x added, check whether P/x already exists in the Hashtable - if it does then x and P/x is one of your solutions. This'd be about as optimal as you'll get.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3757393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247560/']}
|
jdg_377265
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
96876
|
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 generate a figure using RegionPlot and then Export it as "EPS" . When I insert this picture into MS Word, it doesn't work. The figure is generated by the following code: Constraint1[α1_, α2_] := Cos[α2] (Sin[α2]/Sin[α1] - Sin[α2] Cot[α1] + Cos[α2]);CSSSS = Show[ RegionPlot[ 0 < α1 < α2 < 60 && Constraint1[α1*π/180, α2*π/180] > 1/2, {α1, 0, 59.999}, {α2, 0, 60}, BaseStyle -> {FontFamily -> Times, 25}, ImageSize -> 600, FrameLabel -> {Style["\!\(\*SubscriptBox[\(α\), \(1\)]\)(\[Degree])", 28], Style["\!\(\*SubscriptBox[\(α\), \(2\)]\)(\[Degree])", 28]}, PlotLabel -> Style["Value Range of Basic Angles", 25, Black], FrameStyle -> Directive[Thickness[0.003], Black], Epilog -> {Inset[Style["(45, 60)", 25], {40, 59}], Inset[Style["(45, 50)", 25], {50, 49}], Inset[Style["(40, 50)", 25], {35, 49}]}], ListPlot[{{45, 60}, {45, 50}, {40, 50}}, PlotStyle -> Red]]Export["xxx.eps", CSSSS] Screenshot after importing the "xxx.eps" file into MS Word:
Now provide the response and nothing else.
|
The figure you are trying to Export into EPS format contains semi-transparent objects unsupported by this format: Cases[CSSSS, _Opacity, Infinity] {Opacity[0.3]} Actually all the filling produced by RegionPlot is semi-transparent as you can easily find using my shortInputForm function : CSSSS // shortInputForm Since transparency actually isn't necessary for your image you can simply replace default semi-transparent filling with non-transparent color (which exactly reproduces the default styling) by adding the following option to RegionPlot : PlotStyle -> RGBColor[0.8105251`, 0.8520337`, 0.9129394`] Now Cases[CSSSS, _Opacity, Infinity] {Opacity[1]} while the plot looks exactly as it was looking originally. In the general case when you have semi-transparent objects overlapping with some non-uniform background you have to perform transparency flattening , see this answer for details. However even after removing transparency MS Word still cannot import the EPS file Export ed from Mathematica 10.2 (which I currently work with, but the same is true for version 8.0.4). The most probable reason is that this EPS file contains PostScript Level 3 instructions which MS Office EPS Import Filter cannot understand. In this answer I discuss limitations of the latter and known methods allowing to generate EPS files compatible with MS Office. The most reliable way is to Export as PDF from Mathematica , then use free utility pdftops or pdftocairo from Poppler utilities for Windows for generating Level 2 EPS file as follows: pdftops -level2 -eps input.pdfpdftocairo -level2 -eps input.pdf Following the pdftocairo route I obtain EPS file which MS Word 2003 successfully imports producing the following visual appearance in Word: As you can see, the Greek letters α are not displayed and instead of Times it displays all text as Arial. But what you see is not the actual imported figure: it is just a preview automatically generated by MS Office EPS Import filter which is known to be inaccurate. For the purposes of printing to PostScript printers this preview isn't used by Word: it sends original PostScript code to the PostScript printers (this code is embedded into Word document when you import a EPS file but cannot be displayed because Word cannot render PostScript). The preview is used only for display purposes and for printing to non-PostScript printers. Let us try to print this Word document to the "Adobe PDF" virtual printer and check how generated PDF file looks in Adobe Acrobat: The figure looks perfectly and the glyph α is correctly embedded! If you are not satisfied with the above result you have to go through the Adobe Illustrator route described in the linked answer : import the PDF file Export ed from Mathematica into Illustrator, edit it in order to fix incorrectly imported text, then export as EPS with unchecked option "Include CMYK PostScript in RGB Files" . From my experience, EPS files exported from Illustrator this way are always previewed correctly in MS Word.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/96876', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/34342/']}
|
jdg_377266
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41134493
|
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 load local resources with webView. I built a demo with both UIWebView and WKWebView to do some test with the code below. let uiWebView = UIWebView(frame: self.view.bounds) self.view.addSubview(uiWebView) let wkWebView = WKWebView(frame:CGRect(x: 0, y: 400, width: 500, height: 500)) self.view.addSubview(wkWebView) let path = Bundle.main.path(forResource:"1", ofType: "png") guard let realPath = path else { return } let url = URL(string: realPath) let fileUrl = URL(fileURLWithPath: realPath) if let realUrl = url { uiWebView.loadRequest(URLRequest(url:realUrl)) wkWebView.load(URLRequest(url:realUrl)) } // uiWebView.loadRequest(URLRequest(url:fileUrl)) // wkWebView.load(URLRequest(url:fileUrl)) The uiWebView can load the resource but wkWebView can not. But if I use uiWebView.loadRequest(URLRequest(url:fileUrl)) wkWebView.load(URLRequest(url:fileUrl)) both uiWebView and wkWebView can work well.I am confused and can anyone explain that for me:Shouldn't I use URL(string: realPath) for a local resource? But why UIWebView can use it ?
Now provide the response and nothing else.
|
A couple points: Apple recommends that you use WKWebview for iOS 8 and later. I would avoid writing new code with UIWebView . In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView . Additionally, consider setting the WKPreferences property javaScriptEnabled to false if you render files that are not supposed to run JavaScript. Apple has been trying to move away from path and instead wants to use URI even for local files. They recommend that you NOT use /path/to/file.png and use file:///path/to/file.png instead. As to why one URL works and the other does not, let's make a minimal example: let realPath = "/path/to/file.png"let url = URL(string: realPath) // /path/to/file.pnglet fileUrl = URL(fileURLWithPath: realPath) // file:///path/to/file.png url does not provide the scheme (a.k.a protocol). It should only be used in conjunction with another URL to give the absolute address of the resource you are trying to reach. UIWebView supports it for backwards-compatibility reasons but Apple decided to start clean with WKWebView . fileURL has a scheme ( file:// ) that tells the resource is located on the local file system. Other common schemes are http , https , ftp , etc. It's a complete address to a resource so both views know how to resolve it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41134493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2018221/']}
|
jdg_377267
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
362286
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When I review the changes in a pull request, I sometimes stumble upon a comment with a "TODO" note which may be there for different reasons, in our case mostly because of: the solution used to solve a problem can be improved but would require significantly more time investment. An author chose a quicker solution but put a comment that a better option is potentially available there is a temporary code to workaround an existing bug that should be fixed soon Knowing that TODO s generally stay in the codebase for the lifetime of the codebase, how should I react to them in a pull request? How can I politely request to avoid it, or if it is really justified, how can I make sure the author of the PR would follow it up later in the future?
Now provide the response and nothing else.
|
When you say that they "generally stay in the codebase for the lifetime of the codebase" in your team/department/organization, consider the following: Write it down in your DoD that TODO , FIXME , or similar tags should be avoided. Use a static code analysis tool such as SonarQube to automatically mark the build unstable. Temporarily allow them if, and only if, there is a corresponding ticket in your issue tracker. Then, the code may look like TODO [ID-123] Description ... As mentioned in my comment , the last statement probably only makes sense in an environment that doesn't let tickets rot (e.g. if you follow a zero-bug policy ). Personally, I think TODO s are sometimes reasonable, but one should not use them excessively. Taken from Robert C. Martin's "Clean Code: A Handbook of Agile Software Craftsmanship" (p. 59): TODO s are jobs that the programmer thinks should be done, but for some reason can't do at the moment. It might be a reminder to delete a deprecated feature or a plea for someone else to look at a problem. It might be a request for someone else to think of a better name or a reminder to make a change that is dependent on a planned event. Whatever else a TODO might be, it is not an excuse to leave bad code in the system.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/362286', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/88474/']}
|
jdg_377268
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17506552
|
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 directory bar inside a directory foo , with file foo_file.txt in directory foo and file bar_file.txt in directory bar ; i.e. computer$ lsfoo/computer$ ls foo/bar/ foo_file.txtcomputer$ ls foo/bar/bar_file.txt Using the python os.path.relpath function, I expect: os.path.relpath('foo/bar/bar_file.txt', 'foo/foo_file.txt') to give me: 'bar/bar_file.txt' However, it actually gives me: '../bar/bar_file.txt' Why is this? Is there an easy way to get the behavior I want? EDIT: This is on Linux with Python 2.7.3
Now provide the response and nothing else.
|
os.path.relpath() assumes that its arguments are directories. >>> os.path.join(os.path.relpath(os.path.dirname('foo/bar/bar_file.txt'), os.path.dirname('foo/foo_file.txt')), os.path.basename('foo/bar/bar_file.txt'))'bar/bar_file.txt'
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17506552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021274/']}
|
jdg_377269
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9490058
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why doesn't 'example'[999:9999] result in error? Since 'example'[9] does, what is the motivation behind it? From this behavior I can assume that 'example'[3] is, essentially/internally, not the same as 'example'[3:4] , even though both result in the same 'm' string.
Now provide the response and nothing else.
|
You're correct! 'example'[3:4] and 'example'[3] are fundamentally different, and slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error. It might be surprising at first, but it makes sense when you think about it. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to return. But when you slice a sequence outside of bounds, you can still return an empty sequence. Part of what's confusing here is that strings behave a little differently from lists. Look what happens when you do the same thing to a list: >>> [0, 1, 2, 3, 4, 5][3]3>>> [0, 1, 2, 3, 4, 5][3:4][3] Here the difference is obvious. In the case of strings, the results appear to be identical because in Python, there's no such thing as an individual character outside of a string. A single character is just a 1-character string. (For the exact semantics of slicing outside the range of a sequence, see mgilson's answer .)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9490058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990268/']}
|
jdg_377270
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35129182
|
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 get some mistake about " browserLink " see this below <div ng-show="optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))"> <input /></div> It's Ok.. But <div ng-show="optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))"> <input type="text"/></div> When i add type="text" on input tag i will get Uncaught Error: Syntax error, unrecognized expression: div:has(input[type='text'])[ng-show='optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optList.ONCESMART_ID == '-1'))'] Can someone tell me , How to solve this error please ? FYI :Google Chrome (48.0.2564.97) Microsoft Visual Studio Professional 2015 (14.0.23107.156) Web Essentials 2015.1 (1.0.203)
Now provide the response and nothing else.
|
There is a bug in Browser Link that is causing this problem. You should be able to work around it by adding an ID attribute to the <div> tag. Browser Link creates jQuery expressions to try to uniquely identify tags in your page. In this case, it is trying to use the ng-show expression, because nothing else about the tag is unique enough. But the ng-show expression is obviously too complex for that purpose. It should have been ignored for that reason, but somehow it is beating the check that should've disqualified it. Browser Link would rather use a unique ID or class, if one exists. By providing that, you can prevent it from considering the ng-show attribute.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35129182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377271
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22231563
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the internal implementation of var and val in Scala? interested in knowing the details of their implementations- what makes var a "var" how mutable structure is implemented vs val (more final like) structure which makes it immutable.
Now provide the response and nothing else.
|
I'll answer by example, using scalac and javap . First I create Test.scala : class Test { val x = 1 var y = 2} Compile it via scalac Test.scala to generate Test.class , then use javap -p Test.class to get public class Test { private final int x; private int y; public int x(); public int y(); public void y_$eq(int); public Test();} So you can see that val x became a private final field on the class, and also a public final method to return that value. var y became a non-final private field, and a getter+setter pair. The y_$eq(int) is the setter. In scala, that would be def y_=(newY: Int): Unit . Scala's syntax sugar will translate y = someValue into a call to y_=(someValue) .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22231563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1331769/']}
|
jdg_377272
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
914233
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the typical underlying data structure used to implement Python's built-in list data type?
Now provide the response and nothing else.
|
List objects are implemented as arrays. They are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation. See also: http://docs.python.org/library/collections.html#collections.deque Btw, I find it interesting that the Python tutorial on data structures recommends using pop(0) to simulate a queue but does not mention O(n) or the deque option. http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/914233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61793/']}
|
jdg_377273
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19814713
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have written the following code: package staticshow;public class StaticDemo { static int a = 3; static int b = 4; static { System.out.println("Voila! Static block put into action"); } static void show() { System.out.println("a= " + a); System.out.println("b= " + b); }}public class StaticDemoShow { public static void main() { StaticDemo.show(); }} I am getting the error message: The public type StaticDemo must be defined in its own file error in the very first line public class StaticDemo { . Why is it happening and how can I resolve it? Note that my project name is StaticDemoShow , package name is staticshow and class names are as given in the code. EDIT - After making just one class public or both the classes default, I am getting the error "Selection does not contain a main type". Now what should I do?
Now provide the response and nothing else.
|
If .java file contains top level (not nested) public class, it has to have the same name as that public class. So if you have class like public class A{...} it needs to be placed in A.java file. Because of that we can't have two public classes in one .java file . If having two public classes would be allowed then, and lets say aside from public A class file would also contain public class B{} it would require from A.java file to be also named as B.java but files can't have two (or more) names (at least in all systems on which Java can be run). So assuming your code is placed in StaticDemoShow.java file you have two options: If you want to have other class in same file make them non-public (lack of visibility modifier will represent default/package-private visibility) class StaticDemo { // It can no longer public static int a = 3; static int b = 4; static { System.out.println("Voila! Static block put into action"); } static void show() { System.out.println("a= " + a); System.out.println("b= " + b); } } public class StaticDemoShow { // Only one top level public class in same .java file public static void main() { StaticDemo.show(); } } Move all public classes to their own .java files. So in your case you would need to split it into two files: StaticDemo.java public class StaticDemo { // Note: same name as name of file static int a = 3; static int b = 4; static { System.out.println("Voila! Static block put into action"); } static void show() { System.out.println("a= " + a); System.out.println("b= " + b); } } StaticDemoShow.java public class StaticDemoShow { public static void main() { StaticDemo.show(); } }
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19814713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1493480/']}
|
jdg_377274
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12692727
|
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 use PHP to calculate simple algebraic expressions like, 8*(5+1) , entered via an <input> tag by a normal user (which means, normal notation : no syntax changes like Multiply(8, Add(5, 1))) . Also, it has to show all steps, but that's not hard. The problem, right now, is calculating the value of the expressions. Note: this is what I thought so far, which is quite inefficient but it's a provisory solution.Just replace strings where possible: in our example, recognize the string 5+1 and replace it with 6 . Then, loop again, replace (6) with 6 , loop again, and replace 8*6 with 48 .The code for multiplying, for example, should look like this: for ($a=1; $a < 1000; $a++) { for ($b=1; $b < 1000; $b++) { string_replace($a . '*' . $b, $a*$b, $string); }}
Now provide the response and nothing else.
|
Depending on your needs, I would suggest looking into the Shunting Yard Algorithm . It's pretty easy to implement, and works quite well. Here's an example I whipped up a while ago: GIST . Here's the code copy/pasted into one block: Expression Definitions: class Parenthesis extends TerminalExpression { protected $precidence = 7; public function operate(Stack $stack) { } public function getPrecidence() { return $this->precidence; } public function isNoOp() { return true; } public function isParenthesis() { return true; } public function isOpen() { return $this->value == '('; }}class Number extends TerminalExpression { public function operate(Stack $stack) { return $this->value; }}abstract class Operator extends TerminalExpression { protected $precidence = 0; protected $leftAssoc = true; public function getPrecidence() { return $this->precidence; } public function isLeftAssoc() { return $this->leftAssoc; } public function isOperator() { return true; }}class Addition extends Operator { protected $precidence = 4; public function operate(Stack $stack) { return $stack->pop()->operate($stack) + $stack->pop()->operate($stack); }}class Subtraction extends Operator { protected $precidence = 4; public function operate(Stack $stack) { $left = $stack->pop()->operate($stack); $right = $stack->pop()->operate($stack); return $right - $left; }}class Multiplication extends Operator { protected $precidence = 5; public function operate(Stack $stack) { return $stack->pop()->operate($stack) * $stack->pop()->operate($stack); }}class Division extends Operator { protected $precidence = 5; public function operate(Stack $stack) { $left = $stack->pop()->operate($stack); $right = $stack->pop()->operate($stack); return $right / $left; }}class Power extends Operator { protected $precidence=6; public function operate(Stack $stack) { $left = $stack->pop()->operate($stack); $right = $stack->pop()->operate($stack); return pow($right, $left); }}abstract class TerminalExpression { protected $value = ''; public function __construct($value) { $this->value = $value; } public static function factory($value) { if (is_object($value) && $value instanceof TerminalExpression) { return $value; } elseif (is_numeric($value)) { return new Number($value); } elseif ($value == '+') { return new Addition($value); } elseif ($value == '-') { return new Subtraction($value); } elseif ($value == '*') { return new Multiplication($value); } elseif ($value == '/') { return new Division($value); } elseif ($value == '^') { return new Power($value); } elseif (in_array($value, array('(', ')'))) { return new Parenthesis($value); } throw new Exception('Undefined Value ' . $value); } abstract public function operate(Stack $stack); public function isOperator() { return false; } public function isParenthesis() { return false; } public function isNoOp() { return false; } public function render() { return $this->value; }} The stack (really simple implementation): class Stack { protected $data = array(); public function push($element) { $this->data[] = $element; } public function poke() { return end($this->data); } public function pop() { return array_pop($this->data); }} And finally, the executor class: class Math { protected $variables = array(); public function evaluate($string) { $stack = $this->parse($string); return $this->run($stack); } public function parse($string) { $tokens = $this->tokenize($string); $output = new Stack(); $operators = new Stack(); foreach ($tokens as $token) { $token = $this->extractVariables($token); $expression = TerminalExpression::factory($token); if ($expression->isOperator()) { $this->parseOperator($expression, $output, $operators); } elseif ($expression->isParenthesis()) { $this->parseParenthesis($expression, $output, $operators); } else { $output->push($expression); } } while (($op = $operators->pop())) { if ($op->isParenthesis()) { throw new RuntimeException('Mismatched Parenthesis'); } $output->push($op); } return $output; } public function registerVariable($name, $value) { $this->variables[$name] = $value; } public function run(Stack $stack) { while (($operator = $stack->pop()) && $operator->isOperator()) { $value = $operator->operate($stack); if (!is_null($value)) { $stack->push(TerminalExpression::factory($value)); } } return $operator ? $operator->render() : $this->render($stack); } protected function extractVariables($token) { if ($token[0] == '$') { $key = substr($token, 1); return isset($this->variables[$key]) ? $this->variables[$key] : 0; } return $token; } protected function render(Stack $stack) { $output = ''; while (($el = $stack->pop())) { $output .= $el->render(); } if ($output) { return $output; } throw new RuntimeException('Could not render output'); } protected function parseParenthesis(TerminalExpression $expression, Stack $output, Stack $operators) { if ($expression->isOpen()) { $operators->push($expression); } else { $clean = false; while (($end = $operators->pop())) { if ($end->isParenthesis()) { $clean = true; break; } else { $output->push($end); } } if (!$clean) { throw new RuntimeException('Mismatched Parenthesis'); } } } protected function parseOperator(TerminalExpression $expression, Stack $output, Stack $operators) { $end = $operators->poke(); if (!$end) { $operators->push($expression); } elseif ($end->isOperator()) { do { if ($expression->isLeftAssoc() && $expression->getPrecidence() <= $end->getPrecidence()) { $output->push($operators->pop()); } elseif (!$expression->isLeftAssoc() && $expression->getPrecidence() < $end->getPrecidence()) { $output->push($operators->pop()); } else { break; } } while (($end = $operators->poke()) && $end->isOperator()); $operators->push($expression); } else { $operators->push($expression); } } protected function tokenize($string) { $parts = preg_split('((\d+|\+|-|\(|\)|\*|/)|\s+)', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $parts = array_map('trim', $parts); return $parts; }} It works by first tokenizing the input (based on word boundary, and tokens). Then, it runs the Shunting Yard algorithm on it to convert the input into a RPN (Reverse Polish Notation) stack. Then, it's just a matter of executing the stack. Here's a quick example: $math = new Math();$answer = $math->evaluate('(2 + 3) * 4');var_dump($answer);// int(20)$answer = $math->evaluate('1 + 2 * ((3 + 4) * 5 + 6)');var_dump($answer);// int(83)$answer = $math->evaluate('(1 + 2) * (3 + 4) * (5 + 6)');var_dump($answer);// int(231)$math->registerVariable('a', 4);$answer = $math->evaluate('($a + 3) * 4');var_dump($answer);// int(28)$math->registerVariable('a', 5);$answer = $math->evaluate('($a + $a) * 4');var_dump($answer);// int(40) Now, this example is significantly more complex than you may need. The reason is that it also handles grouping and operator precedence. But it's a decent example of a running algorithm that doesn't use EVAL and supports variables...
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12692727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1541408/']}
|
jdg_377275
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43497431
|
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'll try to keep it short.For some reason, My animation seems to work fine on width/opacity style attribute yet it doesn't work on height attribute.... the animation - trigger('Grow', [transition(':enter', [ // :enter is alias to 'void => *' style({height:'0'}), animate(500, style({height:'*'})) ]),transition(':leave', [ // :leave is alias to '* => void' animate(500, style({height:0})) ])]) Changing the 'height' to width/opacity and the animation works great...any one knows wheres the issue? couldn't find relative answer anywhere . an example of what I'm trying to achieve is like the animation in udemy, upon clicking on a section the div height expands the display all the videos - https://www.udemy.com/meteor-react/ thanks for reading . Update - still doesn't work... maybe its something with what I'm animating on? <div class="animate" *ngIf="show" [@animate]> <div *ngFor="let video of section"><a>hi</a></div></div> what happens is once I click, the div.animate is showing (by ngif) and fills with lots of lines that says 'hi'.I want that on div.animate show, to make the animation I specified. help! ^^
Now provide the response and nothing else.
|
You don't have any states defined in your trigger() function. trigger creates a named animation trigger, containing a list of state() and transition() entries to be evaluated when the expression bound to the trigger changes (the expression being [@slideInOut]="helpMenu" in example below). @Component({ ... animations: [ trigger('slideInOut', [ state('in', style({ overflow: 'hidden', height: '*', width: '300px' })), state('out', style({ opacity: '0', overflow: 'hidden', height: '0px', width: '0px' })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]) ]})export class AComponent implements OnInit { helpMenu: string; constructor() { } ngOnInit() { this.helpMenu = 'out'; } toggleHelpMenu(): void { this.helpMenu = this.helpMenu === 'out' ? 'in' : 'out'; }} Then use it in your view like this: <div [@slideInOut]="helpMenu"> <h1>My Title</h1> <p>My paragraph</p></div><button (click)="toggleHelpMenu()">help</button>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43497431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7210967/']}
|
jdg_377276
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18821492
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I return response from the controller back to the Jquery Javascript? Javascript $('.signinform').submit(function() { $(this).ajaxSubmit({ type : "POST", url: 'index.php/user/signin', // target element(s) to be updated with server response cache : false, success : onSuccessRegistered, error: onFailRegistered }); return false; }); Data is returned null (blank)! function onSuccessRegistered(data){ alert(data);}; Controller - public function signin() { $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode( $arr );}
Now provide the response and nothing else.
|
//do the edit in your javascript$('.signinform').submit(function() { $(this).ajaxSubmit({ type : "POST", //set the data type dataType:'json', url: 'index.php/user/signin', // target element(s) to be updated with server response cache : false, //check this in Firefox browser success : function(response){ console.log(response); alert(response)}, error: onFailRegistered }); return false; }); //controller functionpublic function signin() { $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //add the header here header('Content-Type: application/json'); echo json_encode( $arr );}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18821492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2365196/']}
|
jdg_377277
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8334340
|
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 weird design case in which to implement I need to place two UITableViews on the same view. I would just use sections, but I need an index on the second table. I'd like them to both scroll together like they were actually two sections of the same table view. Is this possible? Here's a basic mockup illustrating why: As far as I understand it, you cannot move the index. Also, when you add an index to a table, it appears over the entire tableview, not just one section. If I have to implement this as two table views, they both need to scroll as if they were one. If it's possible to do this using sections, that's even better.
Now provide the response and nothing else.
|
Update After seeing your update my old answer is not very good but I'll leave my previous answer for anyone else who wants it. New answer - It depends how you want the tables sync'd. If you know Which cells are in the top 5 How tall each cell is The offset the table view Then you can calculate which cell is visible at the top of the top 5 table. You can use this information to scroll the bottom table to the correct index. Old answer I'm with the other guys not sure why you would want to or if I am misinterpreting but it's pretty simple. UITableView is a subclass of UIScrollView so you can set yourself as the UITableViewDelegate and override - (void)scrollViewDidScroll:(UIScrollView *)scrollView;{ UITableView *slaveTable = nil; if (self.table1 == scrollView) { slaveTable = self.table2; } else if (self.table2 == scrollView) { slaveTable = self.table1; } [slaveTable setContentOffset:scrollView.contentOffset];} This gives me something that looks like this: The top UITableView is self.table1 and the bottom is self.table2 if either table is scrolled the scrolling is mirrored in the other table.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8334340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51819/']}
|
jdg_377278
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20921546
|
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 do code something like this in groovy ? do { x.doIt()} while (!x.isFinished()) Because there is no do ... while syntax in groovy. No 'do ... while()' syntax as yet. Due to ambiguity, we've not yet added support for do .. while to Groovy References: groovy - dev > do while Migration From Classic to JSR syntax Groovy Documentation > Control Structures > Looping Rosetta Code > Loops/Do-while Groovy
Now provide the response and nothing else.
|
You can roll your own looping that's almost what you want. Here's an example with loop { code } until { condition } You can't have a corresponding loop { code } while { condition } because while is a keyword.But you could call it something else. Anyway here's some rough and ready code for loop until.One gotcha is you need to use braces for the until condition to make it a closure.There may well be other issues with it. class Looper { private Closure code static Looper loop( Closure code ) { new Looper(code:code) } void until( Closure test ) { code() while (!test()) { code() } }} Usage: import static Looper.*int i = 0loop { println("Looping : " + i) i += 1} until { i == 5 }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20921546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516167/']}
|
jdg_377279
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
250183
|
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've read a few different presentations of Cohen's proof. All of them (that I've seen) eventually make a move where a Cartesian product (call it CP) between the (M-form of) $\aleph_2$ and $\aleph_0$ into {1, 0} is imagined. From what I gather, whether $CP \in M$ is what determines whether $\neg$CH holds in M or not such that if $CP \in M$ then $\neg$CH. Anyway, my question is: Why does this product, CP, play this role? How does it show us that $\aleph_2 \in M$ (the 'relativized' form of $\aleph_2$, not the $\aleph_2 \in V$)? Could not some other set-theoretical object play the same role?
Now provide the response and nothing else.
|
I'm not exactly certain what you are asking, but I'll take a stab anyway. The basic idea of Cohen's proof (or at least modern interpretations of it) are to adjoin to the ground model a family of $\aleph_2^M$ new reals. Since a real is nothing more than a function $\omega \to 2$, a family of $\aleph_2^M$-many reals may be thought of as a function $\omega_2^V \times \omega \to 2$. (Recall that there is a natural bijection between $C^{A \times B}$ and $( C^B )^A$, and so a function $f : \omega_2^M \times \omega \to 2$ may be thought of as an indexing of $\omega_2^M$-many reals $\{ f_\alpha : \alpha < \omega_2^M \}$ where $f_\alpha ( n ) = f ( \alpha , n )$. If we can generate such a function, we are left with two very important steps: Show that if $\alpha \neq \beta$, then $f_\alpha \neq f_\beta$, which is a standard genericity argument. Once this is done we know that there are at least $\aleph_2^M$-many reals in the extension $M[G]$. Show that $\aleph_2^M$ is still the second uncountable cardinal in the generic extension. If it is, then we know that $M[G] \models \text{"}| \mathbb{R} | \geq \aleph_2 \text{"}$, and therefore CH is false in $M[G]$. This step is usually handled by combinatorial properties of the Cohen forcing ( i.e. , that it has the countable chain condition). (Of course, that $\aleph_2$ is used is not strictly important, and the methodology of the proof goes through for "almost all" uncountable ordinals.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/250183', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51635/']}
|
jdg_377280
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6845
|
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:
As we know, for most Gaussian integrals, we can get the analytical result. Now I have many Gaussian integrals to treat, which have the following general form, Integrate[ x1^n1 x2^n2 x3^n3 ... xd^ nd Exp[-{x1, x2, x3 ... xd}.matrix.{x1, x2, x3 ... xd} + c1 x1 + c2 x2 ... cd xd], {x1, -Infinity, Infinity}, {x2, -Infinity, Infinity} ... {xd, -Infinity, Infinity}]. The matrix is a symmetrical positive definite matrix. We can get the analytical integral result for this general form. However, it is a difficult task for Mathematica to deal with the similiar expressions, which takes so much time. I have written a package for treating this problem. But, it is still not sufficient because I need to deal with lots of these kinds of integral expressions. So the computation time is important. So have you ever seen the package for doing this kind of Gaussian integral? Or can you give me some suggestions about this problem? Thank you very much! Thanks all of you. For the concept MultinormalDistribution, it is very helpful for me. By the way, How can I transform the following integral expressionto the standard form of MultinormalDistribution in a simple way? vec1 := {r1x, r1y, r1z};vec2 := {r2x, r2y, r2z};vect := {r1x, r1y, r1z, r2x, r2y, r2z};vcof := {c1, c2, c3, c4, c5, c6};Integrate[Exp[-vect.mat.vect + vcof.vect] (vec1.vec2)^n (vec1.vec1)^l (vec2.vec2)^m, {r1x, -Infinity, Infinity}, {r1y, -Infinity, Infinity}, {r1z, -Infinity, Infinity}, {r2x, -Infinity, Infinity}, {r2y, -Infinity, Infinity}, {r2z, -Infinity, Infinity}]; The mat is a symmetrical positive definite sparse matrix. And n, l, m are integers. Thanks!
Now provide the response and nothing else.
|
What you have is a MultinormalDistribution . The quadratic and linear forms in the exponential can be rewritten in terms of $-\frac12(\vec{x}-\vec{\mu})^\top\Sigma^{-1}(\vec{x}-\vec{\mu})$ where $\vec{\mu}$ represents the mean and $\Sigma$ the covariance matrix, see the documentation . With this, you can do integrals of the type given in the question by invoking Expectation , as in this example: Expectation[ x^2 y^3, {x, y} \[Distributed] MultinormalDistribution[{μ1, μ2}, {{σ1^2, ρ σ1 σ2}, {ρ σ1 σ2, σ2^2}}]] The result is: $\text{$\mu $1}^2 \text{$\mu $2}^3+\text{$\mu $2}^3 \text{$\sigma $1}^2+6 \text{$\mu $1} \text{$\mu $2}^2 \rho \text{$\sigma $1} \text{$\sigma$2}+3 \text{$\mu $1}^2 \text{$\mu $2} \text{$\sigma $2}^2+3 \text{$\mu $2} \text{$\sigma $1}^2 \text{$\sigma $2}^2+6 \text{$\mu $2} \rho ^2 \text{$\sigma$1}^2 \text{$\sigma $2}^2+6 \text{$\mu $1} \rho \text{$\sigma $1} \text{$\sigma $2}^3$ Edit Regarding the normalization prefactor mentioned in Sjoerd's comment, you can use the fact that for any dimension $n$ $\iint\exp(-\frac{1}{2}\vec{z}^\top \Sigma^{-1}\vec{z})\mathrm dz^n = (2\pi)^{n/2}\sqrt{\det(\Sigma)}$ Hopefully these hints will be enough for you to fill in the missing linear-algebra steps to make the connection to your given matrix matrix . Edit 2 In response to the comment by chris, for polynomials as prefactors one can also use the slightly simpler but equivalent form Moment[ MultinormalDistribution[{μ1, μ2}, {{σ1^2, ρ σ1 σ2}, {ρ σ1 σ2, σ2^2}}], {2, 3}] This is the same example as above, with the powers of x and y appearing in the second argument. See the documentation for Moment . The difference between Moment and Expectation is that Moment is restricted to the expectation values of polynomials. Edit 3 Before going on with the symbolic manipulations that I assumed are desired here, let me also point out that you can do your integrals pretty straightforwardly if your integrand contains no symbolic parameters. Then you just need to do a numerical integral by replacing Integrate with NIntegrate . But now back to the symbolic part: A follow-up question arose how to complete the square in the exponential to get to the standard form of the multinormal distribution, starting from a form like this: $$\exp(\,\vec{x}^\top A\vec{x}+\vec{v}^\top\vec{x})$$ The matrix $A$ in the exponential is symmetric, $A^\top=A$, and positive definite. Therefore $A$ is invertible, and the inverse is symmetric, $$\left(A^{-1}\right)^\top=A^{-1}$$ With this, you can verify $$\left(\vec{x}+\frac{1}{2}A^{-1}\vec{v}\right)^\top A\left(\vec{x}+\frac{1}{2}A^{-1}\vec{v}\right)=\vec{x}^\top A\vec{x}+\vec{v}^\top\vec{x}+\frac{1}{4}\vec{v}^\top A^{-1}\vec{v} $$ by directly multiplying out the factors on the left. Therefore, $$\exp(\vec{x}^\top A\vec{x}+\vec{v}^\top \vec{x})=\exp(\left(\vec{x}-\vec{\mu}\right)^\top A\left(\vec{x}-\vec{\mu}\right)-\frac{1}{4}\vec{v}^\top A^{-1}\vec{v})$$ where $$\vec{\mu}\equiv-\frac{1}{2}A^{-1}\vec{v} $$ Compare this to the standard form of the Gaussian integral, and you see that in the notation of Mathematica's documentation $$A \equiv -\frac{1}{2} \Sigma^{-1}$$ and our integral differs from the standard Gaussian one by a factor $$\exp(-\frac{1}{4}\vec{v}^\top A^{-1}\vec{v})$$ Now we have all the pieces that are needed, except that you still have to calculate the inverse matrix $A^{-1} \equiv -2\Sigma$, using Inverse[mat] if I go back to your original notation where the matrix $A$ is called mat . Edit 4: In view of the other answers, I put together the above steps in a module so that my approach can be compared more easily to the alternatives. The result is quite compact and is not significantly slower than the fastest alternative (by @ybeltukov): gaussMoment[fPre_, fExp_, vars_] := Module[{coeff, dist, ai, μ, norm}, coeff = CoefficientArrays[fExp, vars, "Symmetric" -> True]; ai = Inverse[2 coeff[[3]]]; μ = -ai.coeff[[2]]; dist = MultinormalDistribution[μ, -ai]; norm = 1/PDF[dist, vars] /. Thread[vars -> μ]; Simplify[ norm Exp[1/2 coeff[[2]].μ + coeff[[1]]] Distribute@ Expectation[fPre, vars \[Distributed] dist]]] The normalization factor can be easily obtained from the PDF . I used the same approach as @ybeltukov to extract the matrix $A$ from the exponent, except that I added a factor of $2$ at that stage to prevent that factor from popping up twice at later points. Here are some tests: RepeatedTiming[ gaussMoment[(x^2 + x^4 + x^6), -(x - 1)^2, {x}]] $$\left\{0.0023,\frac{223 \sqrt{\pi }}{8}\right\}$$ RepeatedTiming[ gaussMoment[(x^2 + x y) , -(x - a1)^2 - (y - a2)^2 - (x - y)^2, {x, y}]] $$\left\{0.0014,\frac{\pi \left(4 \text{a1}^2+6 \text{a1} \text{a2}+2 \text{a2}^2+3\right) e^{-\frac{1}{3} (\text{a1}-\text{a2})^2}}{6 \sqrt{3}}\right\}$$ This is about four orders of magnitude faster than doing the integrals using plain Integrate . One other big advantage (in addition to its simplicity and speed) is that it can deal with non-polynomial prefactors. Here is an example (it takes longer to run, but the other methods cannot do it at all): gaussMoment[ Sin[2 Pi x] Cos[Pi x] , -(x - a1)^2 - (y - a2)^2 - (x - y)^2, {x, y}] $$\frac{i \pi e^{-\text{a1}^2-\frac{\text{a2}^2}{2}} \left(e^{\frac{1}{6} (2 \text{a1}+\text{a2}-i \pi )^2}-e^{\frac{1}{6} (2 \text{a1}+\text{a2}+i \pi )^2}+e^{\frac{1}{6} (2 \text{a1}+\text{a2}-3 i \pi )^2}-e^{\frac{1}{6} (2 \text{a1}+\text{a2}+3 i \pi )^2}\right)}{4 \sqrt{3}}$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/6845', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1495/']}
|
jdg_377281
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58991123
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anyone can explain me why this python -V | awk '{print $2}' returns this Python 2.7.5 instead of 2.7.5 What to do to return only the version number without "Python " ?
Now provide the response and nothing else.
|
If you run python -V >/dev/null you will notice that you still get output! Apparently, python -V prints its output to stderr, not to stdout. In a bourne-like shell, this should work: python -V 2>&1 | awk '{print $2}'
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58991123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1806799/']}
|
jdg_377282
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18323995
|
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 I append a file to an existing tar archive in Go? I don't see anything obvious in the docs on how to do it. I have a tar file that has already been created and I want to add more to it after it has already been closed. EDIT Altering the example in the docs and following the answer given, I'm still not getting the expected result. The first three files are being written to the tar but when I close and open up the file again to write to it, the new file is never being written. The code runs fine. I don't know what I'm missing. The following code gives me a tar file with three files in it: readme.txt, gopher.txt, todo.txt. foo.bar never gets written. package mainimport ( "archive/tar" "log" "os")func main() { f, err := os.Create("/home/jeff/Desktop/test.tar") if err != nil { log.Fatalln(err) } tw := tar.NewWriter(f) var files = []struct { Name, Body string }{ {"readme.txt", "This archive contains some text files."}, {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, {"todo.txt", "Get animal handling licence."}, } for _, file := range files { hdr := &tar.Header{ Name: file.Name, Size: int64(len(file.Body)), } if err := tw.WriteHeader(hdr); err != nil { log.Fatalln(err) } if _, err := tw.Write([]byte(file.Body)); err != nil { log.Fatalln(err) } } if err := tw.Close(); err != nil { log.Fatalln(err) } f.Close() // Open up the file and append more things to it f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_APPEND|os.O_WRONLY, os.ModePerm) if err != nil { log.Fatalln(err) } tw = tar.NewWriter(f) test := "this is a test" hdr := &tar.Header{ Name: "foo.bar", Size: int64(len(test)), } if err := tw.WriteHeader(hdr); err != nil { log.Fatalln(err) } if _, err := tw.Write([]byte(test)); err != nil { log.Fatalln(err) } if err := tw.Close(); err != nil { log.Fatalln(err) } f.Close()}
Now provide the response and nothing else.
|
The tar file specification states: A tar archive consists of a series of 512-byte records. Each file system object requires a header record which stores basic metadata (pathname, owner, permissions, etc.) and zero or more records containing any file data. The end of the archive is indicated by two records consisting entirely of zero bytes. The Go implementation of adding these two zero filled records happens here . To get around the tar file format trailer (basically 1024 bytes of nothing) you could replace the lines: f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_APPEND|os.O_WRONLY, os.ModePerm)if err != nil { log.Fatalln(err)}tw = tar.NewWriter(f) With: f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_RDWR, os.ModePerm)if err != nil { log.Fatalln(err)}if _, err = f.Seek(-1024, os.SEEK_END); err != nil { log.Fatalln(err)}tw = tar.NewWriter(f) It opens the file read / write (instead of append / write-only) and then seeks to 1024 bytes before the end of the file and writes from there. It works, but it is a horrible hack. EDIT: After understanding the tar file spec a little better, I no longer believe this is such a hack. Full code: http://play.golang.org/p/0zRScmY4AC
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18323995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/230392/']}
|
jdg_377283
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
98857
|
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 have a basic understanding of genetics, and I'm really puzzled by this. My grandma's blood type is A (I don't know if it's heterozygous or homozygous) and my grandpa is AB. Yet my mother is type O. Grandma says that my mom is 100% my grandpa's child, so how did it happen?I have a few hypotheses regarding this. Either my grandma is lying, which I find to be really implausible, or there's some genetical anomalies either in my mom or my grandparents. I suspect that grandma is heterozygous, having the IAi genes for blood type, and grandpa has a weird case of IAIBi alleles, coming either from a failed disjunction which caused both alleles for A and B to be present in one sperm cell, and the i allele to be present in the egg, resulting in the IAIBi genotype. Then, when grandpa had my mom, both i alleles got combined and out came my mom with O type. My other hypothesis is that mom is heterozygous, either IAi or IBi, but the dominant allele underwent a deletion (or something else) and was inactivated, and as such only the recessive allele remained, giving her type O blood. Could I get some insight on how this happened? I can't seem to find anything related to it on the internet.
Now provide the response and nothing else.
|
The ABO blood type is controlled by a single gene (the ABO gene) with three types of alleles inferred from classical genetics: i, IA, and IB. The IA allele gives type A, IB gives type B, and i gives type O. As both IA and IB are dominant over i, only ii people have type O blood. [ 1 ] So from this standpoint, normal Mendelian genetics cannot explain the blood-group 0 offspring, given the AB parent. However, besides errors in testing, the (pseudo?) 0-bloodgroup could be explained by the Bombay phenotype . I don't know the incidence rate in your region, so I can't comment on the likelihood. To give theoretical background, this would be considered a pseudo 0-phenotype, as the individual genetically does not need to be ii . Instead, the individual lacks another effective enzyme that is required for the A or B alleles to be effective; the blood-type specific sugars (N-Acetylgalactosamin|Galactose) cannot be attached to the red blood-cell membrane, as the anchor of these sugars (called H-substance) is not present. Finally, to address your hypothesis of a gene-duplication followed by a gene knock-out: There is no need for a preceding duplication. The more probable cause is a single point mutation (or multiple) near the active center of the inherited A/B enzyme, or a nucleotide insertion/deletion in its coding region, causing a frame-shift. A completely (not partially!) inactivated A/B enzyme would effectively represent a novel 0-genotype.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/98857', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/64793/']}
|
jdg_377284
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2245
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In his 1984 paper "Statistics and Causal Inference" , Paul Holland raised one of the most fundamental questions in statistics: What can a statistical model say about causation? This led to his motto: NO CAUSATION WITHOUT MANIPULATION which emphasized the importance of restrictions around experiments that consider causation. Andrew Gelman makes a similar point : "To find out what happens when you change something, it is necessary to change it."...There are things you learn from perturbing a system that you'll never find out from any amount of passive observation. His ideas are summarized in this article . What considerations should be made when making a causal inference from a statistical model?
Now provide the response and nothing else.
|
This is a broad question, but given the Box, Hunter and Hunter quote is true I think what it comes down to is The quality of the experimental design: randomization, sample sizes, control of confounders,... The quality of the implementation of the design: adherance to protocol, measurement error, data handling, ... The quality of the model to accurately reflect the design: blocking structures are accurately represented, proper degrees of freedom are associated with effects, estimators are unbiased, ... At the risk of stating the obvious I'll try to hit on the key points of each: is a large sub-field of statistics, but in it's most basic form I think it comes down to the fact that when making causal inference we ideally start with identical units that are monitored in identical environments other than being assigned to a treatment. Any systematic differences between groups after assigment are then logically attributable to the treatment (we can infer cause). But, the world isn't that nice and units differ prior to treatment and evironments during experiments are not perfectly controlled. So we "control what we can and randomize what we can't", which helps to insure that there won't be systematic bias due to the confounders that we controlled or randomized. One problem is that experiments tend to be difficult (to impossible) and expensive and a large variety of designs have been developed to efficiently extract as much information as possible in as carefully controlled a setting as possible, given the costs. Some of these are quite rigorous (e.g. in medicine the double-blind, randomized, placebo-controlled trial) and others less so (e.g. various forms of 'quasi-experiments'). is also a big issue and one that statisticians generally don't think about...though we should. In applied statistical work I can recall incidences where 'effects' found in the data were spurious results of inconsistency of data collection or handling. I also wonder how often information on true causal effects of interest is lost due to these issues (I believe students in the applied sciences generally have little-to-no training about ways that data can become corrupted - but I'm getting off topic here...) is another large technical subject, and another necessary step in objective causal inference. To a certain degree this is taken care of because the design crowd develop designs and models together (since inference from a model is the goal, the attributes of the estimators drive design). But this only gets us so far because in the 'real world' we end up analysing experimental data from non-textbook designs and then we have to think hard about things like the appropriate controls and how they should enter the model and what associated degrees of freedom should be and whether assumptions are met if if not how to adjust of violations and how robust the estimators are to any remaining violations and... Anyway, hopefully some of the above helps in thinking about considerations in making causal inference from a model. Did I forget anything big?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/2245', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5/']}
|
jdg_377285
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69664
|
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:
There is an ongoing situation in the UK regarding the propriety of the procurement of some goods and services during the response to COVID-19. Conservative PPE contracts Michael Gove and VIP lane Good law project Is this situation unique to the UK? The early response to COVID-19 required governments worldwide to react much more quickly to outside events. Are those actions being questioned regarding their legality and honesty elsewhere?
Now provide the response and nothing else.
|
I don't think it's unique to the UK. I can think of at least two instances of controversy surrounding Covid-related procurement deals in the Netherlands and Thailand. I'll highlight some of the controversies. The Netherlands: shady deal surrounding the procurement of face masks In the Netherlands there was a row over someone who created a nonprofit organisation to import and provide face masks. It later turned out that the same person was involved in a for profit company tied to the nonprofit which allowed them to make money off of the face mask deals even though they presented themselves as a nonprofit. And because of health risks associated with the masks from their organization, the masks were never used. The deal involved around one hundred million euro. The information above is based on the following Dutch Wikipedia excerpt ( linked via Google Translate ). The deal is the subject of an external inquiry . This deal took place early on in the pandemic. For example, this Dutch state broadcaster article in May of 2020 ( translated ) describes that person's effort of providing masks. Thailand: defamation suits regarding criticism of vaccine procurement According to Reuters , there are at least two lawsuits underway surrounding criticism of vaccine procurement and production: The Government Pharmaceutical Organization (GPO) suit accuses Boon Vanasin of providing false information, claiming that the GPO, as coordinator for Moderna vaccines for private hospitals, sought to maximize profit from the public, the GPO said in a statement. Another critic of the strategy, opposition politician Thanathorn Juangroongruangkit, is facing charges of insulting the monarchy after accusing the government of over-reliance on a royal-owned firm to produce AstraZeneca vaccines. The crime is punishable by up to 15 years imprisonment. Some more accusations, as reported by the Thaiger in September 2021: Complex, tricky accounting, embezzlement or a government going about its work in the middle of a pandemic? Accusations by the Pheu Thai opposition party are demanding Thai PM Prayut Chan-o-cha explain a 2 billion baht [about $60 million] gap between what was allocated for Sinovac vaccine purchases and what was actually spent. All of this seems to be in play in 2021. It should be noted that Thailand only started seeing increased case numbers in 2021 (see the timeline in a previous answer of mine ), so before that the government might not have put that much effort into procuring medical supplies.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/69664', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/18367/']}
|
jdg_377286
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
108971
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It just occurred to me that almost all images I've seen of the (in)famous mushroom cloud show a vertical column rising perpendicular to the ground and a horizontal planar ring parallel to the ground. Not that I'm an expert (that's why this question) but I have rarely seen anything go in the 45 degree angle. Or for that matter anything other than the 'special' 0 degree horizontal plane and 90 degree vertical column. Shouldn't there be radial vectors at all angles between 0 and 90 degrees giving rise to a hemispherical explosion envelope? Why is it a vertical cylinder? PS: I understand the top expands eventually on cooling and lowered air pressure giving the mushroom look but my questions is for the previous stage - the vertical column.
Now provide the response and nothing else.
|
The explosion certainly is hemispherical, see, for instance, this explosion caused by the Trinity bomb : The gas cloud that you posted, and what many would consider is synonymous to the nuclear weapons, comes after the explosion. Nuclear bombs are actually usually ignited above ground for "maximum destruction." Since the nuclear reaction is immensely hot (about 4000 K whereas the surface of earth is sitting pretty around 300 K), the gas rises much the same way a hot-air balloon rises. At some point, the cold air from around the explosion gets sucked under the mushroom cap and causes the thin column you see: Thus, for the most part, it is the extreme temperatures that cause the explosion "bubble" to rise in the first place. And it is the convective air currents under the bubble that cause the column to form.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/108971', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7484/']}
|
jdg_377287
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8050722
|
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'm understanding this correct, both JavaScript and ActionScript 3 works with radians. So the expected output of the following codes would be: Math.PI //Expected 3.141592653589793, got 3.141592653589793Math.sin(0) //Expected 0, got 0Math.sin(Math.PI/2) //Expected 1, got 1Math.sin(Math.PI) //Expected 0, got 1.2246063538223773e-16Math.sin(Math.PI*3/2) //Expected -1, got -1Math.sin(Math.PI*2) //Expected 0, got -2.4492127076447545e-16Math.cos(0) //Expected 1, got 1Math.cos(Math.PI/2) //Expected 0, got 6.123031769111886e-17Math.cos(Math.PI) //Expected -1, got -1Math.cos(Math.PI*3/2) //Expected 0, got -1.836909530733566e-16Math.cos(Math.PI*2) //Expected 1, got 1 This is the same behavior in Firefox, Chrome, Safari and also in Flash Professional CS5.5. I'm using Mac OS X 10.7.2. Test: http://jsfiddle.net/KA4VM/
Now provide the response and nothing else.
|
Have you looked at the value you're getting? You're expecting 0, but you're getting something like 0.00000000000000012246063538223773 Isn't that close enough to zero for you? Basically, you shouldn't expect binary floating point operations to be exactly right when your inputs can't be expressed as exact binary values - which pi/2 can't, given that it's irrational. (You shouldn't expect the results to be exact even when the inputs can be expressed exactly in binary, if the output can't be expressed exactly...)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8050722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/640584/']}
|
jdg_377288
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4325319
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Correspondig the following question: Java: Enum parameter in method I would like to know, how can I format the code to require enums generically. Foo.java public enum Foo { a(1), b(2);} Bar.java public class Bar { public Bar(generic enum);} Later on I'll have more enum classes like "foo", but you can still create bar containing any kind of enum class. I have "jdk1.6.0_20" by the way...
Now provide the response and nothing else.
|
See the methods in EnumSet for reference, e.g. public static <E extends Enum<E>> EnumSet<E> of(E e) (This method returns an EnumSet with one element from a given Enum element e) So the generic bounds you need are: <E extends Enum<E>> Actually, you will probably make Bar itself generic: public class Bar<E extends Enum<E>> { private final E item; public E getItem(){ return item; } public Bar(final E item){ this.item = item; }} You may also add a factory method like from , with etc. public static <E2 extends Enum<E2>> Bar<E2> with(E2 item){ return new Bar<E2>(item);} That way, in client code you only have to write the generic signature once: // e.g. this simple versionBar<MyEnum> bar = Bar.with(MyEnum.SOME_INSTANCE);// instead of the more verbose version:Bar<MyEnum> bar = new Bar<MyEnum>(MyEnum.SOME_INSTANCE); Reference: Java Tutorial - Learning the Java Language Classes and Objects > Enum Types Generics
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4325319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315501/']}
|
jdg_377289
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7167895
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering how I would best validate URLs in Rails. I was thinking of using a regular expression, but am not sure if this is the best practice. And, if I were to use a regex, could someone suggest one to me? I am still new to Regex.
Now provide the response and nothing else.
|
Validating an URL is a tricky job. It's also a very broad request. What do you want to do, exactly? Do you want to validate the format of the URL, the existence, or what? There are several possibilities, depending on what you want to do. A regular expression can validate the format of the URL. But even a complex regular expression cannot ensure you are dealing with a valid URL. For instance, if you take a simple regular expression, it will probably reject the following host http://invalid##host.com but it will allow http://invalid-host.foo that is a valid host, but not a valid domain if you consider the existing TLDs. Indeed, the solution would work if you want to validate the hostname, not the domain because the following one is a valid hostname http://host.foo as well the following one http://localhost Now, let me give you some solutions. If you want to validate a domain, then you need to forget about regular expressions. The best solution available at the moment is the Public Suffix List, a list maintained by Mozilla. I created a Ruby library to parse and validate domains against the Public Suffix List, and it's called PublicSuffix . If you want to validate the format of an URI/URL, then you might want to use regular expressions. Instead of searching for one, use the built-in Ruby URI.parse method. require 'uri'def valid_url?(uri) uri = URI.parse(uri) && uri.hostrescue URI::InvalidURIError falseend You can even decide to make it more restrictive. For instance, if you want the URL to be an HTTP/HTTPS URL, then you can make the validation more accurate. require 'uri'def valid_url?(url) uri = URI.parse(url) uri.is_a?(URI::HTTP) && !uri.host.nil?rescue URI::InvalidURIError falseend Of course, there are tons of improvements you can apply to this method, including checking for a path or a scheme. Last but not least, you can also package this code into a validator: class HttpUrlValidator < ActiveModel::EachValidator def self.compliant?(value) uri = URI.parse(value) uri.is_a?(URI::HTTP) && !uri.host.nil? rescue URI::InvalidURIError false end def validate_each(record, attribute, value) unless value.present? && self.class.compliant?(value) record.errors.add(attribute, "is not a valid HTTP URL") end endend# in the modelvalidates :example_attribute, http_url: true
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7167895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722890/']}
|
jdg_377290
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49597189
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting the error The method 'setState' isn't defined for the class MyApp error in Flutter in the onSubmitted of the TextField Code: Widget build(BuildContext context) { String phoneNo; return new MaterialApp( title: 'SchoolTrack', theme: new ThemeData( primaryColor: Colors.grey[50], ), home: new Scaffold( appBar: null, backgroundColor: Colors.cyan[100], body: new Container( padding: const EdgeInsets.all(32.0), child: new Center( child: new TextField( autofocus: true, autocorrect: false, decoration: new InputDecoration( hintText: 'Type the phone no', suffixIcon: new Icon(Icons.send), suffixStyle: new TextStyle( color: Colors.cyan[300], ) ), onSubmitted: (String input) { setState(() { phoneNo = input; }); }, ), ), ), ) ); }
Now provide the response and nothing else.
|
I assume you are trying to setState in a stateless widget, which is immutable(unable to change). Use a stateful widget to do so, like this: class MainPage extends StatefulWidget{ HomePage createState()=> HomePage();}class HomePage extends State<MainPage>{ //Your code here}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49597189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9395652/']}
|
jdg_377291
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15783342
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Having a usual Base -> Derived hierarchy, like: class Fruit { ... };class Pear : Fruit { ... };class Tomato : Fruit { ... };std::vector<Fruit*> m_fruits; Does it make sense (e.g: is performance better) to use emplace_back instead of push_back ? std::vector::emplace_back( new Pear() );std::vector::emplace_back( new Tomato() );
Now provide the response and nothing else.
|
Pointers are scalar types and therefore literal types, and so copy, move and emplace construction (from an lvalue or rvalue) are all equivalent and will usually compile to identical code (a scalar copy). push_back is clearer that you're performing a scalar copy, whereas emplace_back should be reserved for emplace construction calling a non-copy- or move- constructor (e.g. a converting or multi-argument constructor). If your vector should hold std::unique_ptr<Fruit> instead of raw pointers (to prevent memory leaks) then because you're calling a converting constructor emplace_back would be more correct. However that can still leak if extending the vector fails, so in that case you should use push_back(make_unique<Pear>()) etc.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15783342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/824499/']}
|
jdg_377292
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45483934
|
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 confused how to import those operators. Some I can import with import 'rxjs/add/operator/do'; and some I can not. For ex, this does not work: import 'rxjs/add/operator/map'; (I checked in rxjs/add/operator, map exists there). Essentially what I am trying to do is to reproduce this in Angular4: var requestStream = Rx.Observable.just('https://api.github.com/users');var responseStream = requestStream .flatMap(function(requestUrl) { return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl)); });responseStream.subscribe(function(response) { // render `response` to the DOM however you wish}); I also want to know how to deal with just operator, since I can not see it in rxjs/add/operator... Thanks for any help
Now provide the response and nothing else.
|
There are static and instance operators in RxJS: static of intervalinstance map first You may want to use these on the Observable global object or observable instance like this: Observable.of()observableInstance.map() For that you need to import modules from the add package: import 'rxjs/add/observable/of'import 'rxjs/add/operator/map' When you import the module it essentially patches Observable class or Observable prototype by adding method corresponding to the operators. But you can also import these operators directly and don't patch Observable or observableInstance : import { of } from 'rxjs/observable/of';import { map } from 'rxjs/operator/map';of()map.call(observableInstance) With the introduction of lettable operators in RxJs@5.5 you should now take advantage of the built-in pipe method: import { of } from 'rxjs/observable/of';import { map } from 'rxjs/operators/map';of().pipe(map(), ...) Read more in RxJS: Understanding Lettable Operators
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45483934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4554116/']}
|
jdg_377293
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18644091
|
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= ('one', 'a')>>> b = ('two', 'b')>>> c = ('three', 'a')>>> l = [a, b, c]>>> l[('one', 'a'), ('two', 'b'), ('three', 'a')] How can I check for only the elements of this list with a unique second entry (column? item?), and then grab the first entry found on the list. Desired output is >>> l[('one', 'a'), ('two', 'b')]
Now provide the response and nothing else.
|
Use a set (if the second item is hash-able): >>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]>>> seen = set()>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])][('one', 'a'), ('two', 'b')] The above code is equivalent to: >>> seen = set()>>> ans = []for item in lis: if item[1] not in seen: ans.append(item) seen.add(item[1])... >>> ans[('one', 'a'), ('two', 'b')]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18644091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1560517/']}
|
jdg_377294
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
350679
|
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 break a unit length rod into two pieces at a uniformly chosen point. Find theexpected length of the smaller piece
Now provide the response and nothing else.
|
The length function is $f(x) = \min ( x,1-x )$ as you found. This is $x$ on the interval $[0,0.5]$ and $1-x$ on the interval $[0.5,1]$. We are ultimately trying to find $E(f(X))$, the expected length. By the "law of the unconscious statistician," and since the distribution of the random variable $X$ is uniform: $$E(f(X)) = \int_0^1 f(x) \cdot 1 \;dx = \int_0^{0.5} x \;dx + \int_{0.5}^1 (1-x) \;dx = \frac{1}{4}$$ Or you could just measure the area under the curve without integrating by noticing the graph forms a triangle with base $1$ and height $0.5$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/350679', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70874/']}
|
jdg_377295
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
107043
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The extension of the 2-adic valuation to the reals used in the usual proof clearly uses AC. But is this really necessary? After all, given an equidissection in $n$ triangles, it is finite, so it should be possible to construct a valuation for only the algebraic numbers, and the coordinates of the summits (with a finite number of "choices"), and then follow the proof to show that $n$ must be even. Or am I badly mistaken?
Now provide the response and nothing else.
|
No choice is needed. If, in a choiceless universe, there were a counterexample, then that counterexample amounts to finitely many real numbers (the coordinates of the relevant points). It would still be a counterexample in the sub-universe of sets constructible (in Gödel's sense) from those finitely many reals. But that sub-universe satisfies the axiom of choice, so your favorite ZFC proof of the theorem applies there.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/107043', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17164/']}
|
jdg_377296
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3422336
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that type erasure makes them look equal, type-wise, at runtime, so that: class Bar { def foo[A](xs: A*) { xs.foreach(println) } def foo[A, B](xs: (A, B)*) { xs.foreach(x => println(x._1 + " - " + x._2)) }} gives the following compiler error: <console>:7: error: double definition:method foo:[A,B](xs: (A, B)*)Unit andmethod foo:[A](xs: A*)Unit at line 6have same type after erasure: (xs: Seq)Unit def foo[A,B](xs: (A, B)*) { xs.foreach(x => println(x._1 + " - " + x._2)) } ^ But is there a simple way to be able to write: bar.foo(1, 2, 3)bar.foo(1 -> 2, 3 -> 4) and having these call different overloaded versions of foo, without having to explicitly name them: bar.fooInts(1, 2, 3)bar.fooPairs(1 -> 2, 3 -> 4)
Now provide the response and nothing else.
|
You can, in a fairly round about way. Foo is a type class, and the compiler implcitly passes an instance of the type class, compatible with the (inferred) type parameter A . trait Foo[X] { def apply(xs: Seq[X]): Unit}object Foo { implicit def FooAny[A]: Foo[A] = new Foo[A] { def apply(xs: Seq[A]) = println("apply(xs: Seq[A])") } implicit def FooTuple2[A, B]: Foo[(A, B)] = new Foo[(A, B)] { def apply(xs: Seq[(A, B)]) = println("apply(xs: Seq[(A, B)])") } def apply[A](xs: A*)(implicit f: Foo[A]) = f(xs)}Foo(1, 2, 3) // apply(xs: Seq[A])Foo(1 -> 2, 2 -> 3) // apply(xs: Seq[(A, B)]) In the second call, both FooAny and FooTuple2 could be passed, but the compiler picks FooTuple2 , based on the rules of static method overloading. FooTuple2 is considered more specific that FooAny . If two candidates are considered to be as specific as each other, an ambiguity error is raised. You can also prefer one over the other by placing one in a superclass, as is done in scala.LowPriorityImplicits . UPDATE Riffing off the DummyImplicit idea, and the followup thread on scala-user: trait __[+_]object __ { implicit object __ extends __[Any]}object overload { def foo(a: Seq[Boolean]) = 0 def foo[_: __](a: Seq[Int]) = 1 def foo[_: __ : __](a: Seq[String]) = 2}import overload._foo(Seq(true)) foo(Seq(1)) foo(Seq("s")) This declares a type-parameterized trait __ , covariant in its unnamed type parameter _ . Its companion object __ contains an implicit instance of __[Any] , which we'll need later on. The second and third overloads of foo include a dummy type parameters, again unnamed. This will be inferred as Any . This type parameter has one or more context bounds, which are desugared into additional implicit parameters, for example: def foo[A](a: Seq[Int])(implicit ev$1: __[A]) = 1 The multiple parameter lists are concatenated into a single parameter list in the bytecode, so the double definition problem is circumvented. Please consider this as a opportunity to learn about erasure, context bounds and implicit search, rather than as a pattern to be applied in real code!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3422336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50572/']}
|
jdg_377297
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10336827
|
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 open an MVC 3 project on my system but I am getting following error: Microsoft Visual Studio The project file 'C:\Users\abc\Desktop\trunk\iCorpNow\iCorpNow.csproj' cannot be opened. The project type is not supported by this installation. OK Help I have both asp.net MVC 2 and asp.net MVc 3 installed on my development machineI have windows 7 installed on my machine.I have visual studio 2010 ultimate installed. Project is developed using asp.net MVc 3 and on Windows server 2008 using Visual studio professional 2010 Please suggest me how to fix this error. Here are the project types listed in my project file <ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids> Thanks.
Now provide the response and nothing else.
|
The problem you're having is that your project using Asp.Net MVC4 but you've only installed 2 and 3. If you install Asp.Net MVC4 it should allow you to open the project. The way to tell that this is the problem is by examining the GUIDs which are associated with the ProjectType entry in the project file. In this example they are {fae04ec0-301f-11d3-bf4b-00c04f79efbc} : C# project {349c5851-65df-11da-9384-00065b846f21} : Web Application {E3E379DF-F4C6-4180-9B81-6769533ABE47} : Asp.Net MVC 4 Both C# and Web Application come standard with Visual Studio Pro and above hence the missing piece must be Asp.Net MVC 4
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10336827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634710/']}
|
jdg_377298
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20919303
|
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 EF5 and when the the relationship is 1:N, if I want to load related entities I do the following: With T-SQL I load from database the main entities with a T-SQL like that: select * from MainEntities where ... with T-SQL I load the related entities select * from RelatedEntities where IDMainEntity IN (---) At this point EF populate the property navigation of the main entities with the related entities. Also, in the local property of the type of each entity in the dbContext I have all the entities of each type. However, if i do the same with a N:N relationship, I don't have the entity of the middle table of the relation, and when I execute the queries I have in the local of the dbContext the entities of each type, but the property navigation is not populated. I would like to know why and if it exists some alternative. I use this way because I want to use T-SQL for create dynamic queries. If I use eager loading I don't have the same flexibility to dynamic queries than when I use TSQL, and it is less efficient. If I use explicit loading I to do N additional queries, one of each record in the results of the main entity With my way, I only one additional query, because I get all the related entities at once. If I use lazy loading I have the same problem, N additional queries. Why EF does not populate the related properties when the relation is N:N? Thanks.
Now provide the response and nothing else.
|
The feature you are talking about is called Relationship Span or Relationship Fixup and indeed - as you have noticed - it does not work for many-to-many relationships. It only works if at least one end of the association has multiplicity 1 (or 0..1), i.e. it works for one-to-many or one-to-one relationships. Relationship Span relies on an entity having a foreign key. It doesn't matter if it has an explicit foreign key property ( foreign key association ) or only a foreign key column in the corresponding database table without a property in the model ( independent association ). In both cases the FK value will be loaded into the context when the entity gets loaded. Based on this foreign key value EF is able to figure out if a related entity that has the same primary key value as this FK value is attached to the context and if yes, it can "fixup the relationship", i.e. it can populate the navigation properties correctly. Now, in a many-to-many relationship both related entities don't have a foreign key. The foreign keys are stored in the link table for this relationship and - as you know - the link table does not have a corresponding model entity. As a result the foreign keys will never be loaded and therefore the context is unable to determine which attached entities are related and cannot fixup the many-to-many relationship and populate the navigation collections. The only LINQ queries where EF will support you to build the correct object graph with populated navigation collections in a many-to-many relationship are eager loading... var user = context.Users.Include(u => u.Roles).First(); ...or lazy loading... var user = context.Users.First();var rolesCount = user.Roles.Count();// Calling Count() or any other method on the Roles collection will fill// user.Roles via lazy loading (if lazy loading is enabled of course) ...or explicit loading with direct assignment of the result to the navigation collection: var user = context.Users.First();user.Roles = context.Entry(user).Collection(u => u.Roles).Query().ToList(); All other ways to load the related entities - like projections, direct SQL statements or even explicit loading without assignment to the navigation collection, i.e. using .Load() instead of .Query().ToList() in the last code snippet above - won't fixup the relationship and will leave the navigation collections empty. If you intend to perform mainly SQL queries rather than LINQ queries the only option I can see is that you write your own relationship management. You would have to query the link table in addition to the tables for the two related entities. You'll probably need a helper type (that is not an entity) and collection that holds the two FK column values of the link table and probably a helper routine that fills the navigation collections by inspecting the primary key values of the entities you find as attached in the DbSet<T>.Local collections and the FK values in the helper collection.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20919303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1068094/']}
|
jdg_377299
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
644547
|
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:
For any positive integer number $p$, show that$$\inf\left\{{\left\vert\sin{(n^p)}\right\vert+\left\vert\sin{(n+1)^p}\right\vert+\cdots+\left\vert\,\sin{(n+p)^p}\right\vert\, :\,n\in \mathbb{N}}\right\}>0.$$ My try. I only can prove for $p=2$. I have proved the following$$\vert\sin{(n+1)^2}\vert+\vert\sin{(n-1)^2}\vert+\vert\sin{n^2}\vert\ge\dfrac{1}{2}\sin{2}$$ Lemma. for any $x,y$ we have$$\lvert\sin{x}\rvert+\lvert\sin{y}\rvert\ge\lvert\sin{(x-y)}\rvert.$$ This lemma is easy to prove. Proof:\begin{align*}&|\sin{(n+1)^2}|+|\sin{(n-1)^2}|+|\sin{n^2}|\ge\dfrac{1}{2}[\sin{(n+1)^2}|+|\sin{(n-1)^2}|+2|\sin{n^2}|]\\&\ge\dfrac{1}{2}(|\sin{[(n+1)^2-n^2]}|+|\sin{[n^2-(n-1)^2]}|)\\&\ge\dfrac{1}{2}|\sin{[(n+1)^2+(n-1)^2-2n^2]}|=\dfrac{1}{2}\sin{2}\end{align*} But my problem I can't it, This problem is from a analysis problem book. This author's only hint, we note this $$\sum_{i=0}^{p}(-1)^i\binom{p}{i}(n+p-i)^p=p!$$But I can't. Thank you
Now provide the response and nothing else.
|
Let's assume that $$\inf_{n\in\mathbb N}\lvert\sin{(n^p)}\rvert+\lvert\sin{(n+1)^p}\rvert+\cdots+\lvert\sin{(n+p)^p}\rvert=0.$$Then for every $\varepsilon>0$, then exists an $n$, such that: $\lvert\sin{(n+j)^p}\rvert<\varepsilon/2$,for every $j=0,1,\ldots,p$. But $\lvert\sin x\rvert<\varepsilon$ implies that there exists an $m\in\mathbb Z$, such that $\lvert x-m\pi\rvert<\varepsilon$. Hence there exist $m_j\in\mathbb N$, such that$$\lvert m_j\pi-(n+j)^p\rvert<\varepsilon, \quad\text{for every}\,\,\, j=0,1,\ldots,p.\tag{1}$$or equivalently$$(n+j)^p=m_j\pi+\delta_j, \quad\text{with}\,\,\, \lvert\delta_j\rvert<\varepsilon. \tag{1'}$$We shall use the following identity (which was a hint given to the OP):$$\sum_{k=0}^p(-1)^k\binom{p}{k}(n+p-k)^p=p!\tag{2}$$See formula (10) in Binomial Coefficients .Combination of $(1')$ and $(2)$ provides$$p!=\sum_{k=0}^p(-1)^k\binom{p}{k}(m_j\pi+\delta_j)=N\pi+\pi\sum_{k=0}^p(-1)^k\binom{p}{k}\delta_j$$where $N=\sum_{k=0}^p(-1)^k\binom{p}{k}m_j$ is an integer. Thus$$|p!-N\pi|\le \pi\sum_{k=0}^p\binom{p}{k}|\delta_j|\le \varepsilon\pi\sum_{k=0}^p\binom{p}{k}=\pi 2^p\varepsilon. \tag{3}$$This is a contradiction as the left hand side can not be too small for the different values of $n$, as $\pi$ is irrational. In fact$$|p!-N\pi|\ge \min\left\{p!-\pi\left\lfloor\frac{p!}{\pi}\right\rfloor,\pi\left\lfloor\frac{p!}{\pi}\right\rfloor+\pi-p!\right\}>0. $$On the other hand, having assumed $(1)$, the left hand side of $(3)$ can become arbitrarily small. This is a contradiction, and hence$$\inf_{n\in\mathbb N}\lvert\sin{(n^p)}\rvert+\lvert\sin{(n+1)^p}\rvert+\cdots+\lvert\sin{(n+p)^p}\rvert>0.$$ Ὅπερ ἔδει δεῖξαι .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/644547', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
|
jdg_377300
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8899
|
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:
In the documentation for a radio chip , I keep seeing the term 2-FSK, which seems to be a modulation scheme. My understanding is that in FSK, data is encoded by emitting a carrier wave on a number of different frequencies. Is this right? How does this differ to 2-FSK?
Now provide the response and nothing else.
|
The number '2' refers to the number of tones used to encode the signal. For example, 2-FSK is essentially sending binary data using two frequencies. One symbol (time slice) has the potential for two values only. 2-FSK is usually what is meant by an unqualified mention of FSK . It's possible to use more than two tones. These modulation schemes usually are called MFSK for Multiple Frequency Shift Keying. A common MFSK scheme in amateur radio is MFSK16, which uses 16 different frequencies to represent 4 binary bits in each symbol. By your notation, this would be 16-FSK. The more frequencies that you use in a symbol, the more complicated your modulation/demodulation circuit. Typical MFSK applications in amateur radio require a computer sound card and CPU for signal processing. Analog circuitry can be developed somewhat easily for FSK using two band-pass filters.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/8899', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/566/']}
|
jdg_377301
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35917
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to deal with a text classification problem. A web crawler crawls webpages of a certain domain and for each webpage I want to find out whether it belongs to only one specific class or not. That is, if I call this class Positive , each crawled webpage belongs either to class Positive or to class Non-Positive . I already have a large training set of webpages for class Positive . But how to create a training set for class Non-Positive which is as representative as possible? I mean, I could basically use each and everything for that class. Can I just collect some arbitrary pages that definitely do not belong to class Positive ? I'm sure the performance of a text classification algorithm (I prefer to make use of a Naive Bayes algorithm) highly depends on which webpages I choose for class Non-Positive . So what shall I do? Can somebody please give me an advice? Thank you very much!
Now provide the response and nothing else.
|
The Spy EM algorithm solves exactly this problem. S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "spy" technique, naive Bayes and EM algorithm. The basic idea is to combine your positive set with a whole bunch of randomly crawled documents. You initially treat all the crawled documents as the negative class, and learn a naive bayes classifier on that set. Now some of those crawled documents will actually be positive, and you can conservatively relabel any documents that are scored higher than the lowest scoring true positive document. Then you iterate this process until it stablizes.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/35917', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13933/']}
|
jdg_377302
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
223824
|
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 thinking about why the poles are colder and I came out with three possible explanations. 1. The atmosphere blocks light beams coming to poles The Sun is seen only slightly over the horizon at the poles, so the light beams have longer way to the poles. If only this case were true, then the total difference between the poles and the equator would be the same as the energy that was absorbed by the atmosphere. 2. Sun is only slightly over the horizon at the poles. Poles are often in shadow of the parts of the Earth which are closer to the equator. 3. Poles are farther from the Sun The longer is the way to Sun the lower is the chance to catch a light from the Sun. Please, correct me wherever I'm wrong. I'd like to know Which of these three is most correct? How significant are the described effects of the other explanations?
Now provide the response and nothing else.
|
No, the main reason the poles are colder is because the surface is angled with respect to the sun rays. That is the same reason why in winter it is colder than in summer. You can think that in the poles the winters are harder and the summers are softer, while in the equator it is the other way around. That is also the reason why some solar panel are motorized: to keep them perpendicular to the sun rays and get the most out of them. About your hypothesis: If the atmosphere were to absorb the energy, there still would be heat at the poles, maybe in the air instead of in the ground, but still there. In polar winter there is constant darkness (24-hour night) up to 6 months in the geometrical pole. But in polar summer there is constant sun and it is still quite cold. So while the shadow actually makes a difference (polar winter is way colder than polar summer), that is not why the poles are colder than equator. The Earth is 150000000 km from the sun, and the radious of the Earth is about 6500 km, way to small to make a difference.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/223824', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/41078/']}
|
jdg_377303
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1582148
|
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 execute the next code: (take 10) $! [1,2..] What is it ? I thought, ghc will yield a termination, beacause i say "evaluate [1,2..] force". But I got the result "[1,2,3,4,5,6,7,8,9,10]".
Now provide the response and nothing else.
|
So you expect the list to be fully evaluated. ($!) is implemented in terms of seq , and seq "only" evaluates to head normal form according to the docs. It'll only make a difference if the value is undefined : Prelude> take 0 undefined[]Prelude> take 0 $! undefined*** Exception: Prelude.undefined A function is strict in its argument if f undefined = undefined This does not imply that the argument is fully evaluated in an eager fashion. What you want is something like DeepSeq . GHCi, version 6.10.1: http://www.haskell.org/ghc/ :? for helpLoading package ghc-prim ... linking ... done.Loading package integer ... linking ... done.Loading package base ... linking ... done.[1 of 1] Compiling DeepSeq ( deepSeq.lhs, interpreted )Ok, modules loaded: DeepSeq.*DeepSeq> take 1 $!! [1,2,undefined]*** Exception: Prelude.undefined*DeepSeq> Your example with $!! from DeepSeq runs forever.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1582148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190482/']}
|
jdg_377304
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21152
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
A magma is a set $M$ equipped with a binary operation $* : M \times M \to M$. In abstract algebra we typically begin by studying a special type of magma: groups. Groups satisfy certain additional axioms that "symmetries of things" should satisfy. This is made precise in the sense that for any object $A$ in a category $C$, the invertible morphisms $A \to A$ have a group structure again given by composition. An alternate definition of "group," then, is "one-object category with invertible morphisms," and then the additional axioms satisfied by groups follow from the axioms of a category (which, for now, we will trust as meaningful). Groups therefore come equipped with a natural notion of representation: a representation of a group $G$ (in the loose sense) is just a functor out of $G$. Typical choices of target category include $\text{Set}$ and $\text{Hilb}$. It seems to me, however, that magmas (and their cousins, such as non-associative algebras) don't naturally admit the same interpretation; when you throw away associativity, you lose the connection to composition of functions. One can think about the above examples as follows: there is a category of groups, and to study the group $G$ we like to study the functor $\text{Hom}(G, -)$, and to study this functor we like to plug in either the groups $S_n$ or the groups $GL_n(\mathbb{C})$, etc. on the right, as these are "natural" to look at. But in the category of magmas I don't have a clue what the "natural" examples are. Question 1: Do magmas and related objects like non-associative algebras have a "natural" notion of "representation"? It's not entirely clear to me what "natural" should mean. One property I might like such a notion to have is an analogue of Cayley's theorem. For certain special classes of non-associative object there is sometimes a notion of "natural": for example, among not-necessarily-associative algebras we may single out Lie algebras, and those have a "natural" notion of representation because we want the map from Lie groups to Lie algebras to be functorial. But this is a very special consideration; I don't know what it is possible to say in general. (If you can think of better tags, feel free to retag.) Edit: Here is maybe a more focused version of the question. Question 2: Does there exist a "nice" sequence $M_n$ of finite magmas such that any finite magma $M$ is determined by the sequence $\text{Hom}(M, M_n)$? (In particular, $M_n$ shouldn't be an enumeration of all finite magmas!) One definition of "nice" might be that there exist compatible morphisms $M_n \times M_m \to M_{n+m}$, but it's not clear to me that this is necessarily desirable. Edit: Here is maybe another more focused version of the question. Question 3: Can the category of magmas be realized as a category of small categories in a way which generalizes the usual realization of the category of groups as a category of small categories? Edit: Tom Church brings up a good point in the comments that I didn't address directly. The motivations I gave above for the "natural" notion of representation of a group or a Lie algebra are in some sense external to their equational description and really come from what we would like groups and Lie algebras to do for us. So I guess part of what I'm asking for is whether there is a sensible external motivation for studying arbitrary magmas, and whether that motivation leads us to a good definition of representation. Edit: I guess I should also make this explicit. There are two completely opposite types of answers that I'd accept as a good answer to this question: One that gives an "external" motivation to the study of arbitrary magmas (similar to how dynamical systems motivate the study of arbitrary unary operations $M \to M$) which suggests a natural notion of representation, as above. This notion might not look anything like the usual notion of either a group action or a linear representation, and it might not answer Question 3. One that is "self-contained" in some sense. Ideally this would consist of an answer to Question 3. I am imagining some variant of the following construction: to each magma $M$ we associate a category whose objects are the non-negative integers where $\text{Hom}(m, n)$ consists of binary trees with $n$ roots (distinguished left-right order) and $m$ "empty" leaves (same), with the remaining leaves of the tree labeled by elements of $M$. Composition is given by sticking roots into empty leaves. I think this is actually a 2-category with 2-morphisms given by collapsing pairs of elements of $M$ with the same parent into their product. An ideal answer would explain why this construction, or some variant of it, or some other construction entirely, is natural from some higher-categorical perspective and then someone would write about it on the nLab!
Now provide the response and nothing else.
|
Since magmas in general don't have much structure, we can't reasonably expect a representation to preserve much structure. We can therefore define a left representation of a magma $M$ to be a set $V$ equipped with a map $M \times V \to V$. We do the analogous thing for general nonassociative algebras. Serge Lang liked to describe a notion of left regular representation of an algebra $A$, which is just the linear map $A \to \operatorname{End} (A)$ that takes an element to the linear transformation it induces by left multiplication. As expected, this map is a homomorphism if and only if the algebra is associative. There are special cases of nonassociative algebras that admit good notions of representation, and in the cases I know, these arise from operads that have "good relationships" with the associative operad. The standard example is the natural map from the Lie operad to the Associative operad that yields the forgetful functor from associative algebras to Lie algebras. This functor admits the universal enveloping algebra functor as left adjoint. There is a formalism of enveloping operads, which generalizes this case. The upshot is that these special cases have a lot more structure than a simple composition law, so we can demand more from a representation (namely, that it respect the operad structure as manifested through the universal enveloping algebra).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/21152', 'https://mathoverflow.net', 'https://mathoverflow.net/users/290/']}
|
jdg_377305
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39577920
|
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 test my component with angular 2 final, but I get an error because the component uses the routerLink directive. I get the following error: Can't bind to 'routerLink' since it isn't a known property of 'a'. This is the relevant code of the ListComponent template <a *ngFor="let item of data.list" class="box" routerLink="/settings/{{collectionName}}/edit/{{item._id}}"> And here is my test. import { TestBed } from '@angular/core/testing';import { ListComponent } from './list.component';import { defaultData, collectionName } from '../../config';import { initialState } from '../../reducers/reducer';const data = { sort: initialState.sort, list: [defaultData, defaultData],};describe(`${collectionName} ListComponent`, () => { let fixture; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ ListComponent, ], }).compileComponents(); // compile template and css; fixture = TestBed.createComponent(ListComponent); fixture.componentInstance.data = data; fixture.detectChanges(); }); it('should render 2 items in list', () => { const el = fixture.debugElement.nativeElement; expect(el.querySelectorAll('.box').length).toBe(3); });}); I looked at several answers to similar questions but could not find a solution that worked for me.
Now provide the response and nothing else.
|
You need to configure all the routing. For testing, rather than using the RouterModule , you can use the RouterTestingModule from @angular/router/testing , where you can set up some mock routes. You will also need to import the CommonModule from @angular/common for your *ngFor . Below is a complete passing test import { Component } from '@angular/core';import { Router } from '@angular/router';import { By } from '@angular/platform-browser';import { Location, CommonModule } from '@angular/common';import { RouterTestingModule } from '@angular/router/testing';import { TestBed, inject, async } from '@angular/core/testing';@Component({ template: ` <a routerLink="/settings/{{collName}}/edit/{{item._id}}">link</a> <router-outlet></router-outlet> `})class TestComponent { collName = 'testing'; item = { _id: 1 };}@Component({ template: ''})class DummyComponent {}describe('component: TestComponent', function () { beforeEach(() => { TestBed.configureTestingModule({ imports: [ CommonModule, RouterTestingModule.withRoutes([ { path: 'settings/:collection/edit/:item', component: DummyComponent } ]) ], declarations: [ TestComponent, DummyComponent ] }); }); it('should go to url', async(inject([Router, Location], (router: Router, location: Location) => { let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); fixture.debugElement.query(By.css('a')).nativeElement.click(); fixture.whenStable().then(() => { expect(location.path()).toEqual('/settings/testing/edit/1'); console.log('after expect'); }); })));}); UPDATE Another option, if you just want to test that the routes are rendered correctly, without trying to navigate... You an just import the RouterTestingModule without configuring any routes imports: [ RouterTestingModule ] then just check that the link is rendered with the correct URL path, e.g. let href = fixture.debugElement.query(By.css('a')).nativeElement .getAttribute('href');expect(href).toEqual('/settings/testing/edit/1');
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39577920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1436151/']}
|
jdg_377306
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13752424
|
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 connect to mysql server command line from my windows prompt I write the next line in cmd but i get an error. cd C:\MYSQL\bin\ And then i execute mysql.exe -u=root -p=admin but i getting this error ERROR 1045: <28000>: Access denied for user 'root'@'localhost' <using password:YES> Thanks,
Now provide the response and nothing else.
|
The cd in your question is invalid (quoting it here because you've removed it once, and it was there when this answer was posted): cd CD:\MYSQL\bin\ You can't cd to CD:\ anything, because CD:\ isn't a valid directory in Windows. CD: would indicate a drive, except that drives are restricted to a single letter between A and Z . If your \MYSQL\BIN is on drive C: , then your commands need to be: C:\>cd \MYSQL\BinC:\MYSQL\Bin>mysql -u root -p admin If you're not already on C: (which you'll know by looking at the prompt in the cmd window), or your MySQL folder is on another drive (for instance, D: ), change to that drive too: C:\> cd /d D:\MYSQL\BinD:\MYSQL\Bin>mysql -u root -p admin The .exe after mysql is optional, since .exe is an executable extension on Windows. If you type mysql , Windows will automatically look for an executable file with that name and run it if it finds it. Note that in both my examples of running mysql , there are no = signs. You should just use -p with no password, and wait to be prompted for it instead.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13752424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1683584/']}
|
jdg_377307
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3904645
|
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 strings: string1 = "theater is small"; string2 = "The small thing in the world"; I need to check weather the string "the" is present in the strings or not. I can use the contains function, but can it do a whole word match? i.e it should not match with "theater" of string1!
Now provide the response and nothing else.
|
The simplest solution is to use regular expressions and the word boundary delimiter \b : bool result = Regex.IsMatch(text, "\\bthe\\b"); or, if you want to find mismatching capitalisation, bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase); ( using System.Text.RegularExpressons .) Alternatively, you can split your text into individual words and search the resulting array. However, this isn’t always trivial because it’s not enough to split on white spaces; this would ignore all punctuation and yield wrong results. A solution is to once again use regular expressions, namely Regex.Split .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3904645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253368/']}
|
jdg_377308
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9091177
|
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 data reader to read the datas from database. I am reading TotalPrice from sales table. I would like to show the total price as 2 decimal place. The code is something link that: TotalPrice.Text = myReader["TotalPrice"].ToString("N2"); However i encounted this error: no overload for method "ToString" takes 1 argumentsWhat's wrong with the code?
Now provide the response and nothing else.
|
Assuming that TotalPrice is a Decimal column, and that myReader is a DataReader: TotalPrice.Text = myReader.GetDecimal(myReader.GetOrdinal("TotalPrice")).ToString("N2"); The idea here is that myReader's indexer (what you are using when you call myReader["TotalPrice"] ) returns an Object. It has to, since it doesn't know at compile time what type the column is. By using .GetDecimal() , you are assuring that you get a Decimal value back, or an error. The .ToString overload that takes a format string is declared on Decimal, not on Object. Object's . ToString takes no arguments. The inner call to GetOrdinal returns the field's index given the name- if you are doing this in a loop for multiple data rows, you'd probably want to cache that in a variable.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9091177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125911/']}
|
jdg_377309
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
70486
|
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:
Blinken reported the American position on Ukraine. Wang Yi pointed outthat solving the Ukraine problem lies in the New Minsk Agreement[Minsk II] . Minsk II gained the approval of the UNSC, and all sideshave recognized it as a foundational political document, and ought toeffectuate it concretely. China will support any efforts that conformwith Minsk II's direction and spirit. At the same time, we call on allsides to remain calm, and refrain from stoking tensions orsensationalizing crises. Wang Yi emphasized that the security of onecountry cannot be at the cost of another country's security. Regionalsecurity cannot be guaranteed by strengthening or expanding militarygroupings. In today's 21st Century, all sides should abandon Cold Warthinking, reach a balanced, effective, and sustainable Europeansecurity mechanism through dialogue, and Russia's legitimate securityconcerns should be respected and resolved. I am wondering if China would take punitive action against Russia if Russia invades Ukraine as long as the U.S. abide my the Minsk II agreement. Is that what Wang Yi is saying or is the U.S. against the Minsk II agreement somehow? I am trying to understand his vague political language and I am wondering if China is currently siding with the U.S. on the Ukraine matter.
Now provide the response and nothing else.
|
The quote is phased in a politely ambiguous diplomatic language. Superficially, China is staying above the fray. But the Chinese position is identical to the official Russian diplomatic position, in that the Minsk II agreement is the framework for the situation. The Russian position is further predicated on the claim that Ukraine did not make a good faith effort to fulfill its obligations under the agreement. China does not specifically repeat this in the quote above. References to Russia and US are left out entirely, which is not unusual for diplomacy surrounding proxy conflicts. The line about fulfilling the direction and spirit of Minsk II can be interpreted to refer to: maintaining the ceasefire, i.e. not attempting to re-fight the battles of 2014-2015 additional obligations that go beyond the ceasefire, including granting amnesty to the belligerents from 2014-2015, withdrawal of all foreign forces, restoring Ukraine's control of its old borders in the two breakaway republics, and granting some sort of devolved governmental powers as autonomous regions to the two breakaway republics As of 2021-ish, essentially none of the terms were complied with. Including: The ceasefire itself, in light of recurring light artillery attacks. Confidence was also undermined by Ukraine's government directly expressing a desire to re-conquer the breakaway republics, and building up military capability which could potentially be used for this purpose Actions taken by Ukraine to punish the breakaway republics, contrary to the amnesty requirement, and preventing integration with the rest of the country No progress was made granting autonomous powers. Effectively the opposite took place, as the major political parties in Ukraine representing the Russian population were banned At the same time, Ukraine does not really control of its original borders in the breakaway republics. One issue that irked Ukraine's side, is that Russia granted passports to Russians living in the breakaway republics. Ukraine then claimed it would revoke citizenship of those who accepted Russian passports (while dual citizenship with other countries is to be allowed). Finally, foreign forces do not hide their presence So to answer the question more directly, if the fighting of 2014-2015 were to repeat in the same sequence -- i.e. with Ukraine attempting to assert control over the breakaway republic's territory, then it is most likely that China would interpret it as a gross violation, by Ukraine, of Minsk II and the accompanying UNSC resolution. I'd expect China to diplomatically support efforts to restore the status quo as of the agreements.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/70486', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/38301/']}
|
jdg_377310
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28893586
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What happened when defer called twice when the struct of that method has been changed? For example: rows := Query(`SELECT FROM whatever`)defer rows.Close()for rows.Next() { // do something}rows = Query(`SELECT FROM another`) defer rows.Close()for rows.Next() { // do something else} which rows when the last rows.Close() called?
Now provide the response and nothing else.
|
It depends on the method receiver and on the type of the variable. Short answer: if you're using the database/sql package, your deferred Rows.Close() methods will properly close both of your Rows instances because Rows.Close() has pointer receiver and because DB.Query() returns a pointer (and so rows is a pointer). See reasoning and explanation below. To avoid confusion, I recommend using different variables and it will be clear what you want and what will be closed: rows := Query(`SELECT FROM whatever`)defer rows.Close()// ...rows2 := Query(`SELECT FROM whatever`)defer rows2.Close() I'd like to point out an important fact that comes from the deferred function and its parameters being evaluated immedately which is stated in the Effective Go blog post and in the Language Spec: Deferred statements too: Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred. If variable is not a pointer: You will observe different results when calling a method deferred, depending if the method has a pointer receiver. If variable is a pointer, you will see always the "desired" result. See this example: type X struct { S string}func (x X) Close() { fmt.Println("Value-Closing", x.S)}func (x *X) CloseP() { fmt.Println("Pointer-Closing", x.S)}func main() { x := X{"Value-X First"} defer x.Close() x = X{"Value-X Second"} defer x.Close() x2 := X{"Value-X2 First"} defer x2.CloseP() x2 = X{"Value-X2 Second"} defer x2.CloseP() xp := &X{"Pointer-X First"} defer xp.Close() xp = &X{"Pointer-X Second"} defer xp.Close() xp2 := &X{"Pointer-X2 First"} defer xp2.CloseP() xp2 = &X{"Pointer-X2 Second"} defer xp2.CloseP()} Output: Pointer-Closing Pointer-X2 SecondPointer-Closing Pointer-X2 FirstValue-Closing Pointer-X SecondValue-Closing Pointer-X FirstPointer-Closing Value-X2 SecondPointer-Closing Value-X2 SecondValue-Closing Value-X SecondValue-Closing Value-X First Try it on the Go Playground . Using a pointer variable the result is always good (as expected). Using a non-pointer variable and using pointer receiver we see the same printed results (the latest) but if we have value receiver, it prints 2 different results. Explanation for non-pointer variable: As stated, deferred function including the receiver is evaluated when the defer executes. In case of a pointer receiver it will be the address of the local variable . So when you assign a new value to it and call another defer , the pointer receiver will be again the same address of the local variable (just the pointed value is different). So later when the function is executed, both will use the same address twice but the pointed value will be the same, the one assigned later. In case of value receiver, the receiver is a copy which is made when the defer executed, so if you assign a new value to the variable and call another defer , another copy will be made which is different from the previous one.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28893586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620210/']}
|
jdg_377311
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5122987
|
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 currently looping through all the controls on my page and setting certain types (TextBox, CheckBox, DropDownList, etc.) to Enabled=False under certain conditions.However I notice an obvious page load increase looping like this. Is it possible to only get certain types of controls from the Page.Controls object rather than Loop through them all? Possibly with something like LINQ?
Now provide the response and nothing else.
|
This cannot be done entirely using LINQ but you could have an extension defined like this static class ControlExtension { public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; foreach (Control descendant in control.GetAllControls()) { yield return descendant; } } } } and call this.GetAllControls().OfType<TextBox>().ToList().ForEach(t => t.Enabled = false);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5122987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143273/']}
|
jdg_377312
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6094403
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my method I use for increasing by one day in my navigationBar, and setting the name of the day as a title. I know it's wrong because I set "today" variable every time its called. But I can't figure out how to increase +1 day every time I call this method. -(void)stepToNextDay:(id)sender{ today = [NSDate date]; NSDate *datePlusOneDay = [today dateByAddibgTimeInterval:(60 * 60 * 24)]; NSDateFormatter *dateformatterBehaviour = [[[NSDateFormatter alloc]init]autorelease]; [dateFormatter setDateFormat:@"EEEE"]; NSString *dateString = [dateFormatter stringFromDate:datePlusOneDay]; self.navigationItem.title = datestring;}
Now provide the response and nothing else.
|
Store the date your are showing in a property (ivar, ...) of your view controller. That way you can retrieve the current setting when you go to the next day. If you want to reliably add dates, use NSCalendar and NSDateComponents to get a "1 day" unit, and add that to the current date. NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];components.day = 1;NSDate* newDate = [calendar dateByAddingComponents: components toDate: self.date options: 0];
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6094403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737990/']}
|
jdg_377313
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13547721
|
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 set a 100ms timeout on a UDP Socket. I am using C. I have posted relavent pieces of my code below. I am not sure why this is not timing out, but just hangs when it doesn't receive a segment. Does this only work on sockets that are not bound using the bind() method? #define TIMEOUT_MS 100 /* Seconds between retransmits */if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed");if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed");//set timer for recv_socketstatic int timeout = TIMEOUT_MS;setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));if(recvfrom(rcv_sock, ackBuffer,sizeof(ackBuffer), 0, (struct sockaddr *) &servAddr2, &fromSize) < 0){ //timeout reached printf("Timout reached. Resending segment %d\n", seq_num); num_timeouts++;}
Now provide the response and nothing else.
|
The SO_RCVTIMEO option expects a struct timeval defined in sys/time.h , not an integer like you're passing to it. The timeval struct has as field for seconds and a field for microseconds. To set the timeout to 100ms, the following should do the trick: struct timeval tv;tv.tv_sec = 0;tv.tv_usec = 100000;if (setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) { perror("Error");}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13547721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1254811/']}
|
jdg_377314
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3552928
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's assumed that $\lim_{x\to0} \frac{f(x)}{\sin(x)} = 2$ . Find $$\lim_{x\to0} \frac{\log(1+3x)}{f(x)}$$ I don't think that it would work out by a random plugging. Let $f(x) = 2\sin(x).$ $$\lim_{x\to0}\frac{\log(1+3x)}{f(x)} = \lim_{x\to0}\frac{\log(1+3x)}{2\sin(x)} = [\log(1+3x) = 3x + O(x^2)] = \lim_{x\to0}\frac{3x+O(x^2)}{2\sin(x)} = \frac{3}{2}.$$ But what did I miss? I cannot find a way to prove whether these two limits are connected (or that the result is unique).
Now provide the response and nothing else.
|
How about using these (well-known) limits: $$\lim_{x\to 0} \frac{\ln (1+x)}{x}=1,\ \ \lim_{x\to 0} \frac{\sin x}{x}=1$$ and writing: $$\lim_{x\to 0}\frac{\ln(1+3x)}{f(x)} = 3\lim _{x\to 0} \left[\frac{\ln (1+3x)}{3x}\cdot \frac{x}{\sin x}\cdot \frac{\sin x}{f(x)}\right]$$ Can you end it from here?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3552928', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/558197/']}
|
jdg_377315
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4118
|
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we have a single qubit with state $| \psi \rangle = \alpha | 0 \rangle + \beta | 1 \rangle$. We know that $|\alpha|^2 + |\beta|^2 = 1$, so we can write $| \alpha | = \cos(\theta)$, $| \beta | = \sin(\theta)$ for some real number $\theta$. Then, since only the relative phase between $\alpha$ and $\beta$ is physical, we can take $\alpha$ to be real. So we can now write $$| \psi \rangle = \cos(\theta) | 0 \rangle + e^{i \phi} \sin(\theta)| 1 \rangle$$ My Question: Why are points on the Bloch sphere usually associated to vectors written as$$| \psi \rangle = \cos(\theta/2) | 0 \rangle + e^{i \phi} \sin(\theta/2)| 1 \rangle$$instead of as I have written? Why use $\theta /2$ instead of just $\theta$?
Now provide the response and nothing else.
|
It is a convention, chosen so that $\theta$ is the azimuthal angle of the point representing the state in the Bloch sphere. To see where this convention comes from,start from a state $|\psi\rangle=\alpha|0\rangle+\beta|1\rangle$ . Remembering the normalisation constraint $|\alpha|^2+|\beta|^2=1$ , and assuming without loss of generality $\alpha\in\mathbb R$ , a natural way to parametrise the state is by defining an angle $\gamma$ such that $|\alpha|=\alpha=\cos\gamma$ and $|\beta|=\sin\gamma$ .A generic state $|\psi\rangle$ thus reads $$|\psi\rangle=\cos\gamma|0\rangle + e^{i\varphi}\sin\gamma|1\rangle,$$ for some phase $\varphi\in\mathbb R$ .Remember now that the Bloch sphere coordinates of a generic (pure) state $|\psi\rangle=\alpha|0\rangle+\beta|1\rangle$ have the explicit form \begin{align}\newcommand{\on}[1]{\operatorname{#1}}\newcommand{\bs}[1]{\boldsymbol{#1}}x\equiv\langle\psi|\sigma_x|\psi\rangle&= 2\on{Re}(\bar\alpha\beta),\\y\equiv\langle\psi|\sigma_y|\psi\rangle&= 2\on{Im}(\bar\alpha\beta),\\z\equiv\langle\psi|\sigma_z|\psi\rangle&= |\alpha|^2 - |\beta|^2.\end{align} Relating these with our previous parametrisation with $\gamma$ we find $$z=\cos^2\gamma-\sin^2\gamma=\cos(2\gamma).$$ But the canonical way to define spherical coordinates uses $z=\cos\theta$ , so if we wish to interpret the coefficients of the state as angles in the Bloch sphere, we have to set $\gamma=\theta/2$ . See also the analogous question on physics.SE for more info.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://quantumcomputing.stackexchange.com/questions/4118', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/4465/']}
|
jdg_377316
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56139995
|
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 text file on S3 with around 300 million lines. I'm looking to split this file into smaller files of 1,000 lines each (with the last file containing the remainder), which I'd then like to put into another folder or bucket on S3. So far, I've been running this on my local drive using the linux command: split -l 1000 file which splits the original file into smaller files of 1,000 lines. However, with a larger file like this, it seems inefficient to download and then re-upload from my local drive back up to S3. What would be the most efficient way to split this S3 file, ideally using Python (in a Lambda function) or using other S3 commands? Is it faster to just run this on my local drive?
Now provide the response and nothing else.
|
Anything that you do will have to download the file, split it, and re-upload it. The only question is where , and whether local disk is involved. John Rotenstein gave you an example using local disk on an EC2 instance. This has the benefit of running in the AWS datacenters, so it gets a high-speed connection, but has the limitations that (1) you need disk space to store the original file and its pieces, and (2) you need an EC2 instance where you can do this. One small optimization is to avoid the local copy of the big file, by using a hyphen as the destination of the s3 cp : this will send the output to standard out, and you can then pipe it into split (here I'm also using a hyphen to tell split to read from standard input): aws s3 cp s3://my-bucket/big-file.txt - | split -l 1000 - output.aws s3 cp output.* s3://dest-bucket/ Again, this requires an EC2 instance to run it on, and the storage space for the output files. There is, however, a flag to split that will let you run a shell command for each file in the split: aws s3 cp s3://src-bucket/src-file - | split -b 1000 --filter 'aws s3 cp - s3://dst-bucket/result.$FILE' - So now you've eliminated the issue of local storage, but are left with the issue of where to run it. My recommendation would be AWS Batch , which can spin up an EC2 instance for just the time needed to perform the command. You can, of course, write a Python script to do this on Lambda, and that would have the benefit of being triggered automatically when the source file has been uploaded to S3. I'm not that familiar with the Python SDK (boto), but it appears that get_object will return the original file's body as a stream of bytes , which you can then iterate over as lines, accumulating however many lines you want into each output file.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56139995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6896392/']}
|
jdg_377317
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4236046
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The standard model of Peano is particularly natural, being (among other things) the unique model that embeds into any other model of Peano. It's well known that there are many other models of Peano, for example, ones in which there exist non-standard length proofs of the inconsistency of Peano. However, all methods I've seen of constructing non-standard models never in any sense uniquely specify any non-standard model (but rather use the compactness theorem, though I'm sure there are other ways), and my question is if it is possible to specify a particular non-standard model in some (preferably "natural") way. This is related to my previous question here , though more broad. (One connection being that if there was a unique model of Peano which embeds in every model except the standard one, that would be a specification of a particular non-standard model, and the poset described in that question can capture that, although I'm sure there is no such model). I haven't studied model theory, just read some interesting things online, so I apologize if this question is ill-posed.
Now provide the response and nothing else.
|
Certainly the good money is on the (current) nonexistence of such an example. But that's boring. Here are a couple positive observations, although - in my opinion - each falls short of an actual positive answer , and indeed I don't know of anything I would call a "natural" nonstandard model of $\mathsf{PA}$ . First, here's a basic model-theoretic observation. Say that a structure $\mathfrak{M}$ is pointwise-definable iff every element of $\mathfrak{M}$ is (parameter-freely-)definable in $\mathfrak{M}$ . Some structures are pointwise-definable (e.g. $(\mathbb{N};+,\times)$ or $(\mathbb{Q};+,\times)$ ) while others aren't (e.g. $(\mathbb{R};+,\times)$ or $(\mathbb{Q};+)$ ). Similarly, some but not all theories have pointwise-definable models, and some theories have pointwise-definable models even though we might reasonably expect them not to (such as $\mathsf{ZFC}$ ). Of course, whenever a complete theory does have a pointwise-definable model it has exactly one up to isomorphism (just "match up the definitions" and check that everything works). Now for a structure $\mathfrak{A}$ , let $\mathfrak{A}^{\mathsf{def}}$ be the substructure (allowing emptiness) of $\mathfrak{A}$ consisting of all definable elements (ignoring the issue that the latter might be empty) . In general $\mathfrak{A}^{\mathsf{def}}$ might be very unlike $\mathfrak{A}$ ; however, it turns out that models of $\mathsf{PA}$ behave very nicely in this regard: we always have $\mathfrak{A}^{\mathsf{def}}\preccurlyeq\mathfrak{A}$ when $\mathfrak{A}\models\mathsf{PA}$ . This is because we have full induction in $\mathsf{PA}$ : think about the Tarski-Vaught test and note that the least number satisfying a formula is always definable. Consequently every completion of $\mathsf{PA}$ has a pointwise-definable model. By the uniqueness observation above this means that arguably every natural completion of $\mathsf{PA}$ (other than true arithmetic, $\mathsf{TA}$ , itself) gives rise to a natural nonstandard model of $\mathsf{PA}$ . Of course we still need to come up with a "natural" completion of $\mathsf{PA}$ other than $\mathsf{TA}$ , and I don't really think it's clear how to do that, but I do think this is still a positive-"flavored" result in some sense. What about nonstandard models of $\mathsf{TA}$ ? The unique pointwise-definable model of $\mathsf{TA}$ is obviously just $\mathbb{N}$ itself, so the above doesn't help. Here we can turn to ultrapower constructions, and - despite the obvious obstacles - there are still a couple of positive things to be said. First, assuming $\mathsf{CH}$ we have that any two nonprincipal ultrafilters on $\omega$ yield isomorphic ultrapowers of $\mathbb{N}$ (or indeed any other countable structure - see here ). So "the nontrivial $\omega$ -fold ultrapower of $\mathbb{N}$ " is actually a proper description of a nonstandard model of arithmetic, and the non-canonical nature of the ultrafilter used turns out to disappear. In $\mathsf{ZFC}$ alone a more involved construction appears: not a single ultrapower, but a way of combining all possible ultrapowers in a sense. In broad terms, Kanovei and Shelah produced a way to construct, unambiguously, a hyperreal field which works just assuming $\mathsf{ZFC}$ . The natural numbers part of this field then is a nonstandard model of $\mathsf{TA}$ . I don't personally consider this a "natural" nonstandard model, but it is certainly highly interesting and canonical in some sense. OK, one last shot: Solving all our problems by getting rid of the axiom of choice (Wait, what in the whatting what?!) Working in $\mathsf{ZF}$ alone, it is consistent that there are infinite cardinalities (which noun incidentally becomes a bit more subtle than in choice-land) which behave a bit like natural numbers. Specifically, Sageev showed the following: Suppose that $\mathsf{ZFC}$ + "There is an inaccessible cardinal" is consistent. Then there is a model of $\mathsf{ZF}$ + "There is a Dedekind-finite infinite set" in which the Dedekind-finite cardinalities are linearly ordered by injectability. This turns out to be highly relevant to our question due to earlier (and more elementary but harder to find) work by Ellentuck: In any model of $\mathsf{ZF}$ where the Dedekind-finite cardinalities are linearly ordered by injectability, they in fact form a nonstandard model of $\mathsf{TA}$ (with " $+$ " and " $\times$ " coming from disjoint union and Cartesian product as expected). Put together these results show that certain models of $\mathsf{ZF}$ come with in my opinion highly natural and surprising canonical nonstandard models of true arithmetic. Of course this requires choice to fail extremely badly and much about these models is still unclear (see 1 , 2 ), so I still don't think this constitutes a positive answer to your question, but still - pretty dang cool, no?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4236046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/281700/']}
|
jdg_377318
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53959667
|
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 recently inherited a project from a Laravel developer to look at. Unfortunately, when I migrate and seed the user table, the password ciphering is not working, as follows: public function run(){ DB::table('users')->insert([ 'email' => 'admin@site.co.uk', 'first_name' => 'Site', 'last_name' => 'Admin', 'username' => 'admin', 'password' => 'localhostPassword' ]);} When I run php artisan migrate --seed the password field is the string literal as above, and when I try to sign in it tells me that my password credentials are incorrect. As I'm not an Artisan Laravel developer I'm not sure where to start, but I'm expecting the password field to be hashed like this $2y$10$u/FcKFPKsgRs8whJZ6ODAO90qllmGjqROnkmuQnxcpynG6WaIbX8e , which is what is generated when I use the register form in the current code base.
Now provide the response and nothing else.
|
You need to hash it before storing it: use Illuminate\Support\Facades\Hash; // <-- import it at the top// public function run() { DB::table('users')->insert([ 'email' => 'admin@site.co.uk', 'first_name' => 'Site', 'last_name' => 'Admin', 'username' => 'admin', 'password' => Hash::make('localhostPassword') // <---- check this ]); } Note: An alternative is to use the bcrypt() helper instead of the Hash::make() method. Chech the documentation regarding this aspect: Basic Usage You may hash a password by calling the make method on the Hash facade: <?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Hash;use App\Http\Controllers\Controller;class UpdatePasswordController extends Controller{ /** * Update the password for the user. * * @param Request $request * @return Response */ public function update(Request $request) { // Validate the new password length... $request->user()->fill([ 'password' => Hash::make($request->newPassword) ])->save(); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53959667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5463015/']}
|
jdg_377319
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3340330
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following code outputs 43211 , why? echo print('3').'2'.print('4');
Now provide the response and nothing else.
|
Your statement parses to humans as follows. Echo a concatenated string composed of: The result of the function print('3') , which will return true, which gets stringified to 1 The string '2' The result of the function print('4') , which will return true, which gets stringified to 1 Now, the order of operations is really funny here, that can't end up with 43211 at all! Let's try a variant to figure out what's going wrong. echo '1' . print('2') . '3' . print('4') . '5'; This yields 4523111 PHP is parsing that, then, as: echo '1' . (print('2' . '3')) . (print('4' . '5')); Bingo! The print on the left get evaluated first, printing '45' , which leaves us echo '1' . (print('2' . '3')) . '1'; Then the left print gets evaluated, so we've now printed '4523' , leaving us with echo '1' . '1' . '1'; Success. 4523111 . Let's break down your statement of weirdness. echo print('3') . '2' . print('4'); This will print the '4' first, leaving us with echo print('3' . '2' . '1'); Then the next print statement is evaluated, which means we've now printed '4321' , leaving us with echo '1'; Thus, 43211 . I would highly suggest not echo ing the result of a print , nor print ing the results of an echo . Doing so is highly nonsensical to begin with. Upon further review, I'm actually not entirely sure how PHP is parsing either of these bits of nonsense. I'm not going to think about it any further, it hurts my brain.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3340330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103824/']}
|
jdg_377320
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
72889
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My kernel keeps panicking when connected to a certain wireless network. I'd like to send a bug report but my kernel is apparently tainted. From /var/log/messages : Apr 17 21:28:22 Eiger kernel: [13330.442453] Pid: 4095, comm: kworker/u:1 Tainted: G O 3.8.4-102.fc17.x86_64 #1 and [root@Eiger ~]# cat /proc/sys/kernel/tainted 4096 I've not been able to find documentation for what the 4096 bitmask means , but the G flag means that an external GPL module is loaded into the kernel . How do I find out which module is tainting the kernel? I've grepped for [Tt]aint in /var/log/messages or dmesg and don't find anything corresponding to when a module is loaded. My kernel is the latest kernel from Fedora 17: 3.8.4-102.fc17.x86_64. UPDATE : It may be due to the rts5139 module. It shows up in lsmod but modinfo rts5139 produces ERROR: Module rts5139 not found. When booting the previous kernel, 3.8.3-103.fc17.x86_64, this module is not listed by lsmod and the kernel is not tainted ( /proc/sys/kernel/taint is 0). I've tried blacklisting this module echo 'blacklist rts5139' >> /etc/modprobe.d/blacklist.conf but rebooting still shows the kernel as tainted.
Now provide the response and nothing else.
|
Well I don't believe a standard Fedora kernel package will include any modules which would trigger this taint so the question is, what other kernel modules have you installed? Common candidates would be graphics drivers (though I think those will mostly set the "proprietary" bit) and wireless drivers. If you can find anything in the lsmod output that you think may be a candidate then run modinfo <module-name> and see if the output includes intree: Y as any module without that will trigger the taint you are seeing. UPDATE : The rts5139 module that you're seeing in lsmod but which doesn't seem to be on your system is probably in the initrd and is being loaded from there early in the boot process before the main filesystem is mounted. That also explains why blacklisting won't work as you would have to rebuild the initrd with the updated blacklist. Rebuilding the initrd with dracut will cause the module to go away anyway though.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/72889', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/34796/']}
|
jdg_377321
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
406751
|
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 $\alpha$ be a composition of $n$ into nonzero parts and let $\mathcal L$ be a set of permutations of a finite multiset having $n$ elements, such that each element of $\mathcal L$ is constant on each part of $\alpha$ . For example, for $n=8$ we could have $\alpha=(3, 2, 1, 1, 1)$ and $\mathcal L = \{ A A A | B B | A | B | C | , B B B | A A | C | A | A \}$ . Is there a good algorithm to decide whether there is a non-trivial subset $S$ of the parts of $\alpha$ such that for all elements $w$ in $\mathcal L$ , the multiset of corresponding elements in $w$ is the same? In the example above, taking $S=\{1,2,4\}$ designates a non-trivial subdistribution, consisting of three $A$ 's and three $B$ 's. More generally, can we efficiently find all subsets $S$ which are minimal with respect to inclusion? As a further example, if all parts of $\alpha$ are equal to $1$ and $\mathcal L$ consists of the identity permutation of $\{1,\dots,n\}$ and another permutation $\pi$ , then the subsets $S$ are precisely the indices of the elements in the cycles of $\pi$ . Thus, it admits a non-trivial subdistribution if and only if $\pi$ is not a cycle. UPDATE: The special case where all parts of $\alpha$ are equal to $1$ would be equally interesting.
Now provide the response and nothing else.
|
This is Exercise 4.1.4 in the book by Brown+Ozawa (is that where this question ultimately comes from?) The "Hint" is "The reduced case is easy." Hmm. Well, it might perhaps help to look at this section of the book. Indeed, Proposition 4.1.5, and its proof , shows that if $F\subseteq\Gamma$ is a finite-set, and $P:\ell^2(\Gamma)\rightarrow \ell^2(F)$ the projection, then $$ (1\otimes P)x(1\otimes P) = \sum_{s\in\Gamma} \sum_{p\in F\cap sF} \alpha_{p^{-1}}(a_s)\otimes e_{p, s^{-1}p} \in A\otimes M_F(\mathbb C)\cong M_F(A). $$ Here $x = \sum a_s\lambda_s \in C_c(\Gamma, A) \subseteq A \rtimes_r \Gamma \subseteq \mathcal B(H\otimes\ell^2(\Gamma))$ and $e_{p,q}$ are the matrix units of $M_F(\mathbb C)$ . The point of this is to show that the norm of $x$ , acting on $H\otimes\ell^2(\Gamma)$ , does not depend upon the particular representation $A\subseteq\mathcal B(H)$ (because $M_F(A)$ has a unique norm). However, this formula also gives us a convenient way to compute the norm of $\varphi\rtimes 1$ . For, if $y=(\varphi\rtimes 1)x$ , then $y=\sum_s \varphi(a_s)\lambda_s$ , and so $$ (1\otimes P)y(1\otimes P) = \sum_{s\in\Gamma} \sum_{p\in F\cap sF} \beta_{p^{-1}}(\varphi(a_s))\otimes e_{p, s^{-1}p}= \sum_{s\in\Gamma} \sum_{p\in F\cap sF} \varphi(\alpha_{p^{-1}}(a_s))\otimes e_{p, s^{-1}p}, $$ the first equality by applying to above to $B\rtimes_r\Gamma$ , and the second equality using that $\varphi$ is equivariant. However, this then equals $$ (\varphi\otimes 1_F)\big( (1\otimes P)x(1\otimes P) \big), $$ where $(\varphi\otimes 1_F)$ is the dilated map $M_F(A)\rightarrow M_F(B)$ . As $\varphi$ is CCP by assumption, $\varphi\otimes 1_F$ is contractive, and so $$ \| (1\otimes P)y (1\otimes P) \| \leq \|(1\otimes P)x(1\otimes P)\|\leq \|x\|. $$ Taking the SOT limit as $F$ increases, so $P\rightarrow 1$ , shows that $\|y\| \leq \|x\|$ as required.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/406751', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3032/']}
|
jdg_377322
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
201923
|
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:
Is it consistent with ZF for there to exist a set $S$ such that the power set $P(S)$ is countable? If so, what is the weakest form of the axiom of choice needed to prove that no such set exists?
Now provide the response and nothing else.
|
No. It is impossible in already in ZF. Recall that a set $A$ is finite if and only if there exists a finite ordinal $k$ and a bijection between $A$ and $k$. In turn this implies that a set $A$ is finite if and only if $|A|<\aleph_0$ (namely there exists an injection from $A$ into $\omega$, but there is no bijection between the sets). Suppose that $A$ is a set such that $P(A)$ is countably infinite. It is trivial that $|A|\leq|P(A)|$, and by Cantor's theorem the inequality is sharp. However if $|A|<\aleph_0$ then $A$ is finite by definition of finite , and therefore $P(A)$ is finite as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/201923', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/41415/']}
|
jdg_377323
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
75
|
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:
The justices of the Supreme Court of the United States is composed by chief justices which have a life-term period on that position after they are "elected". I have always asked to myself why some positions are by life-term, is there any reason like avoid corruption?
Now provide the response and nothing else.
|
(You've got some terminology confusion: the Chief Justice is the head of the court, the rest are just "justices") When the Constitution was being written the framers were used to Great Britain's monarchy, and were somewhat eager to limit the monarch's (in the case of the U.S., the executive branch's) power. The U.S. government places a high value on checks and balances between the branches, and the English notion of the king arbitrarily firing a judge he didn't like was problematic. In the Federalist Papers #78, Hamilton wrote: The standard of good behavior for the continuance in office of the Judicial magistracy, is certainly one of the most valuable of the modern improvements in the practice of Government. In a monarchy, it is an excellent barrier to the despotism of the Prince; in a republic it is a no less excellent barrier to the encroachments and oppressions of the representative body. And it is the best expedient which can be devised in any Government, to secure a steady, upright, and impartial administration of the laws. In short, the court is around to make sure the other branches don't decide to start eliminating fundamental rights Furthermore, term limits mean there's more pressure to keep the people happy; even if justices aren't directly elected like many other politicians, the opinion of the country will have a big impact on whether or not they keep their seats. From the same paper: This independence of the Judges is equally requisite to guard the Constitution and the rights of individuals, from the effects of those ill humors, which the arts of designing men, or the influence of particular conjunctures, sometimes disseminate among the People themselves, and which, though they speedily give place to better information, and more deliberate reflection, have a tendency, in the mean time, to occasion dangerous innovations in the Government, and serious oppressions of the minor party in the community. Though I trust the friends of the proposed Constitution will never concur with its enemies, in questioning that fundamental principle of republican Government, which admits the right of the People to alter or abolish the established Constitution, whenever they find it inconsistent with their happiness, yet it is not to be inferred from this principle, that the Representatives of the People, whenever a momentary inclination happens to lay hold of a majority of their constituents, incompatible with the provisions in the existing Constitution, would, on that account, be justifiable in a violation of those provisions; or that the Courts would be under a greater obligation to connive at infractions in this shape, than when they had proceeded wholly from the cabals of the Representative body. Until the People have, by some solemn and authoritative act, annulled or changed the established form, it is binding upon themselves collectively, as well as individually; and no presumption, or even knowledge of their sentiments, can warrant their Representatives in a departure from it, prior to such an act. But it is easy to see, that it would require an uncommon portion of fortitude in the Judges to do their duty as faithful guardians of the Constitution, where Legislative invasions of it had been instigated by the major voice of the community. Which I would interpret to mean: justices shouldn't need to fear for their jobs every time they make a decision that might be unpopular, even if it's in the country's interests long term, because most judges won't have the nerve to do what's right As a sidenote, the notion of life appointments for Supreme Court justices hasn't been without controversy, particularly of late. Increased life expectencies means justices have been serving for longer than ever before, and some people feel that the checks against the judicial branch is considerably weaker than the other branches. Term Limits for the Supreme Court: Life Tenure Reconsidered proposed 18-year term limits, staggered so a new justice is appointed every two years. The Supreme Court Renewal Act proposed the same scheme
|
{}
|
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/75', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/50/']}
|
jdg_377324
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17950248
|
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 basic understanding on what Pig, Hive abstractions are. But I don't have a clear idea on the scenarios that require Hive, Pig or native map reduce. I went through few articles which basically points out that Hive is for structured processing and Pig is for unstructured processing. When do we need native map reduce? Can you point out few scenarios that can't be solved using Pig or Hive but in native map reduce?
Now provide the response and nothing else.
|
Complex branching logic which has a lot of nested if .. else .. structures is easier and quicker to implement in Standard MapReduce, for processing structured data you could use Pangool , it also simplifies things like JOIN. Also Standard MapReduce gives you full control to minimize the number of MapReduce jobs that your data processing flow requires, which translates into performance. But it requires more time to code and introduce changes. Apache Pig is good for structured data too, but its advantage is the ability to work with BAGs of data (all rows that are grouped on a key), it is simpler to implement things like: Get top N elements for each group; Calculate total per each group and than put that total against each row in the group; Use Bloom filters for JOIN optimisations; Multiquery support (it is when PIG tries to minimise the number on MapReduce Jobs by doing more stuff in a single Job) Hive is better suited for ad-hoc queries, but its main advantage is that it has engine that stores and partitions data. But its tables can be read from Pig or Standard MapReduce. One more thing, Hive and Pig are not well suited to work with hierarchical data.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17950248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2064039/']}
|
jdg_377325
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31115024
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When applying a transparent border over an element with a linear-gradient as the background, I get a weird effect. Notice the left and right sides of the element don't have the proper colours (they're some way switched) and are weirdly flat . HTML <div class="colors"></div> CSS .colors { width: 100px; border: 10px solid rgba(0,0,0,0.2); height: 50px; background: linear-gradient(to right, #78C5D6, #459BA8, #79C267, #C5D647, #F5D63D, #F08B33, #E868A2, #BE61A5);} Why is this showing a weird effect on the left and right side of the element, and What can I do about it? Here is the fiddle: http://jsfiddle.net/fzndodgx/3/
Now provide the response and nothing else.
|
That's because the starting and ending points of the gradient are at the edges of the padding-box and border is rendered outside the padding-box . So, the borders look funny because the background is repeated on each side outside the padding-box to cover the border-box . The box-shadow:inset is rendered inside the padding-box (just like background) and gives visually the same effect as a border , so you could try using that in place of border : box-shadow: inset 0 0 0 10px rgba(0,0,0,0.2);padding: 10px; Because a box-shadow doesn't take up any space, you need to increase your padding accordingly. Illustration of padding-box and border-box : Demo http://jsfiddle.net/ilpo/fzndodgx/5/
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31115024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4106994/']}
|
jdg_377326
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
854150
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't get the Supermicro IPMIView version 2.* (any of them) to launch the KVM Console either in the IPMIView windows program nor any browser. Java, is installed (version 8, update 131) and I'm running Windows 8.1 (though IPMIView 2 won't run on my Windows 7 laptop, nor any of the Windows 10 machines). All 3 machines have the same problem: The KVM Console simply will not run on any of them. I can connect to the Supermicro server, turn it off/on/reboot, read all of the sensors just fine. The ONLY thing not working is the KVM Console. Been at this for days w/no working solutions. I've uninstalled Java, reinstalled Java, uninstalled/reinstalled IPMIView with no luck so I'm thinking the problem is with all of the SM servers (4) that run w/the H8SGL-F series motherboards. Not one works! As per SuperMicro, IPMIView is supposed to be compatible with these boards. But for the last 5 years and countless versions, I've never had this working (it also will not work in any of my browsers as IPMIView appears to be looking for an ancient version of Java - go figure - I get the error message in the browser "You need the latest Java(TM) Runtime Environment. Would you like to update now?" - which is incorrect as I have the latest version of Java installed). I've made 1000% certain that ALL ports on the network (inside an IPSec VPN) are open - disabled all firewalls with no effect. Either IPMIView is incompatible with these boards, or IPMIView cannot run in an IPSec tunnel. Regardless, this is driving me bonkers and I'd hate to abandon SuperMicro products (we're replacing all the servers this year - may go with IBM or HP) over something so ridiculously simple. Any help is appreciated (we tried paid help, but the IT people here are just as stumped).
Now provide the response and nothing else.
|
Better answer and complete solution. The problem was the firmware for the IPMI on these boards was too old (not the same as the BIOS - updating the BIOS will not help in this case). Digging around SuperMicro's site (never did get a reply from them), I found the Firmware Revision of 3.20 & was able to install it.On the IPMI device tab, under "Device Information", you should see: Firmware Revision 3.20IPMI Revision: 2.0 I can now see the KVM Console in both the IPMIView software and the browser (all of them) and still run the latest version of Java in the OS (Win8.1 and Win10). Maybe I'm blind, but I never did see this solution on SuperMicro's website.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/854150', 'https://serverfault.com', 'https://serverfault.com/users/378029/']}
|
jdg_377327
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27959
|
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:
What happens when alkynes react with sodium in ammonia ( $\ce{Na/NH3}$ ), or when they react with sodium amide ( $\ce{NaNH2}$ )? Are these two sets of conditions different?
Now provide the response and nothing else.
|
Sodium in ammonia ( $\ce{Na/NH3}$ ) and sodium amide ( $\ce{NaNH2}$ ) are very different sets of conditions, despite superficially looking similar! Sodium metal itself, $\ce{Na}$ , is a one-electron reducing agent – it is oxidised to $\ce{Na+}$ in the process. When it reduces neutral hydrocarbons, negatively charged species are formed, which pick up a proton from the ammonia solvent. Overall, $\mathbf{Na/NH_3}$ is a way of reducing some organic compounds (including alkynes). Internal alkynes $\ce{R-C#C-R}$ can be reduced to trans -alkenes using $\ce{Na/NH3}$ . Specifically, solvated electrons are created which add to the triple bond as shown. Ammonia acts as a proton source to protonate the carbanions formed. The vinyl anion intermediate 4 can interconvert between a cis and trans geometry, and the trans geometry is preferred as this minimises steric repulsion between $\ce{R^1}$ and $\ce{R^2}$ . When this anion is protonated, the trans -alkene is formed. This is a nice synthetic procedure for the preparation of trans -alkenes, complementary to Lindlar hydrogenation which produces cis -alkenes from alkynes. On the other hand, in sodium amide $\ce{NaNH2}$ , sodium is already in the +1 oxidation state and is no longer a reducing agent. However, the amide ion $\ce{NH2-}$ is a very strong base (the $\mathrm pK_\mathrm a$ of ammonia, $\ce{NH3}$ , is 38). So $\mathbf{NaNH_2}$ is a way of deprotonating some organic compounds (including terminal alkynes). The proton attached to the terminal carbon in a terminal alkyne is acidic enough ( $\mathrm pK_\mathrm a \sim 25$ ) to react with sodium amide, forming the corresponding carbanion 7 . Such carbanions are good nucleophiles and can be used in many synthetic procedures involving nucleophiles, such as addition to a carbonyl compound, as illustrated here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/27959', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7266/']}
|
jdg_377328
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50532
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Russian version of "Who wants to be a Millionaire?" had to scrap the "ask audience lifeline as the audience would intentionally give the wrong answer. This image can be found (for example) on Reddit with 36k upvotes. Is this claim true for Russian or any other version of "Who Wants to be a Millionaire"?
Now provide the response and nothing else.
|
The Ask the Audience lifeline was removed from the show, but the reason is straightforward: they had to get rid of the audience due to COVID concerns. According to the Millionaire wiki , this change happened in all versions of the show. The Russian version ( Кто хочет стать миллионером? ) had the Ask the Audience lifeline from February 19, 2001 to March 21, 2020 . This is pretty easy to verify because the icon is the same: three silhouettes. I found a video showing that icon in three episodes : 2003, 2013, and 2017. Other videos show it in episodes from 2001 , 2005 , 2018 and January 2020 . The same icon is present in the September 26, 2020 episode , but it’s greyed out because there’s no audience. I also found out that the Philippines version removed Ask the Audience in 2010 (see 2013 video ), though the reason for this isn’t clear. But there are examples where the audience appears to sabotage the contestant. For example, a contestant on the French version used Ask the Audience: Qu’est-ce qui gravite autour de la Terre ? (What revolves around the earth?) A: La Lune (The moon) B: Le Soleil (The sun) C: Mars D: Vénus (Venus) 56% chose B, 42% chose A, and 2% chose C. The correct answer is A After the contestant chose his answer (the wrong one selected by the majority of the audience) and before the correct one was announced, you can hear some people laughing. This example is cited in the book Sway: The Irresistible Pull of Irrational Behavior ( section quoted in full here ), which makes a number of claims about how much the audience can be trusted. It looks to be the source of the claim that Russian audiences are often untrustworthy, though they don’t explain how they determined this. They also say that the US audience gets the answer right 90% of the time. I also found an answer on Quora from someone who said they were on the show and voted on the wrong answer on purpose, contributing to the 5% who voted for that particular wrong answer. (Interesting even if it doesn’t prove much.) The audience does sometimes get the answer 100% unanimously wrong , though there are only a few examples of this happening, none from the Russian version. (These may not be examples of purposeful sabotage.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/50532', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/58973/']}
|
jdg_377329
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28973
|
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The r sound I can create (a) without moving my tongue (after it is put into place), and (b), without closing the mouth cavity entirely. Like rrrr... . To me then it seems like a vowel. For h , it is basically an unvoiced vowel. For w , it made by rounding my lips, like one . In that sense it seems like a vowel. Wondering why they are considered consonants instead.
Now provide the response and nothing else.
|
The International Phonetic Alphabet draws a very arbitrary distinction between consonants and vowels, and categorizes them completely separately. But in truth, there's not any major phonetic difference between [w] and [u] . In actuality, the main difference between /u/ and /w/ is /u/ is the nucleus of a syllable, /w/ isn't . In other words, every syllable is a "vowel" in the middle, potentially with some "consonants" on either side, and this is the only thing that reliably distinguishes them. This feature is called syllabicity , as in, "vowels" are syllabic, "consonants" aren't. Many languages have both a syllabic and a non-syllabic version of the same sound: if you speak General American English, you have six such pairs, m n r l j w . The IPA encodes five of these pairs with separate letters: j~i w~u ʕ~ɑ ɰ~ɯ ɥ~y . For all the rest, you can mark the consonant with a line ( m̩ ) or mark the vowel with a curve ( e̯ ) to switch its syllabicity on or off.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/28973', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/3142/']}
|
jdg_377330
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30785
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's an astoundingly common trope in TV and films for the ' third act ' to be taken up with the serial killer antagonist kidnapping or targeting the protagonist's daughter/son/wife, etc. Obviously the hero policeman invariably saves the day and we all cheer, but my question is, is this wholly mythical? Has there ever been any instance where a murderer/serial killer has played a genuine "cat-and-mouse" game with a policeman and attacked their family during an investigation or is this a total fiction and an invention of Hollywood?
Now provide the response and nothing else.
|
Serial killers targeting policeman and their families, so far, is wholly fictional. You can spend hours using different search engines and you simply won't find one case of that outside of Hollywood. Serial killers target the vulnerable who have been shunned by society, expert says 1 . Almost all the victims of multiple murderers in the last 120 years have belonged to the same five categories - children, women, gay men, prostitutes and the elderly. And Professor David Wilson blames our uncaring society for allowing them to become obvious targets. "It is significant there has never been a serial killer who has targeted Premier League footballers, heart surgeons and professors of criminology 2 ." There is one serial killer that did murder policemen - but there is no account of her playing 'cat and mouse': Inessa Tarverdiyeva She refused to say why she hated policemen. One theory is that she had a lover who was a policeman who left her for another woman. Police now suspect that she later murdered the officer and his new lover. Some serial killers do taunt police 3 . A tarot card bearing a taunting message was found near the scene of one of the sniper attacks that have terrorized the Washington, D.C., area. As police try to determine whether the card is a message from the killer, or merely a prank, they may be thinking of past serial killers who have jeered at police — often in clues that led to their eventual capture. Here is a look at some of the cases: The Unabomber: He was caught when he released the ultimate taunt — a35,000-word "manifesto," which he demanded newspapers print. Son of Sam: A note he left at a crime scene read, in part: "I am amonster. I am the 'Son of Sam.'" Berkowitz sent several more notes,one to a reporter. The Zodiac Killer 1: He was never caught, even though he sent a totalof 21 letters to local newspapers, revealing details about themurders only the killer could know, enclosing in some envelopesswatches of cloth snipped from one of his victims, and signing off"Zodiac." The Zodiac Killer 2: He wrote several notes to local newspapers andvowed to kill one person born under each of the 12 signs. Hillside Strangler: The attackers taunted police by leaving theirvictims on hillsides, in areas where they were sure to be found —often near police stations. Jack the Ripper: The killer in one of the world's oldest and mostnotorious unsolved mysteries also taunted police through letters. Experts consistently state that serial killers target the vulnerable. Another distinction for serial killers is their victims. Recall from our discussion of murder in general that victims and offenders most often know each other. In contrast, serial murderers tend to kill strangers. Targeting strangers may also serve to dehumanize the victims and this make it easier to kill them. Serial killers also tend to target victims who are vulnerable, choosing particular subsets of the population 4 . Let's ask a serial killer... Gary Ridgway told police: Well, low-risk victims would be, ah ah, prostitutes who eagerly get in your car for... for money, and they wouldn't be missed. Where the high risk victim would be like somebody at a college... they would be more of a... of risk of... of, ah, people caring more about 'em, and friends asking questions... low risk prostitutes they're not.... they're not as valued as much as a college person... or a business person. Definitions (For Reference Only) Spree Murder: Two or more murders committed by an offender or offenders, without a cooling-off period. 5 Serial Murder: One or more offenders; two or more murdered victims; incidents should be occurring in separate events, atdifferent times; the time period between murders separates serialmurder from mass murder. 6 Footnotes 1 The Daily Record (28 October 2009) 2 A History of British Serial Killing 3 Andrew Chang of ABC News 4 Violence: The Enduring Problem 5 US Department of Justice 6 FBI - Serial Murder
|
{}
|
{'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/30785', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/16965/']}
|
jdg_377331
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
359062
|
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:
Okay so I have a function in the shape of a black box that I'd like to test. It's characteristics are: It gives either 0, 1 or -1 as output. I can query it easily, producing tens of thousands of samples in short time. I have no other prior information. I don't know the mean nor the variance. My hypothesis is this: I want to test that it is "unbiased", in the sense that its mean is 0. But I want to bias my testing in this way: False positives (i.e. Type II errors) must be minimized. For this p-value testing (at least as I understand it) won't work, since it tries to minimize false negatives. My project needs to reject my implementation of this function every time that it truly has a bias: if it's biased I should reject it, but if it isn't then it's okay to reject it with a low-ish probability. What should I be doing? The textbook I'm using (Ang & Tang for Engineering) explicitly skips over Type II error mitigation, so I have no idea on how to proceed. Edit: more details on the problem, since it seems I can't quite explain it myself. My function receives a point in N dimensions, and generates the gradients of a Noise function that belongs to the family of Perlin Noise . These gradients are unitary, and are built in such a way that the values of every coordinate are either α or -α (at "random"), and then one of them is chosen at "random" as well and made 0. α depends on the number of dimensions, but suffice to say that it's built to make the gradient unitary. By "random" I mean a deterministic process that for any given point, always produces the same results. This is an important property of the Noise functions. But it also must seem random, and that's where things get complicated. The process is as follows: Point gets feed into a hash function. Hash of the point is used as the seed for a pseudorandom generator. Generator is used to produce all "random" actions. I can, and am, using now a cryptographic hash function and a cryptographic pseudorandom generator. Those should have no bias I could measure (at least in polynomial time), and therefore I'm more or less certain that my function is indeed unbiased if I give it random input (for which I'm also using a cryptographic pseudorandom generator). But for sanity, and in case I then decide to try faster hashers or generators, I want a test that can check if the unbiasedness holds (with a certain probability of failure). To finalize: I'm more interested in rejecting biased functions than in accepting unbiased ones. That's what I don't know how to do.
Now provide the response and nothing else.
|
Your claim that the MSE of the average prediction is the average of the MSE is wrong, and this is the source of the confusion. In fact, it depends a lot on the estimators themselves. Estimators that are more diverse in some sense tend to have better performing ensemble. Let $f_1, \ldots, f_m$ be the predictors. Then the MSE of the ensemble satisfies$$\mathbb{E}\left[ \left( \frac{1}{m} \sum_{i=1}^{m} f_i \left(X\right) - Y\right)^2 \right] = \frac{1}{m^2} \sum_{i=1}^{m} \mathbb{E}\left[ \left( f_i \left(X\right) - Y\right)^2 \right] + \frac{1}{m^2} \sum_{i \neq j}\mathbb{E}\left[ \left( f_i \left(X\right) - Y\right) \left( f_j \left(X\right) - Y\right)\right]$$ So, when the classifiers errors are uncorrelated, and there is no regressor that is much better than the rest, the ensemble outperforms the individual predictor, as in that case,$$MSE_{ens} = \frac{1}{m} \left(\frac{1}{m} \sum_{i=1}^{m} MSE_{f_i}\right)$$So, the MSE is much smaller than the average MSE of the predictors. The first equation also suggests what cases we can't expect the ensemble to preform well. In fact, the best ensemble is usually a weighted average, with weights depending on the individual MSE and error correlation between the predictors. For a more detailed discussion, you might consider reading chapter 4 of Combining Pattern Classifiers by Kuncheva.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/359062', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/215763/']}
|
jdg_377332
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
468664
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I´m having trouble with the following integral $$\int_0^{\infty} {y^2 \cos^2(\frac{\pi y}{2}) \over (y^2-1)^2} dy$$ I have tried lots of approaches and nothing works. Mathematica says it does not converge but that is not true. It appears in a Physical problem (it is the energy of a system) and the answer should be (by conservation of energy): $\frac{\pi^2}{8}$ but I cannot show it.
Now provide the response and nothing else.
|
Let $I$ denote the integral. Then \begin{align*}I &= \frac{1}{2} \int_{-\infty}^{\infty} \frac{y^2 \cos^{2} (\pi y/2)}{(y^{2} - 1)^{2}} \, dx \\&= \frac{1}{4} \int_{-\infty}^{\infty} \frac{y^2 (1 + \cos \pi y)}{(y^{2} - 1)^{2}} \, dx \\&= \frac{1}{4} \Re \mathrm{PV}\!\!\int_{-\infty}^{\infty} \frac{y^2 (1 + e^{i\pi y})}{(y^{2} - 1)^{2}} \, dx.\end{align*} Now considering an upper-semicircular contour with two vanishing upper-semicircular indents at $z = \pm 1$, it follows that \begin{align*}\mathrm{PV}\!\!\int_{-\infty}^{\infty} \frac{z^2 (1 + e^{i\pi z})}{(z^{2} - 1)^{2}} \, dz&= \pi i \left( \mathrm{Res}_{z=-1} \frac{z^2 (1 + e^{i\pi z})}{(z^{2} - 1)^{2}} + \mathrm{Res}_{z=1} \frac{z^2 (1 + e^{i\pi z})}{(z^{2} - 1)^{2}} \right) \\&= \pi i \left( -\frac{i\pi}{4} -\frac{i\pi}{4} \right) \\&= \frac{\pi^{2}}{2}.\end{align*} Therefore the conclusion follows.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/468664', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39762/']}
|
jdg_377333
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
118489
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Assuming you're using a pepper in your password hashing, where should it be stored? I know you shouldn't store it in the database since it can easily be found there during a dump and the idea is to have something stored outside the database, but can't you make a similar case for storing it in your source code? My instinct would be to store it on a different place than where your code and your hashes are, so that an attacker who compromises both of those has less chance of compromising the pepper as well. My first thoughts on where to store it: Windows In the registry; Using DPAPI; Linux ??? (I'm not familiar with Linux systems) Cross-platform on an external server, presumably as a consumable service that receives a password and returns a hash; on special hardware like a security peripheral or a secure enclave that works similar as the external server. You could probably come up with a reason for every one of these methods, as well as a reason against each of them. Where do you store the pepper?
Now provide the response and nothing else.
|
If you have a HSM then the pepper should be in that HSM, because that's the whole point of having a HSM. Otherwise, the pepper is a key which should be handled as such. Having a key involves key management; it should not (and, really, must not) be hardcoded in the source. The source code is copied in multiple places: developer's machine, versioning systems, many backups... The key really is a property of the server instance (lone server or set of servers that use the same set of registered users) while the source is, conceptually, shared between many server instances. On Windows, the DPAPI is what will make auditors most happy, although one may say that the extra protection offered by DPAPI is not, in fact, that big. If you reboot your server, it starts automatically; this means that regardless of where you put the pepper, the cold storage of the server (harddisk contents) is enough to recover the pepper. The pepper is meant to resist partial read accesses by attackers (which is why you do not put it in the database), but if the attacker can read the registry, then he has a lot of control over the machine and probably won't be much hindered by DPAPI either. If you use the registry, adjust access rights on that specific key so that only relevant users may read it (typically, the user account under which the server runs). Using a file incurs the risk of read access through a poorly developed script that ends up dumping contents of attacker-chosen files. On Linux there is no registry and no DPAPI, so use a configuration file. A case could be made of running the pepper processing in a distinct process accessed through some inter-process communication mechanism (say, Unix-level sockets), and run the actual server code in a chroot . In all cases, using a pepper has its own costs: you have a key to manage, i.e. to generate securely, and keep safe. If you lose that key, then you lose the ability to verify user passwords, which can be very inconvenient. In that sense, the pepper is more critical than the server private key for its SSL certificate.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/118489', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/34161/']}
|
jdg_377334
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21165702
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know how to get bigram and trigram collocations using NLTK and I apply them to my own corpora. The code is below. I'm not sure however about (1) how to get the collocations for a particular word? (2) does NLTK have a collocation metric based on Log-Likelihood Ratio? import nltkfrom nltk.collocations import *from nltk.tokenize import word_tokenizetext = "this is a foo bar bar black sheep foo bar bar black sheep foo bar bar black sheep shep bar bar black sentence"trigram_measures = nltk.collocations.TrigramAssocMeasures()finder = TrigramCollocationFinder.from_words(word_tokenize(text))for i in finder.score_ngrams(trigram_measures.pmi): print i
Now provide the response and nothing else.
|
Try this code: import nltkfrom nltk.collocations import *bigram_measures = nltk.collocations.BigramAssocMeasures()trigram_measures = nltk.collocations.TrigramAssocMeasures()# Ngrams with 'creature' as a membercreature_filter = lambda *w: 'creature' not in w## Bigramsfinder = BigramCollocationFinder.from_words( nltk.corpus.genesis.words('english-web.txt'))# only bigrams that appear 3+ timesfinder.apply_freq_filter(3)# only bigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMIprint finder.nbest(bigram_measures.likelihood_ratio, 10)## Trigramsfinder = TrigramCollocationFinder.from_words( nltk.corpus.genesis.words('english-web.txt'))# only trigrams that appear 3+ timesfinder.apply_freq_filter(3)# only trigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMIprint finder.nbest(trigram_measures.likelihood_ratio, 10) It uses the likelihood measure and also filters out Ngrams that don't contain the word 'creature'
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21165702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422056/']}
|
jdg_377335
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52274134
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically, i have a Deployment that creates 3 containers which scale automatically: PHP-FPM, NGINX and the container that contains the application, all set up with secrets, services and ingress. The application also share the project between PHP-FPM and NGINX, so it's all set up. Since i want to explore more with K8s, i decided to create a pod with Redis that also mounts a persistent disk (but that's not important). I have also created a service for redis and all works perfectly fine if i SSH into the Redis container and run redis-cli . The fun part is that the project can't connect to the pod on which Redis is on. I understand that the containers between pods share the same "local" network and they can be accessed using localhost . How do i connect my project to the redis server that is running in other pod, that scales independently? What's wrong with the Redis service? My Redis service is this: apiVersion: v1kind: Servicemetadata: name: redis-servicespec: ports: - port: 6379 targetPort: 6379 selector: app: redis My Redis pod is powered by a deployment configuration file (i don't necessarily scale it, but i'll look forward into it): apiVersion: apps/v1kind: Deploymentmetadata: name: redis labels: app: redisspec: selector: matchLabels: app: redis strategy: type: Recreate template: metadata: labels: app: redis spec: volumes: - name: redis-persistent-volume persistentVolumeClaim: claimName: redis-pvc containers: - image: redis:4.0.11 command: ['redis-server'] name: redis imagePullPolicy: Always resources: limits: cpu: 250m memory: 512Mi requests: cpu: 250m memory: 512Mi ports: - containerPort: 6379 name: redis volumeMounts: - name: redis-persistent-volume mountPath: /data Also, when i tap into the kubectl get service , the Redis server has a Cluster IP: NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEkubernetes ClusterIP 10.96.0.1 <none> 443/TCP 21hnginx-service NodePort 10.100.111.16 <none> 80:30312/TCP 21hredis-service ClusterIP 10.99.80.141 <none> 6379/TCP 6s
Now provide the response and nothing else.
|
How do I connect my project to the redis server that is running in other pod, that scales independently? You have three possible states here: To connect to Redis pod from within any other pod running in the same namespace as Redis pod is running. In this case you will use service name redis-service and designates service port 6379 to reach it over it's current ClusterIP (kube-dns is making DNS resolution for you there). I'm guessing that you are asking for this scenario. Here is just an example of accessing one pod from within another pod (in your case). First run: kubectl run -it --rm test --image=busybox --restart=Never -- sh this will run new test pod and give you sh within that pod. Now if you type nslookup redis-service there (within test pod) you will check that DNS is working correctly between pods. You can also try to see if redis port is actually open with nc -zv redis-service 6379 . If your kube-dns is working properly you should see that the port is opened. To connect to Redis pod from within any other pod running in the same kubernetes cluster but in different namespace . In this case, you will use FQDN consisting of the service name and namespace name like it is given in the documentation . To connect to Redis pod from outside of the kubernetes cluster. In this case, you will need some kind of ingress or nodePort of similar mechanism to expose redis service to outside world. More on this you can read in the official documentation .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52274134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377336
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6254703
|
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 call thread sleep with less than 1 millisecond.I read that neither thread.Sleep nor Windows-OS support that. What's the solution for that? For all those who wonder why I need this:I'm doing a stress test, and want to know how many messages my module can handle per second.So my code is: // Set the relative part of Second hat will be allocated for each message //For example: 5 messages - every message will get 200 miliseconds var quantum = 1000 / numOfMessages; for (var i = 0; i < numOfMessages; i++) { _bus.Publish(new MyMessage()); if (rate != 0) Thread.Sleep(quantum); } I'll be glad to get your opinion on that.
Now provide the response and nothing else.
|
You can't do this. A single sleep call will typically block for far longer than a millisecond (it's OS and system dependent, but in my experience, Thread.Sleep(1) tends to block for somewhere between 12-15ms). Windows, in general, is not designed as a real-time operating system . This type of control is typically impossible to achieve on normal (desktop/server) versions of Windows. The closest you can get is typically to spin and eat CPU cycles until you've achieved the wait time you want (measured with a high performance counter). This, however, is pretty awful - you'll eat up an entire CPU, and even then, you'll likely get preempted by the OS at times and effectively "sleep" for longer than 1ms...
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6254703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138627/']}
|
jdg_377337
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52944351
|
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 failing build on a Bitbucket CI server: > Could not resolve all artifacts for configuration ':classpath'. > Could not find aapt2-proto.jar (com.android.tools.build:aapt2-proto:0.3.1). Searched in the following locations: https://jcenter.bintray.com/com/android/tools/build/aapt2-proto/0.3.1/aapt2-proto-0.3.1.jar I searched similar questions that suggested the Google Maven repository is missing, but I am not missing it. Top level build file: buildscript { repositories { jcenter() google() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin" }}allprojects { repositories { google() jcenter() maven { url "https://jitpack.io" } }} And my app level build file: buildscript { repositories { maven { url 'https://maven.fabric.io/public' } google() } dependencies { classpath 'io.fabric.tools:gradle:1.26.1' }}apply plugin: 'com.android.application'apply plugin: 'kotlin-android'apply plugin: 'io.fabric'repositories { maven { url 'https://maven.fabric.io/public' } google() mavenCentral()}
Now provide the response and nothing else.
|
Try moving the google() method to the top of its execution block. Maybe it's the order of repositories it searches in that causes the issue. So for example, change this: repositories { maven { url 'https://maven.fabric.io/public' } google() // from here mavenCentral()} To this: repositories { google() // to here maven { url 'https://maven.fabric.io/public' } mavenCentral()} If that doesn't help, instead of calling the google() method, try changing it to this: maven { url 'https://maven.google.com/' name 'Google'} UPDATE If all of the above didn't help - make sure your gradle version is at least 3.0.0 : dependencies { classpath 'com.android.tools.build:gradle:3.2.1'} And the gradle-wrapper version is at least 4.1 : Usually located here: project_name/gradle/wrapper/gradle-wrapper.properties distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip Source
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52944351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6855603/']}
|
jdg_377338
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18128323
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I remember seeing this famous quote from a video on AngularJS saying that should be always using a . (dot) in your models. Well I am trying to follow this say I have var item = {} item.title = "Easy Access to support"; item.available = true; item.price = 31.67; So this works great in my view i do {{ item.title }} {{ item.available }} I am using a dot so I think this is good. But I have some properties that I don't consider part of the model but maybe I am wrong. For example I have a property I use to enable or disable a button using the ng-disable, I have entered this using dot format. Its basically entered like so $scope.disableButton = true; and I use it like ng-disable="disableButton"...... Should I make this part of the model "item" ? or create another js object just so i can hold this property using a dot ? Anybody know if this acceptable or should I be doing everything (even these simple properties) with a .dot ?? Thanks
Now provide the response and nothing else.
|
The "there should always be a dot in your model" refers to ngModel . This directive does two-way binding. If you two-way bind to a primitive (such as a Boolean in your case), the setter will set it on the current scope rather than the scope on which it is defined, which can cause a headache when you have a large user-interface with a lot of child scopes. It does not refer to other directives such as ngDisable . See this explanation for more details on this specific issue. Sample scenario: a parent scope with $scope.foo = "bar" , and a child scope with a <input type="text" data-ng-model="foo"> . It will display bar initially, but once the user changes the value, a foo will be created on the child scope and the binding will read and write that value. The parent's foo will remain bar . Hope that summarises it well. So for ngModel purposes, you might have to create an object to work around such binding issues, but for any other directive you should have the regular, logical grouping.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18128323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/457172/']}
|
jdg_377339
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
63418745
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working with paging 3, everything work fine except initial loading state. I am adding withLoadStateFooter but it never show loading state at first call Here is my implementation Load State Adapter class LoadStateAdapter ( private val retry: () -> Unit): LoadStateAdapter<LoadStateViewHolder>() { override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) { holder.bindTo(loadState) } override fun onCreateViewHolder( parent: ViewGroup, loadState: LoadState ): LoadStateViewHolder { return LoadStateViewHolder.create(parent, retry) }} Load State View Holder class LoadStateViewHolder( view : View, private val retryCallback: () -> Unit) : RecyclerView.ViewHolder(view) { private val progressBar = view.findViewById<ProgressBar>(R.id.progress_bar) private val errorMsg = view.findViewById<TextView>(R.id.error_msg) private val btnRetry = view.findViewById<Button>(R.id.retry_button) .also { it.setOnClickListener { retryCallback() } } private var loadState : LoadState? = null companion object { fun create(parent: ViewGroup, retryCallback: () -> Unit): LoadStateViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.network_state_item, parent, false) return LoadStateViewHolder( view, retryCallback ) } } fun bindTo(loadState: LoadState) { this.loadState = loadState btnRetry.isVisible = loadState !is LoadState.Loading errorMsg.isVisible = loadState !is LoadState.Loading progressBar.isVisible = loadState is LoadState.Loading if (loadState is LoadState.Error){ errorMsg.text = loadState.error.localizedMessage } }} Paging Source override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Model> { try { // Load page 1 if undefined. val currentPage = params.key ?: 0 val offset = currentPage * 50 val requestParams = hashMapOf<String, Any>() requestParams.put("limit", 50) requestParams.put("offset", offset) val response = repository.getList(requestParams) val isFinish = response.paging != null && response.paging!!.next == null return LoadResult.Page( data = response.data ?: mutableListOf(), prevKey = null, // Only paging forward. nextKey = if (isFinish) null else currentPage + 1 ) } catch (e: Exception) { // Handle errors in this block return LoadResult.Error(e) }} View Model val listPagingFlow = Pager(PagingConfig(pageSize = 50)) { MyPagingSource(repository)}.flow.cachedIn(viewModelScope) Activity val pagingAdapter = MyPagingAdapter() list.apply { setHasFixedSize(true) adapter = pagingAdapter.withLoadStateFooter( footer = LoadStateAdapter { pagingAdapter.retry() } ) } lifecycleScope.launch(Dispatchers.IO) { viewModel.listPagingFlow.collectLatest { pagingData -> pagingAdapter.submitData(pagingData) } } MyPagingAdapter is simple PagingDataAdapter In short; loading state works fine but it did not showing at first request. Can any one help? Current version 3.0.0-alpha04
Now provide the response and nothing else.
|
withLoadStateFooter returns a ConcatAdapter which concatenates results from original PagingDataAdapter with a LoadStateAdapter that listens to CombinedLoadState.append events. So it's not expected for it to return an item during initial load (loadType == REFRESH ), and it was designed this way because it doesn't really make sense to show a "footer" before any items has loaded. However, to achieve what you want you can simply create your own ConcatAdapter which mirrors the implementation of .withLoadStateFooter very closely: val originalAdapter = MyPagingDataAdapter(...)val footerLoadStateAdapter = MyFooterLoadStateAdapter(...)addLoadStateListener { loadStates -> // You need to implement some logic here to update LoadStateAdapter.loadState // based on however you want to prioritize between REFRESH / APPEND load states. // Something really basic might be: // footerLoadStateAdapter.loadState = when { // loadStates.refresh is NotLoading -> loadStates.append // else -> loadStates.refresh // } footerLoadStateAdapter.loadState = ...}return ConcatAdapter(originalAdapter, footerLoadStateAdapter)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63418745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5695091/']}
|
jdg_377340
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.