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
2333909
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 got a homework assignment asking me to invoke a function without explicitly calling it, using buffer overflow. The code is basically this: #include <stdio.h>#include <stdlib.h>void g(){ printf("now inside g()!\n");}void f(){ printf("now inside f()!\n"); // can only modify this section // cant call g(), maybe use g (pointer to function)}int main (int argc, char *argv[]){ f(); return 0;} Though I'm not sure how to proceed. I thought about changing the return address for the program counter so that it'll proceed directly to the address of g(), but I'm not sure how to access it. Anyway, tips will be great. Now provide the response and nothing else.
The basic idea is to alter the function's return address so that when the function returns is continues to execute at a new hacked address. As done by Nils in one of the answers, you can declare a piece of memory (usually array) and overflow it in such a way that the return address is overwritten as well. I would suggest you to not blindly take any of the programs given here without actually understanding how they work. This article is very well written and you'll find it very useful: A step-by-step on the buffer overflow vulnerablity
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2333909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187907/']}
jdg_85241
stackexchange
llm_judgeable_groundtruth_similarity
15439564
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way how to resize UIImage in as few lines as possible? I don't mind of ratio, I just want to set image resolution to 80x60. That's all Now provide the response and nothing else.
This may be overkill but, you can simply take your image, and create a graphics context at that resolution you want, then you can set the tempImage as the UIImageView, overwriting it. UIImage *image = YourImageView.image; UIImage *tempImage = nil; CGSize targetSize = CGSizeMake(80,60); UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectMake(0, 0, 0, 0); thumbnailRect.origin = CGPointMake(0.0,0.0); thumbnailRect.size.width = targetSize.width; thumbnailRect.size.height = targetSize.height; [image drawInRect:thumbnailRect]; tempImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); YourImageView.image = tempImage;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15439564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1602687/']}
jdg_85242
stackexchange
llm_judgeable_groundtruth_similarity
474653
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the following circuit to switch a 24V signal to a PLC. The rising edge is fast and perfect(38 ns) but the falling edge of the signal is not as good(3.5us)!How can I modify this circuit to have faster-falling edges? simulate this circuit – Schematic created using CircuitLab Now provide the response and nothing else.
The basic idea is something like this: simulate this circuit – Schematic created using CircuitLab There are problems with this, though. For example, \$Q_3\$ might oscillate. Some added base resistance is a common fix. But there are other approaches. In this case, I don't think there's much likelihood, though. Just mentioning it, in case it matters. Also, you can always consider adding some emitter resistance for the output BJTs, if you want. But you'd need to know something about what you are driving to figure out those values. So that's also missing. There's also no base protection for either output BJT. You might also consider adding diodes to protect them against short-term reverse-voltage transients. I've also not added local power supply capacitors. Again, you may also want those. Or not. I've also avoided the speed-ups. A fuller circuit with all the crap added might look like this: simulate this circuit In the above, I've left off the base protection diodes. But they are pretty obvious, if you want them. With appropriate component values and those fancy BJTs I mentioned above (the BFT93 and BFR93 or BFR91A), the following Spice simulation results (it assumes some source resistance, as well, for what's driving it, and drives a load represented by two \$20\:\text{k}\Omega\$ resistors in series between the \$+24\:\text{V}\$ and ground. (So a \$10\:\text{k}\Omega\$ load, in short.) As you can easily see, it's pretty cut and dried. Nice and sharp edges and very little change in the duty cycle or its delay relative to the input. And I spent exactly zero time trying to calculate resistors or capacitor values when popping that into Spice.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/474653', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/62675/']}
jdg_85243
stackexchange
llm_judgeable_groundtruth_similarity
7189523
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 a space between two cell in table view, I want cell like this, How can i do that? Now provide the response and nothing else.
you can't set distance between cells directly, but you can set the height for header in section to achieve the same result. 1.set the numbers of cell you need as sections: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 3; // in your case, there are 3 cells} 2.return only 1 cell for each section - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return 1;} 3.set the height for header in section to set space between cells - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{ return 10.; // you can have your own choice, of course} 4.set the header's background color to clear color, so it won't look weird - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{ UIView *headerView = [[UIView alloc] init]; headerView.backgroundColor = [UIColor clearColor]; return headerView;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7189523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/707665/']}
jdg_85244
stackexchange
llm_judgeable_groundtruth_similarity
26128035
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 print out a time_point when the time_point is obtained from high_resolution_clock? timestamp = std::chrono::high_resolution_clock::now();std::time_t now = std::chrono::system_clock::to_time_t(timestamp);std::cout << std::ctime(&now) << std::endl; I get the following error message when compiling: error: no viable conversion from 'time_point<class std::__1::chrono::steady_clock, duration<[...], ratio<[...], 1000000000>>>' to 'const time_point<class std::__1::chrono::system_clock, duration<[...], ratio<[...], 1000000>>>' time_t tt = std::chrono::system_clock::to_time_t(timestamp); Now provide the response and nothing else.
There is no truly graceful way to do this. high_resolution_clock is not known to be related to UTC, or any other calendar. One thing you can portably do is output its current duration from its unspecified epoch, along with the units of that duration: #include <chrono>#include <iostream>intmain(){ using Clock = std::chrono::high_resolution_clock; constexpr auto num = Clock::period::num; constexpr auto den = Clock::period::den; std::cout << Clock::now().time_since_epoch().count() << " [" << num << '/' << den << "] units since epoch\n";} Which for me outputs: 516583779589531 [1/1000000000] units since epoch which means it is 516583779589531 nanoseconds (or 516,583.779589531 seconds) since the epoch of this clock on my machine. On my machine this translates to: my machine has been booted up for nearly 6 days. But that translation is not portable. Ah! And I note from your error message that you are using libc++ . If you are also on OS X, then we have the same definition of high_resolution_clock : It counts nanoseconds since your computer was booted.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26128035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272023/']}
jdg_85245
stackexchange
llm_judgeable_groundtruth_similarity
19877891
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on an implementation, using Amazon S3 . I use the Amazon C# SDK , and I try to upload a created ZIP file using the putObject method. When I upload the file, I get the following error: {Amazon.S3.AmazonS3Exception: The Content-MD5 you specified was invalid I generate a fine and working memorystream, and I can upload it to Amazon S3 without errors. However, when I provide the following line it gives me problems: request.MD5Digest = md5; Am I proving the MD5 the correct way? Is my MD5 generation correct? Or is there something else wrong? The requirement to my upload code : Once the Zip file has been created and you have calculated an MD5 sum value of that file, you should transfer the file to the AWS S3 bucket identified in the S3Access XML. Transfer the file using the AmazonS3, PutObjectRequest and TransferManagerclasses. Ensure the following meta data attributes are included via adding an ObjectMetaDataclass instance to thePutObjectRequest:• MD5Sum (via setContentMD5)• Mime ContentType (setContentType) My upload code The client.PutObject() gives the error: public void UploadFile(string bucketName, Stream uploadFileStream, string remoteFileName, string md5) { using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, config)) { try { StringBuilder stringResp = new StringBuilder(); PutObjectRequest request = new PutObjectRequest(); // request.MD5Digest = md5; request.BucketName = bucketName; request.InputStream = uploadFileStream; request.Key = remoteFileName; request.MD5Digest = md5; using (S3Response response = client.PutObject(request)) { WebHeaderCollection headers = response.Headers; foreach (string key in headers.Keys) { stringResp.AppendLine(string.Format("Key: {0}, value: {1}", key,headers.Get(key).ToString())); //log headers ("Response Header: {0}, Value: {1}", key, headers.Get(key)); } } } catch (AmazonS3Exception amazonS3Exception) { if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) { //log exception - ("Please check the provided AWS Credentials."); } else { //log exception -("An error occurred with the message '{0}' when writing an object", amazonS3Exception.Message); } } } } Overall method My process method (to see the overall flow). Sorry about the current state of the code, which is more pseudo code than production code: public void Process(List<Order> order) { var zipName = UserName + "-" + DateTime.Now.ToString("yy-MM-dd-hhmmss") + ".zip"; var zipPath = HttpContext.Current.Server.MapPath("~/Content/zip-fulfillment/" + zipName); CreateZip(order, zipPath); var s3 = GetS3Access(); var amazonService = new AmazonS3Service(s3.keyid, s3.secretkey, "s3.amazonaws.com"); var fileStream = new MemoryStream(HelperMethods.GetBytes(zipPath)); var md5val = HelperMethods.GetMD5HashFromStream(fileStream); fileStream.Position = 0; amazonService.UploadFile(s3.bucket, fileStream, zipName, md5val); var sqsDoc = DeliveryXml(md5val, s3.bucket, "Test job"); amazonService.SendSQSMessage(sqsDoc.ToString(), s3.postqueue); } MD5 Hashing method: This method is used to create a MD5 hash from my memorystream: public static string GetMD5HashFromStream(Stream stream) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(stream); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } EDIT : Just added fileStream.Position = 0 in the overall method. Still exactly same issue though. Now provide the response and nothing else.
I suspect the problem may be that after computing the hash of the stream, the stream is left at the end of the data... so when anything else reads from it later, there'll be no data. Try add this after the call to GetMD5HashFromStream fileStream.Position = 0; This will "rewind" the stream so you can read from it again. EDIT: Just looked at the documentation, and although the above is a problem, it's not the only one. Currently, you're appending a hex representation of the MD5 hash - but the documentation states: Content-MD5: The base64-encoded 128-bit MD5 digest of the message Note the "base64-encoded" part. So you'll want to change your MD5 code to: public static string GetMD5HashFromStream(Stream stream){ using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(stream); return Convert.ToBase64String(hash); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19877891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197304/']}
jdg_85246
stackexchange
llm_judgeable_groundtruth_similarity
328468
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Here is an interesting question raised by Alice Rhyl . Let $C$ be a category with a terminal object $1$ and finite coproducts. How many different morphisms $f : 1 \to 1 + 1$ can there be? There are always two obvious morphisms $f : 1 \to 1 + 1$ , coming from the definition of coproduct. But if $C$ is the category with one object and one morphism, $1 + 1 = 1$ so these two obvious morphisms are equal and there's really just one. Can there be three different morphisms $f : 1 \to 1 + 1$ ? I don't know. There can be four. Take $C = \mathrm{Set}^2$ ; then the terminal object in $C$ is $(1,1)$ (where $1$ is your favorite one-element set), and there are four different morphisms $f: (1,1) \to (1,1) + (1,1)$ . Indeed, any power of two is possible; just take $C = \mathrm{Set}^n$ . What other numbers are possible? (I find finite cardinals more interesting here.) So far $C$ has just been any category with a terminal object and finite coproducts. In a paper I'm writing with Christian Williams , I'm more interested in the case where $C$ is a cartesian closed category with finite coproducts. How many morphisms $f : 1 \to 1 + 1$ can there be in this case? (All the examples I've given above are categories of this sort.) Now provide the response and nothing else.
Let $V$ be any variety of idempotent operations, such as the varieties of idempotent groupoids (aka magmas), or idempotent semigroups, or semilattices, or lattices. Then $V$ is complete and cocomplete (if we include in $V$ an empty algebra); $1$ is just the $1$ -element algebra, and morphisms $1\to A$ are in 1–1 correspondence with set-theoretical elements of $A$ . The object $1$ is also the free algebra on $1$ generator, hence $1+1$ is the free algebra on $2$ generators. So, all in all, there are as many morphisms $1\to1+1$ as is the cardinality of the free $V$ -algebra on two generators. For example: If $V$ is the variety of semilattices, the number is $3$ . If $V$ is the variety of idempotent semigroups, the number is $6$ . If $V$ is the variety of idempotent groupoids, the number is $\aleph_0$ . More generally, if $V$ is the variety of all algebras with $\kappa\ge\aleph_0$ idempotent binary operations, then the number is $\kappa$ .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/328468', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2893/']}
jdg_85247
stackexchange
llm_judgeable_groundtruth_similarity
331336
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have a question on an argument appearing in this paper P . Setting Let $S=(1,\infty) \times (-1,1) \subset \mathbb{R}^2$ be a split, and let $X=(\{X_t\},\{P_x\}_{x \in S})$ be a Brownian motion in $S$ conditioned to hit $\{1 \} \times (-1,1)$ . We denote by $r(t)$ , $y(t)$ the first coordinate process of $X$ and the second coordinate process of $X$ , respectively. Let $\tau_r=\inf\{t>0 \mid r(t)=r\}$ , $r \ge 1$ . Question We consider random variables: \begin{align*}R_{k}=\int_{\tau_{k}}^{\tau_{k-1}}\frac{1}{r(s)^2}\,ds,\quad 2 \le k \le n. \end{align*} I would like to ask why $\{R_k\}_{k=2}^{n}$ are independent under $P_{n,y}(\cdot \mid y(\tau_j)=y_j,\quad j=1,\cdots,n-1)$ for each $n \ge 2$ and $y \in (-1,1)$ . The author of the above paper claims that strong Markov property yields the independence. However, I couldn't know how to use it. The event $\{y(\tau_j) \in B_j,\quad j=1,\cdots, n-1\}$ , $B_j \in \mathcal{B}((-1,1))$ seems like future events... ADD As RaphaelB4 said, under $P_{n,y}(\cdot \mid y(\tau_j)=y_j,\quad j=1,\cdots,n-1)$ , $X_t$ on $[\tau_i,\tau_{i-1}]$ and $X_{t}$ on $[\tau_{j},\tau_{j-1}]$ $(i \neq j)$ would be independent. But, I don't know how to prove this statement. Now provide the response and nothing else.
Disclaimer 1: Treating these topics properly would require a quick course in numerical analysis. Disclaimer 2: If you are using any sane computer system, it's already going to have a library function to solve linear systems implemented, which is going to be better of what you can code yourself if you don't have a solid grasp of numerical linear algebra and scientific computing. Unless you have special requirements, just use A \ b or scipy.linalg.solve or DGESV or whatever your programming language offers. Disclaimer 3: What follows applies to solving dense, small-scale (let's say $n\leq 10000$ ) square linear systems in IEEE floating point arithmetic. Things may be different if you use integer / rational / symbolic arithmetic in a computer algebra system, or if you compute by hand. That said: LU factorization (with partial pivoting): industry standard. It has the drawback that on some examples (very unlikely, basically just happens in counterexamples), the entries of $U$ may grow as $\sim 2^n$ times the entries of $A$ , and thus it may become unstable. Usually not a concern in practice. QR factorization: costs 2x as LU factorization, but avoids the problem mentioned above. If you don't mind paying 2x the cost just for the added peace of mind, go for it. Gaussian elimination: basically, it's the LU factorization method, but you avoid storing L in memory (so you can't reuse the factorization in case you have multiple right-hand sides $b$ coming at different times). People usually just go with LU, because the few memory writes saved aren't typically worth the trouble. Gaussian elimination without partial pivoting: avoid. Can be ridiculously unstable. inverse method: not super-clear what you mean here since there are different ways to compute a matrix inverse; in any case, avoid. It is more expensive ( $2n^3$ rather than $4/3n^3$ flops) and has worse stability properties (unstable in cases in which $\|b\| \ll \|A\|\|x\|$ ). Gauss-Jordan elimination: Avoid. No advantages over LU, and has worse stability properties (it's forward stable but typically not backward stable). Cholesky and LDL factorization (with suitable pivoting schemes, e.g. Bunch-Kaufmann): specialized solvers for symmetric matrices. Use them over LU if you have symmetric matrices; they are cheaper by a factor 2. Eigenvalue decomposition / Jordan decomposition: Avoid. Can be ridiculously unstable. Schur factorization: Avoid. Way more expensive; if you just have to solve a linear system it's not worth the trouble. Hessenberg reduction + specialized Hessenberg solver: might be useful in the special case in which you have to solve systems with $A+\sigma_i I$ for many values of $\sigma_i$ , since in this case you can re-use the same factorization to solve all the systems. Otherwise, avoid; slower than LU and QR without other advantages. Singular value decomposition: Avoid. Way more expensive; if you just have to solve a square linear system it's not worth the trouble. If you have a least-squares problem, well, it's a whole other story. Note that a performance-aware implementation of any of these methods will require using specialized libraries for the linear algebra primitives (e.g., matrix-vector products or rank-1 updates) and implementing in-place factorizations, compressed representations of orthogonal matrices (for algorithms in which they appear), and (most importantly) blocked versions of these algorithms. TL;DR: use LU factorization for the best speed/stability tradeoff. Don't roll your own code if performance matters. Reference: Higham, Accuracy and stability of numerical algorithms ; Golub, Van Loan, Matrix Computations , 4th ed.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/331336', 'https://mathoverflow.net', 'https://mathoverflow.net/users/68463/']}
jdg_85248
stackexchange
llm_judgeable_groundtruth_similarity
1251
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In 1 st Corinthians 15 , the apostle Paul records the eyewitness accounts of the Lord Jesus Christ's resurrection: For I delivered to you as of first importance what I also received: that Christ died for our sins in accordance with the Scriptures, that he was buried, that he was raised on the third day in accordance with the Scriptures, and that he appeared to Cephas, then to the twelve. Then he appeared to more than five hundred brothers at one time, most of whom are still alive, though some have fallen asleep. Then he appeared to James, then to all the apostles. Last of all, as to one untimely born, he appeared also to me. For I am the least of the apostles, unworthy to be called an apostle, because I persecuted the church of God.—1 st Corinthians 15:3-9 ( ESV ) I had a friend read that passage and ask if the apostle Paul leaves room for a non-physical (perhaps visionary) resurrection. What did the apostle Paul think? Now provide the response and nothing else.
Abstract Paul can't be read to support a non-physical resurrection, in this passage or any other, unless you take his words out of context. N. T. Wright is certainly the person to ask on the topic and he neatly summarizes the argument in an article addressing four reviews of his The Resurrection of the Son of God : [Michael] Goulder, by contrast, proposes that the Jerusalem leadership held the view that Jesus’ resurrection was a matter of ‘spiritual’ transformation, rather than the ‘bodily resurrection’ which he ascribes to Paul. This is remarkable in itself; Goulder, never one to shirk controversial proposals, has stood on its head a more usual position, which is that Paul held a ‘spiritual’ view of the resurrection (based on the common misreading of the soma pneumatikon in 1 Corinthians 15) while some other, less Hellenized and more Jewish, early Christians stuck to a view of bodily resurrection. What Wright calls "the common misreading", comes from 1 st Corinthians 15:42-49 ( ESV ): So is it with the resurrection of the dead. What is sown is perishable; what is raised is imperishable. It is sown in dishonor; it is raised in glory. It is sown in weakness; it is raised in power. It is sown a natural body; it is raised a spiritual body . If there is a natural body, there is also a spiritual body . Thus it is written, “The first man Adam became a living being”; the last Adam became a life-giving spirit. But it is not the spiritual that is first but the natural, and then the spiritual . The first man was from the earth, a man of dust; the second man is from heaven. As was the man of dust, so also are those who are of the dust, and as is the man of heaven, so also are those who are of heaven. Just as we have borne the image of the man of dust, we shall also bear the image of the man of heaven. The word spiritual throughout the passage is pneumatikos < 4152 >, which can mean: 1) relating to the human spirit, or rational soul, as part of the man which is akin to God and serves as his instrument or organ 1a) that which possesses the nature of the rational soul 2) belonging to a spirit, or a being higher than man but inferior to God 3) belonging to the Divine Spirit 3a) of God the Holy Spirit 3b) one who is filled with and governed by the Spirit of God 4) pertaining to the wind or breath; windy, exposed to the wind, blowing While the idea of "spiritual renewal" seems possible to modern readers, in the context of resurrection, which meant a bodily coming back to life, it doesn't work. Paul uses the word "spiritual" because he is struggling to describe the sort of body that will be raised. In verses 35-49, he compares the process to the process of burying a seed. What is planted in the ground does not look like what eventually grows up, but both are of the same kind. In the Resurrection, we don't get an identical copy of our bodies, but something better. "Spiritual", in this case, is of the second definition: "belonging to a spirit, or a being higher than man but inferior to God". (It also might include the third meaning: "belonging to the Divine Spirit".) Wright's book goes into great detail about what might and what might not be meant by resurrection in the New Testament. Here's a summary from another of his articles : The first point to make here is vital. I have argued that the early Christians looked forward to a resurrection which was not a mere resuscitation, nor yet the abandonment of the body and the liberation of the soul, but a transformation, a new type of body living within a new type of world. This belief is embroidered with biblical motifs, articulated in rich theology. Yet in the gospel narratives we find a story, told from different angles of course, without such embroidering and theology—told indeed in restrained, largely unadorned prose. Yet the story is precisely of a single body neither abandoned, nor merely resuscitated, but transformed; and this, though itself totally unexpected, could give rise to exactly that developed view of which I have spoken. The Easter narratives, in other words, appear to offer an answer to why the early Christian hope and life took the form and shape they did.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/1251', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/109/']}
jdg_85249
stackexchange
llm_judgeable_groundtruth_similarity
7072159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Not so much 'How do you...?' but more 'How do YOU...?' If you have a file someone gives you with 200 columns, and you want to reduce it to the few ones you need for analysis, how do you go about it? Does one solution offer benefits over another? Assuming we have a data frame with columns col1, col2 through col200. If you only wanted 1-100 and then 125-135 and 150-200, you could: dat$col101 <- NULLdat$col102 <- NULL # etc or dat <- dat[,c("col1","col2",...)] or dat <- dat[,c(1:100,125:135,...)] # shortest probably but I don't like this or dat <- dat[,!names(dat) %in% c("dat101","dat102",...)] Anything else I'm missing? I know this is sightly subjective but it's one of those nitty gritty things where you might dive in and start doing it one way and fall into a habit when there are far more efficient ways out there. Much like this question about which . EDIT: Or, is there an easy way to create a workable vector of column names? name(dat) doesn't print them with commas in between, which you need in the code examples above, so if you print out the names in that way you have spaces everywhere and have to manually put in commas... Is there a command that will give you "col1","col2","col3",... as your output so you can easily grab what you want? Now provide the response and nothing else.
I use data.table 's := operator to delete columns instantly regardless of the size of the table. DT[, coltodelete := NULL] or DT[, c("col1","col20") := NULL] or DT[, (125:135) := NULL] or DT[, (variableHoldingNamesOrNumbers) := NULL] Any solution using <- or subset will copy the whole table. data.table 's := operator merely modifies the internal vector of pointers to the columns, in place. That operation is therefore (almost) instant.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7072159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597925/']}
jdg_85250
stackexchange
llm_judgeable_groundtruth_similarity
38416602
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 whether a string $uuid is a UUID. I have written this script but for some reason it is not working: uuid="7632f5ab-4bac-11e6-bcb7-0cc47a6c4dbd"if [[ $uuid =~ ^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$ ]]; then echo "true"else echo "false"fi Now provide the response and nothing else.
Your regular expression doesn't accept lowercase letters as valid. Here is a fixed version: #!/bin/bashuuid="7632f5ab-4bac-11e6-bcb7-0cc47a6c4dbd"if [[ $uuid =~ ^\{?[A-F0-9a-f]{8}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{12}\}?$ ]]; then echo "true"else echo "false"fi First of all, you only really need to be searching A-F not A-Z because UUIDs contain hex digits. Notice the addition of a-f in each character class. Your version will reject any UUID that is printed in lowercase. This new version works fine for me now. An alternative solution is to only use an uppercase UUID, instead of the lowercase one that you have. Your [A-Z0-9] classes have for those reasons been replaced with [A-F0-9a-f] . See the post by Ekeyme Mo for safety considerations.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38416602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2768038/']}
jdg_85251
stackexchange
llm_judgeable_groundtruth_similarity
46844852
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: after reading answer to the question How to serve Allure Report without automatically starting the browser I wonder how to use nginx to host allure reports properly?I suppose it would be enough if you may give an example of command for nginx and allure in proper order. PS: I am trying to create a shared Allure report as a hosted website across company without the necessity for each user of the report to have Allure installed on his local machine, without executing "allure serve" on each new test result. Hosting is planned on AWS EC2, resolving domain and etc is planned to be done separetly with AWS ELBs.Allure documentation does not cover this topic, as there are no other questions wth detailed specific answer on this topic on StackOverflow in regards to allure. Thanks in advance. Now provide the response and nothing else.
Configure a web server that everyone in your company can access Sounds like that will be taken care of with your AWS setup. You basically just need a web server that everyone you wish to see the reports can get to. Execute your tests to output the Allure source files Execute your tests with whatever process and framework you are using and make sure to set the configuration so the necessary source files for Allure are output as part of the test run Run the Allure test adapter with the source files from step 2 in order to generate the reports Command line version works Drop the Allure reports from step 3 into the webserver Create a new directory titled "Allure" in the place that your web server is configured to host out of. The html file is already named "index.html" Navigate to " http://machinename/Allure/ " This should pull up your Allure report via the web just as if you had executed "Allure serve" locally In my case I... Create a Windows Server 2012 R2 VM on the company network and configure IIS to host out of C:\inetpub\wwwroot Install the Allure NUnit 2 Adapter to the machine where I run the tests which adds a new "addins" directory with various files to the NUnit install location, edit the config.xml to set the output directory for Allure's source files, and then execute the tests C:\NUnit.org\NUnit-2.6.4\bin\addins\config.xml <results-path>C:\AllureSourceFiles</results-path> Run Allure with the source files to generate the report allure generate --output C:\AllureOutputReport C:\AllureSourceFiles Create an "Allure" directory in the web server and copy all of the Allure report output files/directories into that place from "C:\AllureOutputReport" where the tests were ran C:\inetpub\wwwroot\Allure\app.js C:\inetpub\wwwroot\Allure\favicon.ico C:\inetpub\wwwroot\Allure\index.html C:\inetpub\wwwroot\Allure\styles.css C:\inetpub\wwwroot\Allure\data C:\inetpub\wwwroot\Allure\export C:\inetpub\wwwroot\Allure\history C:\inetpub\wwwroot\Allure\plugins Navigating to " http://machinename/Allure/ " from any browser in the company network shows the allure report
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46844852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8805328/']}
jdg_85252
stackexchange
llm_judgeable_groundtruth_similarity
1530035
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to learn some topology as a hobby, and my understanding is that all manifolds are examples of topological spaces. Similarly, all metric spaces are also examples of topological spaces. I want to explore the relationship between metric spaces and manifolds, could it be that all manifolds are examples of metric spaces? Now provide the response and nothing else.
...all manifolds are examples of topological spaces.$\newcommand{\Reals}{\mathbf{R}}$ This is true by definition; there are numerous formal definitions of a manifold , but all explicitly refer to a topology. Similarly, all metric spaces are also examples of topological spaces. In a hair-splitting sense this is arguably not quite correct. Instead, a metric space $(X, d)$, i.e., a non-empty set $X$ together with a function $d:X \times X \to \Reals$ satisfying the axioms of a metric, is naturally associated to a topology : Take $T$ to be the topology generated by the family of open balls in $(X, d)$. ...could it be that all manifolds are examples of metric spaces? Now we're in less hair-splitting territory: A manifold does not come equipped with a "natural" metric (even if we assume the metric induces the manifold topology), so the literal answer is "no". That said, you can ask whether or not every manifold $(M, T)$ admits a topological metric $d$. The answer is "it depends on your definition". If your definition of "manifold" doesn't stipulate second countable (the topology is generated by countably many open sets), there exist manifolds such as the long line whose topology is not metrizable. Similarly, a non- Hausdorff manifold is not metrizable. If your definition stipulates $(M, T)$ is Hausdorff, second-countable, and paracompact , then "yes, in the sense that every manifold admits a topological metric inducing the topology $T$ ". If $(M, T)$ is connected and smooth , a topological metric can be "constructed" by using paracompactness and a partition of unity to induce a Riemannian metric on $M$, and defining the distance $d(p, q)$ to be the infimum of the lengths of piecewise geodesics joining $p$ to $q$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1530035', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/244758/']}
jdg_85253
stackexchange
llm_judgeable_groundtruth_similarity
3829267
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 looked into WolframAlpha and deduced from some examples that: $$ \sum_{n=k}^{\infty} \frac{1}{ \binom{n}{k}} = \frac{k}{k-1} ~~~~ \text{where} ~~~ k \in \mathbb{N} \setminus \{1\}$$ But why is that? The only thing I could pull of is this: $$ \sum_{n=k}^{\infty} \frac{1}{ \binom{n}{k}} = \sum_{n=k}^{\infty} \frac{k! (n-k)!}{n!} = k! \sum_{n=k}^{\infty} \frac{ (n-k)!}{n!} = k! \sum_{n=k}^{\infty} \frac{1}{(n-k+1) \cdot (n-k+2)\dots \cdot n}$$ Which then got me into a dead-end (for my knowledge) ... I am curious as why is that and but this actually mean "combinatorically" / "statistically" and how to actually evaluate this. Thanks! Now provide the response and nothing else.
So the sum you are concerned with is $$\sum_{n=k}^{\infty} \frac{1}{(n-k+1) \cdot (n-k+2)\dots \cdot n}$$ which has the product of $k$ consecutive integers in the denominator of each summand which you can express as the difference of two fractions each with the product of $k-1$ consecutive terms in the denominator . So, for $n=N$ , the summand is $$\dfrac{1}{(N-k+1)\cdots(N-1) N}\\ = \dfrac1{k-1}\left(\dfrac{1}{(N-k+1)(N-k+2)\cdots (N-1)}-\dfrac{1}{(N-k+2)\cdots(N-1)N}\right)$$ To get a feel of this fix a $k>2$ , say $k=4$ , and explicitly write down a few of the summands at the beginning, you should have $$\dfrac1{1.2.3.4}+\dfrac1{2.3.4.5}+\dfrac1{3.4.5.6}+\cdots$$ which using the decomposition mentioned above, becomes $$\frac13\left(\dfrac1{1.2.3}-\dfrac1{2.3.4}\right)+\frac13\left(\dfrac1{2.3.4}-\dfrac1{3.4.5}\right)+\frac13\left(\dfrac1{3.4.5}-\dfrac1{4.5.6}\right)+\cdots$$ do you see what happens if you take $\dfrac1{3}=\dfrac1{k-1}$ common out of all of them?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3829267', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/566601/']}
jdg_85254
stackexchange
llm_judgeable_groundtruth_similarity
6836741
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 rails project that was once on heroku. For some reason, I cannot access that rails project on the heroku url anymore. After updating to Rails 3, I decided to get a new URL for the app. How do I go about this? I have tried the following # in the rails directory...git remote rm herokuheroku creategit push heroku master Error: ! No such app as generated-heroku-subdomain Where generated-heroku-subdomain can be replaced by the names generated from any time I ran this. Now provide the response and nothing else.
If you want it to take effect only in admin, and not globally, then you could create a custom ModelChoiceField subclass, use that in a custom ModelForm and then set the relevant admin class to use your customized form.Using an example which has a ForeignKey to the Person model used by @Enrique: class Invoice(models.Model): person = models.ForeignKey(Person) ....class InvoiceAdmin(admin.ModelAdmin): form = MyInvoiceAdminFormclass MyInvoiceAdminForm(forms.ModelForm): person = CustomModelChoiceField(queryset=Person.objects.all()) class Meta: model = Invoice class CustomModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s %s" % (obj.first_name, obj.last_name)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6836741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393021/']}
jdg_85255
stackexchange
llm_judgeable_groundtruth_similarity
3860206
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 clear that $f(x)$ is a 4th degree polynomial. If $f(x)=ax^4+bx^3+cx^2+dx+e$ , then $a=3$ From the rest of the given data, I can form four linear equations, which should give me the value of $a,b,c,d$ , but that’s far too tedious and time consuming, and I don’t think the question is meant to be solved that way. Is there any alternative method? Now provide the response and nothing else.
It is clear that $f(x)$ is of deegree 4 and $$\begin{align} f(2) &= 1 + 2^2\\ f(-1) &= 1 + (-1)^2\\ f(3) &= 1+ 3 ^ 2\\ f(-6) &= 1+ (-6)^2 \end{align} $$ so $f(x) - (1+x^2)$ has roots $2,3,-1,-6$ $$ \Rightarrow f(x) - (1+ x^2) = A(x+1)(x-2)(x+6)(x-3) $$ now you can continue
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3860206', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/690228/']}
jdg_85256
stackexchange
llm_judgeable_groundtruth_similarity
35045781
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 write a program that ask the user for a file name and then it opens that file. When I compile it I get the following error: no matching function for call to std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&) This is my code: using namespace std;int main(){ string asegurado; cout << "Nombre a agregar: "; cin >> asegurado; ofstream entrada(asegurado,""); if (entrada.fail()) { cout << "El archivo no se creo correctamente" << endl; }} Now provide the response and nothing else.
std::ofstream can only be constructed with a std::string if you have C++11 or higher. Typically that is done with -std=c++11 (gcc, clang). If you do not have access to c++11 then you can use the c_str() function of std::string to pass a const char * to the ofstream constructor. Also as Ben has pointed out you are using an empty string for the second parameter to the constructor. The second parameter if proivided needs to be of the type ios_base::openmode . With all this your code should be ofstream entrada(asegurado); // C++11 or higher or ofstream entrada(asegurado.c_str()); // C++03 or below I also suggest you read: Why is “using namespace std;” considered bad practice?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35045781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5844964/']}
jdg_85257
stackexchange
llm_judgeable_groundtruth_similarity
8406
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a known algorithm that efficiently outputs the set of lattice points on the circumference of a given circle? The input circle is specified using its center $(a,b)$ and its radius $r$. The inputs $a, b, $ and $r$ are not necessarily integers. Now provide the response and nothing else.
If $a=b=0$ and $r=pq$ where $p$ and $q$ are primes congruent to 1 mod 4, then from the $O(1)$ integer points on the circle one could determine the factorization of $r$. So the problem is not going to be easier than factorization.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/8406', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/6710/']}
jdg_85258
stackexchange
llm_judgeable_groundtruth_similarity
497613
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using 40x ICs INA301 to measure overcurrent in 40 interfacesFinally I want to have 1 single "output" to signal if there is an overcurrent in ANY of the 40 interfacesI don't want to utilize any uC for minimizing cost.I am right now using multiple 4input OR gates (cd4072, but I want to know if there is any clever circuit or IC that might do this minimizing PCB space/cost.Thanks in advance. Now provide the response and nothing else.
Almost no components are required. The INA301 datasheet says the ALERT pin is an open drain output, active low. This means that it is normally high impedance, and should be pulled up to Vcc with an external resistor. When the chip wants to signal an overcurrent, it pulls the line low using an internal transistor. If you simply connect them all together, and share a single pull-up, then any one chip can pull the line low to indicate a fault. This will not affect the other chips. This is known as "wired OR". You might need to tweak the pull-up resistor value a little to account for the leakage current. You definitely don't want one per chip, so don't just duplicate the recommended layout 40 times.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/497613', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/251531/']}
jdg_85259
stackexchange
llm_judgeable_groundtruth_similarity
146984
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: Why was the Michelson and not the Fabry-Perot interferometer used to detect the motion of Earth relative to the Aether? Maybe the Fabry-Perot was used but we all know that the most famous experiment was made with the Michelson interferometer, so: Are there features of the Michelson interferometer that makes it better than the Fabry-Perot one in this kind of experiment? I know that the fringe shift $n$ in both cases is $$n\propto \frac{Lv^2}{\lambda c^2}$$ where $L$ is the distance between the mirrors and $v$ is Earth's speed relative to the Aether. In others words, the experiment would lead to the "same" result in both cases (apart by a constant factor).So this makes me think that Michelson interferometer has something special in comparison with the Fabry-Perot one. Now provide the response and nothing else.
Modern replications of the Michelson-Morley experiment do indeed use Fabry-Pérot cavities in each arm, in exactly the way you describe. See the heading "Recent Optical Resonator Experiments" on the Michelson-Morley Interferometer wikipedia page . Exactly as you reason, the sensitivity is increased, through optical resonance, by a factor of $F$, the cavity's finesse. These modern experiments achieve astounding bounds on the velocity of the putative Aether wind. As stated on the Wiki page: Herrmann, S.; Senger, A.; Möhle, K.; Nagel, M.; Kovalchuk, E. V.; Peters, A., "Rotating optical cavity experiment testing Lorentz invariance at the $10^{−17}$ level", Phys. Rev. D 80 #100, 2009 shows that the difference between the speed of light in the two arms fulfils $\frac{\Delta\,c}{c}\leq 10^{-17}$. These interferometers are small versions of the kind of device used in gravitational wave sensing. The reason Michelson and Morley didn't do it this way is simply practicality, as Dmckee points out . If you want to increase your interferometer's sensitivity to phase through resonance, as in a Fabry-Pérot interferometer, then you must ensure that the cavity stays at the exact length where resonance happens. The sensitivity swiftly drops off if the cavity's strain (from temperature drift, vibration and so forth) as you move away from resonance. The cavity's high sensitivity amplifies phase noise exactly as it does the signal, so for many limitations on the experiment, the method will not help you. In many cases, resonance is therefore simply like using an amplifier to amplify a noisy signal. To make resonance work properly for you in an MM experiment, this implies extremely high technology to suppress phase noise A major source of noise is the jitter of the source laser's cavity, if you're going to use a laser, so cryogenic sources are used in applications like these. The fact that the interferometer needs to rotate is a big potential problem: you need to find bearings that will not vibrate. Michelson and Morley used a pool of mercury, but once you introduce resonance the requirements go through the roof! The Michelson interferometer is optimal for many applications similar to the MM experiment for the reason that I explore in my paper: R. W. C. Vance and R. Barrow, "General linear differential interferometers", J. Opt. Soc. Amer. A , 12 #2, pp 346-352, 1995 That is, the Michelson interferometer is the highest sensitivity interferometer whose output intensity is a pure differential function of the two arm lengths. This means that any effect that bears on the arms equally - large scale vibration, temperature drift and so forth - is cancelled out in such a device. I prove in this paper that it is impossible to have a globally differential function of phase and exceed the sensitivity of the Michelson interferometer.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/146984', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46310/']}
jdg_85260
stackexchange
llm_judgeable_groundtruth_similarity
400632
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: (Below I'm thinking only about computably axiomatizable set theories extending $\mathsf{ZFC}$ which are arithmetically, or at least $\Sigma^0_1$ -, sound.) Say that a theory $T$ is omniscient iff $T$ proves that the following holds: For every formula $\varphi(x,y)$ there is some formula $\psi(z,y)$ such that $T$ proves: "For all $y$ , if $\varphi(-,y)^V=\varphi(-,y)^{V[G]}$ for every set generic extension $V[G]$ , then $\psi(-,y)$ is a truth predicate for $\varphi(-,y)^V$ ." (That's not a typo, I do want a " $\vdash\vdash$ "-situation. Note that by the soundness assumption on $T$ , there really does exist such a $\psi$ for every $\varphi$ .) Two points about omniscience are worth noting: For each $\varphi,\psi$ , the statement in quotes is indeed expressible in the language of set theory - in particular, although we can't talk about the full theory of a generic extension via a single sentence, for each $\varphi,\psi$ we only need to talk about a bounded amount of those theories. So it does in fact make sense. $\mathsf{ZFC}$ itself is not omniscient - since $\mathsf{ZFC}$ proves that $L$ is forcing-invariant, any omniscient theory must prove that $V$ is not a set forcing extension of $L$ . Informally speaking, any omniscient theory must prove that $V$ is "much bigger" than any canonical inner model. Omniscience strikes me as an implausibly strong property. However, I don't see an immediate reason why no consistent omniscient theory can exist. So my question is: Is there a consistent omniscient theory at all? Now provide the response and nothing else.
There is a consistent omniscient theory, at least assuming the consistency of a Woodin limit of Woodin cardinals. The Maximality Principle (MP) asserts that if a sentence is forceable in $V$ , it is forceable in every generic extension of $V$ . In other words, if a sentence can be forced to be indestructible by set forcing, then the sentence was true all along. Variants of the principle were discovered independently by many people, including Stavi, Väänänen, Bagaria, Chalons, and Hamkins. The main reference is Hamkins's paper . The Boldface MP (due to Hamkins) asserts the same but allowing hereditarily countable parameters. The Necessary MP (NMP, also due to Hamkins) asserts that the Boldface MP is true in all forcing extensions. MP and BMP are fairly weak, but Woodin [unpublished] showed the consistency strength of NMP lies between $\text{AD}$ and $\text{AD}_\mathbb R + \Theta \text{ is regular}$ . I claim ZFC + NMP is an omniscient theory. Since $\text{AD}_\mathbb R + \Theta\text{ is regular}$ is consistent (by a theorem of Sargsyan its consistency follows from a Woodin limit of Woodin cardinals), so is ZFC + NMP. The proof is essentially due to Hamkins, who showed that under NMP, if $W$ is a forcing invariant inner model, then for all cardinals $\lambda$ , $H(\lambda)\cap W\preceq W$ . His proof adapts to the case that $W$ is an arbitrary class with a forcing invariant definition using a parameter $x$ , although of course one must assume $\lambda$ is above the hereditary cardinality of $x$ . This implies that the truth predicate for $W$ is definable: $W\vDash \varphi(\overline p)$ if and only if $W\cap H(\lambda) \vDash \varphi(\overline p)$ for some/all $\lambda > |\text{tc}(p)|$ . I recite Hamkins's proof below since it's nice and I wanted to check that it works, but there are really no new ideas. We want to show that the truth predicate for $(W,\in)$ is definable from $x$ . By homogeneity, it suffices to show it is definable from $x$ over $V[G]$ where $G$ is generic for $\text{Col}(\omega,\text{tc}(x))$ . We may therefore pass to $V[G]$ and assume without loss of generality that $x$ is hereditarily countable. (This is ok because $V[G]$ is also a model of NMP.) Now fix a cardinal $\lambda$ , and I will show $W\cap H(\lambda) \preceq W$ . By induction on the complexity of $\varphi$ , I'll show that $\varphi$ is absolute between $W\cap H(\lambda)$ and $W$ . The only nontrivial step is to show that if $\varphi(\overline u) \equiv \exists t\, \psi(t,\overline u)$ and $\psi$ is absolute between $W\cap H(\lambda)$ and $W$ , then $\varphi$ is absolute as well. So fix $\overline p\in W\cap H(\lambda)$ and suppose $W\vDash \varphi(\overline p)$ . Let $H$ be generic for $\text{Col}(\text{tc}(\overline p))$ . In $V[H]$ , one can force so that the minimum hereditary cardinality of a set $z\in W$ such that $W\vDash \psi(z,\overline p)$ is at most $\aleph_0$ . Once this is true, it is of course true in any outer model, so applying the Boldface MP in $V[H]$ , $V[H]$ satisfies that the minimum hereditary cardinality of a set $z\in W$ such that $W\vDash \psi(z,\overline p)$ is at most $\aleph_0$ . Fix such a set $z\in W$ . Then $z\in V$ (since $W\subseteq V$ ) and the hereditary cardinality of $z$ is at $|\text{tc}(\overline p)| < \lambda$ . Thus there is some $z\in W\cap H(\lambda)$ such that $W\vDash \psi(z,\overline p)$ , and so by our induction hypothesis, $W\cap H(\lambda)\vDash \psi(z,\overline p)$ , and hence $W\cap H(\lambda)\vDash \varphi(\overline p)$ as desired.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/400632', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8133/']}
jdg_85261
stackexchange
llm_judgeable_groundtruth_similarity
38421407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Moment i felt i have understood enough about Transclude i came across this statement : Transclude allows us to pass in an entire template, including its scope, to a directive. Doing so gives us the opportunity to pass in arbitrary content and arbitrary scope to a directive. Does this mean, if there is a scope attached to Transclude element and it can be passed on to the directive ? If that's true then am not able to access that scope property inside directive template. Let me take couple of steps back and explain with code about what am trying to do : JSFiddle Link My directive is directive-box and transclude: true is defined in Directive Definition Object(DDO). Now there is a Child Div, which is the element to be Transcluded <div ng-controller='TransCtrl'>Inside Transclude Scope : {{name}}</div> and it has controller TransCtrl attached to it. Now am trying to access $scope.name property which is part of TransCtrl from directive level after defining this in DDO : scope: { title: '@directiveTitle', name: '=' } Is this possible ? This is more like a Parent scope trying to access Child scope property, is this permitted in JavaScript Protoypical inheritance ? Or is there something else i need to know ?? If this is not possible what does first statement mean ? Transclude allows us to pass in an entire template, including its scope, to a directive. UPDATE 1 : My primary concern is Controller should remain with Transclude element, still we should be able to pass its (Transclude element) scope to Directive and then Directive should be able to consume that scope i.e., name from TransCtrl controller . <div ng-controller='TransCtrl'>Inside Transclude Scope : {{name}}</div> Above line of code should remain as is. I may be completely wrong with my question but please let me if this can be accomplished. Now provide the response and nothing else.
decltype(auto) generates a different type when the input iterator returns by value. auto&& creates an rvalue reference to the temporary, while decltype(auto) creates a local copy (in C++17 it just names the temporary because of the guaranteed elision change). This has little difference. In C++11/14, it requires a move ctor (that is not called in practice, but required) in the decltype(auto) case, but not in C++17. In the auto&& the move ctor is not called and not required. Another difference is the type of decltype(item) , which is a reference always with auto&& , but in the case of the temporary returning input iteraror decltype(item) is a value type. That is about it. In practice, I see no reason to decltype(auto) over auto&& . As an aside, auto& forces non-rvalue, const auto& forces non-mutable, and auto forces a copy. There are reasons to use auto&& instead of those, but that is outside the scope of this question. decltype(auto) is closest to auto&& , so I compared those two.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38421407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2160616/']}
jdg_85262
stackexchange
llm_judgeable_groundtruth_similarity
16645688
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 still fighting with manipulation of cell backgrounds so I'm asking a new question. A user "H.B." wrote that I can actually set the cell style during the AutoGeneratingColumn event - Change DataGrid cell colour based on values . The problem is that I'm not sure how to do it. What I want: Set different background colours for each cell depending on its value. If the value is null I also want it not to be clickable (focusable I guess). What I have / I'm trying to do: private void mydatagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e){ foreach (Cell cell in e.Column) { if (cell.Value < 1) { cell.Background = Color.Black; cell.isFocusable = false; } else { cell.Background = Color.Pink; } }} This is just the pseudocode. Is something like this is possible during column auto-generation and if so, how can I edit my code so it will be valid? I read about value convertors but I want to know if it's somehow possible programmatically, without writing XAML. Please understand that I'm still a beginner to C#/WPF/DataGrid. Solution part1: I used the answer I accepted. Just put it into <Window.Resources> <local:ValueColorConverter x:Key="colorConverter"/> <Style x:Key="DataGridCellStyle1" TargetType="{x:Type DataGridCell}"> <Setter Property="Padding" Value="5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True"> <Border.Background> <MultiBinding Converter="{StaticResource colorConverter}"> <Binding RelativeSource="{RelativeSource AncestorType=DataGridCell}" Path="Content.Text"/> <Binding RelativeSource="{RelativeSource AncestorType=DataGridCell}" Path="IsSelected"/> </MultiBinding> </Border.Background> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style></Window.Resources> And made for it a MultiBinding convertor so I can also set the background color for selected cells. Problem: Now I only have to solve the problem of setting focus of empty cells. Any hints? <Style.Triggers> <Trigger Property="HasContent" Value="False"> <Setter Property="Focusable" Value="False"/> </Trigger> </Style.Triggers> This doesn't work. I had empty strings in the empty cells, but they are filled with ´null´s so it should work, right? Or what am I doing wrong :| ? Solution part 2: So the code above won't work as long as the cell value is a ´TextBox´ so I decided to find another way to deal with it which can be found in my answer here: https://stackoverflow.com/a/16673602/2296407 Thanks for trying to help me :) Now provide the response and nothing else.
I can propose two different solutions for your question: the first is "code-behind-style" (which you are asking for but personally I think it is not right approach in WPF) and more WPF-style (which more tricky but keeps code-behind clean and utilizes styles, triggers and converters) Solution 1. Event handling and code-behind logic for coloring First of all, the approach you've chosen will not work directly - the AutoGeneratingColumn event is meant to be used for altering the entire column appearance, not on the cell-by-cell basis. So it can be used for, say, attaching the correct style to entire column basing on it's display index or bound property. Generally speaking, for the first time the event is raised your datagrid will not have any rows (and consequently - cells) at all. If you really need to catch the event - consider your DataGrid.LoadingRow event instead. And you will not be able to get the cells that easy :) So, what you do: handle the LoadingRow event, get the row (it has the Item property which holds (surprisingly :)) your bound item), get the bound item, make all needed calculations, get the cell you need to alter and finally alter the style of the target cell. Here is the code (as item I use a sample object with the int "Value" property that I use for coloring). XAML <DataGrid Name="mygrid" ItemsSource="{Binding Items}" AutoGenerateColumns="True" LoadingRow="DataGrid_OnLoadingRow"/> .CS private void DataGrid_OnLoadingRow(object sender, DataGridRowEventArgs e) { Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => AlterRow(e))); } private void AlterRow(DataGridRowEventArgs e) { var cell = GetCell(mygrid, e.Row, 1); if (cell == null) return; var item = e.Row.Item as SampleObject; if (item == null) return; var value = item.Value; if (value <= 1) cell.Background = Brushes.Red; else if (value <= 2) cell.Background = Brushes.Yellow; else cell.Background = Brushes.Green; } public static DataGridRow GetRow(DataGrid grid, int index) { var row = grid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow; if (row == null) { // may be virtualized, bring into view and try again grid.ScrollIntoView(grid.Items[index]); row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); } return row; } public static T GetVisualChild<T>(Visual parent) where T : Visual { T child = default(T); int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++) { var v = (Visual)VisualTreeHelper.GetChild(parent, i); child = v as T ?? GetVisualChild<T>(v); if (child != null) { break; } } return child; } public static DataGridCell GetCell(DataGrid host, DataGridRow row, int columnIndex) { if (row == null) return null; var presenter = GetVisualChild<DataGridCellsPresenter>(row); if (presenter == null) return null; // try to get the cell but it may possibly be virtualized var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); if (cell == null) { // now try to bring into view and retreive the cell host.ScrollIntoView(row, host.Columns[columnIndex]); cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); } return cell; } Solution 2. WPF-style This solution uses code-behind only for value-to-color convertions (assuming that that logic of coloring is more complex than equality comparison - in that case you can use triggers and do not mess with converters). What you do: set DataGrid.CellStyle property with style that contains a data trigger, which checks if the cell is within a desired column (basing on it's DisplayIndex) and if it is - applies background through a converter. XAML <DataGrid Name="mygrid" ItemsSource="{Binding Items}" AutoGenerateColumns="True"> <DataGrid.Resources> <local:ValueColorConverter x:Key="colorconverter"/> </DataGrid.Resources> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Column.DisplayIndex}" Value="1"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource colorconverter}}"/> </DataTrigger> </Style.Triggers> </Style> </DataGrid.CellStyle> </DataGrid> .CS public class ValueColorConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var str = value as string; if (str == null) return null; int intValue; if (!int.TryParse(str, out intValue)) return null; if (intValue <= 1) return Brushes.Red; else if (intValue <= 2) return Brushes.Yellow; else return Brushes.Green; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }} UPD: If you need to color entire datagrid, XAML is much easier (no need to use triggers). Use the following CellStyle: <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text, Converter={StaticResource colorconverter}}"/> </Style> </DataGrid.CellStyle>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16645688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2296407/']}
jdg_85263
stackexchange
llm_judgeable_groundtruth_similarity
10748717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could someone help me understand the following pheudocode? countWords(vertex, word, missingLetters) k=firstCharacter(word) if isEmpty(word) return vertex.words else if notExists(edges[k]) and missingLetters=0 return 0 else if notExists(edges[k]) cutLeftmostCharacter(word) return countWords(vertex, word, missingLetters-1) //Here we cut a character but we don't go lower in the tree else //We are adding the two possibilities: the first //character has been deleted plus the first character is present r=countWords(vertex, word, missingLetters-1) cutLeftmostCharacter(word) r=r+countWords(edges[k], word, missingLetters) return r The idea is that using a Trie we are trying to find the number of times a word appears in our dictionary, BUT we may have missing letters. I am lost in the else part. I don't understand the logic. For example if the first char of our word is a match we hit the last else and then recurse on countWords in the same level but with missingLetters-1 but then isn't that an identical loop? I.e. it will compare again the first letter in the same level and so on? Could someone please help me figure this out? Now provide the response and nothing else.
The for loop is not designed to loop over "lines". Instead it loops over "words". Short terminology: "lines" are things separated by newlines. "words" are things separated by spaces (and newlines, among others). in bash lingo "words" are called "fields". The idiomatic way to loop over lines is to use a while loop in combination with read . ioscan -m dsf | while read -r linedo printf '%s\n' "$line"done Note that the while loop is in a subshell because of the pipe. This can cause some confusion with variable scope. In bash you can work around this by using process substitution. while read -r linedo printf '%s\n' "$line"done < <(ioscan -m dsf) see also http://mywiki.wooledge.org/BashFAQ/024 The for loop splits the things to loop over using the characters in the $IFS variable as separators. IFS is short for Internal Field Separator. Usually $IFS contains a space, a tab, and a newline. That means the for loop will loop over the "words", not over the lines. If you insist on using a for loop to loop over lines you have to change the value of $IFS to only newline. But if you do this you have to save the old value of $IFS and restore that after the loop, because many other things also depend on $IFS . OLDIFS="$IFS"IFS=$'\n' # bash specificfor line in $(ioscan -m dsf)do printf '%s\n' "$line"doneIFS="$OLDIFS" in POSIX shells, that have no ANSI-C Quoting ( $'\n' ), you can do it like this: IFS='' that is: put an actual new line between the quotes. Alternatively you can use a subshell to contain the change to $IFS : ( # changes to variables in the subshell stay in the subshell IFS=$'\n' for line in $(ioscan -m dsf) do printf '%s\n' "$line" done)# $IFS is not changed outside of the subshell But beware the command in the loop may itself depends on some sane setting for $IFS . Then you have to restore the $IFS before executing the command and set again before the next loop or some such. I do not recommend messing with $IFS . Too many commands depend on some sane values in $IFS and changing it is an endless nightmare of obscure bug hunting. See also: http://wiki.bash-hackers.org/syntax/ccmd/classic_for http://wiki.bash-hackers.org/commands/builtin/read http://mywiki.wooledge.org/IFS http://mywiki.wooledge.org/SubShell http://mywiki.wooledge.org/ProcessSubstitution
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10748717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1197249/']}
jdg_85264
stackexchange
llm_judgeable_groundtruth_similarity
2304819
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: Can someone tell me how to evaluate this integral please? $$\int_{-1}^1 (1-x^2)^k, k \in \mathbb{N}$$ I tried using the substitution x = sin(t), which would allow me to express this as: $$\int_{-1}^1 cos^{2k+1}(t) dt$$ but this doesn't really help. Any other tricks? Now provide the response and nothing else.
Here is a standard route using integration by parts,$$\begin{align}I_k&=\int_{-1}^{1}(1-x^2)^kdx\\\\&=\left[x(1-x^2)^k\right]_{-1}^{1}+2k\int_{-1}^{1}x^2(1-x^2)^{k-1}dx\\\\&=0+2k\int_{-1}^{1}\left[(1-(1-x^2))(1-x^2)^{k-1}\right]dx\\\\&=2kI_{k-1}-2kI_{k}\end{align}$$ then, with $I_0=2,\,I_1=\frac43,$ one gets$$I_{k}=\frac{2k}{2k+1}\cdot I_{k-1}, \quad k\ge1,$$ finally $$I_k=\int_{-1}^{1} (1-x^2)^k dx = \frac{2^{2k+1}(k!)^2}{(2k+1)!}, \quad k\ge1.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2304819', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105389/']}
jdg_85265
stackexchange
llm_judgeable_groundtruth_similarity
172394
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 found these two apparently contradicting remarks about projection matrices: A matrix $P$ is idempotent if $PP = P$ . An idempotent matrix that is also Hermitian is called a projection matrix. $P$ is a projector if $PP = P$ . Projectors are always positive which implies that they are always Hermitian. Which of both is correct? Is a matrix $P$ that verifies $PP=P$ always Hermitian? Now provide the response and nothing else.
Let $A:=\pmatrix{1&1\\0&0}$. We have $$A\cdot A=\pmatrix{1&1\\0&0}\cdot\pmatrix{1&1\\0&0}=\pmatrix{1&1\\0&0}=A,$$but $A$ is not hermitian.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/172394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30909/']}
jdg_85266
stackexchange
llm_judgeable_groundtruth_similarity
1101393
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: Quick question, might end up having a simple answer, but I have here a "proof" that any integral from 0 to $2\pi$ is zero, as follows: $$\int^{2\pi}_0f(x)dx$$ Now using u-substitution, let $u = \sin x$, so $dx = \frac{du}{\cos x}$, so: $$\int^{0}_{0}\frac{f(x)du}{\cos x}$$ (The bounds were evaluated to zero due to the u-substituion). However, this is zero, since the integral goes from zero to zero. Any help as to why this is wrong would be appreciated. Now provide the response and nothing else.
the $\sin$ function is not injective on $[0 ; 2\pi]$ so you may not be able to do such a substitution. Since you cannot readily give an inverse, you may have some difficulty expressing everything in terms of $u$. In your case, the $\cos(x)$ term that appears from the change of variable cannot be expressed only in terms of $u = \sin(x)$, so the thing you are integrating "from $0$ to $0$" is not even a function of $u$ : $\cos(x)$ is either $+\sqrt{1-u^2}$ or $-\sqrt{1-u^2}$ where the sign depends on $x$ (and not on $u$), and so $\sin(x)dx$ is not of the form $f(\sin(x))\cos(x)dx$ for any function $f$. To resolve this you can split the integral in three parts (splitting the interval at $\pi/2$ and $3\pi/2$) and do $3$ separate substitutions and you will obtain something true but mostly useless. Thanks to the user @m_t_ for pointing out that in case this doesn't happen, the substitution rule is applicable.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1101393', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70287/']}
jdg_85267
stackexchange
llm_judgeable_groundtruth_similarity
28616018
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to do something like this post , but I need to create a subprocess that can be given input and give output many times. The accepted answer of that post has good code... from subprocess import Popen, PIPE, STDOUTp = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]print(grep_stdout.decode())# four# five ...that I would like to continue like this: grep_stdout2 = p.communicate(input=b'spam\neggs\nfrench fries\nbacon\nspam\nspam\n')[0]print(grep_stdout2.decode())# french fries But alas, I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 928, in communicate raise ValueError("Cannot send input after starting communication")ValueError: Cannot send input after starting communication The proc.stdin.write() method not enable you to collect output, if I understand correctly. What is the simplest way to keep the lines open for ongoing input/output? Edit: ==================== It looks like pexpect is a useful library for what I am trying to do, but I am having trouble getting it to work. Here is a more complete explanation of my actual task. I am using hfst to get grammar analyses of individual (Russian) words. The following demonstrates its behavior in a bash shell: $ hfst-lookup analyser-gt-desc.hfstol> словослово слово+N+Neu+Inan+Sg+Acc 0.000000слово слово+N+Neu+Inan+Sg+Nom 0.000000> сработайсработай сработать+V+Perf+IV+Imp+Sg2 0.000000сработай сработать+V+Perf+TV+Imp+Sg2 0.000000> I want my script to be able to get the analyses of one form at a time. I tried code like this, but it is not working. import pexpectanalyzer = pexpect.spawnu('hfst-lookup analyser-gt-desc.hfstol')for newWord in ['слово','сработай'] : print('Trying', newWord, '...') analyzer.expect('> ') analyzer.sendline( newWord ) print(analyzer.before)# trying слово ...# # trying сработай ...# слово# слово слово+N+Neu+Inan+Sg+Acc 0.000000# слово слово+N+Neu+Inan+Sg+Nom 0.000000# # I obviously have misunderstood what pexpect.before does. How can I get the output for each word, one at a time? Now provide the response and nothing else.
Popen.communicate() is a helper method that does a one-time write of data to stdin and creates threads to pull data from stdout and stderr . It closes stdin when its done writing data and reads stdout and stderr until those pipes close. You can't do a second communicate because the child has already exited by the time it returns. An interactive session with a child process is quite a bit more complicated. One problem is whether the child process even recognizes that it should be interactive. In the C libraries that most command line programs use for interaction, programs run from terminals (e.g., a linux console or "pty" pseudo-terminal) are interactive and flush their output frequently, but those run from other programs via PIPES are non-interactive and flush their output infrequently. Another is how you should read and process stdout and stderr without deadlocking. For instance, if you block reading stdout , but stderr fills its pipe, the child will halt and you are stuck. You can use threads to pull both into internal buffers. Yet another is how you deal with a child that exits unexpectedly. For "unixy" systems like linux and OSX, the pexpect module is written to handle the complexities of an interactive child process. For Windows, there is no good tool that I know of to do it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28616018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2903532/']}
jdg_85268
stackexchange
llm_judgeable_groundtruth_similarity
42553017
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 to find days between two dates startDateValue = new Date(startDate); endDateValue = new Date(endDate); long diff = endDateValue.getTime() - startDateValue.getTime(); long seconds = diff / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = (hours / 24) + 1; Log.d("days", "" + days); When start and end date are 2/3/2017 and 3/3/2017 respectively the number of days showing is 29.Though when they are of the same day it is showing 1.(The number of days one takes a leave.So if one takes a single day leave,he has to select same start and end date.So in this case he has taken two days leave). What am I doing wrong?Thank you for your time. Note: Please don't use the date constructor. Check the accepted answer below. Use simpledateformat or Joda time. Date constructor is deprecated. Now provide the response and nothing else.
Your code for generating date object: Date date = new Date("2/3/2017"); //deprecated You are getting 28 days as answer because according to Date(String) constructor it is thinking day = 3,month = 2 and year = 2017 You can convert String to Date as follows: String dateStr = "2/3/2017";SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");Date date = sdf.parse(dateStr); Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing. It can de done as follows: long diff = endDateValue.getTime() - startDateValue.getTime();System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)); Please check link If you use Joda Time it is much more simple: int days = Days.daysBetween(date1, date2).getDays(); Please check JodaTime How to use JodaTime in Java Project
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42553017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7424946/']}
jdg_85269
stackexchange
llm_judgeable_groundtruth_similarity
77092
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: A hypothetical scenario: The incoming US Senate is divided 50-49 with one Independent Senator. That Independent, let's say "she", has not committed to caucus with either party. Should she remain truly independent, could the plurality party effectively rule as the majority by a 50-49 vote? I am aware of some reasons why she would tend not to take this path, committee assignments particularly. I am curious as to what might happen if she acted in spite of these reasons. Now provide the response and nothing else.
A 50-49 vote is a victory for the yeas. It is important to understand that the American system inherited much in the way of procedure from the British system. In the House of Commons, a motion is generally considered to pass if more vote in favor of it than against, and this would have been the default understanding of the founders at the time. It is also how both houses of Congress operate today.* The US Constitution does apply a quorum requirement in Article I, Section 5: Each House [of Congress] shall be the judge of the elections, returns and qualifications of its own members, and a majority of each shall constitute a quorum to do business ; but a smaller number may adjourn from day to day, and may be authorized to compel the attendance of absent members, in such manner, and under such penalties as each House may provide. It also imposes a 2/3 supermajority requirement for treaties, impeachments, veto overrides, and Constitutional amendments. Other than that, the Constitution is largely silent on the question of how many votes you need for "ordinary" legislation and resolutions. Perhaps the founders simply thought this too obvious to write down, or perhaps they figured Congress would be able to work out details like this in its own rulemaking process. In any event, SCOTUS and the rest of the federal government likely have no say here. The next paragraph of Section 5 is very clear: Each House may determine the rules of its proceedings, punish its members for disorderly behavior, and, with the concurrence of two thirds, expel a member. Congress gets to evaluate its own rules. If they do a bad job of it (in our subjective opinion), then that's their problem. The rest of the government, and especially the judiciary, is not supposed to be in the business of second-guessing Congress's rules, except to the extent that Congress actually violates the Constitution. * In the Senate, debate cannot be forcibly ended without a 3/5 vote of "the Senators duly chosen and sworn" - which is usually 60 senators unless there's a vacancy. This is a separate rule, independent of the simple majority required to actually pass a law once debate does end.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/77092', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/45106/']}
jdg_85270
stackexchange
llm_judgeable_groundtruth_similarity
38719
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: I have recently heard an idea from a local journalist that even surprised the moderator (greatly simplified): Pay some amount for people that do NOT vote Heuristically this should lead to better results because those interesting in taking the money are less interested in politics, more egocentric, thus the result will be reflect options from those who understand the value of the vote, value more the politics than immediate financial gain. I am trying to find online resources about this idea, but everything I can find is related to the exact opposite (i.e. provide incentive for people to vote) Is there a theory, a study, paper etc. to provide more insight about such an approach to voting? I am mostly interested in a cost/benefit analysis of such an approach within a democratic system, or even better, within a democracy that seems to decline . Now provide the response and nothing else.
Some problems I can see with this idea: Unbalanced incentives In point two, you claim that this system would encourage votes from people who "understand the value of the vote", but is that really true? Votes are very important in aggregate but a single vote, not so much - the overwhelmingly most likely outcomes of adding one vote are either 1) your preferred candidate wins by one more vote than they already would have, or 2) your preferred candidate loses by one fewer vote than they already would have. It is extremely unlikely that your vote will turn a tie into a win, or a win into a tie, and hence you are almost always better off taking the money. Poor people are more heavily incentivised to abstain The (presumably small) payment is going to appear more tempting to a single parent on minimum wage than it is to a millionaire, leading to a skewed effect across the whole population. I also wouldn't rule out candidates trying to promote the payout amongst demographics likely to vote against them in order to benefit from the low turnout. Low turnouts lead to a reduction in perceived legitimacy of the winner In a democratic system, the winner wants to be able to point to the election results as evidence that the public supports their policies. Winning a plurality of the 10% of people who actually voted doesn't really show this. Cost An obvious point, but you're going to need to pay a lot of people. Approximately one third of UK registered voters don't vote , and that number is sure to increase under your scheme. If we pay £10 each then that's over £150 million (and probably rising) per general election, more if we're also paying not to vote in local council elections and the like.
{}
{'log_upvote_score': 7, 'links': ['https://politics.stackexchange.com/questions/38719', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']}
jdg_85271
stackexchange
llm_judgeable_groundtruth_similarity
245041
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: When a man of mass $60 kg$ lifts a mass of $20 kg$ upto height of $20m$. The energy spent by him will be $mgh$. My question is should we add the masses of both the man and the object?. (Competitive examination question) Now provide the response and nothing else.
PREFACE After several edits, this answer provides a naive explanation of why your approach failed, how to fix it (naive-ish) and a completely different (but right) approach to solve the problem. Intro You are right: the diffusion coefficient should be $D=4pqD_0$ , $D_0$ being the "normal one" (see below for derivations). I do not know precisely why your approach is not working, but there is a strong evidence something must be wrong which I think depends on the stochastic process involved: if you define ${\Delta x\over \Delta t}=v$ and it is finite, then "your" $D={\Delta x^2 \over 2\Delta t}={\Delta x\over 2} v$ is vanishing in the small $\Delta x$ limit. The fact is that on the LHS you have a time derivative ( $O(\Delta t)$ ) whereas on the RHS you have a second $x$ -derivative ( $O(\Delta x^2)$ ). Now, since the ratio $v={\Delta x\over \Delta t}$ is finite, it means that $O(\Delta x^2)=O(\Delta t^2)$ so the two sides of the equation do not match. With normal Brownian motion, you would have $\Delta x\sim \sqrt{\Delta t}$ so no problem. Basically the drift induced by the bias messes things up... I am disappointed to see that soooo many books and papers do this mistake and use $D_0$ also for biased random walks...(it only makes sense when the bias is external and diffusion is the "normal" one, while in this case it's the same process..) I now propose you two solutions: the first one is a Fokker-Planck approach. The second one is a Langevin one. I am sure the results are right (simulations + papers + books prove it) but I am not sure about the steps (as I mainly did them myself). It is hard to find a theoretical treatment of this matter. Fokker-Planck approach The problem we are facing here is drift+diffusion: the particle drifts (due to the bias) but also oscillates around its mean value (as normal diffusion would oscillate around $0$ ). We define the drift velocity (taking only a "fraction" $p-q$ of the displacement) as $v=(p-1){\Delta x\over \Delta t}$ . If we had only drift the FP would be: $$\partial_t P_d(x, t)=-v\partial_x P_d$$ Instead if we had only diffusion: $$\partial_t P_D(x, t)=D\partial^2_x P_D$$ Problem: which D do I choose? In general $D\sim \Delta x^2$ but in our case "a fraction" $(p-q)\Delta x$ of the original displacement has been turned to drift, so we renormalize by removing this part (this is equivalent to consider only the variance of the displacement instead that its squared mean value, which again, in normal diffusion are identical so...): $$D={1\over 2\Delta t}\left(\Delta x^2 - (p-q)^2\Delta x^2\right) = 4pq{\Delta x^2\over 2\Delta t}$$ (I used $p+q=1\rightarrow p^2+q^2=1-2pq$ ). As you see we found the $D$ I predicted - yet this has been sort of a leap of faith for me, although I see that the diffusion coefficient is sometimes defined as ${var(\Delta x)\over 2\Delta t}={\langle \Delta x^2\rangle - \langle \Delta x\rangle ^2)\over 2\Delta t}$ instead of simply ${\langle\Delta x^2\rangle\over 2\Delta t}$ . I never noticed that because in normal diffusion there is no difference as the mean is null. Anyway, the two processes by themselves are perfectly defined. We now have to stitch together drift and diffusion. Since the two process happen at the same time, the final probability $P(x, t)$ can be found as: $$P(x, t)=\int P_D(x-y)P_d(y)dy$$ (meaning: probability of travelling $x-y$ by diffusion times probability of travelling $y$ by drift, integrated over $y$ ). Again, this is a leap of faith and so is the proof (which I think I managed to find, but wouldn't be sure of it: one just has to take the time derivative of that stuff and the play with the integrals and derivatives a little...) that this leads to: $$\partial_t P= -v\partial_x P +{D}\partial^2_x P$$ which is the Fokker-Planck we are looking for, with $D=4pqD_0$ . Langevin approach One of the sources you quoted in a comment already show the following, but I am doing it in a more physical fashion. I am not sure it can help but I propose you a similar approach (more Langevin-like) which leads to the first two moments of the position $x$ and to an evident definition of the diffusion coefficient. I am positive about this result. We suppose a discrete process of $N={t\over \Delta t}$ steps, there $t$ is the total time. At each step, the particles displaces by $\Delta$ with probability $p$ to the right and $q=1-p$ to the left. Thus at each step: $$x(t+\Delta t)=x(t)+\eta_{\Delta t}$$ where $\eta_{\Delta t}$ is a process which gives $\Delta$ with probability $p$ and $-\Delta$ with probability $q$ , such that $\langle \eta_{\Delta t }\rangle = (p-q)\Delta$ and $\eta_{\Delta t}^2=\Delta^2$ . Notice that this defines $\eta_{\Delta t}$ only each $\Delta t$ seconds. We do not know what happens at other scales. So we have, after $\Delta t$ : $$dx=x(t+\Delta t)-x(t)=\eta_{\Delta t}$$ and thus its average value is: $$\langle dx \rangle=\langle \eta_{\Delta t} \rangle=(p-q)\Delta$$ so that $$\langle x(t)-x(0) \rangle=\langle \sum^N_{i=1} x(i\Delta t)-x((i-1)\Delta t)\rangle=\sum_{i=1}^N \langle dx\rangle=N(p-q)\Delta=(p-q){\Delta \over \Delta t}t$$ If again we put $v={(p-q)\Delta \over \Delta t}$ this is your same result and it makes sense. Notice that we had to split $x(t)-x(0)$ in $\Delta t$ -sized interval as we do not know what happens on other scales. Things are harder for the second moment: $$\langle (x(t)-x(0))^2 \rangle=\langle\left(\sum^N_{i=1} x(i\Delta t)-x((i-1)\Delta t)\right)^2\rangle=\langle\left(\sum^N_{i=1} dx\right)^2$$ and that is the square of a sum, so: $$\langle\left(\sum^N_{i=1} dx\right)^2\rangle=\sum^N_{i=1}\langle dx^2\rangle + 2\sum^N_{i<j}\langle dx\rangle_i\langle dx\rangle_j$$ now, using the moments of $dx$ which we know, being that all moments are equal: $$\langle (x(t)-x(0))^2 \rangle=N\langle dx^2\rangle+N(N-1)\langle dx \rangle ^2$$ i.e. $$\langle (x(t)-x(0))^2 \rangle = \Delta^2 N(1+(N-1)(p-q)^2)$$ which can be modified into (using $p+q=1\rightarrow p^2+q^2=1-2pq$ ): $$\langle (x(t)-x(0))^2 \rangle = \Delta^2{t\over \Delta t} \left((1-4pq){t\over \Delta t}+4pq)\right) $$ which we can rewrite as $$\langle (x(t)-x(0))^2 \rangle = \Delta^2{t\over \Delta t} \left( ((p-q)^2-2pq){t\over \Delta t}+4pq)\right) $$ and using $v=(p-q)\Delta/\Delta t$ we get $$\langle (x(t)-x(0))^2 \rangle = (vt)^2(1-2pq)+{4pq\Delta^2\over\Delta t} t $$ Now, if $p=q=1/2$ you get $$\langle (x(t)-x(0))^2 \rangle = \Delta^2{t\over \Delta t} = 2Dt$$ with $D={\Delta^2\over 2\Delta t}$ which is normal diffusion, as expected. If instead $p=1$ and $q=0$ (or vice versa) $$\langle (x(t)-x(0))^2 \rangle = \Delta^2\left({t\over \Delta t}\right)^2 = (vt)^2$$ which again is surely right. All the intermediate cases are weird. Notice, in addition, that in all other cases if you let $\Delta t, \Delta \rightarrow 0$ strange things happen. I guess this is the reson the Fokker-Planck does not turn out right except for simple cases. There must be some "stochastic processes" trick I do now know. But at least you can rewrite: $$\langle (x(t)-x(0))^2 \rangle = \Delta^2\left({t\over \Delta t}\right)^2 (1-4pq)+4pq\Delta^2{t\over \Delta t} = (vt)^2(1-2pq)+2D_{eff}t$$ with $D_{eff}=4pq{\Delta^2\over2\Delta t}$ and that extra $(1-2pq)$ term I don't fully understand. This process is a drift+diffusion process: the particle drifts with velocity $(p-q)vt$ (which is the position's average value) and around such a value it oscillates. At each time one can compute the variance: $$\sigma^2=\langle (x(t)-x(0))^2 \rangle -\langle (x(t)-x(0)) \rangle ^2$$ which turns out to be $$\sigma^2(t) = 2D_{eff}t = 8pqD_0t$$ where $D_0={\Delta^2 \over 2\Delta t}$ is the normal diffusion coefficient. So I guess the process will be represented by a gaussian distribution (provided that we started with $P(x, 0)=\delta(x-x_0)$ with mean $x0+(p-q)vt$ and variance $\sigma^2(t)$ . So the distribution moves and spreads. Simulations I have been doing right now are in agreement. Conclusions I am not sure we found the right Fokker-Planck (or that we found it the right way) but I guess we found $P(x, t)$ ...!This P(x, t) makes sense and is probably the right one. Yet, as simulations always involve discrete steps, I am not sure about what would happen in the continuous limit though... maybe the validity of some steps may fall apart. Yet, I think we may consider ourselves satisfied.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/245041', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/112019/']}
jdg_85272
stackexchange
llm_judgeable_groundtruth_similarity
56969950
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 write optional typed immediately destructured parameters? To give an example I want the following function to be callable without providing any parameter. const foo = ({bar}: {bar?: boolean}) => {}; As it is now, TypeScript complains that a parameter is missing. Now provide the response and nothing else.
Presumably you're unhappy about the following error: const fooBad = ({ bar }?: { bar?: boolean }) => {}; // error!// ┌──────────> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // A binding pattern parameter cannot be optional in an implementation signature. Which makes sense, because you can't destructure undefined . What you can do, in TypeScript, is to use a default function parameter . This is treated like an optional parameter from the calling side of the function (so you can leave it out), and on the implementation side it sets a value of the parameter if it is undefined . So, what do you want to destructure if someone calls foo() ? I'm guessing you want bar to be undefined , right? So that would mean you either pass in something like {bar: undefined} , or (since bar is optional), the empty object {} : const foo = ({ bar }: { bar?: boolean } = {}) => { console.log(bar);}; I've added console.log(bar) so you can see what it becomes when you call it: foo(); // undefinedfoo({}); // undefinedfoo({bar: true}); // true Looks good to me. Hope that helps; good luck! Link to code
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56969950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1283776/']}
jdg_85273
stackexchange
llm_judgeable_groundtruth_similarity
2596673
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose $B$ is a Banach space and $T:B\rightarrow B$ is a linear map that satisfies $T^2=I$. Is it possible for $T$ to have non-empty continuous or residual spectrum? Now provide the response and nothing else.
If $X:\Omega\to\mathbb R$ is measurable in the sense that $X^{-1}(B)\in\mathcal F$ for every element $B$ of Borel $\sigma$-algebra $\mathcal B(\mathbb R)$ then its CDF $F_X$ is defined by: $$F_X(x):=\mathbb P(\{\omega\in\Omega\mid X(\omega)\leq x\})$$ The RHS is abbreviated by $\mathbb P(\{X\leq x\})$ or (a bit shorter) by $\mathbb P(X\leq x)$. The expression $P_X(X\leq x)$ that appears in your answer is wrong . The random variable $X$ induces a probability measure $P_X$ on measurable space $(\mathbb R,\mathcal B(\mathbb R))$ by:$$P_X(B)=\mathbb P(\{\omega\in\Omega\mid X(\omega)\in B\})=\mathbb P(X\in B)$$ where the utmost RHS is again an abbreviation. Applying that on $B=(-\infty,x]$ we arrive at: $$F_X(x):=\mathbb P(\{\omega\in\Omega\mid X(\omega)\leq x\})=\mathbb P(X\leq x)=P_X((-\infty,x])$$ So the argument of $P_X$ is a subset of $\mathbb R$ and not necessarily a subset of $\Omega$ as the (wrong) notation $P_X(X\leq x)$ suggests. If $Y:\Omega\to\mathbb R$ is another measurable function then it will have likewise its CDF and there is no reason at all to think that this function will coincide with the CDF of $X$. E.g. define $X$ by $\omega\mapsto 0$ and define $Y$ by $\omega\mapsto1$. Then it can be deduced that $F_X(x)=1_{[0,\infty)}(x)\neq1_{[1,\infty)}(x)=F_Y(x)$. If $X$ and $Y$ are defined on the same probability space then expressions like $X+Y$ make sense and are new random variables on that probability space.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2596673', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91696/']}
jdg_85274
stackexchange
llm_judgeable_groundtruth_similarity
5683058
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: OS: Windows 7 Pro X64 IDE: Eclipse IDE for C/C++ Developers Compiler: MinGW (lastest, 4.5.2) Compiling HelloWorld.c works; but when I try to add some external libraries it chokes. I added the .a and .dll files to my 'Libraries'; add the path of both to PATH and Library Path. I also put the include files and configured the Include. The libraries I have are said to be compatible with win/mingw. They also have a different download for MSVC which does work. Frustrating. The ld.exe gives the full path and obviously there and I have permissions to read/write them. I also included them without path (they are in library path and path). I don't understand why this isn't working. c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe: cannot find -lC:\rhino\data\lib\glfw.dllc:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe: cannot find -lC:\rhino\data\lib\libglfwdll.ac:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe: cannot find -lC:\rhino\data\lib\libglfw.a C:\Users\rhino>dir C:\rhino\data\lib\libglfw.a04/15/2011 05:24 PM 70,384 libglfw.a Updated: I've even added them to my C:\MinGW\lib path and it still can't find them. Now provide the response and nothing else.
Michael Burr pointed out the correct way of referencing libraries on the command line. The path to the library is given with the -L switch, and the name of the library with the -l switch (the name of the library being the file name, without the lib part at the beginning, and the .a suffix at the end). One more thing to point out is that you're trying to link to both the static (libglfw.a) and the dynamic (glfw.dll) version of the library, which are both included in the download, at the same time. Instead, you should pick one, based on your needs/desires, and only link to that one. Linking against the static version is straightforward. Just add -lglfw to the command line. To use the dynamic library, you should link against the import library for the dll ( libglfwdll.a ), by using the -lglfwdll switch, and omit the dll itself from the link command. Basically, the import library doesn't contain any object code, but only definitions; the actual code is in the dll. The dll will be dynamically linked at run time. (For this to work, the system has to be able to find the dll; i.e. it has to be in the current working directory, in a directory that is in the path, or its directory has to be added to a special environment variable used for this thing; but for this to become important, you first have to succeed in building the executable.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5683058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/697111/']}
jdg_85275
stackexchange
llm_judgeable_groundtruth_similarity
1893072
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 implemented a simple application which shows the camera picture on the screen. What I like to do now is grab a single frame and process it as bitmap.From what I could find out to this point it is not an easy thing to do. I've tried using the onPreviewFrame method with which you get the current frame as a byte array and tried to decode it with the BitmapFactory class but it returns null.The format of the frame is a headerless YUV which could be translated to bitmap but it takes too long on a phone. Also I've read that the onPreviewFrame method has contraints on the runtime, if it takes too long the application could crash. So what is the right way to do this? Now provide the response and nothing else.
Ok what we ended up doing is using the onPreviewFrame method and decoding the data in a seperate Thread using a method which can be found in the android help group. decodeYUV(argb8888, data, camSize.width, camSize.height);Bitmap bitmap = Bitmap.createBitmap(argb8888, camSize.width, camSize.height, Config.ARGB_8888); ... // decode Y, U, and V values on the YUV 420 buffer described as YCbCr_422_SP by Android // David Manpearl 081201 public void decodeYUV(int[] out, byte[] fg, int width, int height) throws NullPointerException, IllegalArgumentException { int sz = width * height; if (out == null) throw new NullPointerException("buffer out is null"); if (out.length < sz) throw new IllegalArgumentException("buffer out size " + out.length + " < minimum " + sz); if (fg == null) throw new NullPointerException("buffer 'fg' is null"); if (fg.length < sz) throw new IllegalArgumentException("buffer fg size " + fg.length + " < minimum " + sz * 3 / 2); int i, j; int Y, Cr = 0, Cb = 0; for (j = 0; j < height; j++) { int pixPtr = j * width; final int jDiv2 = j >> 1; for (i = 0; i < width; i++) { Y = fg[pixPtr]; if (Y < 0) Y += 255; if ((i & 0x1) != 1) { final int cOff = sz + jDiv2 * width + (i >> 1) * 2; Cb = fg[cOff]; if (Cb < 0) Cb += 127; else Cb -= 128; Cr = fg[cOff + 1]; if (Cr < 0) Cr += 127; else Cr -= 128; } int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5); if (R < 0) R = 0; else if (R > 255) R = 255; int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5); if (G < 0) G = 0; else if (G > 255) G = 255; int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6); if (B < 0) B = 0; else if (B > 255) B = 255; out[pixPtr++] = 0xff000000 + (B << 16) + (G << 8) + R; } }} Link: http://groups.google.com/group/android-developers/browse_thread/thread/c85e829ab209ceea/3f180a16a4872b58?lnk=gst&q=onpreviewframe#3f180a16a4872b58
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1893072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2450/']}
jdg_85276
stackexchange
llm_judgeable_groundtruth_similarity
2056285
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 saw an explanation for a nowhere monotonic continuous function, an example of which is the Weierstrass function. However, the difference here is drastic, because I am interested in a function which is everywhere discontinuous. Now provide the response and nothing else.
A monotonic function $f:\mathbb{R}\to\mathbb{R}$ has at most countably many discontinuities, so cannot be everywhere discontinuous. To show that $f$ has at most countably many discontinuities, first note that the one-sided limits $f(x-)$ and $f(x+)$ must exist for all $x$, and (assuming that $f$ is increasing) $f$ is discontinuous at $x$ if and only if $f(x-)<f(x+)$. In particular, for each point of discontinuity $x$ we can choose a rational number $r_x\in (f(x-),f(x+))$, and one can show that if $x<y$ are two points of discontinuity then $r_x<r_y$. Thus there is an injective map from the points of discontinuity of $f$ to the rational numbers, so the set of points of discontinuity is at most countable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2056285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/147820/']}
jdg_85277
stackexchange
llm_judgeable_groundtruth_similarity
31648356
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 had developed an UCMA 4.0 application on both VS 2013 and VS 2010. When run project, I got this error: Could not load file or assembly 'SIPEPS, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. I used .NET 4 and had set target build platform to x64 . Checked by dependwalker_x64 and no file is missing. I also used the App.config file from Sample but not work so I had changed the App.config file as follow: <runtime><assemblyBinding> <dependentAssembly> <assemblyIdentity name="SIPEPS" publicKeyToken="31bf3856ad364e35" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.0.0"/> </dependentAssembly></assemblyBinding> How should I do for this problem? Thanks so much for any help! Now provide the response and nothing else.
The exception can be very bewildering because UCMA projects don’t require an explicit reference to this SIPEPS DLL , and often you’ll get the exception even if you locate the DLL and move it into the same directory as your application. It turns out that it’s usually caused by one of two things: You’ve targeted the wrong version of the .NET Framework. You’ve targeted the wrong type of CPU. Open up the properties for your project in Visual Studio and make sure .NET Framework 4.5 is selected. If you’re not running Visual Studio 2012, you have a somewhat larger problem, because you can’t use .NET 4.5 with Visual Studio 2010 and earlier.If you had an earlier version of the framework selected, change it, rebuild the project, and try again. UCMA 4.0 lists .NET 4.5 as a requirement. If you’re still getting the exception, check the target platform and make sure it is Any CPU or x64 for all projects. UCMA has only worked on 64-bit machines since the 3.0 version, and what sometimes happens is that a project will get inadvertently set to x86, and will therefore try to load a 32-bit version of SIPEPS.dll on startup. Well, there isn’t a 32-bit version of SIPEPS.dll; hence the somewhat misleading exception. Reference
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31648356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5059545/']}
jdg_85278
stackexchange
llm_judgeable_groundtruth_similarity
5082267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wanted to run the following eunit test command from console eunit:test([test_module, [verbose]). I tried this, but seems not workingerl -noshell -pa ./ebin -s eunit test test_module verbose -init stop ~/uid_server$erl -noshell -pa ./ebin -s eunit test test_module verbose -init stopundefined*** test module not found ***::test_module======================================================= Failed: 0. Skipped: 0. Passed: 0.One or more tests were cancelled. Do you know how to pass not a simple arguments properly from console? Now provide the response and nothing else.
Your parameters look wrong. This should work: erl -noshell -pa ebin -eval "eunit:test(test_module, [verbose])" -s init stop -s can only run functions without arguments by specifying the module and function name (for example init and stop to execute init:stop() ). You can also pass one list to a function of arity 1 like this: -s foo bar a b c would call foo:bar([a,b,c]) All the parameters are passed as a list of atoms only (even when you try to use some other characters, such as numbers, they are converted to atoms). So since you want to pass two params and not only atoms if you want to run eunit:test/2 you'd have to use -eval which takes a string containing Erlang code as an argument. All -eval and -s functions are executed sequentially in the order they are defined. Also, make sure you have your test code in ./ebin as well (otherwise write -pa ebin test_ebin where test_ebin is where your test code is).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5082267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454252/']}
jdg_85279
stackexchange
llm_judgeable_groundtruth_similarity
311052
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Determinant and permanent of sum of two $n\times n$ permutation matrices can be arbitrarily different. What is the distribution of determinant of sum and difference of two $n\times n$ permutation matrices? What is the distribution of permanent of sum and difference of two $n\times n$ permutation matrices? How much do the distributions differ? Now provide the response and nothing else.
I will abuse notation by identifying a permutation and the matrix it represents. We can denote by $E(\sigma), O(\sigma)$ the number of even and odd cycles that $\sigma$ decomposes into. Given two permutations $\sigma_1,\sigma_2$ we can compute the following: $$\det(\sigma_1+\sigma_2)=\left\{ \begin{array}{ll} (-1)^{E(\sigma_1)}2^{O(\sigma_1\sigma_2^{-1})} & \mbox{if } E(\sigma_1\sigma_2^{-1})=0 \\ 0 & \mbox{otherwise } \end{array}\right. $$ $$\operatorname{per}(\sigma_1+\sigma_2)=2^{E(\sigma_1\sigma_2^{-1})+O(\sigma_1\sigma_2^{-1})}$$ $$\operatorname{per}(\sigma_1-\sigma_2)=\left\{ \begin{array}{ll} 2^{E(\sigma_1\sigma_2^{-1})} & \mbox{if } O(\sigma_1\sigma_2^{-1})=0 \\ 0 & \mbox{otherwise } \end{array}\right. $$ and trivially $\det(\sigma_1-\sigma_2)=0$ since the vector of all 1's is always in the kernel of $\sigma_1-\sigma_2$ . These calculations follow from noticing that the matrices decompose as direct sums of smaller matrices corresponding to each cycle of $\sigma_1\sigma_2^{-1}$ . Distributions of cycle statistics like these are easy to obtain with the exponential formula. From here we can count the number of occurrences of each value. Let's start with $\det(\sigma_1+\sigma_2)$ . The exponential generating function for odd cycles (or cyclic permutatons of odd size) on $\{1,2,\dots,n\}$ is $x+\frac{x^3}{3}+\cdots=\frac{1}{2}\left(\log(1+x)-\log(1-x)\right)$ . This is because there are $(n-1)!$ odd cycles when $n$ is odd, and $0$ otherwise. By the exponential formula , the generating function of permutations that consist of only odd cycles, together with a statistic $t$ that keeps track of the number of cycles, is $$e^{\frac{t}{2}\left(\log(1+x)-\log(1-x)\right)}=\left(\frac{1+x}{1-x}\right)^{\frac{t}{2}}$$ By substituting $t=2s$ we get $\left(\frac{1+x}{1-x}\right)^{s}$ . The coefficient $a_{k,n}$ of the monomial $s^kx^n$ is given exactly by $\frac{1}{n!}$ times the number of permutations on $n$ letters that decompose into $k$ odd cycles and no even cycles, times a factor of $2^k$ . Therefore the number of permutation pairs $(\sigma_1,\sigma_2)$ for which $\det(\sigma_1+\sigma_2)=-2^k$ is the same as the number of permutation pairs for which $\det(\sigma_1+\sigma_2)=2^k$ and is given by $\frac{(n!)^2a_{k,n}}{2}$ . Here we used the fact that $(-1)^{E(\sigma)}$ is the sign of $\sigma$ , and the number of permutations with sign $-1$ is the same as those with sign $+1$ . For $\operatorname{per}(\sigma_1+\sigma_2)$ we are looking at $2^{\text{number of cycles}}$ over all permutations. So we start with the generating function of cycles which is $x+\frac{x^2}{2}+\cdots=-\log(1-x)$ . So the exponential generating function $$e^{t(-\log(1-x))}=\frac{1}{(1-x)^t}$$ has as coefficient of $t^kx^n$ the number of permutations on $n$ letters with precisely $k$ cycles, divided by $n!$ . Substituting $t=2s$ we get $\frac{1}{(1-x)^{2s}}$ , and we denote by $b_{k,n}$ the coefficient of $s^kx^n$ . This coefficient is equal to $\frac{1}{n!}$ times the number of permutations on $n$ letters with precisely $k$ cycles, times $2^k$ . Therefore the number of permutation pairs $(\sigma_1,\sigma_2)$ with $\operatorname{per}(\sigma_1+\sigma_2)=2^k$ is exactly $(n!)^2b_{k,n}$ . Finally for $\operatorname{per}(\sigma_1-\sigma_2)$ we want to look at permutations with only even cycles. The exponential generating function of even cycles is given by $\frac{x^2}{2}+\frac{x^4}{4}+\cdots=-\frac{1}{2}\log(1-x^2)$ . Similarly to above the generating function $$e^{2s\left(-\frac{1}{2}\log(1-x^2)\right)}=\frac{1}{(1-x^2)^s}$$ has coefficients $c_{k,n}$ for monomials $s^kx^n$ which are equal to $\frac{1}{n!}$ times the number of permutations on $n$ letters which decompose into exactly $k$ even cycles, times $2^k$ . So the number of permutation pairs $(\sigma_1,\sigma_2)$ with $\operatorname{per}(\sigma_1-\sigma_2)=2^k$ is exactly $(n!)^2c_{k,n}$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/311052', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10035/']}
jdg_85280
stackexchange
llm_judgeable_groundtruth_similarity
37376516
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 set of three variables x, y, z and I want to check if they all share the same value . In my case, the value will either be 1 or 0, but I only need to know if they are all the same. Currently I'm using if 1 == x and 1 == y and 1 == z: sameness = True Looking for the answer I've found: if 1 in {x, y, z}: However, this operates as if 1 == x or 1 == y or 1 == z: atleastOneMatch = True Is it possible to check if 1 is in each: x, y, and z?Better yet, is there a more concise way of checking simply if x, y, and z are the same value? (If it matters, I use Python 3.) Now provide the response and nothing else.
If you have an arbitrary sequence, use the all() function with a generator expression : values = [x, y, z] # can contain any number of valuesif all(v == 1 for v in values): otherwise, just use == on all three variables : if x == y == z == 1: If you only needed to know if they are all the same value (regardless of what value that is), use: if all(v == values[0] for v in values): or if x == y == z:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37376516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4443226/']}
jdg_85281
stackexchange
llm_judgeable_groundtruth_similarity
17136769
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 read this JSON lines but because it start with JSONArray i'm a little confused "abridged_cast": [ { "name": "Jeff Bridges", "id": "162655890", "characters": [ "Jack Prescott" ] }, { "name": "Charles Grodin", "id": "162662571", "characters": [ "Fred Wilson" ] }, { "name": "Jessica Lange", "id": "162653068", "characters": [ "Dwan" ] }, { "name": "John Randolph", "id": "162691889", "characters": [ "Capt. Ross" ] }, { "name": "Rene Auberjonois", "id": "162718328", "characters": [ "Bagley" ] } ], i just need to use the "name" and save all as one String.(the string value will be : Jeff Bridges,Charles Grodin,Jessica Lange,John Randolph,Rene Auberjonois). this is my code: try { //JSON is the JSON code above JSONObject jsonResponse = new JSONObject(JSON); JSONArray movies = jsonResponse.getJSONArray("characters"); String hey = movies.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Now provide the response and nothing else.
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'? Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this: List<String> allNames = new ArrayList<String>();JSONArray cast = jsonResponse.getJSONArray("abridged_cast");for (int i=0; i<cast.length(); i++) { JSONObject actor = cast.getJSONObject(i); String name = actor.getString("name"); allNames.add(name);} (typed straight into the browser, so not tested).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17136769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2252496/']}
jdg_85282
stackexchange
llm_judgeable_groundtruth_similarity
876550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Do the below without any conditional or comparison operator. if (Number <= 0){ Print '0';}else{ print Number;} thanks.. Now provide the response and nothing else.
My original simple solution: 1. print( (abs(Number)+Number) / 2 ) That solution would work in most cases, unless Number is very large (more than half the maximum e.g. Number >= MAX_INT/2) in which case the addition may cause overflow. The following solution solves the overflow problem: 2. print( (abs(Number)/2) + (Number/2) ) However, there may be a case in which Number is and must remain integer, and the division operator (/) is integer division, so that 7/2=3. In this case solution 2 won't work because if Number=7 it will print 6 (for this case solution 1 will work just fine). So if we need to deal with both large numbers AND integer arithmetic, the following monstrosity comes to the rescue, adding compensation for the 1 that may be lost in the division by 2 in case of odd integer: 3. print( ( (abs(Number)/2)+(Number/2) ) + (( (Number-(2*(Number/2))) + (abs(Number)-(2*(abs(Number)/2))) ) / 2) )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/876550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92242/']}
jdg_85283
stackexchange
llm_judgeable_groundtruth_similarity
3142837
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to capture when the contents of an iframe have fully loaded from the parent page? Now provide the response and nothing else.
<iframe> elements have a load event for that. How you listen to that event is up to you, but generally the best way is to: 1) create your iframe programatically It makes sure your load listener is always called by attaching it before the iframe starts loading. <script>var iframe = document.createElement('iframe');iframe.onload = function() { alert('myframe is loaded'); }; // before setting 'src'iframe.src = '...'; document.body.appendChild(iframe); // add it to wherever you need it in the document</script> 2) inline javascript , is another way that you can use inside your HTML markup. <script>function onMyFrameLoad() { alert('myframe is loaded');};</script><iframe id="myframe" src="..." onload="onMyFrameLoad(this)"></iframe> 3) You may also attach the event listener after the element , inside a <script> tag, but keep in mind that in this case, there is a slight chance that the iframe is already loaded by the time you get to adding your listener. Therefore it's possible that it will not be called (e.g. if the iframe is very very fast, or coming from cache). <iframe id="myframe" src="..."></iframe><script>document.getElementById('myframe').onload = function() { alert('myframe is loaded');};</script> Also see my other answer about which elements can also fire this type of load event
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3142837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32812/']}
jdg_85284
stackexchange
llm_judgeable_groundtruth_similarity
52751
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: Find sum of numbers from $1$ to $100$ which are not divisible by $3$ and $5$? I can understand that the here we require to sum up these numbers: $1+2+4+7+8+11+13+14+16+17+19+22+23+26+28+29+31+32+34$ $+37+38+41+43+44+46+47+49+52+53+56+58+59+61+62+64+67+68+71$ $+73+74+76+77+79+82+83+86+88+89+91+92+94+97+98$ Which gives the sum $= 2632$,but I any didn't relation among the numbers in this series,any ideas? Also,I am supposed to do this under a mint so please hint/answer accordingly. Now provide the response and nothing else.
This is a combinatorial argument called Inclusion-exclusion principle :$$X=1+\ldots+100 - 3(1+\ldots+33) - 5(1+\ldots+20) + 15(1+\ldots+6)$$ First we add all the numbers, then we remove all those which are divisible by $3$, and those divisible by $5$. But wait a minute! What about $15$? We removed that number twice ! We therefore need to add it once, as well the rest of its multiples below $100$. Now using the summation formula: $1+\ldots+n = \frac{n(n+1)}{2}$ the answer follows.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/52751', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2109/']}
jdg_85285
stackexchange
llm_judgeable_groundtruth_similarity
249916
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Linux so pardon me for the possible confusion you may encounter in this question. From what I understand, filesystem specifies how a partition stores/manages file, with standards such as ext2, ext3, reiserfs, xfs, etc. Occasionally I see people seem to refer to each " directory " as /boot filesystem /usr/bin filesystem /root filesystem /bin filesystem Why would we refer to these as filesystems ? If each of them is a partition, that confuses me because as far as I know, /usr and /usr/bin tend to be in the same partition, but I saw people refers to both " /usr filesystem" and " /usr/bin filesystem". If filesystem here is equivalent to Window's directory , it's not clear to me as apparently filesystem is something more than just directories . Also, as far as I know, Linux does not have "directory" concept; all are files. Now provide the response and nothing else.
As I wrote in https://superuser.com/a/293160/38062 : The problem here is the word "filesystem". In the POSIX/Unix/Linux worlds, it is used to mean several different things. The "filesystem" is sometimes the entire system of files, rooted at / and as presented to applications softwares by the operating system kernel. With this meaning, people talk of POSIX operating systems having a "single filesystem tree ", for example. A "filesystem" is sometimes one (or more) slice(s) of a (or several) DASD(s) — one or more collections of contiguous disc sectors formatted as a single volume with a given format — as demarcated by some disc partitioning scheme. With this meaning, people talk of, say, "formatting my /usr filesystem ". " /usr " here is the (expected) mountpoint of the volume, or (in some partitioning schemes) its identifying label. A "filesystem" is sometimes an abstract joinable tree of files and directories, presented by a filesystem driver (i.e. the VFS layer) to the rest of the system. With this meaning, people talk of, say, "mounting the proc filesystem on /proc " or "using a tmpfs filesystem for /tmp ". You're seeing meaning #1 when you see " /usr/bin filesystem". It's a filesystem tree rooted at the directory /usr/bin . Yes, Linux very much does have the concept of directories. Meaning #2 and meaning #3 are what you're mis-reading it as. People are not talking about /usr/bin as an on-disc data set, demarcated by disc slicing/partitioning. Nor are they talking about /usr/bin as a particular type of filesystem driver, or a particular disc volume format. Further reading Ramesh Bangia (2010). "file system". Dictionary of Information Technology . Laxmi Publications, Ltd. ISBN 9789380298153. p. 224. File System . "Base Definitions". The Open Group Base Specifications . Issue 7IEEE 1003.1. The Open Group. 2013. Binh Nguyen (2004-08-16). "filesystem". The Linux Dictionary . Version 0.16. p. 616.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/249916', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/144104/']}
jdg_85286
stackexchange
llm_judgeable_groundtruth_similarity
7537791
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 find recursion, apart from very straight forward ones like factorial, very difficult to understand. The following snippet prints all permutations of a string. Can anyone help me understand it. What is the way to go about to understand recursion properly. void permute(char a[], int i, int n){ int j; if (i == n) cout << a << endl; else { for (j = i; j <= n; j++) { swap(a[i], a[j]); permute(a, i+1, n); swap(a[i], a[j]); } }} int main(){ char a[] = "ABCD"; permute(a, 0, 3); getchar(); return 0;} Now provide the response and nothing else.
PaulR has the right suggestion. You have to run through the code by "hand" (using whatever tools you want - debuggers, paper, logging function calls and variables at certain points) until you understand it. For an explanation of the code I'll refer you to quasiverse's excellent answer. Perhaps this visualization of the call graph with a slightly smaller string makes it more obvious how it works: The graph was made with graphviz . // x.dot// dot x.dot -Tpng -o x.pngdigraph x {rankdir=LRsize="16,10"node [label="permute(\"ABC\", 0, 2)"] n0; node [label="permute(\"ABC\", 1, 2)"] n1; node [label="permute(\"ABC\", 2, 2)"] n2; node [label="permute(\"ACB\", 2, 2)"] n3; node [label="permute(\"BAC\", 1, 2)"] n4; node [label="permute(\"BAC\", 2, 2)"] n5; node [label="permute(\"BCA\", 2, 2)"] n6; node [label="permute(\"CBA\", 1, 2)"] n7; node [label="permute(\"CBA\", 2, 2)"] n8; node [label="permute(\"CAB\", 2, 2)"] n9;n0 -> n1 [label="swap(0, 0)"];n0 -> n4 [label="swap(0, 1)"];n0 -> n7 [label="swap(0, 2)"];n1 -> n2 [label="swap(1, 1)"];n1 -> n3 [label="swap(1, 2)"];n4 -> n5 [label="swap(1, 1)"];n4 -> n6 [label="swap(1, 2)"];n7 -> n8 [label="swap(1, 1)"];n7 -> n9 [label="swap(1, 2)"];}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7537791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/176418/']}
jdg_85287
stackexchange
llm_judgeable_groundtruth_similarity
16161865
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 using following code to export data from worksheet to MS Access database, the code is looping through each row and insert data to MS Access Table. Public Sub TransData()Application.ScreenUpdating = FalseApplication.EnableAnimations = FalseApplication.EnableEvents = FalseApplication.DisplayAlerts = FalseActiveWorkbook.Worksheets("Folio_Data_original").ActivateCall MakeConnection("fdMasterTemp")For i = 1 To rcount - 1 rs.AddNew rs.Fields("fdName") = Cells(i + 1, 1).Value rs.Fields("fdDate") = Cells(i + 1, 2).Value rs.UpdateNext iCall CloseConnectionApplication.ScreenUpdating = TrueApplication.EnableAnimations = TrueApplication.EnableEvents = TrueApplication.DisplayAlerts = TrueEnd Sub Public Function MakeConnection(TableName As String) As Boolean'*********Routine to establish connection with database Dim DBFullName As String Dim cs As String DBFullName = Application.ActiveWorkbook.Path & "\FDData.mdb" cs = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DBFullName & ";" Set cn = CreateObject("ADODB.Connection") If Not (cn.State = adStateOpen) Then cn.Open cs End If Set rs = CreateObject("ADODB.Recordset") If Not (rs.State = adStateOpen) Then rs.Open TableName, cn, adOpenKeyset, adLockOptimistic End IfEnd Function Public Function CloseConnection() As Boolean'*********Routine to close connection with databaseOn Error Resume Next If Not rs Is Nothing Then rs.Close End If If Not cn Is Nothing Then cn.Close End If CloseConnection = True Exit FunctionEnd Function Above code works fine for few hundred lines of records, but apparently it will be more data to export, Like 25000 records, is it possible to export without looping through all records and just one SQL INSERT statement to bulk insert all data to Ms.Access Table in one go? Any help will be much appreciated. EDIT: ISSUE RESOLVED Just for information if anybody seeks for this, I've done a lots of search and found the following code to be work fine for me, and it is real fast due to SQL INSERT, (27648 records in just 3 seconds!!!!): Public Sub DoTrans() Set cn = CreateObject("ADODB.Connection") dbPath = Application.ActiveWorkbook.Path & "\FDData.mdb" dbWb = Application.ActiveWorkbook.FullName dbWs = Application.ActiveSheet.Name scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath dsh = "[" & Application.ActiveSheet.Name & "$]" cn.Open scn ssql = "INSERT INTO fdFolio ([fdName], [fdOne], [fdTwo]) " ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh cn.Execute ssqlEnd Sub Still working to add specific fields name instead of using "Select *", tried various ways to add field names but can't make it work for now. Now provide the response and nothing else.
is it possible to export without looping through all records For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data Option ExplicitSub AccImport() Dim acc As New Access.Application acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb" acc.DoCmd.TransferSpreadsheet _ TransferType:=acImport, _ SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _ TableName:="tblExcelImport", _ Filename:=Application.ActiveWorkbook.FullName, _ HasFieldNames:=True, _ Range:="Folio_Data_original$A1:B10" acc.CloseCurrentDatabase acc.Quit Set acc = NothingEnd Sub
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16161865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471163/']}
jdg_85288
stackexchange
llm_judgeable_groundtruth_similarity
7357127
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble with logout() while testing my project with the Django web server. This is my logout view: def logout(request): logout(request) return render_to_response('main.html', {}) When I access /logout (which calls this view) I get a popup window that says Python crashed. It doesn't give me any trace in the console. Now provide the response and nothing else.
You have a slight problem of recursion there. logout is calling itself, and so on until you get a stack overflow. Rename the view or the Django logout function when you import it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7357127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427299/']}
jdg_85289
stackexchange
llm_judgeable_groundtruth_similarity
44022387
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 made a DNN Regression Model to predicts results which we don't have in data table but I can not make tensorboard. This code is from https://deeplearning4j.org/linear-regression.html and lecture notes written by Sunghun Kim of Hong Kong University. import tensorflow as tf import numpy as np tf.set_random_seed(777) #for reproducibility # data Import xy = np.loadtxt('Training_Data.csv', delimiter=',', dtype=np.float32) x_data = xy[:,0:-1] y_data = xy[:,[-1]] # Make sure the shape and data are OK print(x_data.shape, x_data) print(y_data.shape, y_data) # input place holders X = tf.placeholder(tf.float32, shape=[None, 2]) Y = tf.placeholder(tf.float32, shape=[None, 1]) # weight & bias for nn Layers W1 = tf.get_variable("W1", shape=[2, 512],initializer=tf.contrib.layers.xavier_initializer()) b1 = tf.Variable(tf.random_normal([512])) L1 = tf.nn.relu(tf.matmul(X, W1) + b1) W2 = tf.get_variable("W2", shape=[512, 512], initializer=tf.contrib.layers.xavier_initializer()) b2 = tf.Variable(tf.random_normal([512])) L2= tf.nn.relu(tf.matmul(L1, W2) + b2) W3 = tf.get_variable("W3", shape=[512, 1], initializer=tf.contrib.layers.xavier_initializer()) b3 = tf.Variable(tf.random_normal([1])) hypothesis = tf.matmul(L2, W3) + b3 # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize/Optimizer optimizer = tf.train.AdamOptimizer(learning_rate=1e-5) train = optimizer.minimize(cost) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) # Fit the Line with new training data for step in range(2001): cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={X: x_data, Y: y_data}) if step % 100 == 0: print(step, "Cost: ", cost_val, "/n Prediction: /n", hy_val) # Command What value you want print("wing loadings will be ", sess.run(hypothesis, feed_dict={X: [[0.0531, 0.05]]})) w2_hist=tf.summary.histogram("weight2",W2) cost_summ=tf.summary.scalar("cost",cost) summary=tf.summary.merge_all() #Create Summary writer writer=tf.summary.FileWriter('C:\\Users\\jh902\\Documents\\.logs') writer.add_graph(sess.graph) s,_= sess.run([summary, optimizer], feed_dict={X: x_data, Y: y_data}) writer.add_summary(s, global_step=2001) TypeError Traceback (most recent call last) C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn) 266 self._unique_fetches.append(ops.get_default_graph().as_graph_element( --> 267 fetch, allow_tensor=True, allow_operation=True)) 268 except TypeError as e: C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation) 2469 with self._lock: -> 2470 return self._as_graph_element_locked(obj, allow_tensor, allow_operation) 2471 C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation) 2558 raise TypeError("Can not convert a %s into a %s." -> 2559 % (type(obj).__name__, types_str)) 2560 TypeError: Can not convert a AdamOptimizer into a Tensor or Operation. During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-20-b8394996caf6> in <module>() ----> 1 s,_= sess.run([summary, optimizer], feed_dict={X: x_data, Y: y_data}) 2 writer.add_summary(s, global_step=2001) C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata) 765 try: 766 result = self._run(None, fetches, feed_dict, options_ptr, --> 767 run_metadata_ptr) 768 if run_metadata: 769 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 950 951 # Create a fetch handler to take care of the structure of fetches. --> 952 fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string) 953 954 # Run request and get response. C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, graph, fetches, feeds) 406 """ 407 with graph.as_default(): --> 408 self._fetch_mapper = _FetchMapper.for_fetch(fetches) 409 self._fetches = [] 410 self._targets = [] C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in for_fetch(fetch) 228 elif isinstance(fetch, (list, tuple)): 229 # NOTE(touts): This is also the code path for namedtuples. --> 230 return _ListFetchMapper(fetch) 231 elif isinstance(fetch, dict): 232 return _DictFetchMapper(fetch) C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches) 335 """ 336 self._fetch_type = type(fetches) --> 337 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches] 338 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) 339 C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in <listcomp>(.0) 335 """ 336 self._fetch_type = type(fetches) --> 337 self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches] 338 self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) 339 C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in for_fetch(fetch) 236 if isinstance(fetch, tensor_type): 237 fetches, contraction_fn = fetch_fn(fetch) --> 238 return _ElementFetchMapper(fetches, contraction_fn) 239 # Did not find anything. 240 raise TypeError('Fetch argument %r has invalid type %r' % C:\Users\jh902\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in __init__(self, fetches, contraction_fn) 269 raise TypeError('Fetch argument %r has invalid type %r, ' 270 'must be a string or Tensor. (%s)' --> 271 % (fetch, type(fetch), str(e))) 272 except ValueError as e: 273 raise ValueError('Fetch argument %r cannot be interpreted as a ' TypeError: Fetch argument <tensorflow.python.training.adam.AdamOptimizer object at 0x000001E08E7E1CF8> has invalid type <class 'tensorflow.python.training.adam.AdamOptimizer'>, must be a string or Tensor. (Can not convert a AdamOptimizer into a Tensor or Operation.) tensorboard --logdir=.logs File "<ipython-input-83-e4b16f0da480>", line 1 tensorboard --logdir=.logs ^ SyntaxError: invalid syntax Now provide the response and nothing else.
I have spotted an error here optimizer = tf.train.AdamOptimizer(learning_rate=1e-5) instead it should have been optimizer = tf.train.AdamOptimizer(learning_rate=1e-5).minimize(cost) Otherwise, you would end up evaluating the optimizer itself. Or else you should replace the optimizer near s,_= sess.run([summary, optimizer], feed_dict={X: x_data, Y: y_data}) by s,_= sess.run([summary, train], feed_dict={X: x_data, Y: y_data})
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44022387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8024700/']}
jdg_85290
stackexchange
llm_judgeable_groundtruth_similarity
62102475
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 struggling with Apache HUE Rest API and django csrf. The problem is that I can kind-a login, but the rest doesn't work. I always get redirected to login page. Seems like server doesn't like my csrftoken or sessionid cookie. I have absolutely no idea why.Here is my login code: val accessToken = getAccessToken(Http(s"$baseUrl/accounts/login/?next=/").asString) val response = Http(s"$baseUrl/accounts/login/") .postForm(Seq( "username" -> username, "password" -> password, "csrfmiddlewaretoken" -> accessToken.csrftoken.getValue, "next" -> "/" )) .cookie(accessToken.csrftoken) .asString getAccessToken(response) // wrapper for cookies and headers from response Now I try just to get page from HUE protected with csrf def getDir(hdfsPathDirParent: String): Unit = { val accessToken = login() val response = Http(s"$baseUrl/filebrowser/view=$hdfsPathDirParent") .cookie(accessToken.csrftoken) // retrieved after login .cookie(accessToken.sessionid) // retrieved after login .header("X-CSRFToken", accessToken.csrftoken.getValue) .header("Host", "localhost:8888") .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9") .header("Connection", "keep-alive") .header("Sec-Fetch-Dest", "empty") .header("Sec-Fetch-Mode", "cors") .header("Sec-Fetch-Site", "same-origin") //.header("Sec-Fetch-User", "?1") .header("Upgrade-Insecure-Requests", "1") .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36") .header("Accept-Encoding", "gzip, deflate, br") .header("Accept-Language", "en,en-US;q=0.9,ru;q=0.8") .header("Cache-Control", "max-age=0") .header("X-Requested-With", "XMLHttpRequest") .asString I literally copy-pasted all tokens from Google Chrome debug panel. It doesn't work [30/May/2020 05:19:29 -0700] access WARNING 172.17.0.1 test_user - "POST /accounts/login/ HTTP/1.1" -- Successful login for user: test_user[30/May/2020 05:19:29 -0700] middleware INFO Redirecting to login page: /filebrowser/view=/user/test_user[30/May/2020 05:19:29 -0700] access INFO 172.17.0.1 -anon- - "GET /filebrowser/view=/user/test_user HTTP/1.1" -- login redirection So I do pass login form, but the rest doesn't work. Can't find what I miss... Their code example doesn't work http://cloudera.github.io/hue/latest/developer/api/ Now provide the response and nothing else.
I don't think (but I might be wrong) that there's a correct way of doing it per se, but what you could do it have a central module ( maindash.py ) around your startup code app = dash.Dash(__name__) , and have different callbacks simply import app from my_dash_app.maindash . This would set up the callbacks in their own separate modules but re-use that one central module for the app instance. It's easiest to show an overview of it like this: app.py being the main script called to start everything up. maindash.py is in charge of creating the main app instance. first_view.py is where the decorators are defined to set up all the callbacks. Here's the result: .├── my_dash_app│ ├── app.py│ ├── maindash.py│ └── views│ ├── first_view.py│ └── __init__.py└── setup.py Since imports are re-used in Python, there's no real harm in doing from my_dash_app.maindash import app several times from different other modules, such as event handlers and the main script. They'll share the same import instance - thus re-using the dash.Dash() instance as well. Just make sure you import the central module before setting up the handlers, and you should be good to go. Here's the code snippets separated for testing: app.py from my_dash_app.maindash import appfrom my_dash_app.views.first_view import make_layoutif __name__ == '__main__': app.layout = make_layout() app.run_server(debug=True) maindash.py import dashapp = dash.Dash(__name__) first_view.py from my_dash_app.maindash import appfrom dash.dependencies import Input, Outputimport dash_core_components as dccimport dash_html_components as htmldef make_layout(): return html.Div([ dcc.Input(id='my-id', value='initial value', type='text'), html.Div(id='my-div') ])@app.callback(Output(component_id='my-div', component_property='children'), [Input(component_id='my-id', component_property='value')])def update_output_div(input_value): return 'You\'ve entered "{}"'.format(input_value)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62102475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/498690/']}
jdg_85291
stackexchange
llm_judgeable_groundtruth_similarity
3294659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to cast a 4 byte array to an ulong in C#. I'm currently using this code: atomSize = BitConverter.ToUInt32(buffer, 0); The byte[4] contains this: 0 0 0 32 However, the bytes are Big-Endian. Is there a simple way to convert this Big-Endian ulong to a Little-Endian ulong? Now provide the response and nothing else.
I believe that the EndianBitConverter in Jon Skeet's MiscUtil library ( nuget link ) can do what you want. You could also swap the bits using bit shift operations: uint swapEndianness(uint x){ return ((x & 0x000000ff) << 24) + // First byte ((x & 0x0000ff00) << 8) + // Second byte ((x & 0x00ff0000) >> 8) + // Third byte ((x & 0xff000000) >> 24); // Fourth byte} Usage: atomSize = BitConverter.ToUInt32(buffer, 0);atomSize = swapEndianness(atomSize);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3294659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367680/']}
jdg_85292
stackexchange
llm_judgeable_groundtruth_similarity
6469209
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an objective C class. In it, I created a init method and set up a NSNotification in it //Set up NSNotification[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData) name:@"Answer Submitted" object:nil]; Where do I set the [[NSNotificationCenter defaultCenter] removeObserver:self] in this class? I know that for a UIViewController , I can add it into the viewDidUnload method So what needs to be done if I just created an objective c Class? Now provide the response and nothing else.
The generic answer would be "as soon as you no longer need the notifications". This is obviously not a satisfying answer. I'd recommend, that you add a call [notificationCenter removeObserver: self] in method dealloc of those classes, which you intend to use as observers, as it is the last chance to unregister an observer cleanly. This will, however, only protect you against crashes due to the notification center notifying dead objects. It cannot protect your code against receiving notifications, when your objects are not yet/no longer in a state in which they can properly handle the notification. For this... See above. Edit (since the answer seems to draw more comments than I would have thought) All I am trying to say here is: it's really hard to give general advice as to when it's best to remove the observer from the notification center, because that depends: On your use case (Which notifications are observed? When do they get send?) The implementation of the observer (When is it ready to receive notifications? When is it no longer ready?) The intended life-time of the observer (Is it tied to some other object, say, a view or view controller?) ... So, the best general advice I can come up with: to protect your app. against at least one possible failure, do the removeObserver: dance in dealloc , since that's the last point (in the object's life), where you can do that cleanly. What this does not mean is: "just defer the removal until dealloc is called, and everything will be fine". Instead, remove the observer as soon as the object is no longer ready (or required) to receive notifications . That is the exact right moment. Unfortunately, not knowing the answers to any of the questions mentioned above, I cannot even guess, when that moment would be. You can always safely removeObserver: an object multiple times (and all but the very first call with a given observer will be nops). So: think about doing it (again) in dealloc just to be sure, but first and foremost: do it at the appropriate moment (which is determined by your use case).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6469209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683898/']}
jdg_85293
stackexchange
llm_judgeable_groundtruth_similarity
31410528
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 understand the whole Spring Framework. To my knowledge, the relatively new techniques of using gradle makes a lot of the tutorials and posts online outdated? The main issue that I am running in to is when I try to display a jsp or html page, the webpage's body shows text: "filename.jsp". The project was created by New-> Other-> Spring Starter Project using Gradle and STS 3.7.The goal is to create a web application using MVC pattern. folder structure: TEST --Spring Elements (created by STS) --src/main/java ++--TEST ++++--TestApplication.java (created by STS) ++--TEST.Controller ++++--JSPController.java --sec/main/resources ++--application.properties (created by STS , EMPTY file) --src/main/webapp ( ** I created this directory, but is this required?) ++--WEB-INF ++++--home.jsp ++++--home.html ++++--web.xml (** Additional question below) TestApplication.java package TEST;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); }} home.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Test</title></head><body> <h1>Test 1</h1> <form> First name:<br> <input type="text" name="firstname"> <br> Last name:<br> <input type="text" name="lastname"> </form></body></html> JSPController.java package TEST.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class JSPController { @RequestMapping(value = "/jsp", method = RequestMethod.GET) public String home(){ return "/webapp/WEB-INF/home.jsp"; } } web.xml //empty file right now build.gradle buildscript { ext { springBootVersion = '1.2.5.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE") }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'idea'apply plugin: 'spring-boot' apply plugin: 'io.spring.dependency-management' jar { baseName = 'TEST' version = '0.0.1-SNAPSHOT'}sourceCompatibility = 1.8targetCompatibility = 1.8repositories { mavenCentral()}dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") }eclipse { classpath { containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER') containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8' }}task wrapper(type: Wrapper) { gradleVersion = '2.3'} When I go to http://localhost:8080/jsp ,the html page has the body: /webapp/WEB-INF/home.jsp So the jsp is not displaying at all. I have tried html and with or without method=RequestMethod.GET/POST. Nothing works. **Additional question:A lot of online posts/tutorial goes in to .xml files, for example, web.xml. To my understanding, these are no longer required or needed because spring + gradle generates a .xml automatically from the @notations? Now provide the response and nothing else.
That's because you are using the annotation @RestController instead of @Controller . Change your class annotation from @RestControllerpublic class JSPController { ...} to: @Controllerpublic class JSPController { ...} When you annotate a class with RestController , all methods annotated with @RequestMapping assume @ResponseBody semantics by default. In other words, your method #home is serializing the String /webapp/WEB-INF/home.jsp as JSON, instead of mapping its value to a view.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31410528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3040451/']}
jdg_85294
stackexchange
llm_judgeable_groundtruth_similarity
8685
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: This has just dawned on me that if you're writing an operating system then what are you writing it on? I ask this as I am reading a microprocessor fundamentals book from 1980 and this question popped in to my head: How was the first microprocessor chip programmed? The answer may be obvious but its bugging me. Now provide the response and nothing else.
I will take your question literally and discuss mostly microprocessors, not computers in general. All computers have some sort of machine code. An instruction consists of an opcode and one or more operands. For example, the ADD instruction for the Intel 4004 (the very first microprocessor) was encoded as 1000RRRR where 1000 is the opcode for ADD and RRRR represented a register number. The very first computer programs were written by hand, hand-encoding the 1's and 0's to create a program in machine language. This is then programmed into the chip. The first microprocessors used ROM (Read-Only Memory); this was later replaced by EPROM (Erasable Programmable ROM, which was erased with UV light); now programs are usually programmed into EEPROM ( "Electrically...-EPROM" , which can be erased on-chip), or specifically Flash memory. Most microprocessors can now run programs out of RAM (this is pretty much standard for everything but microcontrollers), but there has to be a way of loading the program into RAM in the first place. As Joby Taffey pointed out in his answer, this was done with toggle switches for the Altair 8080, which was powered by an Intel 8080 (which followed the 4004 and 8008). In your PC, there is a bit of ROM called the BIOS which is used to start up the computer, and load the OS into RAM. Machine language gets tedious real fast, so assembler programs were developed that take a mnemonic assembler language and translate it, usually one line of assembly code per instruction, into machine code. So instead of 10000001, one would write ADD R1. But the very first assembler had to be written in machine code. Then it could be rewritten in its own assembler code, and the machine-language version used to assemble it the first time. After that, the program could assemble itself. This is called bootstrapping and is done with compilers too -- they are typically first written in assembler (or another high-level language), and then rewritten in their own language and compiled with the original compiler until the compiler can compile itself. Since the first microprocessor was developed long after mainframes and minicomputers were around, and the 4004 wasn't really suited to running an assembler anyway, Intel probably wrote a cross-assembler that ran on one of its large computers, and translated the assembly code for the 4004 into a binary image that could be programmed into the ROM's. Once again, this is a common technique used to port compilers to a new platform (called cross-compiling ).
{}
{'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/8685', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1623/']}
jdg_85295
stackexchange
llm_judgeable_groundtruth_similarity
48211622
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 sth similiar to Intellisense in .NET in Laravel. So far I've been using .NET and autocompletion for models is awesome and makes my work way more easy. Now I need to create Laravel application, I've been following this tutorial to prepare my environment but the only autocompletion I get is for default PHP functions and some predefined methods (ex. SaveSessionListener from Symfony\Component\HttpKernel\EventListener - I am not even using Symfony anywhere). What I'd like to achieve is get autocompletion from models, for example there is a class called Model in Laravel, I have class Page which extends Model. use App/Page$home = new Page();$home->content = "lorem ipsum";$home->save(); I don't have any completion when I write $home-> , no content , no save() , only some random functions. I can understand why there might be no content autocompletion - its not written directly into code, but its written on database and object-database engine is parsing that one, I didn't figure out how yet, but I don't understand why even save() doesn't get autocompletion. I tried to google the issue, but without any good result. Now provide the response and nothing else.
I figured it out how to get it work with Visual Studio Code. First and most important is the link morph provided me in comment: laravel-ide-helper I just followed docs and generated basic helper + model helper. I guess later I'll automate those generation commands, its also explained how to do it in docs. Second thing is that it works only with: PHP Intelephense plugin Note that you need to reset VSC before it actually works. Third thing I did - VSC have build-in php autocompletion, it was pretty annoying cause it started to show me model fields in suggestions, but it was between dozens of other suggestions. To disable build-in autocompletion I added line to user settings: "php.suggest.basic": false, Last thing I did - I have moved snippets to bottom of suggestions box to clear autocompletion results a little bit more: "editor.snippetSuggestions": "bottom" And that works really decent as Laravel programming environment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48211622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3358153/']}
jdg_85296
stackexchange
llm_judgeable_groundtruth_similarity
11064292
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In this c program a=8;main(){ printf("%d", a);} variable a has been declared without any data type and still this program compiles successfully and gives the desired output. output :: 8 see it on ideone . but, when i declared the same variable inside main, it gives compilation error. main(){ a=8; printf("%d", a);} output :: prog.c:2: warning: return type defaults to ‘int’prog.c: In function ‘main’:prog.c:3: error: ‘a’ undeclared (first use in this function)prog.c:3: error: (Each undeclared identifier is reported only onceprog.c:3: error: for each function it appears in.)prog.c:4: warning: implicit declaration of function ‘printf’prog.c:4: warning: incompatible implicit declaration of built-in function ‘printf’ see here . How the first program is working but the second? Now provide the response and nothing else.
What you see here is the "Implicit Int Rule" at work. Simply put the rule says: "A variable declared without an explicit type name is assumed to be of type int ." Note that this rule was revoked in the c99 Standard [Ref 1] .However, depending on your compiler and its settings, the first example might compile with a warning, or will fail to compile( with strict compilation settings ) If you compile your first example with strict settings adhering to c99 Standard the compiler will tell you the root cause. check here . cc1: warnings being treated as errors prog.c:1: error: data definition has no type or storage class prog.c:1: error: type defaults to ‘int’ in declaration of ‘a’ prog.c:3: error: return type defaults to ‘int’ prog.c: In function ‘main’: prog.c:4: error: implicit declaration of function ‘printf’ prog.c:4: error: incompatible implicit declaration of built-in function ‘printf’ EDIT: why does the first example work but second does not? Note the emphasis on the words "variable declared" in the rule. In first example, since the statement is at the global scope it is treated as an Implicit declaration , and the Implicit Int Rule gets applied to it. In Second example, the statement acts as an Assignment and not a Declaration . Since there is no declaration the Implicit int rule does not apply here. In the absence of any type the compiler cannot determine what is the type of a and hence reports the error. [Ref 1] C99 Standard: Foreword Para 5: This edition replaces the previous edition, ISO/IEC 9899:1990 , as amended and corrected by ISO/IEC 9899/COR1:1994 , ISO/IEC 9899/COR2:1995 , and ISO/IEC 9899/AMD1:1995 . Major changes from the previous edition include: ..... ..... — remove implicit int ..... .....
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11064292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981787/']}
jdg_85297
stackexchange
llm_judgeable_groundtruth_similarity
2571436
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following lines in my ~/.emacs.d/init.el (custom-set-variables '(flymake-allowed-file-name-masks (quote ( ("\\.cc\\'" flymake-simple-make-init) ("\\.cpp\\'" flymake-simple-make-init)))))(add-hook 'find-file-hook 'flymake-find-file-hook) When I open a C++ file that has a proper Makefile in the same folder, I get on-the-fly compilation and error reporting (Flymake will check the syntax and report errors and warnings during code editing). The Makefile has a check-syntax target: .PHONY: check-syntaxcheck-syntax: $(CXX) -Wall -Wextra -pedantic -fsyntax-only $(CHK_SOURCES) The problem is that when I open a .cc file that has no corresponding Makefile I get an annoying dialog box that warns me about flymake being disabled. So if I launch emacs *.cc in a folder with 20 C++ files I get 20 modal dialog boxes saying something like No buildfile found for [...]. Flymake will be switched off . Is there some hook I can use to disable that warning? Can you provide sample elisp code and explanation on how you found the proper hook? Now provide the response and nothing else.
Easiest way to do this, and still recieve the messages, is to leave the customization variable set to true, and redefine the flymake-display-warning function. ;; Overwrite flymake-display-warning so that no annoying dialog box is;; used.;; This version uses lwarn instead of message-box in the original version. ;; lwarn will open another window, and display the warning in there.(defun flymake-display-warning (warning) "Display a warning to the user, using lwarn" (lwarn 'flymake :warning warning));; Using lwarn might be kind of annoying on its own, popping up windows and;; what not. If you prefer to recieve the warnings in the mini-buffer, use:(defun flymake-display-warning (warning) "Display a warning to the user, using lwarn" (message warning))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2571436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295076/']}
jdg_85298
stackexchange
llm_judgeable_groundtruth_similarity
583656
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 no idea what to do now. Is there any way to find the integers $x$ and $y$ by factoring? Thank you. Now provide the response and nothing else.
Dividing by $2^x$ gives$$2^{-x}+2^{-y}=1$$Since $2^{x}\gt0$ for any $x$, we must have both $2^{-x}\lt1$ and $2^{-y}\lt1$; that is, $x\gt0$ and $y\gt0$. Since $x$ and $y$ are integers, the biggest that $2^{-x}$ or $2^{-y}$ can be is $\frac12$ and since their sum is $1$, they must both be $\frac12$. That means $x=y=1$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/583656', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104187/']}
jdg_85299
stackexchange
llm_judgeable_groundtruth_similarity
28099441
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 define a recursive function within another function in Go but I am struggling to get the right syntax. I am looking for something like this: func Function1(n) int { a := 10 Function2 := func(m int) int { if m <= a { return a } return Function2(m-1) } return Function2(n)} I'd like to keep Function2 inside the scope of Function1 as it is accessing some elements of its scope. How can I do this in Go? Many thanks Now provide the response and nothing else.
You can't access Function2 inside of it if it is in the line where you declare it. The reason is that you're not referring to a function but to a variable (whose type is a function) and it will be accessible only after the declaration. Quoting from Spec: Declarations and scope: The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block. In your example Function2 is a variable declaration, and the VarSpec is: Function2 := func(m int) int { if m <= a { return a } return Function2(m-1)} And as the quote form the language spec describes, the variable identifier Function2 will only be in scope after the declaration, so you can't refer to it inside the declaration itself. For details, see Understanding variable scope in Go . Declare the Function2 variable first, so you can refer to it from the function literal : func Function1(n int) int { a := 10 var Function2 func(m int) int Function2 = func(m int) int { if m <= a { return a } return Function2(m - 1) } return Function2(n)} Try it on Go Playground .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28099441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2641547/']}
jdg_85300
stackexchange
llm_judgeable_groundtruth_similarity
533883
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: Ok, long story short.I have a new TV that occasionally switches on all by itself. In case anyone is wondering it's a Sony XH90 and this problem is documented on www. Not trying to go into details about this, makes no sense. The thing is, someone suggested to me, try reversing the power plug. For the heck of it, I tried without any hope. But, to my surprise, it actually solved the problem! I am an EE and know a few things about power line, electronic design, SMPS design. This TV is not grounded (double isolation design), same as all other equipment attached to it (exclusively through HDMI). I know power line has line and neutral, but even then, how could reversing the power plug possibly make any difference. Any ideas? Final conclusion This issue was in fact a non-issue. What i described did happen, but not again after the TV had been rebooted by unplugging it, nor after re-reversing the power plug. It must have been a software bug that disappeared after a reboot. Nevertheless, someone trustworthy did suggest the solution (where there's smoke, there's fire), and Andy aka did give a very likely solution in case the issue would have been real. Kudos to Andy for what he wrote, i will certainly keep his thoughts in mind whenever applicable. Now provide the response and nothing else.
Background (with a little speculation) Inside the TV's switch mode power supply will be one or several Y capacitors that connect the internally produced DC voltages to either live or neutral. They are there to reduce the common mode noise produced by the high frequency switching transformer from affecting the DC outputs. Without the Y capacitors, all the internal DC rails will be wobbling up and down at 100 ish kHz due to inter-winding capacitive coupling between the flyback primary transformer and its various secondaries. The wobble will not be massive but could be around 1 volt p-p. If this were not a TV, then there might be no real use for the flyback noise suppression capacitors but, consider this; the TV has to connect to an antenna of some sort and, you don't want the noisy internal 0 volts of the TV to be superimposing several volts peak-to-peak of 100 kHz onto your antenna or satellite input signal. You might be sharing the antenna system with other homes (say in an apartment building) so, the internal design of the TV has to accommodate this scenario. If using a satellite dish then it will be connected via long wires with high capacitance to ground and 100 kHz noise is going to cause some detriment somewhere to the received signal. Infrared remote The infrared remote receiver in the TV will be active all the time whenever the TV is plugged into a wall socket so it will be constantly looking for an infrared signal that is encoded as "ON". The infrared detection circuit will use high gain circuits that feed into a form of data slicer that gives a digital output so, how many bits of encoding are used to represent "ON" and how long will it take random noise (via a high gain infrared detection circuit) to erroneously reproduce the bit stream that represents "ON"? I have had some experience here to draw on. A high-speed data link I designed (650 Mbits per second) when not connected to a valid signal would trigger approximately every millisecond or so to indicate it had received a correct frame ID and, about every minute or so it would find exactly the same frame header in exactly the right place hundreds of bits later on. It would then indicate that it had received a valid frame of data. Of course it hadn't (and we knew that) but, just like false alien transmissions that people rave about, the hardware told us differently. Just random numbers coinciding. Tossing a coin How many times would you have to toss a coin to get 16 heads in a row? The data stream was 650 Mbps and in 1 ms the data receiver would get 650 kbits (with one false positive) - so "tossing a coin" 650,000 times resulted in a good chance of seeing 16 consecutive heads. OK I can't remember whether it was 1 millisecond or 5 milliseconds but, the point is this; if you do the experiment enough times (and very quickly) the number of false positives will be huge! What has this got to do with the question? If the Y capacitors were connected to the neutral incoming AC lead, it would offer better noise reduction than if it were connected to live. Now clearly, the live and neutral wires can be interchanged so you could ideally choose to have Y capacitor noise reduction capacitors connected to the "earthier" of the incoming AC wires and, if this gives slightly better noise reduction on the infrared detection circuits then it might make a big difference in receiving a false "ON" demand every hour or so and detecting a false "ON" every month or year.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/533883', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/175573/']}
jdg_85301
stackexchange
llm_judgeable_groundtruth_similarity
1008740
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My Rails app is starting to need complicated queries. Should I just start using raw SQL queries? What is the trend in the Rails community? Update: I do not have written queries right now, I wanted to ask this question before I start. But here is an example of what I want to do: I have books which have categories. I want to say- Give me all books that were: -created_at (added to store) between date1 and date2-updated_at before date3-joined with books that exist in shopping carts right now I haven't written the query yet but I think the rails version will be something like this: books_to_consider = Book.find(:all, :conditions => "created_at <= '#{date2}' AND created_at >= '#{date1}' AND updated_at <= '#{date3}'", :joins => "as b inner join carts as c on c.book_id = b.id") I am not saying ActiveRecord can't handle this query, but is it more accepted to go with raw SQL for readability (or maybe there are other limitations I don't know of yet)? Now provide the response and nothing else.
The general idea is to stick to ActiveRecord -generated queries as much as possible, and use SQL fragments only where necessary . SQL fragments are explicitly supported because the creators of ActiveRecord realised that SQL cannot be completely abstracted away. Using the the find method without SQL fragments is generally rewarded with better maintainability. Given your example, try: Book.find(:all, :conditions => ["created_at >= ? AND created_at <= ? AND updated_at <= ?", date1, date2, date3] :include => :carts) The :inlude => :carts will do the join if you added has_many :carts to your Book model. As you can see, there does not have to be much SQL involved. Even the quoting and escaping of input can be left to Rails, while still using SQL literals to handle the >= and <= operators. Going a little bit further, you can make it even clearer: class Book < AciveRecord::Base # Somewhere in your Book model: named_scope :created_between, lambda { |start_date, end_date| { :conditions => { :created_at => start_date..end_date } } } named_scope :updated_before, lambda { |date| { :conditions => ["updated_at <= ?", date] } } # ...endBook.created_between(date1, date2).updated_before(date3).find(:all, :include => :carts) Update: the point of the named_scope s is, of course, to reuse the conditions. It's up to you to decide whether or not it makes sense to put a set of conditions in a named scope or not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1008740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45849/']}
jdg_85302
stackexchange
llm_judgeable_groundtruth_similarity
23544
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: According to this article from "ADF" and this in the Washington Post , the city of Coeur d'Alene is requiring the Knapps, an ordained couple, to conduct same sex weddings or face penalties for discrimination. Donald and Evelyn Knapp are apparently ordained ministers who run The Hitching Post, a chapel in Coeur d’Alene, Idaho, at which they conduct weddings. (This strikes me as quite similar to many ministers’ practice of charging to officiate weddings when they are invited to do so at other venues.) Coeur d’Alene has an ordinance banning discrimination based on, among other things, sexual orientation in places of public accommodation. Earlier this year, after a federal judge in Idaho held that Idaho had to recognize same-sex weddings, a City of Couer d’Alene deputy city attorney was quoted by a local TV station (KXLY) as saying, “For profit wedding chapels are in a position now where last week the ban would have prevented them from performing gay marriages, this week gay marriages are legal, pending an appeal to the 9th Circuit,” Warren Wilson with the Coeur d’Alene City Attorney’s Office said…. “If you turn away a gay couple, refuse to provide services for them, then in theory you violated our code and you’re looking at a potential misdemeanor citation,” Wilson said. Is this a "real" case or is there something that I'm missing? Is this law actually being enforced in Coeur d'Alene? This law seems precisely tailored to prey on the fears of pastors like myself. It seems amazingly broad, and the stories have a whiff of sensationalism. If real, this seems like an religious liberty v. discrimination case that would ultimately be very far reaching. Now provide the response and nothing else.
Is Idaho forcing pastors to conduct same-sex weddings or face penalties? Yes and no: Yes: It's a real (albeit recent) story There is a lawsuit, and it is in Idaho The people involved are "ordained Christian ministers" No: It's a city (Coeur D'Alene) ordinance, not the state's (Idaho) That the city "would" enforce the bylaw is the opinion of the Deputy City Attorney The lawsuit is a restraining order and injunction to prevent the city's enforcement The ordinance says that "Religious corporations and associations" are excepted from the by-law, and that the by-law doesn't intend to alter or abridge other laws like the First Amendment In summary: The ordinance is meant to force commercial businesses, which provide services to the public, to do so without discriminating on the basis of sexual orientation and/or gender identity/expression. It applies to commercial businesses, religious entities are exempt. The claim is that the place in question is a for-profit business and not a church The counter-claim seems (in my opinion) to be that the wedding service, decoration and accessories, as well as the pastors, are "religious". Is it being enforced? There is online evidence that the lawsuit exists, and that the ordinance exists. I saw no evidence that the city is enforcing the law yet . The following paragraphs of the lawsuit say that according to the city attorney, the law "would" apply: Mr. Knapp asked if the Coeur d’Alene anti-discrimination ordinance required him and the Hitching Post to perform same-sex wedding ceremonies. Wilson or Gridley responded that the Coeur d’Alene ordinance would require Mr. Knapp to perform same-sex wedding ceremonies and that Mr. Knapp was not exempt from this requirement. The lawsuit is asking for a restraining order and an injunction, among other things, so to some extent it is pre-emptive (perhaps a small extent: they do seem to have reason to believe that the law would be enforced given time). Do the ordinance and lawsuit exist? The copy of the lawsuit which is linked in the first article of the OP, dated 10/17/2014, quotes city "Ordinance §9.56". I haven't necessarily found the ordinance online. Using Google I found two links which are labeled as the "proposed ordinance": link and link . And, here is an extract of the ordinance from the official Coeur d'Alene web site: this extract only includes the portion which prohibits discrimination when renting housing. Does the ordinance 'force pastors'? Both copies of the "draft legislation" include a section: 9.56.040: EXCEPTIONS A. Notwithstanding any other provision herein, nothing in this Chapter is intended to alter or abridge other rights, protections, or privileges secured under state and/or federal law. This ordinance shall be construed and applied in a manner consistent with First Amendment jurisprudence regarding the freedom of speech and exercise of religion. B. This chapter does not apply to: Religious corporations, associations, educational institutions, or societies. According to the lawsuit, there's a city attorney who thinks that the ordinance applies to weddings; for example, the lawsuit quotes this newspaper article : “I think that term is broad enough that it would capture (wedding) activity,” city attorney Warren Wilson said. Some further relevant paragraphs from the lawsuit include (the emphasis is mine), That article stated the following (emphasis added): Wedding venues that turn away gay couples may violate local laws, such as Coeur d’Alene’s prohibition on discrimination based on sexual orientation. The provision adopted by the City Council last year applies to housing, employment and places of public accommodation, including businesses that render public services. “I think that term is broad enough that it would capture (wedding) activity,” city attorney Warren Wilson said. Similar laws have applied to florists, bakeries and photographers that have refused to work on same-sex weddings in other states, Wilson noted. “Those have all been addressed in various states and run afoul of state prohibitions similar to this,” he said. “I would think that the Hitching Post would probably be considered a place of public accommodation that would be subject to the ordinance.” In Washington, no clergy person is required to marry a couple if doing so would violate the dictates of their faith tradition. Idaho does not have a similar exemption in place, but religious entities are exempt from the Coeur d’Alene ordinance, so pastors in the city are not obligated to perform same-sex weddings. But any nonreligious business that hosts civil ceremonies would fall under the city law , Wilson said. and, Mr. Knapp asked Wilson if the Coeur d’Alene anti-discrimination ordinance required him and the Hitching Post to perform same-sex wedding ceremonies. Mr. Knapp also asked if he was exempt from the ordinance since he was an ordained minister. Wilson responded that Mr. Knapp would have to perform same-sex wedding ceremonies because of the Coeur d’Alene ordinance. Wilson also responded that Mr. Knapp was not exempt from the ordinance because the Hitching Post was a business and not a church A large part of the lawsuit consists of evidence which tries to prove that the Knapps and the business are religious.
{}
{'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/23544', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/5707/']}
jdg_85303
stackexchange
llm_judgeable_groundtruth_similarity
34113609
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 asked this question before about killing a process that uses too much memory, and I've got most of a solution worked out. However, there is one problem: calculating massive numbers seems to be untouched by the method I'm trying to use. This code below is intended to put a 10 second CPU time limit on the process. import resourceimport osimport signaldef timeRanOut(n, stack): raise SystemExit('ran out of time!')signal.signal(signal.SIGXCPU, timeRanOut)soft,hard = resource.getrlimit(resource.RLIMIT_CPU)print(soft,hard)resource.setrlimit(resource.RLIMIT_CPU, (10, 100))y = 10**(10**10) What I expect to see when I run this script (on a Unix machine) is this: -1 -1ran out of time! Instead, I get no output. The only way I get output is with Ctrl + C , and I get this if I Ctrl + C after 10 seconds: ^C-1 -1ran out of time!CPU time limit exceeded If I Ctrl + C before 10 seconds, then I have to do it twice, and the console output looks like this: ^C-1 -1^CTraceback (most recent call last): File "procLimitTest.py", line 18, in <module> y = 10**(10**10)KeyboardInterrupt In the course of experimenting and trying to figure this out, I've also put time.sleep(2) between the print and large number calculation. It doesn't seem to have any effect. If I change y = 10**(10**10) to y = 10**10 , then the print and sleep statements work as expected. Adding flush=True to the print statement or sys.stdout.flush() after the print statement don't work either. Why can I not limit CPU time for the calculation of a very large number? How can I fix or at least mitigate this? Additional information: Python version: 3.3.5 (default, Jul 22 2014, 18:16:02) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] Linux information: Linux web455.webfaction.com 2.6.32-431.29.2.el6.x86_64 #1 SMP Tue Sep 9 21:36:05 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux Now provide the response and nothing else.
TLDR: Python precomputes constants in the code. If any very large number is calculated with at least one intermediate step, the process will be CPU time limited. It took quite a bit of searching, but I have discovered evidence that Python 3 does precompute constant literals that it finds in the code before evaluating anything. One of them is this webpage: A Peephole Optimizer for Python . I've quoted some of it below. ConstantExpressionEvaluator This class precomputes a number of constant expressions and stores them in the function's constants list, including obvious binary and unary operations and tuples consisting of just constants. Of particular note is the fact that complex literals are not represented by the compiler as constants but as expressions, so 2+3j appears as LOAD_CONST n (2) LOAD_CONST m (3j) BINARY_ADD This class converts those to LOAD_CONST q (2+3j) which can result in a fairly large performance boost for code that uses complex constants. The fact that 2+3j is used as an example very strongly suggests that not only small constants are being precomputed and cached, but also any constant literals in the code. I also found this comment on another Stack Overflow question ( Are constant computations cached in Python? ): Note that for Python 3, the peephole optimizer does precompute the 1/3 constant. (CPython specific, of course.) – Mark Dickinson Oct 7 at 19:40 These are supported by the fact that replacing y = 10**(10**10) with this also hangs, even though I never call the function! def f(): y = 10**(10**10) The good news Luckily for me, I don't have any such giant literal constants in my code. Any computation of such constants will happen later, which can be and is limited by the CPU time limit. I changed y = 10**(10**10) to this, x = 10print(x)y = 10**xprint(y)z = 10**yprint(z) and got this output, as desired! -1 -11010000000000ran out of time! The moral of the story: Limiting a process by CPU time or memory consumption (or some other method) will work if there is not a large literal constant in the code that Python tries to precompute.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34113609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1473772/']}
jdg_85304
stackexchange
llm_judgeable_groundtruth_similarity
6282
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Cayley graphs produced by Mathematica 8.0's CayleyGraph function represent actions that are their own inverses in an unconventional way: rather than using a single edge without arrows, it uses two edges, each represented by an arrow. Is there a way to replace all (and only) pairs of such reflexive arrows in a Cayley diagram with a single undirected edge, while leaving any unpaired directed edges untouched? For example is there a way to make edges in this CayleyGraph[DihedralGroup[4]] look like this Note that I'm aware that one could generate the desired output "manually", using Graph (as was done to generate the example above), but the solution I'm seeking must work for far more complex graphs than the one illustrated here from the simple group specifications that can be provided to CayleyGraph . Now provide the response and nothing else.
You can use custom EdgeShapeFunction as in ClearAll[fromDirectedToMixedGraph]; fromDirectedToMixedGraph[g_Graph] := Module[{edges = (EdgeList[g]) // DeleteDuplicates[#, Sort@#1 == Sort@#2 &] &, vertices = VertexList[g], vcoords = AbsoluteOptions[g, VertexCoordinates], esf = EdgeShapeFunction -> (If[MemberQ[(Pick[ EdgeList[g], (Count[EdgeList[g], # | Reverse[#]] > 1) & /@ EdgeList[g], False]), #2 | Reverse[#2]], Arrow[#1], Line[#1]] &), options},options = {First@# -> Select[Last@#, (MemberQ[edges, First@#] &)]} & /@ (Options[g]);Graph[vertices, edges, vcoords, esf, options]] Example: Grid@Table[{g, fromDirectedToMixedGraph[g]}, {g, {CayleyGraph[DihedralGroup[4]], CayleyGraph[AbelianGroup[{2, 2, 2, 2, 2}]]}}] EDIT: The following variant adds two options to control the rendering of multiple edges (as lines or bi-directional arrows). It also allows inheriting the options from the input graph and using any Graph option. ClearAll[mixedEdgeGraph];Options[mixedEdgeGraph] = Join[Options[Graph], {"arrowSize" -> .03, "setBack" -> .1, "biDirectionalEdges" -> "line"}];mixedEdgeGraph[g_Graph, opts : OptionsPattern[mixedEdgeGraph]] := Module[{doubleEdges, singleEdges, vcoords, esf, options, edges = DeleteDuplicates[EdgeList[g], Sort@#1 == Sort@#2 &],vertices = VertexList[g]}, {doubleEdges, singleEdges} = DeleteDuplicates[#, Sort@#1 == Sort@#2 &] & /@ (Pick[EdgeList[g], (MemberQ[EdgeList[g], Reverse[#]]) & /@ EdgeList[g], #] & /@ {True, False});(* remove from Options[g] properties and option values that belong to deleted edges *)options = Sequence @@ DeleteCases[ Options[g], (e_ -> __) /; MemberQ[Complement[EdgeList[g], edges], e], {1, Infinity}];(* default EdgeShapeFunction to render multi-edges as lines or bidirectional arrows*)esf = If[FilterRules[{opts}, EdgeShapeFunction] =!= {}, FilterRules[{opts}, EdgeShapeFunction], EdgeShapeFunction -> (If[MemberQ[singleEdges, #2 |Reverse[#2]], {Arrowheads[{{OptionValue["arrowSize"], 1}}], Arrow[#1, OptionValue["setBack"]]}, {If[OptionValue["biDirectionalEdges"] =!= "line", Arrowheads[{-OptionValue["arrowSize"], OptionValue["arrowSize"]}], Arrowheads[{{0., 1}}]], Arrow[#1, OptionValue["setBack"]]}] &)];(* use vertex coordinates of g unless VertexCooordinates or GraphLayout is specified *)vcoords = If[FilterRules[{opts}, {GraphLayout}] =!= {}, VertexCoordinates -> Automatic, AbsoluteOptions[g, VertexCoordinates]];(* explictly provided Graph options override the default options inherited from g *)Graph[vertices, edges, FilterRules[{opts}, Options[Graph]], vcoords, esf, options]] Examples: optns = Sequence @@ {VertexLabels -> Placed["Name", Center], VertexSize -> 0.4, ImageSize -> 300};g1 = CayleyGraph[AbelianGroup[{2, 2, 2, 2}], optns];g2 = CayleyGraph[AbelianGroup[{2, 2, 2}], optns];g3 = CayleyGraph[SymmetricGroup[4], optns];g4 = CayleyGraph[PermutationGroup[{Cycles[{{1, 5, 4}}], Cycles[{{3, 4}}]}], optns]; Additional examples: g5 = RandomGraph[BernoulliGraphDistribution[7, 0.6], DirectedEdges -> True, VertexLabels -> Placed["Name", Center], VertexSize -> 0.2, ImageSize -> 300];g6 = AdjacencyGraph[{{0, 1, 1, 1, 1}, {1, 0, 1, 0, 1}, {0, 1, 0, 1, 1}, {0, 1, 1, 0, 1}, {0, 0, 1, 1, 0}}, DirectedEdges -> True, VertexLabels -> Placed["Name", Center], VertexSize -> 0.2, ImageSize -> 300];(PropertyValue[{g5, #}, EdgeStyle] = Hue[RandomReal[]]) & /@ EdgeList[g5];(PropertyValue[{g6, #}, EdgeStyle] = Hue[RandomReal[]]) & /@ EdgeList[g6];Grid[{#, mixedEdgeGraph[#], mixedEdgeGraph[#, GraphLayout -> "SpringElectricalEmbedding", "biDirectionalEdges" -> "doublearrows"]} & /@ {g5, g6}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/6282', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/37/']}
jdg_85305
stackexchange
llm_judgeable_groundtruth_similarity
2789
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In computer science, we have often have to solve recurrence relations , that is find a closed form for a recursively defined sequence of numbers. When considering runtimes, we are often interested mainly in the sequence's asymptotic growth . Examples are The runtime of a tail-recursive function stepping downwards to $0$ from $n$ whose body takes time $f(n)$: $\qquad \begin{align} T(0) &= 0 \\ T(n+1) &= T(n) + f(n) \end{align}$ The Fibonacci sequence : $\qquad \begin{align} F_0 &= 0 \\ F_1 &= 1 \\ F_{n+2} &= F_n + F_{n+1} \end{align}$ The number of Dyck words with $n$ parenthesis pairs: $\qquad\begin{align} C_0 &= 1 \\ C_{n+1}&=\sum_{i=0}^{n}C_i\,C_{n-i} \end{align}$ The mergesort runtime recurrence on lists of length $n$: $\qquad \begin{align} T(1) &= T(0) = 0 \\ T(n) &= T(\lfloor n/2\rfloor) + T(\lceil n/2\rceil) + n-1 \end{align}$ What are methods to solve recurrence relations? We are looking for general methods and methods for a significant subclass as well as methods that yield precise solutions and methods that provide (bounds on) asymptotic growth. This is supposed to become a reference question. Please post one answer per method and provide a general description as well as an illustrative example. Now provide the response and nothing else.
Converting Full History to Limited History This is a first step in solving recurrences where the value at any integer depends on the values at all smaller integers. Consider, for example, the recurrence$$T(n) = n + \frac{1}{n}\sum_{k=1}^n \big(T(k-1) + T(n-k)\big)$$which arises in the analysis of randomized quicksort . (Here, $k$ is the rank of the randomly chosen pivot.) For any integer $n$, the value of $T(n)$ depends on all $T(k)$ with $k<n$. Recurrences of this form are called full history recurrences. To solve this recurrence, we can transform it into a limited history recurrence, where $T(n)$ depends on only a constant number of previous values. But first, it helps to simplify the recurrence a bit, to collect common terms and eliminate pesky fractions.\begin{align*}n T(n) &= n^2 + 2\sum_{k=1}^{n-1} T(k)\end{align*}Now to convert to a limited-history recurrence, we write down the recurrence for $T(n-1)$, subtract, and regather terms:\begin{align*}(n-1) T(n-1) &= (n-1)^2 + 2\sum_{k=1}^{n-2} T(k)\\\implies nT(n) - (n-1)T(n-1) &= (2n-1) + 2T(n-1)\\[1ex]\implies n T(n) &= (2n-1) + (n+1) T(n-1)\\[1ex]\implies \frac{T(n)}{n+1} &= \frac{2n-1}{n(n+1)} + \frac{T(n-1)}{n}\end{align*} Now if we define $t(n) = T(n)/(n+1)$ and replace the fraction $\frac{2n-1}{n(n+1)}$ with the simpler asymptotic form $\Theta(1/n)$, we obtain the much simpler recurrence$$t(n) = \Theta(1/n) + t(n-1).$$Expanding this recurrence into a summation immediately gives us $t(n) = \Theta(H_n) = \Theta(\log n)$, where $H_n$ is the $n$th harmonic number . We conclude that $\boldsymbol{T(n) = \Theta(n\log n)}$.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/2789', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/98/']}
jdg_85306
stackexchange
llm_judgeable_groundtruth_similarity
40043097
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 enable CORS in .NET Core in this way: public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseCors("AllowAll"); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }} However, when I am sending a request to my app with Angular 2 I am getting the famous "No 'Access-Control-Allow-Origin' header is present on the requested resource." error message. I am also using Windows Authentication + WebListener. If I am checking with postman the only response headers are: Content-Length →3533 Content-Type →application/json; charset=utf-8 Date →Fri, 14 Oct 2016 12:17:57 GMT Server →Microsoft-HTTPAPI/2.0 So there must be still something wrong configured. Any proposals? If I remove the outcommented line it works, but I need Windows Authentication :-( var host = new WebHostBuilder() .UseWebListener() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() //.UseWebListener(options => options.Listener.AuthenticationManager.AuthenticationSchemes = AuthenticationSchemes.NTLM) .Build(); Now provide the response and nothing else.
Assume you have the answer, but for the benefit of searchers, I had the same problem with the standard tutorial on .NET Core Cors . One of the many errors encountered: XMLHttpRequest cannot load localhost:64633/api/blogs. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:56573' is therefore not allowed access. The response had HTTP status code 500. After playing around, the following code worked. Full class posted below to aid understanding of what goes where. using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Microsoft.EntityFrameworkCore;using Microsoft.AspNetCore.Cors.Infrastructure;namespace NetCoreWebApiTesting{ public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsEnvironment("Development")) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: true); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // ******************** // Setup CORS // ******************** var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); // For anyone access. //corsBuilder.WithOrigins("http://localhost:56573"); // for a specific url. Don't add a forward slash on the end! corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("SiteCorsPolicy", corsBuilder.Build()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseMvc(); // ******************** // USE CORS - might not be required. // ******************** app.UseCors("SiteCorsPolicy"); } }} To use it you can add the EnableCorsAttribute either on the controller or on the method. e.g. [EnableCors("SiteCorsPolicy")][Route("api/[controller]")]public class BlogsController : Controller{} or // POST api/value[EnableCors("SiteCorsPolicy")][HttpPost]public HttpResponseMessage Post([FromBody]Blog value){ // Do something with the blog here.... var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK); return msg;} When I called this using the following code (using standard js/jQuery for easy of copy and paste), the communication stopped being rejected. function HandleClick() { var entityData = { "blogId": 2, "url": "http://blog.com/blog1", "posts": [ { "postId": 3, "title": "Post 1-1", "content": "This is post 1 for blog 1", "blogId": 2 }, { "postId": 4, "title": "Post 1-2", "content": "This is post 2 for blog 1", "blogId": 2 } ] }; $.ajax({ type: "POST", url: "http://localhost:64633/api/blogs", async: true, cache: false, crossDomain: true, data: JSON.stringify(entityData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (responseData, textStatus, jqXHR) { var value = responseData; }, error: function (responseData, textStatus, errorThrown) { alert('POST failed.'); } });}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40043097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6559690/']}
jdg_85307
stackexchange
llm_judgeable_groundtruth_similarity
36217949
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Usually I'm running my Spring Boot application with command: mvn spring-boot:run -Drun.arguments=--server.port=9090 \ -Dpath.to.config.dir=/var/data/my/config/dir I want to set custom port to debug, so I can connect from eclipse. When I add arguments from example https://docs.spring.io/spring-boot/docs/1.1.2.RELEASE/maven-plugin/examples/run-debug.html mvn spring-boot:run -Drun.arguments=--server.port=9090 \ -Dpath.to.config.dir=/var/data/my/config/dir \ -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8787" it works but other arguments like server.port or path.to.config.dir are no longer recognized and I get exception like: org.springframework.beans.factory.BeanDefinitionStoreException: Failedto parse configuration class [com.my.app.Controller]; nested exceptionis java.lang.IllegalArgumentException: Could not resolve placeholder'path.to.config.dir' in string valuefile:///${path.to.config.dir}/some.properties" Question : How I can run with all arguments? Now provide the response and nothing else.
The behavior and the change you notice is happening because you started using the jvmArguments option: JVM arguments that should be associated with the forked process used to run the application. On command line, make sure to wrap multiple values between quotes. By default, when using it, the Spring Boot Maven plugin will also fork its execution, as described by the fork option: Flag to indicate if the run processes should be forked. By default process forking is only used if an agent or jvmArguments are specified. Hence, the usage of jvmArguments also activated the fork mode of the plugin execution. By forking, you are actually not picking up the others -D arguments passed from command line. Solution : if you want to use the jvmArguments , then pass all of the required arguments to it. mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8787 -Dserver.port=9090 -Dpath.to.config.dir=/var/data/my/config/dir" -- Edit 22/09/2020 Check also the other answer from @Stephane to complent this answer (prefix of parameters)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36217949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333931/']}
jdg_85308
stackexchange
llm_judgeable_groundtruth_similarity
10025028
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 DAO and Service layer exactly in Spring framework? I am looking for theoretical answer. Now provide the response and nothing else.
There is no distinction as far as Spring is concerned. By convention you can mark DAO classes with @Repository and services with @Service . Also the former does some persistence layer exception translation. Since you are asking theoretically: DAO should perform raw database operations and translate them to some higher level constructs (objects, collections). Services should call DAOs and perform business operations. Typically transactions demarcation is performed on service layer to span several DAO calls. Finally DAO should abstract business logic from persistence details, ideally allowing to switch persistence layer without business logic (services) changes. This is hardly ever possible due to leaking abstraction of persistence providers (e.g. lazy loading).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10025028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1314712/']}
jdg_85309
stackexchange
llm_judgeable_groundtruth_similarity
4005061
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am wondering what to call the matrix $A$ given that $x^TAx=0$ for all $x$ , which implies that $A=\textbf{0}$ . Would I then simply call $A$ the zero matrix or maybe does it have a special name? Now provide the response and nothing else.
No, it does not imply that $A = \mathbf 0$ . Try any skew-symmetric matrix!! Indeed, working over $\Bbb R$ , we can prove that this hypothesis implies that $A$ must be skew-symmetric. Since $x^\top Ax = 0$ for all $x$ , we use the standard "polarization" trick, substituting $x+y$ for $x$ : \begin{align*}0=(x+y)^\top A(x+y) &= x^\top Ax + x^\top Ay + y^\top Ax + y^\top Ay \\ &= x^\top Ay + y^\top Ax = x^\top (A+A^\top)y.\end{align*} But if $x^\top By = 0$ for all $x$ and $y$ , we must have $B=\mathbf 0$ (take the standard basis vectors, if you want). So we conclude that $A^\top = -A$ . (The fundamental formula here at the last step is that, identifying a scalar and a $1\times 1$ matrix, we have $$x^\top Ay = (x^\top Ay)^\top = y^\top A^\top x = y^\top A^\top x.)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4005061', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332966/']}
jdg_85310
stackexchange
llm_judgeable_groundtruth_similarity
19649764
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is this piece of code safe from memory leaks? s := TStringList.Create; // create first objecttry // Here line comes that seems to be dangerous s := GetSomeSettings; // Overrides reference to first object by second onefinally s.free; // Destroying only second object, leave first object to live somewhere in memoryend;function GetSomeSettings : TStringList;var rawString : string; settings : TStringList;begin // Singleton pattern implementation // Trying to find already existing settings in class variable settings := TSettingsClass.fSettings; // If there is no already defined settings then get them if not Assigned(settings) then begin GetSettingsInDB(rawString); TSettingsClass.fSettings := ParseSettingsString(rawString); settings := TSettingsClass.fSettings; end; Result := settings;end; I'm wondering s := GetSomeSettings; potentially harmful and ignoring first object, keeps it in the memory? Now provide the response and nothing else.
Yes, the StringList created on line 1 is leaked. Essentialy, you are doing: s := TStringList.Create;s := AnotherStringList;AnotherStringList.Free; As for the GetSomeSettings routine: Normally it is not wise or encouraged to return newly created instances as function results, because you transfer the responsibility for ownership and destruction to the calling code. Unless you have a mechanism/framework in place that takes care of it, which seems to be the case with your TSettingsClass , but there is not enough evidence for that in this little piece of code. Nevertheless, the combination of both pieces of code display another problem: After s.Free , TSettingsClass.fSettings is destroyed but not nil. Thus the second time GetSomeSettings is called, it returns a dangling pointer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19649764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799007/']}
jdg_85311
stackexchange
llm_judgeable_groundtruth_similarity
26165996
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 see something like the following in code examples on StackOverflow and in themes for sale even (never in Bootstrap's examples). <div class="container"> <div class="row"> <div class="col-xs-12"> <p>Words go here</p> </div> </div> </div> OR <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <p>Words go here</p> </div> </div> </div> It drives me nuts because both are incorrect for full width single columns as per Bootstrap's own documentation and common sense. When do you actually use the grid system? When does col-*-12 come into play? Now provide the response and nothing else.
If something is full width, you don't need it at all. Learn: http://getbootstrap.com/examples/grid/ The correct html for both of the above examples is this: <div class="container"> <p>Words go here</p> </div> <!--/.container for entire grouping of elements you do not want to exceed the width(s) set in the CSS for this class --> If you want your columns to be full width, it will be under the last column class you used. The following will be full width below where the col-sm- min-width starts (so 767px and UNDER in a default download of Bootstrap 3.x). <div class="row"> <div class="col-sm-4"> Stuff </div><!-- /.col-sm-4 --> <div class="col-sm-8"> Stuff </div><!-- /.col-sm-8 --></div><!-- /.row --> Don't forget the outer .container or .container-fluid (one per grouping of content that does not change width). The .container or .container-fluid zeros out the negative margin on the .row so you won't get horizontal scroll bars. The situations when you use col-*-12 is where you want a full width AFTER the min-width of the smaller column class: <div class="row"> <div class="col-sm-6 col-md-12"> Stuff </div><!-- /.col-sm-6 col-md-12 --> <div class="clearfix visible-md"></div> <div class="col-sm-6 col-md-4"> Stuff </div><!-- /.col-sm-6 col-md-12 --></div><!-- /.row --> Anyway, col-*-12 comes in handy in nesting situations, especially with forms.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26165996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004312/']}
jdg_85312
stackexchange
llm_judgeable_groundtruth_similarity
15591364
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 subclassed the UITableViewCell in order to customize it, but I think I'm missing something because: 1) It's not working and 2) There are a couple of things I'm confused on. Along with customizing the look of the .xib file, I also changed the backgroundView, and that part is working fine. The part that I least understand/am most confused about is the init method, so I posted that here. If it turns out that is correct, please tell me so I can post more code that may be the cause. This is the init method, which I customized. I'm sort of confused around the "style" idea and I think I'm just returning a normal UITableViewCell with a different backgroundView. I mean, there's nothing in there that refers to the .xib or does anything but change the .backgroundView from the self: - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier wait: (float) wait fadeOut: (float) fadeOut fadeIn: (float) fadeIn playFor: (float) playFor{ self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { CueLoadingView* lview = [[CueLoadingView alloc] initWithFrame:CGRectMake(0, 0, 320, 53)]; self.backgroundView = lview; [self setWait:wait]; // in turn edits the lview through the backgrounView pointer [self setFadeOut:fadeOut]; [self setFadeIn:fadeIn]; [self setPlayFor:playFor]; } return self;} Other than the .xib and several setters and getters, this is the only real part of my code, that relates to retrieving a cell. Additional Information: 1) This is my .xib, which is linked to the class. 2) This is the code that calls/creates the UITableView (the delegate/view controller): - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *simpleTableIdentifier = @"CueTableCell"; CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { cell = [[CueTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier wait:5.0 fadeOut:1.0 fadeIn:1.0 playFor:10.0]; [cell updateBarAt:15]; } return cell;} Now provide the response and nothing else.
The easiest way (available since iOS 5.0) to create a custom table view cell in a nib file is to use registerNib:forCellReuseIdentifier: in the table view controller. The big advantage is that dequeueReusableCellWithIdentifier: then automatically instantiates a cell from the nib file if necessary. You don't need the if (cell == nil) ... part anymore. In viewDidLoad of the table view controller you add [self.tableView registerNib:[UINib nibWithNibName:@"CueTableCell" bundle:nil] forCellReuseIdentifier:@"CueTableCell"]; and in cellForRowAtIndexPath you just do CueTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CueTableCell"];// setup cellreturn cell; Cells loaded from a nib file are instantiated using initWithCoder , you can override that in your subclass if necessary. For modifications to the UI elements, you should override awakeFromNib (don't forget to call "super").
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15591364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1218699/']}
jdg_85313
stackexchange
llm_judgeable_groundtruth_similarity
553816
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: Hypothetical situation here, as techniques like bootstrapping often fail for very small datasets. Taking bootstrapping as an example nonetheless. we can easily compute the number of possible bootstrap (re)samples. A nice answer is given by @whuber here: Amount of Possible Bootstrap Samples Suppose for a moment that bootstrapping is perfectly valid for low sample sizes. Now, say we have $n = 5$ . From the posted solution above, it is found that there are a total of 126 possible boostrap resamples that can be drawn. In bootstrapping, we usually take a large number of replications (10000 for instance). Taking this many replicates for such a small dataset, like the one above, seems bizarre, since resamples will be counted multiple times. Question : Does this really matter? If yes. what is the effect on inference? Now provide the response and nothing else.
When bootstrapping, we are assuming that the sample is representative of the population. The whole purpose of bootstrapping is to estimate a sampling distribution and infer the likely standard errors and confidence intervals for the population as a whole. However, the issue with small sample sizes is that bias is more likely to exist relative to large samples - and (contrary to popular belief) bootstrapping does not fix this bias or remedy the issue of small sample sizes. For instance, suppose one were to roll a dice five times. The numbers 4, 5, 6, 6, 6 are obtained, for an average of 5.4 . If one were to roll a dice a hundred times, an average closer to 3.5 could be expected - which is the theoretical mean. However, small samples have a higher chance of deviating significantly from the population mean and so bootstrap sampling will not remedy this by virtue of simply generating more observations.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/553816', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/175663/']}
jdg_85314
stackexchange
llm_judgeable_groundtruth_similarity
43937031
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 2 Spring Boot (1.4.1-RELEASE) console applications using Logback. Both configuration files are more or less identical, are located in my /src/main/resources folder and named logback-spring.xml . Both projects include the maven dependency spring-boot-starter-logging in their pom.xml and fetch the logback Version 1.1.7. The Spring Boot config as defined in both poms: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> <relativePath /></parent><groupId>d.m.v.app-a</groupId><artifactId>my-app-a</artifactId><version>1.0.16-SNAPSHOT</version><packaging>jar</packaging> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency></dependencies> However, when running the applications one of them seems to fully ignore the logback configuration while the other picks it up like expected. If I change the filename to logback.xml for the application that didn't work properly it suddenly works fine (even with the spring profiles that I'm using in them). There is no apparent difference in any of the configurations involved (meaning the pom.xml, application.properties, etc.). Does anybody know why that might be the case? I find this behaviour rather confusing. Now provide the response and nothing else.
I know it is somewhat old, but i had the same issue and figured it out... so the reason is simply that you have a logback.xml on your classpath (somewhere, not necessarily in your project which you start, in my case it was a dependency). Take a look here: org.springframework.boot.logging.AbstractLoggingSystem.initializeWithConventions(LoggingInitializationContext, LogFile) set a breakpoint, then you will see. If spring boot doesn't find any logback configurations ("logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml") on the classpath, logback-spring.xml will be picked up.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43937031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7068769/']}
jdg_85315
stackexchange
llm_judgeable_groundtruth_similarity
1846836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between the "Floyd-Warshall algorithm" and "Dijkstra's Algorithm" , and which is the best for finding the shortest path in a graph? I need to calculate the shortest path between all the pairs in a net and save the results to an array as follows: **A B C D E**A 0 10 15 5 20B 10 0 5 5 10C 15 5 0 10 15D 5 5 10 0 15E 20 10 15 15 0 Now provide the response and nothing else.
Dijkstra 's algorithm finds the shortest path between a node and every other node in the graph. You'd run it once for every node. Weights must be non-negative, so if necessary you have to normalise the values in the graph first. Floyd-Warshall calculates the shortest routes between all pairs of nodes in a single run! Cycle weights must be non-negative, and the graph must be directed (your diagram is not). Johnson 's algorithm is using Dijkstra's algorithm to find all pairs in a single pass, and is faster for sparse trees (see the link for analysis).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1846836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217228/']}
jdg_85316
stackexchange
llm_judgeable_groundtruth_similarity
26822717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: [Running perl 5.16.2 on OS X 10.9.5] I have a little Secret Santa perl script I dust off once a year, and now this time it has decided to give me a hassle. (I do have a new computer as well, so there does exist a different environment from last year.) I am calling: $smtp = Net::SMTP::SSL->new(Host => "mail.mydomain.org", Port => 465); and when this returns, $smtp contains no value ( 'p $smtp' in the perl debugger just displays a blank line) and subsequent accesses like $stmp->domain (and $smtp->auth() ) fail with the error Can't call method "domain" on an undefined value at ./secretsanta.pl line 67. What am I missing here? Thanks for any pointers. EDIT: when I turn on SSL debugging ( perl -MIO::Socket::SSL=debug4 secretsanta.pl ) I get: DEBUG: .../IO/Socket/SSL.pm:1769: Invalid default certificate authority locations SSL error: 8606: 1 - error:2006D002:BIO routines:BIO_new_file:system lib SSL error: 8606: 2 - error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system libDEBUG: .../IO/Socket/SSL.pm:1774: Invalid default certificate authority locations error:0200100D:system library:fopen:Permission denied DEBUG: .../IO/Socket/SSL.pm:529: socket not yet connected DEBUG: .../IO/Socket/SSL.pm:531: socket connected DEBUG: .../IO/Socket/SSL.pm:553: ssl handshake not started DEBUG: .../IO/Socket/SSL.pm:1769: SSL structure creation failedDEBUG: .../IO/Socket/SSL.pm:1774: SSL structure creation failed error:140BA0C3:SSL routines:SSL_new:null ssl ctxDEBUG: .../IO/Socket/SSL.pm:1758: IO::Socket::INET configuration failed (I am using an SSL cert provided by my hosting company that doesn't match the DNS name of my mail server, but obviously something changed from last year to cause this not to work.) Now provide the response and nothing else.
By default, GCC compiles C++-code for gnu++98 , which is a fancy way of saying the C++98 standard plus lots of gnu extenstions. You use -std=??? to say to the compiler what standard it should follow. Don't omit -pedantic though, or it will squint on standards-conformance. The options you could choose: standard with gnu extensionsc++98 gnu++98c++03 gnu++03c++11 (c++0x) gnu++11 (gnu++0x)c++14 (c++1y) gnu++14 (gnu++1y) Coming up: c++1z gnu++1z (Planned for release sometime in 2017, might even make it.) GCC manual: https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/Standards.html#Standards Also, ask for full warnings, so add -Wall -Wextra . There are preprocessor-defines for making the library include additional checks : _GLIBCXX_CONCEPT_CHECKS to add additional compile-time-checks for some templates prerequisites. Beware that those checks don't actually always do what they should, and are thus deprecated. _GLIBCXX_DEBUG . Enable the libraries debug-mode. This has considerable runtime-overhead. _GLIBCXX_DEBUG_PEDANTIC Same as above, but checks against the standards requirements instead of only against the implementations.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26822717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/610090/']}
jdg_85317
stackexchange
llm_judgeable_groundtruth_similarity
52558150
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 Jenkins running on an EC2 Instance. I have the EC2 Plugin Configured in a Peered VPC, and when a job is tagged 'support_ubuntu_docker' it will spin up an Jenkins Slave, with Docker pre-installed. I am able to follow the examples, and get my job to connect to the local docker running on the Slave, and run commands inside the container. Working: https://pastebin.com/UANvjhnA pipeline { agent { docker { image 'node:7-alpine' label 'support_ubuntu_docker' } } stages { stage('Test') { steps { sh 'node --version' } } }} Not Working https://pastebin.com/MsSZaPha pipeline { agent { docker { image 'hashicorp/terraform:light' label 'support_ubuntu_docker' } } stages { stage('Test') { steps { sh 'terraform --version' } } }} I have tried with the ansible/ansible:default image, as well as a image I created myself. FROM alpine:3.7RUN apk add --no-cache terraformRUN apk add --no-cache ansibleENTRYPOINT ["/bin/ash"] This image behaves locally. [jenkins_test] docker exec -it 3843653932c8 ash 10:56:42 ☁ master ☂ ⚡ ✭/ # terraform --versionTerraform v0.11.0/ # ansible --versionansible 2.4.6.0 config file = None configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.15 (default, Aug 22 2018, 13:24:18) [GCC 6.4.0]/ # I really just want to be able to clone my terraform git repo, and use the terraform in the container to run my init/plan/applies. The error im getting for all of these is. java.io.IOException: Failed to run top 'c9dfeda21b718b9df1035500adf2ef80c5c3807cf63e724317d620d4bcaa14b3'. Error: Error response from daemon: Container c9dfeda21b718b9df1035500adf2ef80c5c3807cf63e724317d620d4bcaa14b3 is not running Now provide the response and nothing else.
The question really should have been a Docker question; what's the difference between node:7-alpine and hashicorp/terraform:light ? hashicorp/terraform:light has an ENTRYPOINT entry, pointing to /bin/terraform . Basically that means you run it this way: docker run hashicorp/terraform:light --version And it will exit right away, i.e., it's not interactive. So if you want an interactive shell within that Docker container, you'll have to override the ENTRYPOINT to point at a shell, say, /bin/bash and also tell Docker to run interactively: pipeline { agent { docker { image 'hashicorp/terraform:light' args '-it --entrypoint=/bin/bash' label 'support_ubuntu_docker' } } stages { stage('Test') { steps { sh 'terraform --version' } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52558150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9891985/']}
jdg_85318
stackexchange
llm_judgeable_groundtruth_similarity
14323082
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <html> <head> <title> Colors </title> </head> <body> <script type="text/javascript"> var a = parseInt(prompt("Enter R")); var b = parseInt(prompt("Enter G")); var c = parseInt(prompt("Enter B")); document.body.style.backgroundColor=rgb(a,b,c); </script> </body></html> Why doesn't the background color change according to the RGB values? What have I done wrong?? Now provide the response and nothing else.
You need to use quotes: document.body.style.backgroundColor = 'rgb(' + a + ',' + b + ',' + c + ')'; JS Fiddle demo . Or: document.body.style.backgroundColor = 'rgb(' + [a,b,c].join(',') + ')'; JS Fiddle demo . Unquoted the JavaScript is passing the variables, as arguments, a , b and c to an undefined function called rgb() . As you're setting a CSS property you need to pass a string, hence the requirement of quoting . Oh, and also you're using parseInt() which doesn't require a radix to be passed in, but it's better (and easier to avoid problems) if you do (the radix being the expected number-base): var a = parseInt(prompt("Enter R"), 10) || 255, b = parseInt(prompt("Enter G"), 10) || 255, c = parseInt(prompt("Enter B"), 10) || 255; JS Fiddle demo (In the demo I use 105 just so it's clear the default is being used if the cancel button is used). And if someone hits 'cancel' on the prompt, you might want to supply a default argument to ensure that an actual colour-value is passed, since cancel otherwise, I think, evaluates to false (I'm assuming you'd prefer 255 , but obviously adjust to taste). You could also, of course, simply define a function: function rgb(r,g,b) { return 'rgb(' + [(r||0),(g||0),(b||0)].join(',') + ')';} var a = parseInt(prompt("Enter R"), 10), b = parseInt(prompt("Enter G"), 10), c = parseInt(prompt("Enter B"), 10); document.body.style.backgroundColor = rgb(a,b,c); JS Fiddle demo And this approach has the (perhaps specious) benefit of allowing a custom default value to be used: function rgb(r,g,b, def) {def = parseInt(def, 10) || 0; return 'rgb(' + [(r||def),(g||def),(b||def)].join(',') + ')';}var a = parseInt(prompt("Enter R"), 10), b = parseInt(prompt("Enter G"), 10), c = parseInt(prompt("Enter B"), 10);document.body.style.backgroundColor = rgb(a,b,c,40); JS Fiddle demo References: || (logical OR ) operator . Array.join() . Element.style . parseInt() .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14323082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1643837/']}
jdg_85319
stackexchange
llm_judgeable_groundtruth_similarity
249369
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have many big CSV files for processing in Mathematica.And each time loading them into Mathematica takes a long time.Meanwhile, it takes much less time using Pandas under Python . For example, Mathematica takes much longer to import this test file ( download ) than Pandas: fn = "/Users/sunt05/Dropbox/Public/test.csv";(*Mathematica*)ds = Import[fn, "Dataset", "HeaderLines" -> 1]; // AbsoluteTiming(*{7.48445, Null}*)(*Pandas*)session = StartExternalSession["Python"];py = ExternalEvaluate[session];py[StringTemplate["import pandas as pd; res=pd.read_csv('``')"][fn]] // AbsoluteTiming(*{0.966052, Null}*) So, how can we build a fast CSV reader in Mathematica? Edit: Thanks folks for the interests! For using Dataset in the comparison, I just wanted to make the comparison more fair from the user perspective with respect to functionality: Dataset seems more analogous to pandas.DataFrame if a user wants to further process the imported data. Now provide the response and nothing else.
I think you've actually answered the question yourself - which is to say, perhaps just use pandas with ExternalEvaluate ? The answer here and the "Python" External Evaluation System guide suggest that data can be transferred quite efficiently back to Mathematica (at-least in the case of numpy arrays, but the cost of converting should be manageable). So we can do something like this: AbsoluteTiming[ds2 = ExternalEvaluate["Python", "import pandas as pdres=pd.read_csv('/home/george/Downloads/test.csv')res.to_numpy()"];]{1.28181, Null} This is indeed much faster than Import : AbsoluteTiming[ds = Import["/home/george/Downloads/test.csv", "HeaderLines" -> 1];]{5.93136, Null} PS your "Dataset" format specification was part of the timing discrepancy above, so perhaps a slightly unfair comparison.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/249369', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/260/']}
jdg_85320
stackexchange
llm_judgeable_groundtruth_similarity
28557384
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 created two Docker containers. The first one provides a private Docker registry and the second one is a mirror of the official Docker registry: docker run -d --name registry -v /local/path/to/registry:/registry -e SETTINGS_FLAVOR=local -e STORAGE_PATH=/registry -p 5000:5000 registrydocker run -d --name mirror -v /local/path/to/mirror:/registry -e STORAGE_PATH=/registry -e STANDALONE=false -e MIRROR_SOURCE=https:/registry-1.docker.io -e MIRROR_SOURCE_INDEX=https://index.docker.io -p 5555:5000 registry Now I would like to combine both. Whenever a user pulls images it should first query the private registry and then the mirror. And when images are pushed they should only be pushed to the private registry. I do not have an idea about how this can be done. Any help is appreciated. Now provide the response and nothing else.
You cannot just force all docker push commands to push to your private registry. One reason is that you can have any number of those registers. You have to first tell docker where to push by tagging the image (see lower). Here is how you can setup docker hosts to work with a running private registry and local mirror. Client set-up Lets assume that you are running both mirror and private registry on (resolvable) host called dockerstore . Mirror on port 5555, registry on 5000. Then on client machine(s) you should pass extra options to docker daemon startup. In your case: Add --registry-mirror=http://dockerstore:5555 to tell daemon to prefer using local mirror rather then dockerhub. source Add --insecure-registry dockerstore:5000 to access the private registry without further configuration. See this answer Restart docker daemon Using the mirror When you pull any image the first source will be the local mirror. You can confirm by running a docker pull, e.g. docker pull debian In the output there will be message that image is being pulled from your mirror - dockerstore:5000 Using local registry In order to push to private registry first you have to tag the image to be pushed with full name of the registry. Make sure that you have a dot or colon in the first part of the tag , to tell docker that image should be pushed to private registry. Docker looks for either a “.” (domain separator) or “:” (port separator) to learn that the first part of the repository name is a location and not a user name. Example: Tag 30d39e59ffe2 image as dockerstore:5000/myapp:stable docker tag 30d39e59ffe2 dockerstore:5000/myapp:stable Push it to private registry docker push dockerstore:5000/myapp:stable Then you can pull as well docker pull dockerstore:5000/myapp:stable
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28557384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2706422/']}
jdg_85321
stackexchange
llm_judgeable_groundtruth_similarity
728043
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 .NET 3.5 and building pages inside of the Community Server 2008 framework. On one of the pages, I am trying to get an UpdatePanel working. I took a sample straight from ASP.NET website, update a time in an UpdatePanel to current time by clicking a button, but for some reason when I try and perform the function the whole page refreshes. Here is what I have: protected void Button1_Click(object sender, EventArgs e){ Label1.Text = "Panel refreshed at " + DateTime.Now.ToString(); Label2.Text = "Panel refreshed at " + DateTime.Now.ToString();} <asp:ScriptManager ID="ScriptManager1" runat="server"/><asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <fieldset> <legend>UpdatePanel</legend> <asp:Label ID="Label1" runat="server" Text="Panel created."></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </fieldset> </ContentTemplate></asp:UpdatePanel> Whenever I click the button, sure the panel updates - but the whole page posts back! I can see the whole page flashing. What the heck am I doing wrong? I am inside of a nested Masterpage, but I'm not sure if this is a problem. Could there be something in this Community Server framework that I'm using that causes all events to postback? Now provide the response and nothing else.
Did you try setting Button1 as an AsyncPostBackTrigger in the Triggers section? Set the ChildrenAsTriggers property to true and the UpdateMode property to Conditional . protected void Button1_Click(object sender, EventArgs e){ Label1.Text = "Panel refreshed at " + DateTime.Now.ToString(); UpdatePanel1.Update();} <asp:ScriptManager ID="ScriptManager1" runat="server"/><asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" /> </Triggers> <ContentTemplate> <fieldset> <legend>UpdatePanel</legend> <asp:Label ID="Label1" runat="server" Text="Panel created."></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </fieldset> </ContentTemplate></asp:UpdatePanel>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/728043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53885/']}
jdg_85322
stackexchange
llm_judgeable_groundtruth_similarity
21013678
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 up to build my first in-app purchase app. I would like to know whether there is a way to verify purchase on your server. I have to build the whole user management, and I would like to know for all registered user what they already bought on their iOS devices, so that they get web app for free, or something like that. So, is there a way for me to check on Apple store side, if this user has already buy some product? EDIT: Scenario is like this: User A buy app B on mobile device. After this I would like to check on my server (on my web page,...) if user A is bought app B, or (similar) which app was bought by user A. I don't want to send message from mobile device to my server that user A buy app B, because users can reproduce this call on server even if they didn't buy app B. I would check on server side whit app Store if user A bought app B. Now provide the response and nothing else.
Fetch the app's receipt (from the file at [[NSBundle mainBundle] appStoreReceiptURL] ) and send it to your server. Then either… Parse the receipt and check its signature against Apple's certificate as described here (on your server, not in the app). Or, Send the receipt (again, from your server) to the app store for validation as described here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21013678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2791346/']}
jdg_85323
stackexchange
llm_judgeable_groundtruth_similarity
35248217
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to combine multiple CTEs in single query? I am looking for way to get result like this: WITH cte1 AS (...),WITH RECURSIVE cte2 AS (...),WITH cte3 AS (...)SELECT ... FROM cte3 WHERE ... As you can see, I have one recursive CTE and two non recursive. Now provide the response and nothing else.
Use the key word WITH once at the top. If any of your Common Table Expressions (CTE) are recursive (rCTE) you have to add the keyword RECURSIVE at the top once also, even if not all CTEs are recursive: WITH RECURSIVE cte1 AS (...) -- can still be non-recursive, cte2 AS (SELECT ... UNION ALL SELECT ...) -- recursive term, cte3 AS (...)SELECT ... FROM cte3 WHERE ... The manual: If RECURSIVE is specified, it allows a SELECT subquery toreference itself by name. Bold emphasis mine. And, even more insightful: Another effect of RECURSIVE is that WITH queries need not be ordered :a query can reference another one that is later in the list. (However,circular references, or mutual recursion, are not implemented.)Without RECURSIVE , WITH queries can only reference sibling WITH queries that are earlier in the WITH list. Bold emphasis mine again. Meaning that the order of WITH clauses is meaningless when the RECURSIVE key word has been used. BTW, since cte1 and cte2 in the example are not referenced in the outer SELECT and are plain SELECT commands themselves (no collateral effects), they are never executed (unless referenced in cte3 ).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35248217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5773006/']}
jdg_85324
stackexchange
llm_judgeable_groundtruth_similarity
604712
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I randomly pick $k$ elements form a set $A$ of $n$ elements ($\binom{n}{k}$ combinations).Assume the random distribution is totally even. I now examine a given subset $B$ of $m$ elements from set $A$. How can I calculate the average number $r$ of elements, randomly picked from $A$ that belong to $B$? My stab at my own answer (with some help) is to first find the probability of finding $i$ elements ($i$ ranging from $0$ to $k$) in $B$ that were chosen in $A$: $P(i) = {\binom{m}{i} \times \binom{n-m}{k-i}\over{\binom{n}{k}}}$. Then $r = \sum_{i=0}^k{i*P(i)}$. I know this is wrong but I can't say why. Any help appreciated. Now provide the response and nothing else.
This follows immediately from the Cauchy–Schwarz inequality :$$\left(\int_0^1 f(x)dx\right) \left(\int_0^1 \frac{1}{f(x)} dx\right) \ge \left(\int_0^1 \sqrt{f(x)} \frac{1}{\sqrt{f(x)}} dx\right)^2 = 1$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/604712', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6258/']}
jdg_85325
stackexchange
llm_judgeable_groundtruth_similarity
1879255
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any performance testing results available in comparing traditional for loop vs Iterator while traversing a ArrayList,HashMap and other collections? Or simply why should I use Iterator over for loop or vice versa? Now provide the response and nothing else.
Assuming this is what you meant: // traditional for loopfor (int i = 0; i < collection.size(); i++) { T obj = collection.get(i); // snip}// using iteratorIterator<T> iter = collection.iterator();while (iter.hasNext()) { T obj = iter.next(); // snip}// using iterator internally (confirm it yourself using javap -c)for (T obj : collection) { // snip} Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible. Edit: I believe that micro-benchmarking is root of pretty much evil, just like early optimization. But then again, I think it's good to have a feeling for the implications of such quite trivial things. Hence I've run a small test : iterate over a LinkedList and an ArrayList respecively with 100,000 "random" strings summing up their length (just something to avoid that compiler optimizes away the whole loop) using all 3 loop styles (iterator, for each, for with counter) Results are similar for all but "for with counter" with LinkedList. All the other five took less than 20 milliseconds to iterate over the whole list. Using list.get(i) on a LinkedList 100,000 times took more than 2 minutes (!) to complete (60,000 times slower). Wow! :) Hence it's best to use an iterator (explicitly or implicitly using for each), especially if you don't know what type and size of list your dealing with.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1879255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169651/']}
jdg_85326
stackexchange
llm_judgeable_groundtruth_similarity
258020
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following function f = 1/Gamma[(1 + d)/2] \[Pi]^( 1/2 (-1 + d)) (( Sqrt[2] (-1 + d) r^5 (2 + r^(-4 + 2 d)) Hypergeometric2F1[-(1/2), 1/(-4 + 2 d), 1 + 1/(-4 + 2 d), -(1/2) r^(-4 + 2 d)])/( 2 r^4 + r^(2 d)) + ( r^(-1 + d) (6 - 4 d + ( Sqrt[2] (2 - 3 d + d^2) r^( 2 + d) (2 + r^(-4 + 2 d)) Hypergeometric2F1[1/2, (3 - 2 d)/( 4 - 2 d), (7 - 4 d)/( 4 - 2 d), -(1/2) r^(-4 + 2 d)])/((-3 + 2 d) (2 r^4 + r^( 2 d))) + 2 (-1 + d) Log[(2 r^d)/(r^d + r^2 Sqrt[2 + r^(-4 + 2 d)])]))/( 2 (-1 + d))) Mathematica can not evaluate the limit of $f$ when $r$ goes to infinity. Limit[f, r -> Infinity, Assumptions -> d >= 4] Is there anyway that this limit can be evaluated by Mathematica?Note that if I first put $d=4$ or $5$ or ... and then take the limit, Mathematica find the answer. Limit[f /. d -> 4, r -> Infinity]-(2/9) 2^(3/4) Sqrt[\[Pi]] (9 Gamma[-(3/4)] + 4 Gamma[1/4]) Gamma[5/4] But I need the general relation as a function of $d$ . Now provide the response and nothing else.
f[d_, r_] = 1/Gamma[(1 + d)/2] π^(1/2 (-1 + d))((Sqrt[2] (-1 + d) r^5 (2 + r^(-4 + 2 d)) Hypergeometric2F1[-(1/2), 1/(-4 + 2 d), 1 + 1/(-4 + 2 d), -(1/2) r^(-4 + 2 d)])/(2 r^4 + r^(2 d)) + (r^(-1 + d) (6 - 4 d + (Sqrt[2] (2 - 3 d + d^2) r^(2 + d) (2 + r^(-4 + 2 d)) Hypergeometric2F1[1/2, (3 - 2 d)/(4 - 2 d), (7 - 4 d)/(4 - 2 d), -(1/2) r^(-4 + 2 d)])/((-3 + 2 d) (2 r^4 + r^(2 d))) + 2 (-1 + d) Log[(2 r^d)/(r^d + r^2 Sqrt[2 + r^(-4 + 2 d)])]))/(2 (-1 + d)));F[d_] := F[d] = Limit[f[d, r], r -> ∞]Table[F[d] == -((2^(1/2 (-3 + 1/(-2 + d))) π^(-1 + d/2) * Gamma[-((-1 + d)/(2 (-2 + d)))] * Gamma[1/(-4 + 2 d)])/Gamma[(1 + d)/2]), {d, 4, 20}] // FullSimplify(* {True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True} *) So it looks like the limit is $$-\frac{2^{\frac{1}{2} \left(\frac{1}{d-2}-3\right)} \pi ^{\frac{d}{2}-1} \Gamma \left(-\frac{d-1}{2 (d-2)}\right) \Gamma \left(\frac{1}{2 d-4}\right)}{\Gamma \left(\frac{d+1}{2}\right)}$$
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/258020', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1894/']}
jdg_85327
stackexchange
llm_judgeable_groundtruth_similarity
148391
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently became interested in agile practices in software development and I since have seen a lot of articles point out that these practices allow for reduced overall costs. The logic behind that usually goes like this: if your requirements change, you can reflect this change in the next sprint backlog and this will lead to reduced cost, because designing the new feature and implementing it is close together in terms of time, so the cost goes down, according to the famous rule that the later you need to make a change to your requirements the more expensive it will be to satisfy that requirement. But mid to big software projects are complex. A sudden change to requirements does not mean you won't have to touch other parts of your system in order to satisfy that requirement. In a lot of cases the architecture will need to be modified very significantly, which will also mean you'll need to re-implement all the features that relied on the older architecture. So the whole point of reduced costs kinda goes away here. Of course if a new requirement calls for a new independent part of the system, that's not a problem, the old architecture just grows, it doesn't need to be rethought and reimplemented. And the opposite. If you are using waterfall and you suddenly realize that a new requirement has to be introduced, you can go and change your design. If it requires that existing architecture is altered, you redesign it. If it does not really mess with it but just introduces a new part of the system, then you go and do all the work, no problem here. With that said, it seems to me like the only advantage agile development has is working feature complete builds between sprints, and for a lot of people and prjects this is not critical. In addition, agile seems like it results in bad software architecture overall, because features kinda get slapped one onto another, agile teams only care that a feature works, not how it works. This seems like that when systems grow in complexity with time, agile development practices actually increase chaos in the overall product architecture, thus eventually resulting in higher costs, since it will be increasingly more difficult to introduce changes, whereas waterfall allows you to perfect your architecture before you release anything. Can somebody please point me as to where I'm going wrong here, because obviously a lot of people use agile in production environments, so I must be wrong somewhere. Now provide the response and nothing else.
First off, the "waterfall" model was always a straw man describing how NOT to run a software development project. Look it up. Anyhow, most "waterfall" SDLC projects entail a "Change Management" process, for when people discover that the assumptions that were written into the specifications are no longer valid (and this always happens on large complex projects). Unfortunately, the change management process is built as an exception handling measure, and is stupidly expensive, meaning the project will end up late, or of poor quality. The idea behind Agile methodologies is that change is a given--it will happen. Therefore, you must make "change management" standard operation rather than exception handling. This isn't easy, but folks have found that if you use a lot of good design practices, you can do it. Another major problem with front loaded design is that (most often) so much time is spent in requirements gathering and design, development and testing time suffers. Also, if testing is the last phase, and a serious problem is discovered, it is highly unlikely to get fixed within your time frame. Perhaps one of the best features of an Agile approach is that it demands continued interaction (that is, real communication) between the team developing the solution, and the customer who needs it. Priorities are made, so that the highest priority items are done first (and if time runs out, it's the low priority items that are cut). Feedback comes quickly. Going back to the question of dramatic changes--you really need to use methods that mitigate changes. Good SOLID OO principals can play a good part of this, as can building solid automated test suites so that you can regression test your software. You should do these things regardless of your methodology, but they become truly essential if you are trying to be agile.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/148391', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/53916/']}
jdg_85328
stackexchange
llm_judgeable_groundtruth_similarity
193201
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: This is an exercise for the book Abstract Algebra by Dummit and Foote(pg. 519): show $x^{5}-ax-1\in\mathbb{Z}[x]$ is irreducible for $a\neq-1,0,2$ I need help with this exercise, I don't have an idea on how to provethere are no quadratic factors for $a\neq-1,0,2$ (for $a=-1$ thereis a quadratic factor). Now provide the response and nothing else.
Let $P=X^5-aX-1$ . If $P$ had a rational root $\frac{p}{q}$ with $p$ and $q$ coprime, we would deduce $p^5-apq^4-q^5=0$ . Then $p$ divides $p^5-apq^4$ , we see that $p$ divides $q^5$ . By iterating Gauss' lemma, $p$ divides $q^4,q^3,q^2$ etc and finally $p$ divides $1$ , so $p=\pm 1$ . Similarly $q$ divides $p^5$ so $q=\pm 1$ . So the only rational roots possible are $-1$ (corresponding to $a=2$ ) and $1$ (corresponding to $a=0$ ). So $P$ has no degree $1$ factors. So all we've left to show is that there is no factor of degree $2$ . So assume $P=UV$ , with $U,V \in {\mathbb Z}[X]$ and ${\sf deg}(U)=3, {\sf deg}(V)=2$ . Since $P$ is monic, $U$ and $V$ are monic also (we replace them by their opposites if necessary). Write $U=X^3+u_2X^2+u_1X+u_0$ and $V=X^2+v_1X+v_0$ . Then, $$P=UV=X^5+(u_2+v_1)X^4+(u_2v_1+u_1+v_0)X^3+(u_2v_0+u_1v_1+u_0)X^2+(u_1v_0+u_0v_1)X+u_0v_0$$ Identifying the coefficients in $X^4,X^3,X^2$ , we express $u_0,u_1,u_2$ in terms of the other coefficients : $$u_2=-v_1,u_1=v_1^2-v_0,u_0=2v_0v_1-v_1^3$$ Then the product $UV$ becomes $$UV=X^5-(v_1^4-3v_0v_1^2+v_0^2)X+(2v_0^2v_1-v_0v_1^3)$$ The constant coefficient can be factorized as $v_0v_1(2v_0-v_1^2)$ . So $v_0,v_1$ and $2v_0-v_1^2$ must all be equal to $1$ or $-1$ . So necessarily $v_0=1,v_1=-1$ , and hence $U=X^3+X^2-1,V=X^2-X+1,a=-1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/193201', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21335/']}
jdg_85329
stackexchange
llm_judgeable_groundtruth_similarity
58593887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my .env file, I have specified my app environment to be dev and debug to be true like so: APP_ENV=devAPP_DEBUG=true In my config/packages/dev/web_profiler.yaml file I have the following: web_profiler: toolbar: true intercept_redirects: falseframework: profiler: { only_exceptions: false } The routing within config/routes/dev/web_profiler.yaml seems to be fine: web_profiler_wdt: resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml' prefix: /_wdtweb_profiler_profiler: resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml' prefix: /_profiler So when I run the server with symfony server:start everything is fine, but the profiler doesn't appear. Did I miss something that enables that feature within Symfony? To clarify, the page is outputting a proper HTML page with the appropriate content. There is just no profiler showing up. My base twig template: <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %} {% endblock %}</title> {{ encore_entry_script_tags('base') }} <link rel="icon" type="image/x-icon" href="{{ asset('build/images/favicon.ico') }}" /> <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,500|Playfair+Display:400,700&display=swap" rel="stylesheet"> {{ encore_entry_link_tags("base") }} {% block stylesheet %}{% endblock %} </head> <body {% if app.request.get('_route') == 'home' %} class='homepage' {% endif %} > <header> <div id='top-navigation' class='padding-lg__left-md padding-lg__right-md padding-lg__top-sm padding-lg__bottom-sm row row__align-center row__justify-start'> <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Mission</span> <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Team</span> <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Where the Money Goes</span> <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Community Leadership</span> <span class='text-color__white text-size__small text-weight__bold'>Policies</span> <span class='text-color__white text-size__small text-weight__bold margin-lg__left-auto icon-set'> <span class='icon size__small color__white margin-lg__right-xsm'>{{ source('@public_path'~asset('build/images/icons/feedback.svg')) }}</span>Submit Feedback</span> </div> <nav class="padding-lg__top-md padding-lg__bottom-md padding-lg__left-md padding-lg__right-md row row__align-center row__justify-start {% if app.request.get('_route') == 'home' %} homepage {% endif %}"> <div id='logo'> <a href="{{ url('home') }}"> <img src="{{ asset('build/images/logo_placeholder.png') }}" alt="logo"> </a> </div> {% if app.request.get('_route') == 'creator-register' %} {% else %} {% if not is_granted('IS_AUTHENTICATED_FULLY') %} <div class='margin-lg__left-auto'> <a href="{{ url('login') }}"> <div class='icon-set'> <span class='icon margin-lg__right-xsm'> {{ source('@public_path'~asset('build/images/icons/user.svg')) }} </span> <span class='nav-item'>Login</span> </div> </a> </div> {% endif %} {% endif %} </nav> </header> {% if app.request.get('_route') != 'home' %} <div class='container is_top'> {% endif %} {% block body %} {% endblock %} {% if app.request.get('_route') != 'home' %} </div> {% endif %} </body></html> Security.yaml firewall: firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: anonymous: true guard: authenticators: - App\Security\LoginFormAuthenticator logout: path : logout remember_me: secret: '%kernel.secret%' lifetime: 2592000 #<- 30 days in seconds - defaults to one year if you take this out! Results on php bin/console debug:router | grep _profiler : _profiler_home ANY ANY ANY /_profiler/ _profiler_search ANY ANY ANY /_profiler/search _profiler_search_bar ANY ANY ANY /_profiler/search_bar _profiler_phpinfo ANY ANY ANY /_profiler/phpinfo _profiler_search_results ANY ANY ANY /_profiler/{token}/search/results _profiler_open_file ANY ANY ANY /_profiler/open _profiler ANY ANY ANY /_profiler/{token} _profiler_router ANY ANY ANY /_profiler/{token}/router _profiler_exception ANY ANY ANY /_profiler/{token}/exception _profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css Lastly homepage controller: <?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Annotation\Route;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;class HomepageController extends AbstractController{ /** * @Route("/", name="home") */ public function output(){ return $this->render('homepage/home.html.twig',[ 'title' => 'yo', ]); }}?> Added public/index.php: <?phpuse App\Kernel;use Symfony\Component\Debug\Debug;use Symfony\Component\HttpFoundation\Request;require dirname(__DIR__).'/config/bootstrap.php';if ($_SERVER['APP_DEBUG']) { umask(0000); Debug::enable();}if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);}if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts([$trustedHosts]);}$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);$request = Request::createFromGlobals();$response = $kernel->handle($request);$response->send();$kernel->terminate($request, $response); Now provide the response and nothing else.
It's very hard, if not impossible, to debug this for you remotely. The exact problem is tied to something specific in your local setup, and someone without access to your project would not have a chance to see exactly what is wrong. Some general and specific troubleshooting advice for your situation: 1st. Reinstall the profiler pack While unusual, the installation could be borked. Make sure your profiler package is alright. First remove it ( composer remove profiler ), and then install it again: composer require --dev profiler ). 2nd. Check the configuration Use Symfony's console command to verify your configuration. First for the built-in profiler: $ bin/console debug:config framework profiler Which should return something like this: Current configuration for "framework.profiler"==============================================only_exceptions: falseenabled: truecollect: trueonly_master_requests: falsedsn: 'file:%kernel.cache_dir%/profiler' And then for the profiler toolbar: $ bin/console debug:config web_profiler Which should return something like: Current configuration for extension with alias "web_profiler"=============================================================web_profiler: toolbar: true intercept_redirects: false excluded_ajax_paths: '^/((index|app(_[\w]+)?)\.php/)?_wdt' 3rd. Check the container Check how the Profiler service will be instantiated: $ bin/console debug:container profiler --show-arguments Expect something like this: Information for Service "profiler"================================== Profiler. ---------------- ------------------------------------------------------------------------------------- Option Value ---------------- ------------------------------------------------------------------------------------- Service ID profiler Class Symfony\Component\HttpKernel\Profiler\Profiler Tags monolog.logger (channel: profiler) kernel.reset (method: reset) Calls add, add, add, add, add, add, add, add, add, add, add, add, add, add, add, add, add Public yes Synthetic no Lazy no Shared yes Abstract no Autowired no Autoconfigured no Arguments Service(profiler.storage) Service(monolog.logger.profiler) 1 ---------------- ------------------------------------------------------------------------------------- And then for the web_toolbar: # bin/console debug:container web_profiler.debug_toolbar --show-arguments For something like this: Information for Service "web_profiler.debug_toolbar"==================================================== WebDebugToolbarListener injects the Web Debug Toolbar. ---------------- ------------------------------------------------------------------------ Option Value ---------------- ------------------------------------------------------------------------ Service ID web_profiler.debug_toolbar Class Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener Tags kernel.event_subscriber container.hot_path Public no Synthetic no Lazy no Shared yes Abstract no Autowired no Autoconfigured no Arguments Service(twig) 2 Service(router.default) ^/((index|app(_[\w]+)?)\.php/)?_wdt Service(web_profiler.csp.handler) ---------------- ------------------------------------------------------------------------ (Note the 2 , which enables the toolbar). 4th. Check the event dispatcher. The web debug toolbar is injected during the kernel.response event. Check that the callback is appropriately hooked: $ bin/console debug:event-dispatcher kernel.response Which will return something like this: Registered Listeners for "kernel.response" Event================================================ ------- -------------------------------------------------------------------------------------------- ---------- Order Callable Priority ------- -------------------------------------------------------------------------------------------- ---------- #1 ApiPlatform\Core\Hydra\EventListener\AddLinkHeaderListener::onKernelResponse() 0 #2 Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse() 0 #3 Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelResponse() 0 #4 Symfony\Component\WebLink\EventListener\AddLinkHeaderListener::onKernelResponse() 0 #5 Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse() 0 #6 ApiPlatform\Core\HttpCache\EventListener\AddHeadersListener::onKernelResponse() -1 #7 Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse() -100 #8 Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse() -128 #9 Symfony\Component\HttpKernel\EventListener\TestSessionListener::onKernelResponse() -128 #10 Symfony\Component\HttpKernel\EventListener\DisallowRobotsIndexingListener::onResponse() -255 #11 Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelResponse() -1000 #12 Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse() -1024 ------- -------------------------------------------------------------------------------------------- ---------- Notice item #7 , which is the Profiler collector (which among other things will include the X-Debug-Token header in the response, which will be later checked by the Web Debug Toolbar, which is item #8 in the above listing. If any of the above checks fails You'll have to focus on that specific part to find out why it is failing. Maybe some other bundle interfering? A problem with one of the configuration files? Everything checks out ... but still not working? Well, that's weird. Make sure that your returned template has a </body> tag, and that the returned response has text/html content-type. But if all of the above checks out... it should work. In a comment you say that framework.profiler.collect is set to false when performing these checks. Set it to true by changing config/packages/dev/web_profiler.yaml like this: framework: profiler: only_exceptions: false collect: true
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58593887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972101/']}
jdg_85330
stackexchange
llm_judgeable_groundtruth_similarity
469
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What's the meaning of the double turnstile symbol in logic or mathematical notation? : $\models$ Now provide the response and nothing else.
Just to enlarge on Harry's answer: Your symbol denotes one of two specified notions of implication in formal logic $\vdash$ -the turnstile symbol denotes syntactic implication (syntactic here means related to syntax, the structure of a sentence), where the 'algebra' of the logical system in play (for example sentential calculus ) allows us to 'rearrange and cancel' the stuff we know on the left into the thing we want to prove on the right. An example might be the classic "all men are mortal $\wedge$ socrates is a man $\vdash$ socrates is mortal" ('$\wedge$' of course here just means 'and'). You can almost imagine cancelling out the 'man bit' on the left to just give the sentence on the right (although the truth may be more complex...). $\models$ -the double turnstile , on the other hand, is not so much about algebra as meaning (formally it denotes semantic implication)- it means that any interpretation of the stuff we know on the left must have the corresponding interpretation of the thing we want to prove on the right true. An example would be if we had an infinite set of sentences: $\Gamma$:= {"1 is lovely", "2 is lovely", ...} in which all numbers appear, and the sentence A= " the natural numbers are precisely {1,2,...}" listing all numbers. Any interpretation would give us B="all natural numbers are lovely". So $\Gamma$, A $\models$ B. Now, the goal of any logician trying to set up a formal system is to have $\Gamma \vdash A \iff \Gamma \models A$, meaning that the 'algebra' must line up with the interpretation, and this is not something we can take as given. Take the second example above- can we be sure that algebraic operations can 'parse' those infinitely many sentences and make the simple sentence on the right?? (this is to do with a property called compactness ) The goal can be split into two distict subgoals: Soundness: $A \vdash B \Rightarrow A \models B$ Completeness: $A \models B \Rightarrow A \vdash B$ Where the first stops you proving things that aren't true when we interpret them and the second means that everything we know to be true on interpretation, we must be able to prove. Sentential calculus, for example, can be proved complete (and was in Godel's lesser known, but celebrated completeness theorem), but other for other systems Godel's incompleteness theorem, give us a terrible choice between the two. In summary: The interplay of meaning and axiomatic machine mathematics, captured by the difference between $\models$ and $\vdash$, is a subtle and interesting thing.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/469', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97/']}
jdg_85331
stackexchange
llm_judgeable_groundtruth_similarity
715387
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a pair of Broadcom NetXtreme 57711 10GbE cards. I put one in a Dell R710; it boots with the card fine, the OS (CentOS 7) recognizes it, and all seems well. However, when I put the other card in an R730xd (also running CentOS), something unexpected happens: the R730xd's fans kick into high speed as soon as the system starts to boot the OS, and run continuously at high speed no matter what is happening. The fans do not run at full speed when interacting with the Lifecycle Controller or the BIOS screens. They only start spinning at full speed when the computer starts to boot the OS and before the OS comes up, so it doesn't seem to be a function of the OS. I've updated the R730xd's firmware to the latest versions available, I've tried setting the CPU performance profiles in the BIOS, and I've tried setting the thermal profile in the iDRAC, but nothing seems to change the behavior; the system always goes into full-on jet-engine mode. Googling reveals at least one other person encountering similar fan behavior related to adding a PCI card to an R730xd (though it's unclear whether it's the same card – it doesn't appear to be). What am I doing wrong? More importantly, can this behavior be changed, so that the fans do not stay stuck at full speed? Now provide the response and nothing else.
After tearing my hair out on newly arrived lovely R730xd with 16 3.5" disk slots spinning fans at 15k RPM when Intel X520-DA2 10G card is in any PCI slot, I've found following solution for CentOS 6.7 to quiesce fans in jet mode, although it is brute force, not taking into account 10G card's temperature probe - may result it card burnout from overheating, but I believe it is unlikely. Probably there's a way to monitor X520's thermal metrics. ** Description:The default automatic cooling response on PowerEdge 13G server for third-party PCIe cards provisions airflow based on common industry card requirements. Our thermal algorithm targets delivery of maximum 55C inlet air to the PCIe card region based on that industry standard. For some cards may not need additional cooling above the baseline (such as ones that have their own fan), Dell has enabled an OEM IPMI based command to disable this default fan response to the new PCIe card. To remediate: 1.Install IPMI tools: yum install OpenIPMI OpenIPMI-toolschkconfig ipmi on # << optional for the taskservice ipmi start # << optional for the task 2. Query Dell's Third-Party PCIe card based default system fan response: ipmitool raw 0x30 0xce 0x01 0x16 0x05 0x00 0x00 0x00# response like below means Disabled16 05 00 00 00 05 00 01 00 00# response like below means Enabled16 05 00 00 00 05 00 00 00 00 3. Jets off or Set Third-Party PCIe Card Default Cooling Response Logic To Disabled: ipmitool raw 0x30 0xce 0x00 0x16 0x05 0x00 0x00 0x00 0x05 0x00 0x01 0x00 0x00 4. Jets on or Set Third-Party PCIe Card Default Cooling Response Logic To Enabled: ipmitool raw 0x30 0xce 0x00 0x16 0x05 0x00 0x00 0x00 0x05 0x00 0x00 0x00 0x00 References: Windows utility ( link )Spiceworks post for Windows and 3rd party GPU card causing Gen13 Dell to spin fans ( link ) Other findings:Dell's X520-2 firmware pack ( here ) doesn't recognize Amazon-sourced new in-box $188 vs Dell branded $586
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/715387', 'https://serverfault.com', 'https://serverfault.com/users/221763/']}
jdg_85332
stackexchange
llm_judgeable_groundtruth_similarity
1840590
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Offending bit of code Vector moves = new Vector();moves.add(new Integer(x)); Error: ConnectFour.java:82: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector moves.add(new Integer(x)); Not really sure how much info is needed for an error like this.... Now provide the response and nothing else.
The problem is that the code above is not using generics . The following will work: Vector<Integer> moves = new Vector<Integer>();move.add(new Integer(x)); The type name inside the <> (in the case of Vector , the type parameter E for the element to hold) tells the compiler what type of object it should expect. If one tries to add an object that is of the specified type, such as in this case, trying to add an String to and Vector<Integer> , an compile-time error will occur, indicating that a type of object that is not of the expected type is being added. That said, one should try not to use the Vector class. For more purposes, a class implementing List such as ArrayList from the Java Collections Framework would be sufficient, and better performing. Edit Although not directly related to the question about generics, Adam Paynter brought up a good point in the comments about the use of auto-boxing. Since Java 5, primitives and their wrapper classes, e.g. int and Integer will be automatically converted between each other as necessary. Therefore, it is possible to add an value specified as an int or an int literal into a class expecting an Integer : Vector<Integer> v = new Vector<Integer>();v.add(5); // Not necessary to use an Integer value.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1840590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36545/']}
jdg_85333
stackexchange
llm_judgeable_groundtruth_similarity
1182589
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 been proposed the following theorem: Show that if $D\subset \mathbb{R}^n$ is an open set in $\mathbb{R}^n$ then $S \subset D$ is open in $D$ if and only if it is open in $\mathbb{R}^n$. I know the definition of being an open set, but what is the definition of being open in another set? Now provide the response and nothing else.
The flaw lies in the sentence "the first horse in the group is of the same color as the horses in the middle, who in turn are of the same color as the last horse". When $n=2$, this does not apply as there are no horses "in the middle", hence the "first" and "last" horses needn't be of the same color. So $P(1)$ holds, and $P(n)$ does imply $P(n+1)$, but provided $n>2$: this suffices to ruin the argument.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1182589', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/175846/']}
jdg_85334
stackexchange
llm_judgeable_groundtruth_similarity
6918138
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 figure out why a two-line button in my application is being shifted a couple of pixels lower than the other buttons: This does not happen if I shorten the text on the third button until it fits on one line, which tells me it has something to do with the line break. Adding android:layout_gravity="top" to the button's layout doesn't seem to help. Any ideas what might be causing this one? Edit: Here's the layout XML file: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center_horizontal" android:padding="10dip" android:layout_width="wrap_content"> <TextView android:id="@+id/error_text" android:layout_height="wrap_content" android:layout_marginBottom="5dip" android:text="Place holder" android:layout_width="wrap_content" android:textSize="17dip"/> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_horizontal" android:padding="10dip" android:layout_width="wrap_content"> <Button android:id="@+id/ok_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/ok" android:textColor="@color/black" android:textStyle="bold"/> <Button android:id="@+id/cancel_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dip" android:text="@string/cancel_login" android:textColor="@color/black" android:textStyle="bold" android:visibility="gone"/> <Button android:id="@+id/third_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dip" android:textColor="@color/black" android:textStyle="bold" android:visibility="gone"/> </LinearLayout></LinearLayout> Now provide the response and nothing else.
A horizontal LinearLayout aligns the baselines of all its child controls by default. So the first line of text in your multi-line button is vertically aligned with the single line of text in the other buttons. To disable this behaviour, set android:baselineAligned="false" on the LinearLayout .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6918138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/71421/']}
jdg_85335
stackexchange
llm_judgeable_groundtruth_similarity
7961211
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 be able to specialize based on a constant c style string. The problem is that when I call my templatized function the type is const char[N] where 'N' is the size of the string +1 (null character). How can I specialize for all c-style strings? The following code displays the problem. You can see the specialization for const char [15] gets matched for "const char [15]" but for "const char[5]" it goes to Generic. Is there any way to do this? template <typename T>struct Test { static const char* type() { return "Generic"; }};template <>struct Test<const char*> { static const char* type() { return "const char*"; }};template <>struct Test<const char[]> { static const char* type() { return "const char[]"; }};template <>struct Test<const char[15]> { static const char* type() { return "const char[15]"; }};template <>struct Test<char*> { static const char* type() { return "char*"; }};template <>struct Test<char[]> { static const char* type() { return "char[]"; }};template <typename T>void PrintType(const T& expected) { std::cerr << expected << " type " << Test<T>::type() << std::endl;}int main(int argc, char* argv[]) { const char* tmp = "const char*"; PrintType(tmp); PrintType("const char[]"); PrintType("const char[15]"); PrintType("const char[5]");} output when run in Windows 7 - VS 2008 const char* type const char*const char[] type Genericconst char[15] type const char[15]const char[5] type Generic Now provide the response and nothing else.
A specialization for any array of char s is: template< std::size_t N >struct Test< const char[N] > { ... }; However you can no longer return a char* from type() , unless you write more metafunctions to turn a non-type template parameter into its textual representation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7961211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972281/']}
jdg_85336
stackexchange
llm_judgeable_groundtruth_similarity
3783034
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f\in C^{3}[0,1]$ such that $f(0)=f'(0)=f(1)=0$ and $\big|f''' (x)\big|\le 1$ .Prove that $$\left|30240\int_{0}^{1}x(1-x)f(x)f'(x)dx\right|\le1 .$$ I couldn't make much progress on this problem. I thought that maybe I should try using polynomial interpolation since I have a bound for $|f'''|$ , but I can't determine the interpolation polynomial and I am quickly stuck (there is also the problem that I am dealing with both $f$ and $f'$ under the integral). Apart from this, I don't think that there is much we can do, the solution probably relies on this technique, but I can't make further progress. Now provide the response and nothing else.
First, using integration by parts, and noting that $f(0)=f'(0)=0$ we get $$f(x)=\frac{x^2}{2}f''(0)+\frac{1}{2}\int_0^x(x-t)^2f^{(3)}(t)dt\tag{1}$$ And from $f(1)=0$ we get also $$0=f(1)=\frac{1}{2}f''(0)+\frac{1}{2}\int_0^1(1-t)^2f^{(3)}(t)dt$$ Hence $$\eqalign{0&=\frac{x^2}{2}f''(0)+\frac{1}{2}\int_0^xx^2(1-t)^2f^{(3)}(t)dt\cr&+\frac{1}{2}\int_x^1x^2(1-t)^2f^{(3)}(t)dt\tag{2}}$$ Subtracting from $(1)$ from $(2)$ we get $$f(x)=-\int_0^1k(x,t)f^{(3)}(t)dt\tag{3}$$ with $$k(x,t)=\cases{\dfrac{x^2(1-t)^2-(x-t)^2}{2}& if $t\leq x$\cr\dfrac{x^2(1-t)^2}{2}& if $ x\leq t$}$$ (Note that $k(x,t)\ge 0$ for $0\leq x,t\leq 1$ ). Now, we note that $$\eqalign{I&=\int_0^1x(1-x)f(x)f'(x)dx=\int_0^1\left(x-\frac{1}{2}\right)(f(x))^2dx\\&=\int_0^1\int_0^1\int_0^1\left(x-\frac{1}{2}\right)k(x,t)k(x,s)f^{(3)}(t)f^{(3)}(s)dtdsdx\\&=\int_0^1\int_0^1H(t,s)f^{(3)}(t)f^{(3)}(s)dtds\tag{4}}$$ with $$H(t,s)=\int_0^1\left(x-\frac{1}{2}\right)k(x,t)k(x,s)dx\tag{5}$$ Now, $H(s,t)=H(t,s)$ and for $0\leq t\leq s\leq 1$ we find $$H(t,s)=\frac{1}{240} (s-1)^2 t \left(s^4 (t-2)+s^3 (t+2)+s^2 (1-4 t)+s t+(t-1) t^4\right)$$ It is not very easy but we can show (see the remark below,) that $H$ is nonnegative, and this is the crucial point. As it is depicted in the next figure It follows from the condition $|f^{(3)}|\leq 1$ that $$|{I}|\leq \int_0^1\int_0^1H(t,s)dtds=\frac{1}{30240}.$$ Remark. Let me add a proof of the positivity of $H(t,s)$ . Indeed, It is a matter of verification that for $0<t\leq s\leq 1$ we have $$\eqalign{\frac{240 }{(1-s)^2 t}H(t,s)&=(1-t) \left(s^2-t^2\right)+2 s^2 (1-s) (s-t)\\&+s (s+1) (1-s)^2 t+(1-t)^2 t^2 (t+1)}$$ which is a sum of positive terms.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3783034', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/589373/']}
jdg_85337
stackexchange
llm_judgeable_groundtruth_similarity
8540975
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the never-ending quest for UI responsiveness, I would like to gain more insight into cases where the main thread performs blocking operations. I'm looking for some sort of "debugging mode" or extra code, or hook, or whatever, whereby I can set a breakpoint/log/something that will get hit and allow me to inspect what's going if my main thread "voluntarily" blocks for I/O (or whatever reason, really) other than for going idle at the end of the runloop. In the past, I've looked at runloop cycle wall-clock duration using a runloop observer, and that's valuable for seeing the problem, but by the time you can check, it's too late to get a good idea for what it was doing, because your code is already done running for that cycle of the runloop. I realize that there are operations performed by UIKit/AppKit that are main-thread-only that will cause I/O and cause the main thread to block so, to a certain degree, it's hopeless (for instance, accessing the pasteboard appears to be a potentially-blocking, main-thread-only operation) but something would be better than nothing. Anyone have any good ideas? Seems like something that would be useful. In the ideal case, you'd never want to block the main thread while your app's code is active on the runloop, and something like this would be very helpful in getting as close to that goal as possible. Now provide the response and nothing else.
So I set forth to answer my own question this weekend. For the record, this endeavor turned into something pretty complex, so like Kendall Helmstetter Glen suggested, most folks reading this question should probably just muddle through with Instruments. For the masochists in the crowd, read on! It was easiest to start by restating the problem. Here's what I came up with: I want to be alerted to long periods of time spent in syscalls/mach_msg_trap that are not legitimate idle time. "Legitimate idle time" is defined as time spent in mach_msg_trap waiting for the next event from the OS. Also importantly, I didn't care about user code that takes a long time. That problem is quite easy to diagnose and understand using Instruments' Time Profiler tool. I wanted to know specifically about blocked time. While it's true that you can also diagnose blocked time with Time Profiler, I've found it considerably harder to use for that purpose. Likewise, the System Trace Instrument is also useful for investigations like this, but is extremely fine grained and complex. I wanted something simpler -- more targetted to this specific task. It seemed evident from the get-go that the tool of choice here would be Dtrace. I started out by using a CFRunLoop observer that fired on kCFRunLoopAfterWaiting and kCFRunLoopBeforeWaiting . A call to my kCFRunLoopBeforeWaiting handler would indicate the beginning of a "legitimate idle time" and the kCFRunLoopAfterWaiting handler would be the signal to me that a legitimate wait had ended. I would use the Dtrace pid provider to trap on calls to those functions as a way to sort legitimate idle from blocking idle. This approach got me started, but in the end proved to be flawed. The biggest problem is that many AppKit operations are synchronous , in that they block event processing in the UI, but actually spin the RunLoop lower in the call stack. Those spins of the RunLoop are not "legitimate" idle time (for my purposes), because the user can't interact with the UI during that time. They're valuable, to be sure -- imagine a runloop on a background thread watching a bunch of RunLoop-oriented I/O -- but the UI is still blocked when this happens on the main thread. For example, I put the following code into an IBAction and triggered it from a button: NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: @"http://www.google.com/"] cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 60.0]; NSURLResponse* response = nil;NSError* err = nil;[NSURLConnection sendSynchronousRequest: req returningResponse: &response error: &err]; That code doesn't prevent the RunLoop from spinning -- AppKit spins it for you inside the sendSynchronousRequest:... call -- but it does prevent the user from interacting with the UI until it returns. This is not "legitimate idle" to my mind, so I needed a way to sort out which idles were which. (The CFRunLoopObserver approach was also flawed in that it requred changes to the code, which my final solution does not.) I decided that I would model my UI/main thread as a state machine. It was in one of three states at all times: LEGIT_IDLE, RUNNING or BLOCKED, and would transition back and forth between those states as the program executed. I needed to come up with Dtrace probes that would allow me to catch (and therefore measure) those transitions. The final state machine I implemented was quite a bit more complicated than just those three states, but that's the 20,000 ft view. As described above, sorting out legitimate idle from bad idle was not straightforward, since both cases end up in mach_msg_trap() and __CFRunLoopRun . I couldn't find one simple artifact in the call stack that I could use to reliably tell the difference; It appears that a simple probe on one function is not going to help me. I ended up using the debugger to look at the state of the stack at various instances of legitimate idle vs. bad idle. I determined that during legitimate idle, I'd (seemingly reliably) see a call stack like this: #0 in mach_msg#1 in __CFRunLoopServiceMachPort#2 in __CFRunLoopRun#3 in CFRunLoopRunSpecific#4 in RunCurrentEventLoopInMode#5 in ReceiveNextEventCommon#6 in BlockUntilNextEventMatchingListInMode#7 in _DPSNextEvent#8 in -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]#9 in -[NSApplication run]#10 in NSApplicationMain#11 in main So I endeavored to set up a bunch of nested/chained pid probes that would establish when I had arrived at, and subsequently left, this state. Unfortunately, for whatever reason Dtrace's pid provider doesn't seem to be universally able to probe both entry and return on all arbitrary symbols. Specifically, I couldn't get probes on pid000:*:__CFRunLoopServiceMachPort:return or on pid000:*:_DPSNextEvent:return to work. The details aren't important, but by watching various other goings on, and keeping track of certain state, I was able to establish (again, seemingly reliably) when I was entered and left the legit idle state. Then I had to determine probes for telling the difference between RUNNING and BLOCKED. That was a bit easier. In the end, I chose to consider BSD system calls (using Dtrace's syscall probe) and calls to mach_msg_trap() (using the pid probe) not occurring in periods of legit idle to be BLOCKED. (I did look at Dtrace's mach_trap probe, but it did not seem to do what I wanted, so I fell back to using the pid probe.) Initially, I did some extra work with the Dtrace sched provider to actually measure real blocked time (i.e. time when my thread had been suspended by the scheduler) but that added considerable complexity, and I ended up thinking to myself, "If I'm in the kernel, what do I care if the thread is actually asleep or not? It's all the same to the user: it's blocked." So the final approach just measures all time in (syscalls || mach_msg_trap()) && !legit_idle and calls that the blocked time. At this point, catching single kernel calls of long duration (like a call to sleep(5) for instance) is rendered trivial. However, more often UI thread latency comes from many little latencies accumulating over multiple calls into the kernel (think of hundreds of calls to read() or select()), so I thought it would also be desirable to dump SOME call stack when the overall amount of syscall or mach_msg_trap time in a single pass of the event loop exceeded a certain threshold. I ended up setting up various timers and logging accumulated time spent in each state, scoped to various states in the state machine, and dumping alerts when we happened to be transitioning out of the BLOCKED state, and had gone over some threshold. This method will obviously produce data that is subject to misinterpretation, or might be a total red herring (i.e. some random, relatively quick syscall that just happens to push us over the alert threshold), but I feel like it's better than nothing. In the end, the Dtrace script ends up keeping a state machine in D variables, and uses the described probes to track transitions between the states and gives me the opportunity to do things (like print alerts) when the state machine is transitioning state, based on certain conditions. I played around a bit with a contrived sample app that does a bunch of disk I/O, network I/O, and calls sleep(), and was able to catch all three of those cases, without distractions from data pertaining to legitimate waits. This was exactly what I was looking for. This solution is obviously quite fragile, and thoroughly awful in almost every regard. :) It may or may not be useful to me, or anyone else, but it was a fun exercise, so I thought I'd share the story, and the resulting Dtrace script. Maybe someone else will find it useful. I also must confess being a relative n00b with respect to writing Dtrace scripts so I'm sure I've done a million things wrong. Enjoy! It was too big to post in line, so it's kindly being hosted by @Catfish_Man over here: MainThreadBlocking.d
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8540975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438982/']}
jdg_85338
stackexchange
llm_judgeable_groundtruth_similarity
181430
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $V_0$ is the subspace consisting of matrices of the form $C=AB-BA$ for some $A,B$ in a vector space $V$ then $V_0=\{A\in V|\operatorname{Trace}(A)=0\}$. The problem above is one of the past qualifying exam problems. I can prove that $V_0\subset\{A\in V|\operatorname{Trace}(A)=0\}$ but I do not know what to do with converse. Thank you in advance. Now provide the response and nothing else.
Here is a geometric approach: Let $\langle A, B \rangle = \mathbb{tr} (A^* B)$. It is straightforward to check that this is an inner product on the set of $p \times p$ matrices. Let $V_1 = \{A\in V|\operatorname{Trace}(A)=0\}$. It is clear that $V_0 \subset V_1$; we need to show the reverse inclusion. Note that $V_1 = \{ A | \langle I, A \rangle = 0 \}$, where $I$ is the identity. Also note that $V_0, V_1$ are both (closed) subspaces. To show inclusion it suffices to show that $V_0^\bot \subset V_1^\bot$. It is easy to see that $V_1^\bot = \mathbb{sp} \{I \}$. Suppose $X \in V_0^\bot$. Then, for any matrices $A,B$, we have $\langle X, AB \rangle = \langle X, BA \rangle$. Let $E_{ij} = e_i e_j^T$, and choose $A= E_{ij}, B = E_{mn}$. Then we get $\langle X, AB \rangle = \langle X, E_{ij} E_{mn} \rangle = \delta_{jm} [X]_{in}$. Similarly, we get $\langle X, BA \rangle = \delta_{in} [X]_{mj}$. Consequently we have $\delta_{jm} [X]_{in} = \delta_{in} [X]_{mj}$ for all $i,j,m,n$. Now choose $j=m$, this simplifies to $ [X]_{in} = \delta_{in} [X]_{jj}$. If $i \neq n$, this gives $[X]_{in} = 0$, if $i = n$, this shows that all diagonal elements are equal, so we have $X = \lambda I$, for some $\lambda$. Consequently $X \in V_1^\bot$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/181430', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13755/']}
jdg_85339
stackexchange
llm_judgeable_groundtruth_similarity
16547643
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 convert a list of dot-separated strings, e.g. ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero'] into a tree (nested lists or dicts - anything that is easy to walk through).The real data happens to have 1 to 4 dot-separated parts of different length and has 2200 records in total.My actual goal is to fill in the set of 4 QComboBox'es with this data, in manner that the 1st QComboBox is filled with first set items ['one', 'five', 'twelve'] (no duplicates). Then depending on the chosen item, the 2nd QComboBox is filled with its related items: for 'one' it would be: ['two', 'six'], and so on, if there's another nested level. So far I've got a working list -> nested dicts solution, but it's horribly slow, since I use regular dict(). And I seem to have a trouble to redesign it to a defaultdict in a way to easily work out filling the ComboBoxes properly. My current code: def list2tree(m): tmp = {} for i in range(len(m)): if m.count('.') == 0: return m a = m.split('.', 1) try: tmp[a[0]].append(list2tree(a[1])) except (KeyError, AttributeError): tmp[a[0]] = list2tree(a[1]) return tmpmain_dict = {}i = 0for m in methods: main_dict = list2tree(m) i += 1 if (i % 100) == 0: print i, len(methods)print main_dict, i, len(methods) Now provide the response and nothing else.
ls = ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero']tree = {}for item in ls: t = tree for part in item.split('.'): t = t.setdefault(part, {}) Result: { "twelve": { "zero": {} }, "five": { "nine": { "ten": {} } }, "one": { "six": { "seven": { "eight": {} } }, "two": { "three": { "four": {} } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16547643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2378440/']}
jdg_85340