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
526176
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was told that satellites are doing free-fall. But I don't think so, I think, assuming that the satellite is moving at a constant speed in a circular motion, the satellite does not do free-fall motion, because its distance from the earth has not changed, and it has no free-fall. Am i right? As shown in the figure, the blue straight line is the horizon. This is the horizon without bending. The direction of gravity is parallel and perpendicular to the horizon. The red line is a horizontal straight line. Throw an object horizontally to the left, and the object moves along a parabola under gravity. When the speed tends to infinity, the object moves straight along the red line without free fall. As shown in the figure, the blue line is the horizon, the horizon is curved, and the red line is concentric with the horizon. Gravity is perpendicular to the horizon. In other words, gravity is along the normal direction of the horizon. Throw objects along and perpendicular to the horizon normal, and the objects move along a "parabola". When the speed is appropriate, the object moves along the red line without free fall. Now provide the response and nothing else.
May be Newton's cannonball -thought-experimentcan convince your intuitionthat there is no principal differencebetween a body falling down to the earthand a satellite circulating the earth. Consider a cannon located on top of a high mountain,shooting in horizontal direction.And let's neglegt air resistance. (image from Wikipedia - Newton's cannonball ) When shooting the cannonball with low speed,it will hit the ground after a short distance at point A. When shooting the cannonball with higher speed,it will hit the ground after a longer distance at point B. When shooting the cannonball with really high speed (= 7.9 km/s),it is fast enough to fly around the earth in a circle through point C,and will eventually reach the cannon again from the back.The cannonball is a satellite in a circular orbit. When shooting the cannonball with even higher speed (> 7.9 km/s),it will again fly around the earth, through point D.The cannonball is a satellite in an elliptical orbit. In all the above scenarios the cannonball feels only the gravityof the earth, and hence it accelerates towards the center of the earth.Therefore it makes sense in all cases to say"the cannonball is in free fall".
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/526176', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/176092/']}
jdg_374541
stackexchange
llm_judgeable_groundtruth_similarity
2178167
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From what I can see, the ForEach method is available only for the List class . Why is that? I can see no reason for ForEach not to be available to any class implementing the IEnumerable / IEnumerator interfaces, and this is a really useful method if you need to perform a small action (1 line is more readable than 1 line + 2 boilerplate foreach syntax...). Update: I'll clarify my question. There are perfectly valid reasons for including ForEach in sequences. There are perfectly good reasons for not including ForEach in all sequences. But I cannot understand why would ForEach be included in just some of the sequences. Now provide the response and nothing else.
See Eric Lippert's post: "foreach" vs "ForEach" A number of people have asked me why there is no Microsoft-provided “ForEach” sequence operator extension method. The List class has such a method already of course, but there’s no reason why such a method could not be created as an extension method for all sequences. ... But we can go a bit deeper here. I am philosophically opposed to providing such a method, for two reasons. ... The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects. ... The second reason is that doing so adds zero new representational power to the language. ... Well, the VS Languages team does not have any influence on what goes into List. I personally find the "ForEach" method on List philosophically troubling for all the same reasons that I would find an extension method on IEnumerable troubling. (And the VSL team does control that.) The one mitigating factor is that List is clearly designed to be a mutable, not-side-effect-free data structure, so using expressions that mutate it seems slightly less bad. -- Eric
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2178167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55094/']}
jdg_374542
stackexchange
llm_judgeable_groundtruth_similarity
2855140
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 recursively add files by a pattern (or glob) located in different directories? For example, I'd like to add A/B/C/foo.java and D/E/F/bar.java (and several other java files) with one command: git add '*.java' Unfortunately, that doesn't work as expected. Now provide the response and nothing else.
Sergio Acosta's answer is probably your best bet if some of the files to be added may not already be tracked. If you want to limit yourself to files git already knows about, you could combine git-ls-files with a filter: git ls-files [path] | grep '\.java$' | xargs git add Git doesn't provide any fancy mechanisms for doing this itself, as it's basically a shell problem: how do you get a list of files to provide as arguments to a given command.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2855140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309962/']}
jdg_374543
stackexchange
llm_judgeable_groundtruth_similarity
43122096
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 perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP , albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli): class CIstr(unicode): """Case insensitive with respect to hashes and comparisons string class""" #--Hash/Compare def __hash__(self): return hash(self.lower()) def __eq__(self, other): if isinstance(other, basestring): return self.lower() == other.lower() return NotImplemented def __ne__(self, other): return not (self == other) def __lt__(self, other): if isinstance(other, basestring): return self.lower() < other.lower() return NotImplemented def __ge__(self, other): return not (self < other) def __gt__(self, other): if isinstance(other, basestring): return self.lower() > other.lower() return NotImplemented def __le__(self, other): return not (self > other) I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode ). My questions are: did I get the operators right ? is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ? is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings ). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this. Python 3 compatibility tips are appreciated ! Tiny demo: d = {CIstr('A'): 1, CIstr('B'): 2}print 'a' in d # Trues = set(d)print {'a'} - s # set([]) Now provide the response and nothing else.
You can use a strategy from this collection of Bit Twiddling Hacks : function bitCount (n) { n = n - ((n >> 1) & 0x55555555) n = (n & 0x33333333) + ((n >> 2) & 0x33333333) return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24}console.log(bitCount(0xFF)) //=> 8 Note that the above strategy only works for 32-bit integers (a limitation of bitwise operators in JavaScript). A more general approach for larger integers would involve counting 32-bit chunks individually (thanks to harold for the inspiration): function bitCount (n) { var bits = 0 while (n !== 0) { bits += bitCount32(n | 0) n /= 0x100000000 } return bits}function bitCount32 (n) { n = n - ((n >> 1) & 0x55555555) n = (n & 0x33333333) + ((n >> 2) & 0x33333333) return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24}console.log(bitCount(Math.pow(2, 53) - 1)) //=> 53 You could also use a regular expression: function bitCount (n) { return n.toString(2).match(/1/g).length}console.log(bitCount(0xFF)) //=> 8
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43122096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281545/']}
jdg_374544
stackexchange
llm_judgeable_groundtruth_similarity
55983
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: Following command prints the path of the song being played. mpc | head -n 1 songs/oldSongs/Mukesh_D/041 KANHAIYA = YAAD AAYI ADHI RAAT KO.mp3 Can I delete this file by modifying the command I used to print it? Now provide the response and nothing else.
To answer your more general question, that's the job of xargs to take a list of words on standard input and convert it to a list of arguments to a command. However, xargs expects the list as a space, tab and newline (and possibly more blank characters depending on the locale and xargs implementation) separated list of words where single quotes, double quotes and backslash are used to escape those separators (with varying behaviors with regards to nesting of those by different implementations of xargs). If the input is a newline-terminated list, the canonical way to convert it to the format expected by xargs is to escape every character (though only, backslash, single quote, double quote, underscore (potentially), space and tab (and possibly other blanks if not in the C locale) are necessary) but newline with a backslash character, which we can do with sed . mpc | head -n 1 | sed 's/./\\&/g' | xargs rm -- Note that some xargs implementations have a rather low limit on the maximum line length they expect on stdin, so you may want to only escape the necessary characters with those. With GNU xargs at least, you don't need to do that, you can do: mpc | head -n 1 | xargs -rd '\n' rm -- (also using the GNU specific -r option to avoid running any command if the input is empty).
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/55983', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5362/']}
jdg_374545
stackexchange
llm_judgeable_groundtruth_similarity
8802845
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 noticed a strange behavior while defining custom error objects in Javascript: function MyError(msg) { Error.call(this, msg); this.name = "MyError";}MyError.prototype.__proto__ = Error.prototype;var error = new Error("message");error.message; // "message"var myError = new MyError("message");myError instanceof Error; // truemyError.message; // "" ! Why does new Error("message") set the message property, while Error.call(this, msg); does not? Sure, I can just define this.message = msg in the MyError constructor, but I don't quite understand why it is not already set in the first place. Now provide the response and nothing else.
A. Like, Raynos said, The reason message isn't being set is that Error is a function that returns a new Error object and does not manipulate this in any way. B. The way to do this right is to set the result of the apply from the constructor on this , as well as setting the prototype in the usual complicated javascripty way: function MyError() { var tmp = Error.apply(this, arguments) tmp.name = this.name = 'MyError' this.message = tmp.message // instead of this.stack = ..., a getter for more optimizy goodness Object.defineProperty(this, 'stack', { get: function () { return tmp.stack } }) return this}var IntermediateInheritor = function () {}IntermediateInheritor.prototype = Error.prototypeMyError.prototype = new IntermediateInheritor()var myError = new MyError("message")console.log("The message is: '"+myError.message+"'") // The message is: 'message'console.log(myError instanceof Error) // trueconsole.log(myError instanceof MyError) // trueconsole.log(myError.toString()) // MyError: messageconsole.log(myError.stack) // MyError: message \n // <stack trace ...> The only problems with this way of doing it at this point (i've iteratted it a bit) are that properties other than stack and message aren't included in MyError , and the stacktrace has an additional line that isn't really necessary. The first problem could be fixed by iterating through all the non-enumerable properties of error using the trick in this answer: Is it possible to get the non-enumerable inherited property names of an object? , but this isn't supported by ie<9. The second problem could be solved by tearing out that line in the stack trace, but I'm not sure how to safely do that (maybe just removing the second line of e.stack.toString() ??). Update I created an inheritance library that does this ^ https://github.com/fresheneesz/proto
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8802845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834833/']}
jdg_374546
stackexchange
llm_judgeable_groundtruth_similarity
38508172
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to make Typescript objects iterable?In Python 3 I can do class EndlessCounter: def __init__(self): self.count = 0 def __iter__(self): return self def __next__(self): self.count += 1 return self.count but what is the Typescript equivalent of this code? Thanks! Now provide the response and nothing else.
Javascript supports Iterators and generators , typescript doesn't add much to it: typescript Iterators and Generators . Your code can be done like this in javascript: function* generator() { let counter = 0; while (true) { yield counter++; }}var iterator = generator();console.log(iterator.next().value); // 0console.log(iterator.next().value); // 1console.log(iterator.next().value); // 2 Edit You can do the same with a class: class Counter implements Iterator<number> { private counter = 0; public next(): IteratorResult<number> { return { done: false, value: this.counter++ } }}let c = new Counter();console.log(c.next().value); // 0console.log(c.next().value); // 1console.log(c.next().value); // 2 2nd Edit The first solution with the generator works well with the for/of loop: function* generator() { let counter = 0; while (counter < 5) { yield counter++; }}for (let i of generator()) console.log(i); Prints 0 to 5, however, to do that with an instance you'll need to do: class Counter implements Iterable<number> { private counter = 0; public [Symbol.iterator]() { return { next: function() { return { done: this.counter === 5, value: this.counter++ } }.bind(this) } }}let c = new Counter();for (let i of c) console.log(i);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38508172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6586141/']}
jdg_374547
stackexchange
llm_judgeable_groundtruth_similarity
483476
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: Using the formal definition of convergence of a sequence, show that the sequence converges to 0 as n tends to infinity. So we want to show that for every $\epsilon>0$, there exists $N$ such that when $n\geq N$, $$\left|\frac{1}{n}+\frac{(-1)^n}{n^2}\right|<\epsilon\;.$$ Using the triangle inequality, we obtain: $$\left|\frac{1}{n}+\frac{(-1)^n}{n^2}\right|\leq\frac{n+1}{n^2} $$ i) From here, is it possible to solve the right hand side explicitly for n in terms of $\epsilon$? 2) Why is it wrong to say that since $n+1\geq\frac{n+1}{n^2}$ for all n, then$$\left|\frac{1}{n}+\frac{(-1)^n}{n^2}\right|\leq n+1$$ and so then let $\epsilon=n+1$? I can see why 'intuitively' that it shouldn't be right, if $\epsilon$ is a n arbitrary small number then it would make no sense to have $N=\epsilon-1$, but is there some rule that says $N(\epsilon)$ should involve some other operation on $\epsilon?$ For instance, most examples I see are usually like $N=\frac{2}{\epsilon}$, where N gets larger as $\epsilon$ gets smaller, which is what expect.Also, I can't see where I made an error in my reasoning which led to $N=\epsilon-1$. Thanks Now provide the response and nothing else.
The problem here is this: you don't get to choose $\epsilon$ . You have to consider $\epsilon$ as being given to you "by the enemy" -- that is, you need to show that you can make the absolute value smaller than $\epsilon$, no matter what $\epsilon$ you're given . As a hint for how you can do the problem: given $\epsilon>0$, can you choose $n$ so that $$\frac{1}{n}<\frac{\epsilon}{2}\qquad\text{and}\qquad\frac{1}{n^2}<\frac{\epsilon}{2}?$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/483476', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90113/']}
jdg_374548
stackexchange
llm_judgeable_groundtruth_similarity
42890315
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 setup a EC2 Scaling group that scales depending on how many items are in an SQS queue. When the SQS queue has items visible I need the Scaling group to have 1 instance available and when the SQS queue is empty (e.g. there are no visible or non-visible messages) I want there to be 0 instances. Desired instances it set to 0, min is set to 0 and max is set to 1. I have setup cloudwatch alarms on my SQS queue to trigger when visible messages are greater than zero, and also triggers an alarm when non visible messages are less than one (i.e no more work to do). Currently the Cloudwatch Alarm Triggers to create an instance but then the scaling group automatically kills the instance to meet the desired setting. I expected the alarm to adjust the desired instance count within the min and max settings but this seems to not be the case. Now provide the response and nothing else.
Yes, you can certainly have an Auto Scaling group with: Minimum = 0 Maximum = 1 Alarm: When ApproximateNumberOfMessagesVisible > 0 for 1 minute, Add 1 Instance This will cause Auto Scaling to launch an instance when there are messages waiting in the queue. It will keep trying to launch more instances, but the Maximum setting will limit it to 1 instance. Scaling-in when there are no messages is a little bit tricker. Firstly, it can be difficult to actually know when to scale-in . If there are messages waiting to be processed, then ApproximateNumberOfMessagesVisible will be greater than zero. However, there are no messages waiting, it doesn't necessarily mean you wish to scale-in because messages might be currently processing ("in flight"), as indicated by ApproximateNumberOfMessagesNotVisible . So, you only want to scale-in if both of these are zero. Unfortunately, a CloudWatch alarm can only reference one metric, not two. Secondly, when an Amazon SQS queue is empty, it does not send metrics to Amazon CloudWatch. This sort of makes sense, because queues are mostly empty, so it would be continually sending a zero metric. However, it causes a problem that CloudWatch does not receive a metric when the queue is empty. Instead, the alarm will enter the INSUFFICIENT_DATA state. Therefore, you could create your alarm as: When ApproximateNumberOfMessagesVisible = 0 for 15 minutes, Remove 1 instance but set the action to trigger on INSUFFICIENT_DATA rather than ALARM Note the suggested "15 minutes" delay to avoid thrashing instances . This is where instances are added and removed in rapid succession because messages are coming in regularly, but infrequently. Therefore, it is better to wait a while before deciding to scale-in. This leaves the problem of having instances terminated while they are still processing messages . This can be avoided by taking advantage of Auto Scaling Lifecycle Hooks , which send a signal when an instance is about to be terminated, giving the application the opportunity to delay the termination until work is complete. Your application should then signal that it is ready for termination only when message processing has finished. Bottom line Much of the above depends upon: How often your application receives messages How long it takes to process a message The cost savings involved If your messages are infrequent and simple to process, it might be worthwhile to continuously run a t2.micro instance. At 2c/hour, the benefit of scaling-in is minor. Also, there is always the risk when adding and removing instances that you might actually pay more , because instances are charged by the hour -- running an instance for 30 minutes, terminating it, then launching another instance for 30 minutes will actually be charged as two hours. Finally, you could consider using AWS Lambda instead of an Amazon EC2 instance. Lambda is ideal for short-lived code execution without requiring a server. It could totally remove the need to use Amazon EC2 instances, and you only pay while the Lambda function is actually running.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42890315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1640309/']}
jdg_374549
stackexchange
llm_judgeable_groundtruth_similarity
173757
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We run a medium-size site that gets a few hundred thousand pageviews a day. Up until last weekend we ran with a load usually below 0.2 on a virtual machine. The OS is Ubuntu. When deploying the latest version of our application, we also did an apt-get dist-upgrade before deploying. After we had deployed we noticed that the load on the CPU had spiked dramatically (sometimes reaching 10 and stopping to respond to page requests). We tried dumping a full minute of Xdebug profiling data from PHP, but looking through it revealed only a few somewhat slow parts, but nothing to explain the huge jump. We are now pretty sure that nothing in the new version of our website is triggering the problem, but we have no way to be sure. We have rolled back a lot of the changes, but the problem still persists. When look at processes, we see that single Apache processes use quite a bit of CPU over a longer period of time than strictly necessary. However, when using strace on the affected process, we never see anything but accept(3, and it hangs for a while before receiving a new connection, so we can't actually see what is causing the problem. The stack is PHP 5, Apache 2 (prefork), MySQL 5.1. Most things run through Memcached. We've tried APC and eAccelerator. So, what should be our next step? Are there any profiling methods we overlooked/don't know about? Now provide the response and nothing else.
The answer ended up being not-Apache related. As mentioned, we were on a virtual machine. Our user sessions are pretty big (think 500kB per active user), so we had a lot of disk IO. The disk was nearly full, meaning that Ubuntu spent a lot of time moving things around (or so we think). There was no easy way to extend the disk (because it was not set up properly for VMWare). This completely killed performance, and Apache and MySQL would occasionally use 100% CPU (for a very short time), and the system would be so slow to update the CPU usage meters that it seemed to be stuck there. We ended up setting up a new VM (which also gave us the opportunity to thoroughly document everything on the server). On the new VM we allocated plenty of disk space, and moved sessions into memory (using memcached). Our load dropped to 0.2 on off-peak use and around 1 near peak use (on a 2-CPU VM). Moving the sessions into memcached took a lot of disk IO away (we were constantly using about 2MB/s of disk IO, which is very bad). Conclusion; sometimes you just have to start over... :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/173757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1606/']}
jdg_374550
stackexchange
llm_judgeable_groundtruth_similarity
14420795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to make the background transparent for some charts I have made with google charts. They work perfectly in everything except IE7 and 8, I get a white backgound. I have tried every combination I can find for the color attribute to change it but nothing works. The only thing left to try was a suggesting that someone made on here a few months ago for someone else with the same issue. Their suggestion was... For a transparent background, use chf=bg,s,FFFFFF00 But I have no idea how to implement this? Now provide the response and nothing else.
chf=bg,s,FFFFFF00 is a code for the old Google Image Charts . Those codes will only work with the non-SVG versions of charts. Google Image Charts have been deprecated (as you can see from their help pages ), so unless you want to implement the old-style charts, you won't be able to implement the above code on your new, fancy, interactive SVG charts. For the new fancy SVG charts, I have luck with backgroundColor: "transparent" Copy-paste this in to Google Playground to test: <!--You are free to copy and use this sample in accordance with the terms of theApache license (http://www.apache.org/licenses/LICENSE-2.0.html)--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> Google Visualization API Sample </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['corechart']}); </script> <script type="text/javascript"> function drawVisualization() { // Create and populate the data table. var data = google.visualization.arrayToDataTable([ ['Year', 'Austria', 'Bulgaria', 'Denmark', 'Greece'], ['2003', 1336060, 400361, 1001582, 997974], ['2004', 1538156, 366849, 1119450, 941795], ['2005', 1576579, 440514, 993360, 930593], ['2006', 1600652, 434552, 1004163, 897127], ['2007', 1968113, 393032, 979198, 1080887], ['2008', 1901067, 517206, 916965, 1056036] ]); // Create and draw the visualization. new google.visualization.BarChart(document.getElementById('visualization')). draw(data, {title:"Yearly Coffee Consumption by Country", width:600, height:400, vAxis: {title: "Year"}, hAxis: {title: "Cups"}, backgroundColor: "transparent"} ); } google.setOnLoadCallback(drawVisualization); </script> </head> <body style="font-family: Arial;border: 0 none;" bgcolor="#E6E6FA"> <div id="visualization" style="width: 600px; height: 400px;"></div> </body></html> This is just the standard bar chart example with two things added: bgcolor="#E6E6FA" to the body element (make it blue so we can tell if transparent) backgroundColor="transparent" to the options (make it transparent) This works in FireFox. I don't know if it works in IE7 (no testing environment). Let us know if it works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14420795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1267224/']}
jdg_374551
stackexchange
llm_judgeable_groundtruth_similarity
35097710
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 learning Rust, but when I print a decimal number, only the integer part is printed, not the decimal part: fn main(){ println!("{:.3}", 22/7);}// This only show 3 but when I print the decimal number explicitly, it works correctly: fn main(){ println!("{:.3}", 0.25648);}// this print 0.256 Now provide the response and nothing else.
Just like in C and C++, dividing integers results in another integer. Try this C++ program to see: #include <iostream>using namespace std;int main(){ cout << 22 / 7 << endl; // 3 cout << 22.0 / 7.0 << endl; // 3.14286} Similarly in Rust, you need to specify both numbers as floats instead, which is done by putting a decimal anywhere in the number. Try this Rust equivalent of the above program: fn main() { println!("{:.3}", 22 / 7); // 3 println!("{:.3}", 22.0 / 7.0); // 3.143} If you have variables, you can convert them with as to either f32 or f64 , depending on your needs: fn main() { let x = 22; println!("{:.3}", x / 7); // 3 println!("{:.3}", x as f32 / 7.0); // 3.143}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35097710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5840022/']}
jdg_374552
stackexchange
llm_judgeable_groundtruth_similarity
9848851
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 an adapter for a client-side HTML/JS templating system to use dust.js under the hood. Unfortunately the API expects render operations to occur synchronously: the rendered output should be returned from the render() call. Dust.js is asynchronous and passes render output to a callback function. Is there any way to work around this, either in the Dust APIs or through some crazy Javascript hack? Now provide the response and nothing else.
DustJS is only going to execute things asynchronously when the resources it needs to render (templates, partials) haven't already all been loaded. If all the dependencies of a template are loaded before you execute that template then it'll execute synchronously (as far as I can tell anyhow). So you can do something like: var result;dust.render("tpl", data, function(err, res) { result = res;});console.log(result); // result will actually already be filled out if dustjs didn't// have to go look for resources somewhere. Here is a fuller example below:(and here is a jsfiddle link so you can run it: http://jsfiddle.net/uzTrv/1/ ) <script type="text/javascript" src="dust.js"></script><script> var tpl = dust.compile("Omg {#people} {.} {/people} are here! {>partial/}", "tpl"); var partial = dust.compile("I'm a partial but I've already been included so things still run {how}", "partial"); dust.loadSource(tpl); dust.loadSource(partial); var data = { people: ["jim", "jane", "jack", "julie"], how: "synchronously!" }; var result; dust.render("tpl", data, function(err, res) { result = res; }); console.log(result);</script> There could be cases (besides the one I mentioned) where I'm wrong... I don't know everything about dustjs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9848851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41754/']}
jdg_374553
stackexchange
llm_judgeable_groundtruth_similarity
4397295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: this thing works fine: SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr FROM cities c INNER JOIN jobs j ON (j.city_id = c.id ) WHERE j.is_active = 1 GROUP BY c.namelimit 100 but when i wanna put condition on new column nr it says column not found SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr FROM cities c INNER JOIN jobs j ON (j.city_id = c.id ) WHERE j.is_active = 1 and nr > 100 GROUP BY c.namelimit 100 Now provide the response and nothing else.
You should put the condition on nr in the HAVING clause, like this: SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr FROM cities c INNER JOIN jobs j ON (j.city_id = c.id ) WHERE j.is_active = 1 GROUP BY c.name HAVING nr > 100limit 100 This is because nr is the result of an aggregate function (COUNT(*)) and as such is not available at the time the WHERE filter is applied. EDIT: in some database servers, the reference to nr doesn't work; you can also use HAVING COUNT(*) > 100 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4397295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536269/']}
jdg_374554
stackexchange
llm_judgeable_groundtruth_similarity
4515396
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: Textbook problem: Two numbers, first $x$ and then $y$ , are chosen at random between $1$ and $2$ . What is the average value of the quotient $\frac{x}{y}$ ? Can you argue on elementary grounds that the answer must exceed 1? My answer: If $x$ has been picked, then the average of the quotient is $$\int_1^2 \frac{x}{y}\,dy = x\ln(2)$$ Averaging over possible values of $x$ yields $$\int_1^2 x\ln(2)\, dx = \frac{3}{2}\ln(2) \approx 1.03$$ But this is not an argument based on elementary grounds I don't think. Interpreting the average value of a function over an interval as being the height of the rectangle with base on the interval and with the same area as the area under the function over the interval leads me to the following argument. The average value of $x$ is $3/2$ . The quotient $x/y$ then ranges from $3/4$ to $3/2$ . We can underestimate the area under this curve by splitting it up into a rectangle with length $1$ and height $3/4$ and a right triangle on top of the rectangle whose hypotenuse is the tangent line to the curve $\frac{3}{2y}$ at the point $(3/2,1)$ . This gives a triangle with height $7/12$ and base $7/8$ . So an underestimate for the area under the curve would be $\left(1\cdot \frac{3}{4}\right) + \left(\frac{1}{2}\cdot \frac{7}{8}\cdot \frac{7}{12}\right) = \frac{193}{192}$ . Here is an illustration of my quotient function with $x = 3/2$ , the tangent line, and the rectangle: Since the base of the rectangle with the same area on $[1,2]$ has length $1$ its height must be at least $\frac{193}{192}$ to match the area under the graph. Hence, the height, or average value, exceeds $1$ . Question: Does this seem to be an argument the author could be looking for instead of integrating? This is a single variable calculus text. The section is ''The Average Value of a Function". Note that not until the next chapter is probability introduced. Update: I have obtained a copy of the author's own solutions manual. Here is the official solution: To argue on elementary grounds that the answer must exceed 1, note that the outcomes $a/b$ and $b/a$ must occur equally often, so that the answer is certainly greater than the minimum over all $a$ and $b$ in $[1,2]$ of the average of these two numbers. Now this average is $$\frac{1}{2}\left[\frac{a}{b} + \frac{b}{a}\right] = \frac{a^2 + b^2}{2ab}$$ and this is always greater than 1 because $a^2 + b^2 - 2ab = (a-b)^2 > 0$ . Now provide the response and nothing else.
We can argue as follows. The probability distribution is symmetric w.r.t. interchanging $x$ and $y$ . This means that we can compute the expectation value by restricting $x$ to be larger than or equal to $y$ and computing the expectation value of $f(x,y) = \frac{1}{2}\left(\frac{x}{y} + \frac{y}{x}\right)$ over this modified probability distribution. The fact that the expectation value exceeds $1$ then follows from the fact that the function $f(x,y)$ is larger than or equal to $1$ : $$f(x,y) - 1 = \frac{1}{2}\left(\frac{x}{y} + \frac{y}{x}-2\right) = \frac{x^2+y^2-2xy}{2xy} = \frac{(x-y)^2}{2 xy}\geq 0$$ The function $f(x,y)$ is then equal to $1$ when $x = y$ which occurs on a subset of measure zero, so the expectation value is clearly larger than $1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4515396', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/996771/']}
jdg_374555
stackexchange
llm_judgeable_groundtruth_similarity
9141
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm receiving "You have mail" messages and according to How to remove “You have mail” welcome message I should read my mail with mail . However I cannot find the command in my system (Ubuntu 10.04 server). What do I need to install? Now provide the response and nothing else.
On Debian and derived distributions, you can use the apt-file command to search for a package containing a file. Install apt-file ( apt-get install apt-file ) and download its database ( apt-file update , Ubuntu does it automatically if you're online). Then search for bin/mail : apt-file -x search 'bin/mail$' With the command-not-found package installed, if you type a command that doesn't exist but can be installed from the Ubuntu repositories, you get an informative message: $ mailThe program 'mail' can be found in the following packages: * heirloom-mailx * mailutilsTry: sudo apt-get install <selected package> If you're not after mail specifically, but after any program to read your local mail from the command line, there are much better alternatives. All mail user agents provide the mail-reader virtual package, so browse the list of packages that provide mail-reader and install one or more that looks good to you (and doesn't use a GUI, if it's for a server). mutt 's motto is “All mail clients suck. This one just sucks less.” , and I tend to agree, but in the end it's a very personal choice.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/9141', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/250/']}
jdg_374556
stackexchange
llm_judgeable_groundtruth_similarity
16139752
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: var gridData = {};var TestRow = { "name": "xx", "description": "xx", "subjectId": 15 };gridData.push(TestRow) How can I find out the index number of the new data that I just pushed into the gridData object? Now provide the response and nothing else.
First off, I'll assume the gridData is an array, not an object as you've shown in your sample code because an object doesn't have a .push() method, but an array does. Use .length - 1 as the index to the last item you pushed onto the array or save the returned value from .push() which is the new length of the array. This will be the index of the element that you just pushed onto the array and will be valid until you modify the array before that index (adding or removing items before that index). var testRowIndex = gridData.push(TestRow) - 1;// then you can access that item like this var item = gridData[testRowIndex]; Though, this doesn't make a whole lot of sense since you already have the data right in TestRow . As usual, if you describe what problem you're really trying to solve, we can probably provide more useful answers.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16139752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374557
stackexchange
llm_judgeable_groundtruth_similarity
1685389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use __getitem__(self, x, y): on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python).I'm calling it like this: print matrix[0,0] Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a tuple? Now provide the response and nothing else.
__getitem__ only accepts one argument (other than self ), so you get passed a tuple. You can do this: class matrix: def __getitem__(self, pos): x,y = pos return "fetching %s, %s" % (x, y)m = matrix()print m[1,2] outputs fetching 1, 2 See the documentation for object.__getitem__ for more information.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1685389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/130758/']}
jdg_374558
stackexchange
llm_judgeable_groundtruth_similarity
4246795
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 ListView containing some ListViewItems. By default, selecting items makes their background to some deep blue. I would like to apply a style such that selecting an item does not change its look. In my xaml I already achieved this: <Style TargetType="ListViewItem"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> </Style.Resources></Style> Unfortunately, this does not do the trick. It just simply makes the selection white instead of blue. Does anyone have an idea? Best wishes,Christian EDIT: Sample Code: <Window.Resources> <Style TargetType="ListViewItem"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> </Style.Resources> </Style></Window.Resources><ListView x:Name="lvTestRun" ItemsSource="{Binding Path=TestRunData}" Margin="177,26,8,53.277" SelectionMode="Multiple"> <ListView.View> <GridView> <GridViewColumn Header="Status"/> <GridViewColumn Header="Duration"/> <GridViewColumn Header="Start Time"/> <GridViewColumn Header="End Time"/> </GridView> </ListView.View></ListView> In order to reproduce this, you may have to set the background color of a single ListViewItem to something like green or red. Now provide the response and nothing else.
I'm not sure I understand what you mean by white instead of blue. When a ListViewItem is selected the foreground and background is changed by a trigger. To change the foreground of a ListViewItem you can use this <ListView ...> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <Style.Resources> <!-- Foreground for Selected ListViewItem --> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/> <!-- Background for Selected ListViewItem --> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> </Style.Resources> </Style> </ListView.ItemContainerStyle> ...</ListView> Update Try this for re-templating. I removed all triggers for selected <ListView ...> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <Style.Resources> <LinearGradientBrush x:Key="ListItemHoverFill" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFF1FBFF" Offset="0"/> <GradientStop Color="#FFD5F1FE" Offset="1"/> </LinearGradientBrush> </Style.Resources> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListViewItem}"> <Border CornerRadius="2" SnapsToDevicePixels="True" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}"> <Border Name="InnerBorder" CornerRadius="1" BorderThickness="1"> <Grid> <Grid.RowDefinitions> <RowDefinition MaxHeight="11" /> <RowDefinition /> </Grid.RowDefinitions> <Rectangle Name="UpperHighlight" Visibility="Collapsed" Fill="#75FFFFFF" /> <GridViewRowPresenter Grid.RowSpan="2" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> </Grid> </Border> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="{StaticResource ListItemHoverFill}" /> <Setter Property="BorderBrush" Value="#FFCCF0FF" /> <Setter TargetName="UpperHighlight" Property="Visibility" Value="Visible" /> </Trigger> <!--<Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource ListItemSelectedFill}" /> <Setter Property="BorderBrush" Value="#FF98DDFB" /> <Setter TargetName="InnerBorder" Property="BorderBrush" Value="#80FFFFFF" /> <Setter TargetName="UpperHighlight" Property="Visibility" Value="Visible" /> <Setter TargetName="UpperHighlight" Property="Fill" Value="#40FFFFFF" /> </Trigger>--> <!--<MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True" /> <Condition Property="Selector.IsSelectionActive" Value="False" /> </MultiTrigger.Conditions> <Setter Property="Background" Value="{StaticResource ListItemSelectedInactiveFill}" /> <Setter Property="BorderBrush" Value="#FFCFCFCF" /> </MultiTrigger>--> <!--<MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True" /> <Condition Property="IsMouseOver" Value="True" /> </MultiTrigger.Conditions> <Setter Property="Background" Value="{StaticResource ListItemSelectedHoverFill}" /> <Setter Property="BorderBrush" Value="#FF98DDFB" /> </MultiTrigger>--> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListView.ItemContainerStyle></ListView>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4246795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/490230/']}
jdg_374559
stackexchange
llm_judgeable_groundtruth_similarity
40584424
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 made a list of items a few times using Android's RecyclerView , but it is a rather complicated process. Going through one of the numerous tutorials online works ( this , this , and this are good), but I am looking a bare bones example that I can copy and paste to get up and running quickly. Only the following features are necessary: Vertical layout A single TextView on each row Responds to click events Because I have wished for this several times, I finally decided to make the answer below for my future reference and yours. Now provide the response and nothing else.
The following is a minimal example that will look like the following image. Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs. Add dependencies to gradle Add the xml layout files for the activity and for the RecyclerView row Make the RecyclerView adapter Initialize the RecyclerView in your activity Update Gradle dependencies Make sure the following dependencies are in your app gradle.build file: implementation 'com.android.support:appcompat-v7:28.0.0'implementation 'com.android.support:recyclerview-v7:28.0.0' You can update the version numbers to whatever is the most current . Use compile rather than implementation if you are still using Android Studio 2.x. Create activity layout Add the RecyclerView to your xml layout. activity_main.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/rvAnimals" android:layout_width="match_parent" android:layout_height="match_parent"/></RelativeLayout> Create row layout Each row in our RecyclerView is only going to have a single TextView . Create a new layout resource file. recyclerview_row.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="10dp"> <TextView android:id="@+id/tvAnimalName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp"/></LinearLayout> Create the adapter The RecyclerView needs an adapter to populate the views in each row with your data. Create a new java file. MyRecyclerViewAdapter.java public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; private ItemClickListener mClickListener; // data is passed into the constructor MyRecyclerViewAdapter(Context context, List<String> data) { this.mInflater = LayoutInflater.from(context); this.mData = data; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.recyclerview_row, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { String animal = mData.get(position); holder.myTextView.setText(animal); } // total number of rows @Override public int getItemCount() { return mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView myTextView; ViewHolder(View itemView) { super(itemView); myTextView = itemView.findViewById(R.id.tvAnimalName); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } // convenience method for getting data at click position String getItem(int id) { return mData.get(id); } // allows clicks events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); }} Notes Although not strictly necessary, I included the functionality for listening for click events on the rows. This was available in the old ListViews and is a common need. You can remove this code if you don't need it. Initialize RecyclerView in Activity Add the following code to your main activity. MainActivity.java public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener { MyRecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // data to populate the RecyclerView with ArrayList<String> animalNames = new ArrayList<>(); animalNames.add("Horse"); animalNames.add("Cow"); animalNames.add("Camel"); animalNames.add("Sheep"); animalNames.add("Goat"); // set up the RecyclerView RecyclerView recyclerView = findViewById(R.id.rvAnimals); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new MyRecyclerViewAdapter(this, animalNames); adapter.setClickListener(this); recyclerView.setAdapter(adapter); } @Override public void onItemClick(View view, int position) { Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show(); }} Notes Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle row click events in onItemClick . Finished That's it. You should be able to run your project now and get something similar to the image at the top. Going on Adding a divider between rows You can add a simple divider like this DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation());recyclerView.addItemDecoration(dividerItemDecoration); If you want something a little more complex, see the following answers: How to add dividers and spaces between items in RecyclerView? How to indent the divider in a linear layout RecyclerView (ie, add padding, margin, or an inset only to the ItemDecoration) Changing row color on click See this answer for how to change the background color and add the Ripple Effect when a row is clicked. Updating rows See this answer for how to add, remove, and update rows. Further reading CodePath YouTube tutorials Android RecyclerView Example (stacktips tutorial) RecyclerView in Android: Tutorial
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/40584424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681880/']}
jdg_374560
stackexchange
llm_judgeable_groundtruth_similarity
5892653
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 generally heard that production code should avoid using Lazy I/O. My question is, why? Is it ever OK to use Lazy I/O outside of just toying around? And what makes the alternatives (e.g. enumerators) better? Now provide the response and nothing else.
Lazy IO has the problem that releasing whatever resource you have acquired is somewhat unpredictable, as it depends on how your program consumes the data -- its "demand pattern". Once your program drops the last reference to the resource, the GC will eventually run and release that resource. Lazy streams are a very convenient style to program in. This is why shell pipes are so fun and popular. However, if resources are constrained (as in high-performance scenarios, or production environments that expect to scale to the limits of the machine) relying on the GC to clean up can be an insufficient guarantee. Sometimes you have to release resources eagerly, in order to improve scalability. So what are the alternatives to lazy IO that don't mean giving up on incremental processing (which in turn would consume too many resources)? Well, we have foldl based processing, aka iteratees or enumerators, introduced by Oleg Kiselyov in the late 2000s , and since popularized by a number of networking-based projects. Instead of processing data as lazy streams, or in one huge batch, we instead abstract over chunk-based strict processing, with guaranteed finalization of the resource once the last chunk is read. That's the essence of iteratee-based programming, and one that offers very nice resource constraints. The downside of iteratee-based IO is that it has a somewhat awkward programming model (roughly analogous to event-based programming, versus nice thread-based control). It is definitely an advanced technique, in any programming language. And for the vast majority of programming problems, lazy IO is entirely satisfactory. However, if you will be opening many files, or talking on many sockets, or otherwise using many simultaneous resources, an iteratee (or enumerator) approach might make sense.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5892653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208257/']}
jdg_374561
stackexchange
llm_judgeable_groundtruth_similarity
15705892
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 just confused with ws-addressing. Wikipedia says it is a specification of transport-neutral mechanisms that allow web services to "communicate addressing information". Communicate addressing information? Don't SOAP web services already have that ability to begin with, otherwise how would they be able to communicate at all? What value does it give and why isn't is part of the default stuff to begin with given that it seems to be providing a core functionality? Now provide the response and nothing else.
WS-Addressing is most useful in the context of asynchronous communication through different protocols . It's used to label the messages so that the request and delayed responses can be reconciled against each other later on, regardless of which protocol it's sent through. If you're using HTTP all the way, you will not need WS-Addressing, that's why it's turned off by default. However, we tend to assume that SOAP can be transmitted only through HTTP, when in fact, it can be transmitted through other means, like SMTP or JMS . He's an illustration to deliver the point. With WS-Addressing , the transport-specific data are copied over to the SOAP headers. This decouples the address data away from the protocol and into the SOAP message itself, achieving the "transport-neutrality" Wikipedia is talking about. WS-Addressing plays an important role in the WS* group of specifications (i.e. WS-Security, WS-ReliableMessaging, WS-Coordination).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15705892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2224794/']}
jdg_374562
stackexchange
llm_judgeable_groundtruth_similarity
159101
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: Well, the question is obvious: how can I create the following e-seal (with the rotated wrapped text, inserted image etc) with Mathematica? The central image is the following So, the following issues should be solved: (1). How to embed an image inside circles. (2). How to wrap text along a circle with a specific radius and orientation.Any good ideas?! Here is my try g1 = Circle[{0, 0}, 1.3];g2 = Circle[{0, 0}, 1.6];g3 = Circle[{0, 0}, 1.7];plot = Graphics[{{Thickness[0.008], g1}, {Thickness[0.008], g2}, {Thickness[0.018], g3}, Inset[img, {0, 0}]}];Show[plot, ImageSize -> 300] Now two main things are missing: (a) The wrapped text inside the circles. (b) A way to rotate the central image and control its relative size. Any suggestions? Now provide the response and nothing else.
Credit goes to this answer in the linked thread, but I used a somewhat simpler geometric transformation to wrap the text around a circle. Maybe this will get you started (updated to include rotation of central image, clear and reload all symbols): Clear[a, plot, intermediate]pts = Point[1.45 ({Cos@#, Sin@#} & /@ {-Pi/2 + 1/2, 3 Pi/2 - 1/2})]g1 = Circle[{0, 0}, 1.3, {-Pi/2 + 1/2, 3 Pi/2 - 1/2}];g2 = Circle[{0, 0}, 1.6];g3 = Circle[{0, 0}, 1.7];plot[a_] = Graphics[{{Thickness[0.008], g1}, {Thickness[0.008], g2}, {Thickness[0.018], g3}, Inset[img, {0, 0}, Center, 2, {Cos[a], Sin[a]}]}];intermediate[a_] = Show[plot[a], ImageSize -> 300]Clear[text]text[txt_, p1_, p2_, p3_, p4_] := With[{l = text[txt]}, {{l /. {x_Real, y_Real} :> (p1 + y)/ p2 {Sin[1/p3 x + p4], Cos[1/p3 x + p4]}}}]text[txt_String] := text[txt] = Cases[First[ First[ImportString[ ExportString[ Style[txt, Bold, FontFamily -> "Calibri", FontSize -> 12], "PDF"], "TextMode" -> "Outlines"]]], FilledCurve[a__] :> {EdgeForm[Black], Gray, FilledCurve[a]}, Infinity]Manipulate[ Show[{intermediate[p5], Graphics[{PointSize[Large], pts}, PlotRange -> 2], Graphics[text["This is a test", p1, p2, p3, p4]]}], {{p1, 33}, 1, 50}, {{p2, 27}, 1, 50}, {{p3, 22}, 1, 40}, {{p4, -1}, -Pi, Pi}, {p5, 0, 2 Pi}] To get the text to wrap around the other way, you can do the following: text2[txt_, p1_, p2_, p3_, p4_] := With[{l = text[txt]}, {{l /. {x_Real, y_Real} :> (p1 + y)/ p2 {-Sin[1/p3 x + p4], Cos[1/p3 x + p4]}}}]Manipulate[ Show[{intermediate[p5], Graphics[{PointSize[Large], pts}, PlotRange -> 2], Graphics[text2["Test", p1, p2, p3, p4]]}], {{p1, -38.4}, -50, 50}, {{p2, -27}, -50, 50}, {{p3, 22}, 1, 40}, {{p4, 2.8}, -Pi, Pi}, {p5, 0, 2 Pi}] This is just a slightly modified geometric transformation. The Manipulate is just a means to play around with the parameters, once you find appropriate values, you can stick Graphics[{text[...], text[...], text2[...]}] inside the Show` with appropriate numeric values and export the result.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/159101', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']}
jdg_374563
stackexchange
llm_judgeable_groundtruth_similarity
6954874
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 making a browser based PHP game and in my database for the players it has a record of that players total EXP or experience. What i need is a formula to translate that exp into a level or rank, out of 100. So they start off at level 1, and when they hit say, 50 exp, go to level 2, then when they hit maybe 125/150, level 2. Basically a formula that steadily makes each level longer (more exp) Can anyone help? I'm not very good at maths :P Now provide the response and nothing else.
Many formulas may suit your needs, depending on how fast you want the required exp to go up. In fact, you really should make this configurable (or at least easily changed in one central location), so that you can balance the game later. In most games these (and other) formulas are determined only after playtesting and trying out several options. Here's one formula: First level-up happens at 50 exp; second at 150exp; third at 300 exp; fourth at 500 exp; etc. In other words, first you have to gather 50 exp, then 100 exp, then 150exp, etc. It's an Arithmetic Progression . For levelup X then you need 25*X*(1+X) exp. Added: To get it the other way round you just use basic math. Like this: y=25*X*(1+X)0=25*X*X+25*X-y That's a standard Quadratic equation , and you can solve for X with: X = (-25±sqrt(625+100y))/50 Now, since we want both X and Y to be greater than 0, we can drop one of the answers and are left with: X = (sqrt(625+100y)-25)/50 So, for example, if we have 300 exp, we see that: (sqrt(625+100*300)-25)/50 = (sqrt(30625)-25)/50 = (175-25)/50 = 150/50 = 3 Now, this is the 3rd levelup , so that means level 4.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6954874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/880356/']}
jdg_374564
stackexchange
llm_judgeable_groundtruth_similarity
42027973
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Goal I'm very new to Heroku, and I'm trying to deploy a very simple site into Heroku. Site Structure As you can see, I'm not trying to deploy a complex Node.js or Laravel Site here. Steps I log-in to heroku of course, then cd idesign4u/git initheroku git:remote -a idesign4ugit add .git commit -am "Project Initialization"heroku buildpacks:set heroku/php I got this Buildpack set. Next release on idesign4u will use heroku/php.Run git push heroku master to create a new release using this buildpack. I thought I am all set. Then I ran git push heroku master Result I kept getting Counting objects: 67, done.Delta compression using up to 4 threads.Compressing objects: 100% (64/64), done.Writing objects: 100% (67/67), 60.75 MiB | 6.16 MiB/s, done.Total 67 (delta 2), reused 0 (delta 0)remote: Compressing source files... done.remote: Building source:remote: remote: -----> Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/php.tgzremote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failureremote: remote: ! Push failedremote: Verifying deploy...remote: remote: ! Push rejected to idesign4u.remote: To https://git.heroku.com/idesign4u.git ! [remote rejected] master -> master (pre-receive hook declined)error: failed to push some refs to 'https://git.heroku.com/idesign4u.git' Failed to detect set buildpack https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/php.tgz Questions How do I bypass that? Are there any other settings that I need to do in the Heroku site? Note I found some SO post like this one here: Push rejected, failed to detect set buildpack heroku/php I took a look at it, but it is not really relevant in my case here. Now provide the response and nothing else.
It appears that you are trying to deploy a static website to Heroku but specifying the heroku/php builpack which expects, well… a PHP app. Two possible ways of doing this: Meet the requirements of the heroku/php webpack : Have some PHP code. For example, an index.php file with a redirect, like: <?php header( 'Location: /index.html' ) ; ?> Have a composer.json file, which can just be: {} Use heroku-buildpack-static : This is a custom webpack for serving static sites. A complete guide is available here , but the highlights are: heroku plugins:install heroku-cli-staticheroku buildpacks:set https://github.com/hone/heroku-buildpack-staticheroku static:initheroku static:deploy
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42027973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4480164/']}
jdg_374565
stackexchange
llm_judgeable_groundtruth_similarity
41447044
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 group my android RecyclerView items with a header made based on date like this: 1 week ago - item - item - item - item 2 weeks ago - item - item - item that sort of thing or grouping based on some element. Now provide the response and nothing else.
Here is a solution i came by with the aid of alot research over the net and this blog link as well Kartikey Kuswhaha so its not all my credit but i just want to give more clarity to it. below is the code:create the following files: PojoOfJsonArray , MainActivity , ListItem , GeneralItem , DateItem , Adapter PojoOfJsonArray .java -this file wil represent your POJO class or whatever pojo you got going on in your app so: public class PojoOfJsonArray { public PojoOfJsonArray(String name, String date) { this.name = name; this.date = date; } private String name,date; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; }} MainActivity .java this is the activity that you will use to implement you recyclerview : public class MainActivity extends AppCompatActivity { private List<PojoOfJsonArray> myOptions = new ArrayList<>(); List<ListItem> consolidatedList = new ArrayList<>(); private RecyclerView mRecyclerView; private Adapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview); mRecyclerView.setHasFixedSize(true); myOptions.add(new PojoOfJsonArray("name 1", "2016-06-21")); myOptions.add(new PojoOfJsonArray("name 2", "2016-06-05")); myOptions.add(new PojoOfJsonArray("name 2", "2016-06-05")); myOptions.add(new PojoOfJsonArray("name 3", "2016-05-17")); myOptions.add(new PojoOfJsonArray("name 3", "2016-05-17")); myOptions.add(new PojoOfJsonArray("name 3", "2016-05-17")); myOptions.add(new PojoOfJsonArray("name 3", "2016-05-17")); myOptions.add(new PojoOfJsonArray("name 2", "2016-06-05")); myOptions.add(new PojoOfJsonArray("name 3", "2016-05-17")); HashMap<String, List<PojoOfJsonArray>> groupedHashMap = groupDataIntoHashMap(myOptions); for (String date : groupedHashMap.keySet()) { DateItem dateItem = new DateItem(); dateItem.setDate(date); consolidatedList.add(dateItem); for (PojoOfJsonArray pojoOfJsonArray : groupedHashMap.get(date)) { GeneralItem generalItem = new GeneralItem(); generalItem.setPojoOfJsonArray(pojoOfJsonArray);//setBookingDataTabs(bookingDataTabs); consolidatedList.add(generalItem); } } adapter = new Adapter(this, consolidatedList); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(adapter); } private HashMap<String, List<PojoOfJsonArray>> groupDataIntoHashMap(List<PojoOfJsonArray> listOfPojosOfJsonArray) { HashMap<String, List<PojoOfJsonArray>> groupedHashMap = new HashMap<>(); for (PojoOfJsonArray pojoOfJsonArray : listOfPojosOfJsonArray) { String hashMapKey = pojoOfJsonArray.getDate(); if (groupedHashMap.containsKey(hashMapKey)) { // The key is already in the HashMap; add the pojo object // against the existing key. groupedHashMap.get(hashMapKey).add(pojoOfJsonArray); } else { // The key is not there in the HashMap; create a new key-value pair List<PojoOfJsonArray> list = new ArrayList<>(); list.add(pojoOfJsonArray); groupedHashMap.put(hashMapKey, list); } } return groupedHashMap; }} the myOptions is where one would use to feed your data into. ListItem .java public abstract class ListItem { public static final int TYPE_DATE = 0; public static final int TYPE_GENERAL = 1; abstract public int getType();} GeneralItem .java public class GeneralItem extends ListItem { private PojoOfJsonArray pojoOfJsonArray; public PojoOfJsonArray getPojoOfJsonArray() { return pojoOfJsonArray; } public void setPojoOfJsonArray(PojoOfJsonArray pojoOfJsonArray) { this.pojoOfJsonArray = pojoOfJsonArray; } @Override public int getType() { return TYPE_GENERAL; }} DateItem .java public class DateItem extends ListItem { private String date; public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Override public int getType() { return TYPE_DATE; }} Adapter .java this adapter is for the recyclerview if your not well informed on how to make simple sectioned recyclerview then i suggest you read on those and be good in the area because this is abit more tricky anyways: public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; List<ListItem> consolidatedList = new ArrayList<>(); public Adapter(Context context, List<ListItem> consolidatedList) { this.consolidatedList = consolidatedList; this.mContext = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView.ViewHolder viewHolder = null; LayoutInflater inflater = LayoutInflater.from(parent.getContext()); switch (viewType) { case ListItem.TYPE_GENERAL: View v1 = inflater.inflate(R.layout.items, parent, false); viewHolder = new GeneralViewHolder(v1); break; case ListItem.TYPE_DATE: View v2 = inflater.inflate(R.layout.itemsh, parent, false); viewHolder = new DateViewHolder(v2); break; } return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { switch (viewHolder.getItemViewType()) { case ListItem.TYPE_GENERAL: GeneralItem generalItem = (GeneralItem) consolidatedList.get(position); GeneralViewHolder generalViewHolder= (GeneralViewHolder) viewHolder; generalViewHolder.txtTitle.setText(generalItem.getPojoOfJsonArray().getName()); break; case ListItem.TYPE_DATE: DateItem dateItem = (DateItem) consolidatedList.get(position); DateViewHolder dateViewHolder = (DateViewHolder) viewHolder; dateViewHolder.txtTitle.setText(dateItem.getDate()); // Populate date item data here break; } } // ViewHolder for date row item class DateViewHolder extends RecyclerView.ViewHolder { protected TextView txtTitle; public DateViewHolder(View v) { super(v); this.txtTitle = (TextView) v.findViewById(R.id.txt); } } // View holder for general row item class GeneralViewHolder extends RecyclerView.ViewHolder { protected TextView txtTitle; public GeneralViewHolder(View v) { super(v); this.txtTitle = (TextView) v.findViewById(R.id.txt); } } @Override public int getItemViewType(int position) { return consolidatedList.get(position).getType(); } @Override public int getItemCount() { return consolidatedList != null ? consolidatedList.size() : 0; }} and this has two layout being used . thus all
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41447044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6334851/']}
jdg_374566
stackexchange
llm_judgeable_groundtruth_similarity
2466
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: Say I have a population of 50 million unique things, and I take 10 million samples (with replacement)... The first graph is I've attached shows how many times I sample the same "thing", which is relatively rare as the population is larger than my sample. However if my population is only 10 million things, and I take 10 million samples, as the second graph shows I will more often sample the same thing repeated times. My question is - from my frequency table of observations (the data in the bar charts) is it possible to get an estimate of the original population size when it is an unknown? And it would be great if you could provide a pointer to how to go about this in R. Now provide the response and nothing else.
How's the Garvan? The problem is we don't know how many zero counts are observed. We have to estimate this. A classic statistical procedure for situations like this is the Expectation-Maximisation algorithm. A simple example: Assume we draw from an unknown population (of 1,000,000) with a poisson constant of 0.2. counts <- rpois(1000000, 0.2)table(counts) 0 1 2 3 4 5818501 164042 16281 1111 62 3 But we don't observe the zero counts. Instead we observe this: table <- c("0"=0, table(counts)[2:6])table 0 1 2 3 4 5 0 164042 16281 1111 62 3 Possible frequencies observed k <- c("0"=0, "1"=1, "2"=2, "3"=3, "4"=4, "5"=5) Initialise mean of Poisson distribution - just take a guess (we know it's 0.2 here). lambda <- 1 Expectation - Poisson Distribution P_k <- lambda^k*exp(-lambda)/factorial(k)P_k 0 1 2 3 4 50.367879441 0.367879441 0.183939721 0.061313240 0.015328310 0.003065662 n0 <- sum(table[2:6])/(1 - P_k[1]) - sum(table[2:6])n0 0105628.2 table[1] <- 105628.2 Maximisation lambda_MLE <- (1/sum(table))*(sum(table*k)) lambda_MLE [1] 0.697252 lambda <- lambda_MLE Second iteration P_k <- lambda^k*exp(-lambda)/factorial(k) n0 <- sum(table[2:6])/(1 - P_k[1]) - sum(table[2:6]) table[1] <- n0 lambda <- (1/sum(table))*(sum(table*k)) population lambda_MLE [1,] 361517.1 0.5537774 Now iterate until convergence: for (i in 1:200) { P_k <- lambda^k*exp(-lambda)/factorial(k) n0 <- sum(table[2:6])/(1 - P_k[1]) - sum(table[2:6])table[1] <- n0lambda <- (1/sum(table))*(sum(table*k))}cbind( population = sum(table), lambda_MLE) population lambda_MLE[1,] 1003774 0.1994473 Our population estimate is 1003774 and our poisson rate is estimated at 0.1994473 - this is the estimated proportion of the population sampled. The main problem you will have in the typical biological problems you are dealing with is assumption that the poisson rate is a constant. Sorry for the long-winded post - this wiki is not really suitable for R code.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/2466', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1210/']}
jdg_374567
stackexchange
llm_judgeable_groundtruth_similarity
5139467
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 new at LINQ and really need a help with some coding. At the moment, I have a string and a var variables. string temp = "from product in myEntities.Products where product.Name.Contains(_Name) select product";var _Products = temp;LvProducts.DataSource = _Products;LvProducts.DataBind(); Basically, what I want to do is to be able to create a custom/complicated LINQ query by assigning it into a string beforehand. After done with composing, I assign the string into the var variable. However, this is obviously will not work. Therefore, can anyone assist me on this? Now provide the response and nothing else.
You have a few options: Use the the Dynamic Linq libraries to construct you queries onthe fly. The best place to getstarted is by reading ScottGu's blogentry . However, I don't thinkthese libraries support the containsmethod in your example. Here isa blog post explaining how to addthis support. Directly execute SQL statements. Check out the MSDN docs for Linq to Sql or Linq to Entities . var _Products = myEntities.ExecuteStoreQuery<Product>(@"SELECT * FROM Products WHERE [Name] In ('Item1', 'Item2')"); Use Linq's composable behaviour . This might not be the most elegant solution but it works really well if you do not have too many options. You can just construct your query in multiple parts. var _Products = from product in myEntities.Products select product_Products = from product in _Products where product.Name.Contains(_Name) select productif FilterByPrice { _Products = from product in _Products where product.Price > 100 select product}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5139467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/448732/']}
jdg_374568
stackexchange
llm_judgeable_groundtruth_similarity
14506389
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 viewcontrollerA.h I have: @property (nonatomic, assign) NSInteger showCommentOrCreate;+ (PhotoViewController *) sharedManager; in viewcontrollerA.m I use: PhotoViewController* sharedSingleton = [PhotoViewController sharedManager];...(long)sharedSingleton.showCommentOrCreate...+ (PhotoViewController *)sharedManager{static PhotoViewController *shaderManager = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{ shaderManager = [[PhotoViewController alloc] init];});return shaderManager;} ...to find the value of the integer. In viewcontrollerB I import ViewcontrollerA.h, and in ViewcontorllerB.m, I attribute a value to showCommentOrCreate. The only problem is that it seams I have to assign the value to the integer twice for it to change. e.g: Doesn't work: -(IBAction)addAnImageForCommenting:(id)sender{PhotoViewController* sharedSingleton = [PhotoViewController sharedManager];sharedSingleton.showCommentOrCreate = 2;PhotoViewController* sharedSingleton2 = [PhotoViewController sharedManager];sharedSingleton2.showCommentOrCreate = 2;} Doesn't work: -(IBAction)addAnImageForCommenting:(id)sender{PhotoViewController* sharedSingleton2 = [PhotoViewController sharedManager];sharedSingleton2.showCommentOrCreate = 2;} Works: - (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer {for (UIImageView *imageView in imageArray){ if (([imageView isKindOfClass:[UIImageView class]] && imageView.tag == ((UITapGestureRecognizer *)gestureRecognizer).view.tag)) { // for(UIGestureRecognizer *gesture in [imageView gestureRecognizers]){ // if([gesture isKindOfClass:[UITapGestureRecognizer class]]){ if (imageView.frame.size.height == 60){ [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.27]; imageView.contentMode = UIViewContentModeScaleAspectFit; imageView.frame = CGRectMake( 20, imageView.frame.origin.y, 710, 200); [UIView commitAnimations]; [imageView setImage:[UIImage imageNamed: @"Massages retina iPad.png"]]; z = 200; for (MKMapView* map in mapViewArray) { if (imageView.tag == map.tag +1) { [imageView addSubview:map]; } } }else { /*[UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.27]; imageView.contentMode = UIViewContentModeScaleAspectFit; imageView.frame = CGRectMake( 20, imageView.frame.origin.y, 710, 60); [UIView commitAnimations]; [imageView setImage:[UIImage imageNamed: @"message small.png"]];*/ z = 60; for (MKMapView* map in mapViewArray) { if (imageView.tag == map.tag +1) { //[map removeFromSuperview]; } } } } else if([imageView isKindOfClass:[UIImageView class]] && imageView.tag > ((UITapGestureRecognizer *)gestureRecognizer).view.tag){ if (z == 200){ [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.27]; imageView.frame = CGRectMake( 20, imageView.frame.origin.y +150, 710, imageView.frame.size.height); [UIView commitAnimations]; }else { /*[UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.27]; imageView.frame = CGRectMake( 20, imageView.frame.origin.y -150, 710, imageView.frame.size.height); [UIView commitAnimations];*/ } }}for (UIImageView *imageView in imageArray){ if (([imageView isKindOfClass:[UIImageView class]] && imageView.tag == ((UISwipeGestureRecognizer *)gestureRecognizer).view.tag)) {[UIView transitionWithView:imageView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{ //imageView.image = secondImage; } completion:^(BOOL f){ UIStoryboard *sb = [UIStoryboard storyboardWithName:@"PhotoViewControllerStoryboard" bundle:nil]; UIViewController *vc = [sb instantiateInitialViewController]; vc.modalTransitionStyle = UIViewAnimationOptionCurveEaseIn; vc.modalPresentationStyle = UIModalPresentationFormSheet; [self presentModalViewController:vc animated:YES]; vc.view.superview.frame = CGRectMake(15, 43, 735, 982); PhotoViewController* sharedSingleton = [PhotoViewController sharedManager]; sharedSingleton.tagNumber = imageView.tag; //NSLog(@"The tagNumber is: %ld", (long)sharedSingleton.tagNumber); //sharedSingleton.showCommentOrCreate = 1; }]; PhotoViewController* sharedSingleton = [PhotoViewController sharedManager]; sharedSingleton.tagNumber = imageView.tag; sharedSingleton.showCommentOrCreate = [NSNumber numberWithInt:1];}}} As you can see I set the value of the integer twice, and it works, otherwise it doesn't. When It doesn't, if i call the code twice with a time interval, the right value is set. Any ideas?? EDIT: Updated the code I claim to work Now provide the response and nothing else.
Yes, you can place any object in ContentControl.Content , however depending on what determines what UserControl you want, there are multiple ways of accomplishing this. My personal favorite is to go with a DataTrigger that determines the ContentControl.ContentTemplate based on some condition Here's an example that bases the ContentControl.Content on a ComboBox's selected value: <DataTemplate DataType="{x:Type DefaultTemplate}"> <TextBlock Text="Nothing Selected" /></DataTemplate><DataTemplate DataType="{x:Type TemplateA}"> <localControls:UserControlA /></DataTemplate><DataTemplate DataType="{x:Type TemplateB}"> <localControls:UserControlB /></DataTemplate><Style TargetType="{x:Type ContentControl}" x:Key="MyContentControlStyle"> <Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" /> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="A"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" /> </DataTrigger> <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedValue}" Value="B"> <Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" /> </DataTrigger> </Style.Triggers></Style>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14506389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191072/']}
jdg_374569
stackexchange
llm_judgeable_groundtruth_similarity
65876736
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From Android Docs, https://developer.android.com/training/data-storage/manage-all-files#all-files-access "An app can request All files access from the user by doing the following: Declare the MANAGE_EXTERNAL_STORAGE permission in the manifest. Use the ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent action to direct users to a system settings page where they can enable the following option for your app: Allow access to manage all files." What I've tried The only way I know how to request permissions is with ActivityCompat . I've tried: ActivityCompat.requestPermissions(this, new String[]{Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION},1); and ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.MANAGE_EXTERNAL_STORAGE},1); Neither of which do anything. The Android docs are extensive but not exactly the most welcoming for newcomers. I understand intents, and know they can be used to switch between activities, but I don't know what an "intent action" is and how it can be used to request permissions Now provide the response and nothing else.
In Kotlin: val uri = Uri.parse("package:${BuildConfig.APPLICATION_ID}") startActivity( Intent( Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri ) ) (from this sample project ) You are probably used to an implicit Intent . The docs are asking you to use an explicit Intent , one with an action string and, in this case, a Uri . The Uri will have the package scheme and identify your app by its application ID. That code snippet will start a system-supplied activity that, in theory, will let the user opt into granting your app the MANAGE_EXTERNAL_STORAGE permission.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65876736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8940624/']}
jdg_374570
stackexchange
llm_judgeable_groundtruth_similarity
1422368
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 received a Python project (which happens to be a Django project, if that matters,) that uses the fcntl module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an ImportError , because this module does not exist here. Is there any way for me to make a small change in the program to make it work on Windows? Now provide the response and nothing else.
The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip. In other words, porting a fcntl -heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any. There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting. If you provide more details about the fcntl calls people can find windows equivalents.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1422368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76701/']}
jdg_374571
stackexchange
llm_judgeable_groundtruth_similarity
647399
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 am a part-time Windows 7 administrator in an office with about 10 PCs and a standalone networked printer... No Windows print server, though we do have an Active Directory domain. So I have been scouring the web, have read Why use a print server? . Obviously, a print server is not necessary to overlord a small office but I wonder if I can deploy/modify printer settings across all the Windows desktops without one? Everywhere I see "Group Policy" being applied to, for example, setting the printer to default to black-and-white, there is a print server involved. Is it necessary to have a print server in order to distribute changes to the Windows clients? If not, how would I do it? I do have a PC with the Windows Administrative tools installed on it. Thanks. Now provide the response and nothing else.
Printers can be assigned by script, or GPO/GPP, with or without the presence of a print server. A print server just makes centralized management easier... and provides a convenient place for all the damn printer drivers to be found. There are bunch of good examples of scripts for assigning printers here in this Q&A . In your case, you'd just remove the print server variables and references. If done by script, this is most often done by a logon script, so the printers are mapped when the user logs on, but there's nothing saying it has to be done that way. Without a print server, you'd need to map directly to the printer and install the drivers programmatically, which wouldn't be too tough, but it may be difficult (or a much bigger pain than you'd like, at least) to assign defaults to a printer that's not attached to a print server. I can't seem to find a reference I like for deploying printers by GPP or GPO right now, and am feeling kind of lazy, so I'll just say I can add that on request - I also have the suspicion you're not managing domain-joined workstations, which limits the usefulness of Group Policy anyway.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/647399', 'https://serverfault.com', 'https://serverfault.com/users/63931/']}
jdg_374572
stackexchange
llm_judgeable_groundtruth_similarity
31524452
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 studying the concept of Memory Management Unit(MMU) from the book titled "Operating System Concepts" - by Abraham Silberschatz and Galvin. Though things were fine till chapter 8. As soon I started with chapter 9, things started messing up. I am not clear about what my virtual memory is? Also, physical and logical addresses seems to be confusing now? Does it(virtual memory) exists in real or not? As per my understanding of now, the RAM of my system is what I call Physical(or main) Memory. I have 8GB RAM and 64- bit OS. Thus, my RAM can accommodate 2^64-1 addresses. Is this what I call physical address space? Also, what exactly is logical address space? Every process has to be in main memory for execution otherwise it resides on hard disk. Are the addresses given to instructions of my code residing on hard disk is what I call logical address? And when it's loaded in RAM, because location is not fixed and hence the code can be loaded anywhere, the addresses assigned here(RAM) called Physical Addresses? This mapping I suppose is referred to as Logical-Physical address mapping. Now, because size of my code or process can be large than the size of RAM available, here comes the use of virtual memory. As I understood, it's an abstraction to give the programmer a view that he has an infinite amount of memory available on the system. It's basically an area of hard disk where some processes(which are seldom used) from RAM are swapped out. Simultaneously desired pages are brought in the main memory. Is it so? Then what determines the size of this area on hard disk? Also, RAM is cheap, then why do we need to have such a mechanism? Can't we increase our RAM size instead of including this overhead of swapping? I have searched much on web but didn't find the exact definition and difference between these terms. Please help! Thanks Now provide the response and nothing else.
I am not clear about what my virtual memory is? Also, physical and logical addresses seems to be confusing now? Does it(virtual memory) exists in real or not? You can read a decent explanantion on Wikipedia about Virtual Memory . I am not going to discuss the whole thing here. Yes, virtual memory exists in real. It maps memory addresses used by a program, called virtual addresses, into physical addresses in computer memory. Main storage as seen by a process or task appears as a contiguous address space or collection of contiguous segments. The primary benefits of virtual memory include freeing applications from having to manage a shared memory space, increased security due to memory isolation, and being able to conceptually use more memory than might be physically available, using the technique of paging. Thanks to David Schwartz for helping me improve the content. Still in embedded devices, virtual-memory is used just for the page-mapping, it's native purpose for which it was defined. But, now in modern OS', it has taken a totally different form. People are exploiting the usage of virtual-memory in paging/segmentation,thus swapping being the most-important. The extra memory area is also known as swap-area or swap-partition nowadays which is generally reserved for usage by OS(Unix/Linux) for swapping process in and out of the main-memory. Windows has pagefiles for achieving the same. I have 8GB RAM and 64- bit OS. Thus, my RAM can accommodate 2^64-1 addresses. Is this what I call physical address space? You should talk about processor here, and not OS or the RAM directly. In principle, a 64-bit microprocessor can address 16 EiBs (16 × 2^60 bytes) of memory. In practice, it is less than that. This memory is what you can possibly use as RAM . Also, what exactly is logical address space? Logical address space is the address space consisting of addresses at which items (memory cell, storage element, network host) appear to reside from the perspective of an executing application program. A logical address may be different from the physical address due to the operation of an address translator or mapping function. Such mapping functions may be, in the case of a computer memory architecture, a memory management unit (MMU) between the CPU and the memory bus, or an address translation layer, e.g., the Data Link Layer, between the hardware and the internetworking protocols (Internet Protocol) in a computer networking system. In a system supporting virtual memory, there may actually not be any physical memory mapped to a logical address until an access is attempted. The access triggers special functions of the operating system which reprogram the MMU to map the address to some physical memory, perhaps writing the old contents of that memory to disk and reading back from disk what the memory should contain at the new logical address. In this case, the logical address may be referred to as a virtual address. Every process has to be in main memory for execution otherwise it resides on hard disk. Are the addresses given to instructions of my code residing on hard disk is what I call logical address? And when it's loaded in RAM, because location is not fixed and hence the code can be loaded anywhere, the addresses assigned here(i RAM) called Physical Addresses? This mapping I suppose is referred to as Logical-Physical address mapping. Nowadays, almost all systems support virtual memory(there are a few exceptions). So, yes, when your processes are swapped out from RAM so that other processes could execute, they are separately kept in that reserved portion of hard-disk called virtual memory. And, there is an addressing scheme for virtual-memory which is what you call as a logical address. Page tables are used to translate the virtual addresses seen by the application into physical addresses used by the hardware to process instructions; such hardware that handles this specific translation is often known as the memory management unit. Each entry in the page table holds a flag indicating whether the corresponding page is in real memory or not. If it is in real memory, the page table entry will contain the real memory address at which the page is stored. Now, because size of my code or process can be large than the size of RAM available, here comes the use of virtual memory. As I understood, it's an abstraction to give the programmer a view that he has an infinite amount of memory available on the system. It's basically an area of hard disk some processes(which are seldom used) from RAM are swapped out. Simultaneously desired pages are brought in the main memory. Is it so? Then what determines the size of this area on hard disk? Exactly the same as described above. And, this size of reserved hard-disk space(virtual-memory) is recommended by different types of OS differently. But, generally it is defined to be on a different partition on Unix/Linux OS(swap partition). Windows has pagefile compared to *nix's swap partition; although there are many technical differences between the two.. This is OS-specific but the concept is almost the same. In *nix systems I have seen that it is recommended to keep the size of swap partition to be double of the size of the RAM in the system. I can't argue more about this,maybe someone can suggest more detail. Also, RAM is cheap, then why do we need to have such a mechanism? Can't we increase our RAM size instead of including this overhead of swapping? No, as compared to the cost of the RAM, the price of hard-disk is still much economical. Also, RAM is expensive and not all PCs can be upgraded to increase RAM. Luckily increasing virtual memory is the best option when you are low on memory. Also, Microsoft recommends that you set virtual memory to be no less than 1.5 times and no more than 3 times the amount of RAM on your computer. ( Source of the last line ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31524452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3552407/']}
jdg_374573
stackexchange
llm_judgeable_groundtruth_similarity
108128
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a matrix stored as a SparseArray . How can I convert it to a List of its rows, where each row is stored as a SparseArray ? Note that the matrix is huge, so the conversion should use as little memory as possible (the lower bound being the memory of the final List object). Now provide the response and nothing else.
List @@ s will do the trick: s = 1000000 // RandomInteger[{1, 1000000}, {#, 2}] -> RandomReal[1, #]& // SparseArray;s // Head(* SparseArray *)s // Dimensions(* {1000000, 1000000} *)l = List @@ s;l // Head(* List *)l // Dimensions(* {1000000, 1000000} *)l // First // Head(* SparseArray *)Take[l, 4] Why Does This Work? Commentators observe that replacing the head of the (apparent) FullForm of a SparseArray ought to produce a nonsensical result. Why, then, does this work? Despite appearances, a SparseArray is an atom: SparseArray[Range[10]] // AtomQ(* True *) The full-form is therefore synthetic. Any operations that operate upon the (notionally non-existent) subparts of these atoms are implemented as special definitions. The documentation strongly implies that a SparseArray is meant to act virtually interchangeably with a regular List . The Details section gives explicit examples where the parts of a multidimensional sparse array themselves appear as sparse arrays to operations like Map , Part , Listable , etc. In light of this, it stands to reason that replacing the notional head of a multidimensional sparse array with List would result in a list of sparse arrays. It is likely that the implementation has explicit code to handle this case. I cannot point to a definitive statement in the documentation that guarantees the behaviour of List @@ s . But I would argue that it is so strongly implied that it would be a regression if it were changed in some future release.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/108128', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/534/']}
jdg_374574
stackexchange
llm_judgeable_groundtruth_similarity
62409
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently attended a PhD thesis defence in which one committee members claimed that "manual feature extraction is outdated. Nowadays, we have [deep] machine learning models doing that job for us automatically." Is this statement true? If yes, please provide a reference substantiating this claim. Edit: Apparently, there seem to be different answers depending on the data type. Thus, please let me know about any references substantiating your claims for images, time series, etc... separately. Now provide the response and nothing else.
In the general case, this is by no means true. Let's break down the case for different data scenarios: For discriminative image models (e.g. image classification/labeling) this is true for some scenarios. You just throw some convnets (even pretrained models) at your data, and that's it. Nevertheless, convnets themselves profit from the "expert knowledge" that information locality is important and so is hierarchical information processing. For some other scenarios, applying domain knowledge (e.g. specific data transformations) may give the edge to reach the needed level of quality in the results. For many image processing problems, neural networks work best when infused with some kind of inductive bias, e.g. attention. For Natural Language Processing (NLP) problems, a good amount of craftsmanship is needed nowadays, especially in the data preprocessing stage. For "typical data science" problems, it is also crucial to do feature extraction. You can have a look at Kaggle competitions to verify this. For time series problems, it is also normal to rely on expert knowledge to understand which models fit best based on the nature of the data. However, I think that the trend of the areas where deep learning is applicable (i.e. tons of available data) is to try to devise systems that are trained end-to-end, with the least possible ad hoc processing. Nevertheless, many times this is achieved by infusing the expert knowledge into the network in the form of inductive biases.
{}
{'log_upvote_score': 5, 'links': ['https://datascience.stackexchange.com/questions/62409', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/53994/']}
jdg_374575
stackexchange
llm_judgeable_groundtruth_similarity
3181211
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 wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object. Let's suppose we have the following class X : class X{private: int i;public: X(){i=0;} X& operator ++ (){ ++i; return *this; } //prefix increment X operator ++ (int unused){ //postfix increment X ret(*this); i++; return ret; } operator int(){ return i; } //int cast}; First of all, have I implemented the prefix/postfix increment operators properly? Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X object copies are created when each version of the operator is used? An explanation of exactly what happens with return-by-reference vs return-by-value might help me understand. Edit: For example, with the following code... X a;X b=a++; ...are a and b now aliases? Now provide the response and nothing else.
This is a correct implementation. It is typical that a postfix operator will be worse on performance because you have to create another copy before doing the increment (and this is why I've gotten in the habit of always using prefix unless I need something else). With return-by-reference, you're returning an l-value reference to the current object. The compiler would typically implement this by returning the address of the current object. This means that returning the object is as simple as returning a number. However, with return-by-value, a copy must be done. This means there's more information to copy over during the return (instead of just an address) as well as a copy constructor to call. This is where your performance hit comes in. The efficiency of your implementation looks on-par with typical implementations. EDIT:With regards to your addendum, no, they are not aliases. You have created two separate objects. When you return by value (and when you created a new object from within the postfix increment operator) this new object is placed in a distinct memory location. However, in the following code, a and b are aliases: int a = 0; int& b = ++a; b is an address which references a.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3181211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2045611/']}
jdg_374576
stackexchange
llm_judgeable_groundtruth_similarity
15825872
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 does the \1 do? For example "foo bar bag".gsub(/(bar)/,'car\1') I believe it has something to do with how you use parentheses, but I'm not really sure. Could someone explain it to me? And can you do stuff like \2? If so, what would that do? Now provide the response and nothing else.
Each item that you surround with parenthesis in the searching part will correspond to a number \1 , \2 , etc., in the substitution part. In your example, there's only one item surrounded by parenthesis, the "(bar)" item, so anywhere you put a \1 is where the part inside the parenthesis, will be swapped in. You can put in the \1 multiple times, which is handy if you want to repeat that found item, so you could legitimately write car\1\1\1 and "bar" will be swapped in three times. There's no use for \2 because there's only one item surrounded by parentheses. However, if you had (bar)(jar) , then the \1 would represent "bar" and \2 would represent "jar" . You could even do things like this: \1\2\1\2\2\1 which would become: barjarbarjarjarbar Here's a real-world example where this comes in handy. Let's say you have a name list like this: Jones, Tom Smith, Alan Smith, Dave Wilson, Bud and you want to change it to this: Tom Jones Alan Smith Dave Smith Bud Wilson You could search for: (.+), (.+) and replace with: \2 \1 You could also replace with: \1: \2 \1 Which would become: Jones: Tom Jones Smith: Alan Smith Smith: Dave Smith Wilson: Bud Wilson
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15825872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2245960/']}
jdg_374577
stackexchange
llm_judgeable_groundtruth_similarity
6870362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I define the following [parameter(Mandatory = $true)][alias("db")][string]$database, then I get an error Parameter alias cannot be specified because an alias with the name 'db'was defined multiple times for the command. Which is true, since db is already an alias for the universal -Debug parameter. Is it possible to define this alias without renaming the parameter? Now provide the response and nothing else.
Sorry, you can't. -Debug is a common parameter, so -Debug and -db are switches that are available on pretty much everything including the functions you write yourself. As the error tells you, it's already defined. Even if it were possible to go around undefining built-in aliases, that unexpectantly changes the meaning of a call like test-db -db for someone else who frequently uses -db instead of -Debug . They expect it to enable debugging output, not specify a different parameter. Consider this function: function test-db{ param( [parameter(mandatory=$true)] [string]$database) write-host 'database' $database write-debug 'debugging output'} Now call it with test-db server , test-db -db server , and test-db server -db . The first doesn't do write-debug , while the other 2 do, no matter where -db is. You also can't define a separate parameter [string]$db (or rename $database to $db ) because Powershell will give you this error: Parameter 'db' cannot be specified because it conflicts with the parameter alias of the same name for parameter 'Debug'. More info on this, per MSDN (updated since old link died): In addition to using the System.Management.Automation.Aliasattribute attribute, the Windows PowerShell runtime performs partial name matching, even if no aliases are specified. For example, if your cmdlet has a FileName parameter and that is the only parameter that starts with F , the user could enter Filename , Filenam , File , Fi , or F and still recognize the entry as the FileName parameter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6870362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39068/']}
jdg_374578
stackexchange
llm_judgeable_groundtruth_similarity
690024
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: Why must the base of a logarithm be a positive real number not equal to 1? and why must $x$ be positive? Thanks. Now provide the response and nothing else.
By definition, $\log_bx$ is the number for which, if you take $b$ to that power, you get $x$ . Symbolically: $$b^{\log_b x} = x$$ For example, what power do we need to raise $2$ to in order to get $4$ ? Well, it's $\log_24 = 2$ . What power do we need to raise $81$ to in order to get $9$ ? Well, it's $\log_{81}9 = 0.5$ . Ask yourself what $\log_1x$ means. It's the power, say $p$ , for which $1^p=x$ . Unless $x=1$ , there is no solution, and when $x=1$ any power will do, so $\log_11$ is any number. For the same reason $\log_0$ doesn't make sense because we can't solve $0^y=x$ unless $x=0$ , and when $x=0$ , any power will do, so $\log_00$ could be any number. Why can logarithms only be applied to positive arguments? Well, $\log_2(-1)$ would be the power, say $p$ , for which $2^p = -1$ . Hopefully, you can see that $2^p > 0$ for all real numbers $p$ .
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/690024', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131423/']}
jdg_374579
stackexchange
llm_judgeable_groundtruth_similarity
398413
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 have a text file containing tweets and I'm required to count the number of times a word is mentioned in the tweet. For example, the file contains: Apple iPhone X is going to worth a fortuneThe iPhone X is Apple's latest flagship iPhone. How will it pit against it's competitors? And let's say I want to count how many times the word iPhone is mentioned in the file. So here's what I've tried. cut -f 1 Tweet_Data | grep -i "iPhone" | wc -l it certainly works but I'm confused about the 'wc' command in unix. What is the difference if I try something like: cut -f 1 Tweet_Data | grep -c "iPhone" where -c is used instead? Both of these yield different results in a large file full of tweets and I'm confused on how it works. Which method is the correct way of counting the occurrence? Now provide the response and nothing else.
Given such a requirement, I would use a GNU grep (for the -o option ), then pass it through wc to count the total number of occurrences: $ grep -o -i iphone Tweet_Data | wc -l3 Plain grep -c on the data will count the number of lines that match, not the total number of words that match. Using the -o option tells grep to output each match on its own line, no matter how many times the match was found in the original line. wc -l tells the wc utility to count the number of lines. After grep puts each match in its own line, this is the total number of occurrences of the word in the input. If GNU grep is not available (or desired), you could transform the input with tr so that each word is on its own line, then use grep -c to count: $ tr '[:space:]' '[\n*]' < Tweet_Data | grep -i -c iphone3
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/398413', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/255849/']}
jdg_374580
stackexchange
llm_judgeable_groundtruth_similarity
6337879
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 actually playing with Javascript doing a small game and I would like to implement what I've found on http://www.crockford.com/javascript/inheritance.html which is something similar to: ZParenizor.method('toString', function () { if (this.getValue()) { return this.uber('toString'); } return "-0-";}); I can't find any reference the the library used to make such development possible. Any ideas? Otherwise, I'm looking for a good library that will aid my OOP developments. Thank you Edit: I am looking for a OOP solution / library for Node.js. Please note that I'm new to Node.js Now provide the response and nothing else.
2 months later Maybe you do need a library, ES5 is verbose as hell so I've created pd Original answer I am looking for a OOP solution / library for Node.js. You don't need a library. You have ES5 . JavaScript does not have classical OOP. It has prototyping OOP. This means you have only objects. The only thing you can do with objects is extend, manipulate and clone them. Manipulate var o = {};o.foo = "bar"; Extend var o = someObject;Object.defineProperties(o, { "foo": { value: "foo" }, "bar": { value: "bar" } "method": { value: function () { } }} Clone var o = someObject;var p = Object.create(o); Clone and extend var o = someObject;var p = Object.create(o, { "foo": { value: "foo" }, "bar": { value: "bar" } "method": { value: function () { } }} It's important to understand how Object.create , Object.defineProperty and Object.defineProperties work. The cloning operation isn't actually cloning. It's creating a new object from a blueprint. A blueprint is an object. It places the blueprint in the [[Prototype]] . The [[Prototype]] lives in the .__proto__ property which I'll use for demonstration. var o = {};var p = Object.create(o);p.__proto__ === o; // truevar q = Object.create(p);q.__proto__.__proto__ === o;var r = Object.create(q);r.__proto__.__proto__.__proto__ === o; Disclaimer: .__proto__ is deprecated. Don't use it in code. It has it's uses for debugging and sanity checks though. The main point here is that accessing properties from o in r it has to walk 3 levels up the prototype chain and this gets expensive. To solve that problem, rather then cloning random objects you should clone specific blueprints (and you should have one blueprint per object). // Parent blueprintvar Parent = (function _Parent() { // create blank object var self = Object.create({}); // object logic return self;}());// factory functionvar createParent = function _createParent(foo) { // create a object with a Parent prototype return Object.create(Parent, { foo: { value: foo } });}var Child = (function _Child() { var self = Object.create(Parent); // other stuff return self;}());var createChild = function _createChild(bar) { return Object.create(Child, { bar: { value: bar } })}; Here's a snippet from some code I'm working on that you can use as an example: var Sketchpad = (function _SketchPad() { var self = Object.create({}); var mousemove = function _mousemove(e) { this.drawLine(e); }; self._init = function _init() { this.$elem.bind({ "mousemove": mousemove.bind(this), }); this.pens = {}; $("#clear").bind("click", this.clear.bind(this)); $("#undo").bind("click", (function _undoPath() { this.pen.undo(); }).bind(this)); return this; }; self.clear = function() { this.paper.clear(); }; return self; }());createSketch = function _createSketchPad(id, w, h) { var paper = Raphael(id, w, h); var pen = createPen(paper); var o = Object.create(Sketchpad, { paper: { value: paper }, $elem: { value: $("#" + id) }, pen: { get: function() { return pen; }, set: function(v) { pen = v; } } }); return o._init();};
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6337879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311352/']}
jdg_374581
stackexchange
llm_judgeable_groundtruth_similarity
37617677
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to write a function template that operates on a container of strings, for example a std::vector . I'd like to support both CString and std::wstring with the same template function. The problem is that CString and wstring have different interfaces, for example to get the "length" of a CString , you call the GetLength() method, instead for wstring you call size() or length() . If we had a "static if" feature in C++, I could write something like: template <typename ContainerOfStrings>void DoSomething(const ContainerOfStrings& strings){ for (const auto & s : strings) { static_if(strings::value_type is CString) { // Use the CString interface } static_else_if(strings::value_type is wstring) { // Use the wstring interface } }} Is there some template programming technique to achieve this goal with currently available C++11/14 tools? PS I know it's possible to write a couple of DoSomething() overloads with vector<CString> and vector<wstring> , but that's not the point of the question. Moreover, I'd like this function template to work for any container on which you can iterate using a range-for loop. Now provide the response and nothing else.
#include <type_traits>template <typename T, typename F>auto static_if(std::true_type, T t, F f) { return t; }template <typename T, typename F>auto static_if(std::false_type, T t, F f) { return f; }template <bool B, typename T, typename F>auto static_if(T t, F f) { return static_if(std::integral_constant<bool, B>{}, t, f); }template <bool B, typename T>auto static_if(T t) { return static_if(std::integral_constant<bool, B>{}, t, [](auto&&...){}); } Test: template <typename ContainerOfStrings>void DoSomething(const ContainerOfStrings& strings){ for (const auto & s : strings) { static_if<std::is_same<typename ContainerOfStrings::value_type, CString>{}> ([&](auto& ss) { // Use the CString interface ss.GetLength(); })(s); static_if<std::is_same<typename ContainerOfStrings::value_type, wstring>{}> ([&](auto& ss) { // Use the wstring interface ss.size(); })(s); }} DEMO
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37617677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1629821/']}
jdg_374582
stackexchange
llm_judgeable_groundtruth_similarity
432870
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So, if i do this: su -c 'screen -dmS screenname script to run' - user to run as It won't work. The screen command is working if excecuted from root, so there is no problem there. If I do: su - userscreen I get: Cannot open your terminal '/dev/pts/0' - please check. What is wrong? EDIT:I've been searching around and can't seem to find any good solution to this problem. I'll be going for the next best thing: running the screens as root. Now provide the response and nothing else.
The reason is that when you login, you get a tty which in your case is currently called /dev/pts/0. You are the only one with access to that tty, otherwise other users could mess with your session while you're working. (Root, of course, also has access, because root always has access to everything.) When you su to someone else, you still keep your own tty - because that's where your stuff will be shown. But now you want the other user you're su-ing to be able to take over your tty and start showing their own stuff in it. If you trust everybody else on the server, or at least the other user you're suing to, you can make your tty writable for all, or add yourself and that other user to a group and make it writable for that group. Or you could start the screen as yourself and then su from within it instead.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/432870', 'https://serverfault.com', 'https://serverfault.com/users/134992/']}
jdg_374583
stackexchange
llm_judgeable_groundtruth_similarity
650793
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 thought that because this is true: $$ \sin^2x=(\sin x)^2,$$ I could differentiate the expression like this: $$ \frac{d}{dx}\sin^2x=2\cos x.$$ But I am supposed to get $$ \sin(2x) \quad \text{or}\quad 2\sin x \cos x.$$ Why am I wrong? Now provide the response and nothing else.
You can only use the rule:$ \frac{d}{dx} x^n = nx^{n-1} $ if $x$ is just $x$ and not a function. In the case for $\sin^2{x}$ then as you write it in the form $(\sin{x})^2$ you can see that we can't use the power rule because it's not just an $x$ term being raised to a constant power, it's a function being raised to a constant power. To differentiate $\sin^2{x}$ one must use the Chain Rule because $\sin{x}$ is a function of $x$ within another function (the function that is squaring $\sin{x}$) $x^2$. The chain rule is: $\frac{d}{dx}f(g(x))=g'(x)\times(f'(g(x))$ so you can apply that rule for this case with $f(x)=x^2$ and $g(x)=\sin{x}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/650793', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/100744/']}
jdg_374584
stackexchange
llm_judgeable_groundtruth_similarity
7564792
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 entity called Product class Product{ public Id { get; set; } public Name { get; set; }} and i have a list of all products: IEnumerable<Product> products = _productRepository.GetAll() i want to get an array of strings from this list of products this array will contains the product Id + Product Name, so when i try to cast it using the following code: string[] s = products.Cast<string>().ToArray(); i got the following exception: Unable to cast object of type 'Product' to type 'System.String' the exception really makes alot fo scence, so if i had a method string ProductToString(Product p){ return p.Name;} or an override to ToString() for the product object so how i can use this method to get the list of string[] from IEnumerable ? Now provide the response and nothing else.
Well, given that method you can use 1 : string[] s = products.Select<string>(ProductToString).ToArray(); However, it would be more idiomatic to do this without a separate method, usually, using a lambda expression: // Matches ProductToString, but not your descriptionstring[] s = products.Select(p => p.Name).ToArray(); I'd only use a separate method if it was going to be called from various places (ensuring consistency) or did a lot of work. EDIT: I've just noticed that your description (wanting ID + name) doesn't actually match the ProductToString method you've given (which just gives the name). For the ID + name I'd use: string[] s = products.Select(p => p.ID + " " + p.Name).ToArray(); or string[] s = products.Select(p => string.Format("{0} {1}", p.ID, p.Name)) .ToArray(); Or you could just change your ProductToString method, of course. Alternatively, you could override ToString() in Product , if this is usually how you want to convert a Product to a string . You could then either use a method group conversion or a lambda expression to call ToString . 1 It's possible that you don't need to specify the type argument explicitly - that: string[] s = products.Select(ProductToString).ToArray(); will work fine - the rules for type inference and method group conversions always confuse me and the compiler behaviour has changed slightly over time. A quick test just now looks like it does work, but there could be subtleties in slightly different situations.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7564792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722783/']}
jdg_374585
stackexchange
llm_judgeable_groundtruth_similarity
60841785
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a service (in .NET Core 3.1 and Refit if it matters) that pulls transaction activities from my PayPal business account for a given date range to use on an admin dashboard. Currently I'm following the tutorial here: https://developer.paypal.com/docs/api/get-an-access-token-postman/ and here: https://developer.paypal.com/docs/api/transaction-search/v1/ The first part, I can get an authorization key just fine (using curl or postman, curl below curl --location --request POST 'https://api.paypal.com/v1/oauth2/token' \--header 'Content-Type: application/x-www-form-urlencoded' \--header 'Authorization: Basic <my client id>:<my secret>' \--header 'Content-Type: application/x-www-form-urlencoded' \// not sure what this is, postman specific maybe? --header 'Cookie: tsrce=devdiscoverynodeweb; ts=vr%3D0cee9361171ac120001362adffec14c3%26vreXpYrS%3D1679730671%26vteXpYrS%3D1585061694%26vt%3D0cee9390171ac120001362adffec14c2' \--data-urlencode 'grant_type=client_credentials' This gives me an auth token both in postman and my custom service just fine. Next, when I try to pull the transactions (both in Postman and in code), I get an error cUrl: curl --location --request GET 'https://api.paypal.com/v1/reporting/transactions?start_date=2020-03-01T00:00:00Z&end_date=2020-03-31T23:59:59Z' \--header 'Authorization: Bearer <my token>' \// Postman???--header 'Cookie: tsrce=devdiscoverynodeweb; ts=vr%3D0cee9361171ac120001362adffec14c3%26vreXpYrS%3D1679730671%26vteXpYrS%3D1585061694%26vt%3D0cee9390171ac120001362adffec14c2' Error: { "localizedMessage": "No permission for the requested operation. ", "suppressed": [], "name": "PERMISSION_DENIED", "message": "No permission for the requested operation. ", "details": [ { "field": null, "value": null, "location": null, "issue": "No permission for the requested operation. " } ], "information_link": "https://developer.paypal.com/docs/classic/products/permissions/", "debug_id": "7e315038e8073"} The info link in the error starts talking about 3rd party permissions, which I'm not sure is applicable because it is my Business account. Anyone have any ideas? I checked transaction history on my app in PayPal, so I'm at a lost. Thanks in advance Now provide the response and nothing else.
You need the scope https://uri.paypal.com/services/reporting/search/read .. if it's not there in the oauth2 response, double check your REST App's permissions. Refreshing an access token Existing access tokens are cached for 9 hours--so if you already requested an API token and then just added this permission to your app, it can take up to 9 hours for that permission's new scope to be reflected in the next token's generation. To avoid waiting 9 hours, you can terminate that existing cached token with: curl -X POST https://api.sandbox.paypal.com/v1/oauth2/token/terminate \ -u "yourclientid:yoursecret" \ -d "token=REPLACE_WITH_YOUR_TOKEN" After termination, your next call to get a token will get a newly-generated one, including the new scope that was just added to the REST app.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60841785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1623145/']}
jdg_374586
stackexchange
llm_judgeable_groundtruth_similarity
13244875
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 the code below on an aspx page on button click event to generate csv file. This works when I do not name my file but when I try to use: Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv"); to name the file as myfilename.csv, the excel sheet generated is the screen shot of the web page instead of having text in it. Can someone help me with this problem. Thanks! DataGrid dg = new DataGrid();dg.DataSource = GetData();htmlTextWriter.WriteLine("<b>Details</b>");//Get the html for the controldg.HeaderStyle.Font.Bold = true;dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;dg.DataBind();dg.RenderControl(htmlTextWriter);//Write the HTML back to the browser.Response.Clear();Response.ContentType = "application/vnd.ms-excel";//Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");this.EnableViewState = false;Response.Write(textWriter.ToString());Response.End();private System.Data.DataTable GetData(){ System.Data.DataTable dt = new System.Data.DataTable("TestTable"); dt.Columns.Add("SSN"); dt.Columns.Add("Employee ID"); dt.Columns.Add("Member Last Name"); dt.Columns.Add("Member First Name"); dt.Columns.Add("Patient Last Name"); dt.Columns.Add("Patient First Name"); dt.Columns.Add("Claim No."); dt.Columns.Add("Service Line No."); dt.Columns.Add("Error Code"); dt.Columns.Add("Error Message"); dt.Rows.Add(123456789,4455,"asdf","asdf","sdfg","xzcv","dsfgdfg123",1234,135004,"some error"); dt.Rows.Add(123456788,3344,"rth","ojoij","poip","wer","aadf124",1233,135005,"Some Error"); dt.Rows.Add(123456787,2233,"dfg","sdfg","vcxb","cxvb","UHCAL125",1223,135006,"another error"); return dt;} Now provide the response and nothing else.
I am not exactly sure what you are aiming for here, so I have assumed that you are wanting to create a CSV file in a button click event and send that back to the user. What you currently have appears to write the HTML of the control into an XLS file. Try this: protected void Button1_Click(object sender, EventArgs e){ var dataTable = GetData(); StringBuilder builder = new StringBuilder(); List<string> columnNames = new List<string>(); List<string> rows = new List<string>(); foreach (DataColumn column in dataTable.Columns) { columnNames.Add(column.ColumnName); } builder.Append(string.Join(",", columnNames.ToArray())).Append("\n"); foreach (DataRow row in dataTable.Rows) { List<string> currentRow = new List<string>(); foreach (DataColumn column in dataTable.Columns) { object item = row[column]; currentRow.Add(item.ToString()); } rows.Add(string.Join(",", currentRow.ToArray())); } builder.Append(string.Join("\n", rows.ToArray())); Response.Clear(); Response.ContentType = "text/csv"; Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv"); Response.Write(builder.ToString()); Response.End();} When I run this I am prompted by the browser to save the CSV file. Edit: If you would like to maintain your current approach (which is producing HTML, not CSV) then try this: Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.xls"); Note that I have simply changed the file extension from CSV to XLS. When using the CSV extension, the text appeared in Excel as HTML. Using XLS, it appears just as it does when the above line is commented out.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13244875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178192/']}
jdg_374587
stackexchange
llm_judgeable_groundtruth_similarity
9672084
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 implement the Revealing Module Pattern but I'm unable to expose a modified private property. var myRevealingModule = (function(){ var name = 'Diogo'; function setName () { name = name + ' Cardoso'; } return { fullName: name, set: setName };}());// Sample usage:myRevealingModule.set();console.log(myRevealingModule.fullName); // "Diogo" instead of the excepted "Diogo Cardoso". Now provide the response and nothing else.
return { fullName: name, set: setName}; That uses the values of name and setName . It does not create a reference to the variable. Effectively, name is copied. You need to create a corresponding getName method, to take advantage of closures so that you can keep a reference to a variable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9672084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574419/']}
jdg_374588
stackexchange
llm_judgeable_groundtruth_similarity
15327745
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 developing a cross-platform system and I need to make a rest API to tie them together. I have long experience in PHP and I want to use this for this service. I could develop a API 100% manually, but I am hoping there is some great libraries out there that could ease my development. Does anyone have any experience with libraries like this? Anything you could recommend? Now provide the response and nothing else.
I got the badge Popular question for this question, so I feel it's about time I elaborate how I did my REST-soluton. I did look at both Laravel, Sympfony2 and Codeigniter for this REST Api. They all had some elements I liked and some I disliked. My main concern was how to do the authentication because I had a rather complex algorithm where my users can log in with the apps' access_token or access_tokens served by Google or Facebook. I also perfer being in complete control of my framework and the frameworks mentioned above had some elements I felt unnecessary and hard to work around. Because of this I decided to make my own REST-solution. It is not as hard as one might expect, and it can be done in several ways. The way I did it requires some knowledge about OOP-programming. Okey, so starting out a made a base-class called REST. This class takes care of all the stuff that is in common for every call. Like authentication, parsing the requested path to a method, checking access_token etc. One of the central things in this class is the requested path and how this is translated into a method. I did this inspired by Laravel. I have a array with key => value where the key is the url it should match and the value is the actual method to call. I also included the way Lavavel parses variables in the URL like so: '/user/(:id)' => 'user_id', This would match any /user/[number]. It also checks what type of request this is, so if this is a simple get-method it would try to call get_user_id . Anything parsed with (:id) would be used as an argument when calling that method (so it is actually calling get_user_id($id) ). After authentication the actual method-call gets evaluated. I did not want all the methods (like get_user_id ) in the REST-class itself, so I broke these up in different controllers that extends the REST-class. This is done by looking at the url being requested. If it is /user/(:id) the script will check if there is a controller named userController.php . If it exists, check if the method we are going to call exists. If it does, check if the number of arguments matches what we have. If everything is good, execute the method, if not return an error message. Structure and error-messages are very important when making a API like this. In the different controllers I call the constructor for the REST-class to get the authentication, parsing of the url etc resolved. The tricky part here is that I did not want to do: $controller = new MyController();$controller->printResponse(); In the bottom of every controller. So I made a little hack and a script called run.php that does this dynamically for every controller-class. Before I include the run.php I save the path for the controller by simply doing $path = explode('/',__FILE__); . This is used in the run-script. The run-script looks like this: // Splitting the file-name, removing the extension$name = explode('.',$path[count($path)-1]);// Uppercasing the first letter to be nice and OOP-ish$classToCall = ucfirst($name[0]);// Creating a new instance$controller = new $classToCall();// Logging$controller->doLog();// Printing the final response$controller->printResponse(); I found this to be a perfect solution for how I wanted to build my API. I can easily add new methods by supplying it in the array that parses urls to methods, and I can add new methods in the nicely broken apart controllers for maximum cleanness. Some people might think this is too much work, but it actually took me only a few hours to get it up and running. I'd also call this highly dynamic as I can just add new controllers and the system will recognize them if they are valid url-patterns. A few friendly advices. If you decide to go with something resembling this solution, these can be some good tips. In each controller, do something like this: public function __construct() { // Loading the class-name, setting it in the REST-class, so we can check if it holds the method being called $this->className = get_class($this); // Calling RESTs constructor parent::__construct();} We will need to store what class we are currently working from. This would be UserController or something like that. In the REST-class I can then use this variable to check if the actual method getting called does exist in this controller. I've done that this way: // Checking if the method existsif (method_exists($this->className,$method_name)) { // Check to see if we have the required number of arguments represented $ReflectionClass = new ReflectionClass($this->className); if ($ReflectionClass->getMethod($method_name)->getNumberOfParameters() == count($this->methodUrl['args'])) { $this->response['response'] = call_user_func_array(array($this, $method_name), $this->methodUrl['args']); I hope that can get you all going. Happy codin'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15327745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/921563/']}
jdg_374589
stackexchange
llm_judgeable_groundtruth_similarity
3537706
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 processing some Java source code using Java. I'm extracting the string literals and feeding them to a function taking a String. The problem is that I need to pass the unescaped version of the String to the function (i.e. this means converting \n to a newline, and \\ to a single \ , etc). Is there a function inside the Java API that does this? If not, can I obtain such functionality from some library? Obviously the Java compiler has to do this conversion. Now provide the response and nothing else.
The Problem The org.apache.commons.lang.StringEscapeUtils.unescapeJava() given here as another answer is really very little help at all. It forgets about \0 for null. It doesn’t handle octal at all . It can’t handle the sorts of escapes admitted by the java.util.regex.Pattern.compile() and everything that uses it, including \a , \e , and especially \cX . It has no support for logical Unicode code points by number, only for UTF-16. This looks like UCS-2 code, not UTF-16 code: they use the depreciated charAt interface instead of the codePoint interface, thus promulgating the delusion that a Java char is guaranteed to hold a Unicode character. It’s not. They only get away with this because no UTF-16 surrogate will wind up looking for anything they’re looking for. The Solution I wrote a string unescaper which solves the OP’s question without all the irritations of the Apache code. /* * * unescape_perl_string() * * Tom Christiansen <tchrist@perl.com> * Sun Nov 28 12:55:24 MST 2010 * * It's completely ridiculous that there's no standard * unescape_java_string function. Since I have to do the * damn thing myself, I might as well make it halfway useful * by supporting things Java was too stupid to consider in * strings: * * => "?" items are additions to Java string escapes * but normal in Java regexes * * => "!" items are also additions to Java regex escapes * * Standard singletons: ?\a ?\e \f \n \r \t * * NB: \b is unsupported as backspace so it can pass-through * to the regex translator untouched; I refuse to make anyone * doublebackslash it as doublebackslashing is a Java idiocy * I desperately wish would die out. There are plenty of * other ways to write it: * * \cH, \12, \012, \x08 \x{8}, \u0008, \U00000008 * * Octal escapes: \0 \0N \0NN \N \NN \NNN * Can range up to !\777 not \377 * * TODO: add !\o{NNNNN} * last Unicode is 4177777 * maxint is 37777777777 * * Control chars: ?\cX * Means: ord(X) ^ ord('@') * * Old hex escapes: \xXX * unbraced must be 2 xdigits * * Perl hex escapes: !\x{XXX} braced may be 1-8 xdigits * NB: proper Unicode never needs more than 6, as highest * valid codepoint is 0x10FFFF, not maxint 0xFFFFFFFF * * Lame Java escape: \[IDIOT JAVA PREPROCESSOR]uXXXX must be * exactly 4 xdigits; * * I can't write XXXX in this comment where it belongs * because the damned Java Preprocessor can't mind its * own business. Idiots! * * Lame Python escape: !\UXXXXXXXX must be exactly 8 xdigits * * TODO: Perl translation escapes: \Q \U \L \E \[IDIOT JAVA PREPROCESSOR]u \l * These are not so important to cover if you're passing the * result to Pattern.compile(), since it handles them for you * further downstream. Hm, what about \[IDIOT JAVA PREPROCESSOR]u? * */public final staticString unescape_perl_string(String oldstr) { /* * In contrast to fixing Java's broken regex charclasses, * this one need be no bigger, as unescaping shrinks the string * here, where in the other one, it grows it. */ StringBuffer newstr = new StringBuffer(oldstr.length()); boolean saw_backslash = false; for (int i = 0; i < oldstr.length(); i++) { int cp = oldstr.codePointAt(i); if (oldstr.codePointAt(i) > Character.MAX_VALUE) { i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/ } if (!saw_backslash) { if (cp == '\\') { saw_backslash = true; } else { newstr.append(Character.toChars(cp)); } continue; /* switch */ } if (cp == '\\') { saw_backslash = false; newstr.append('\\'); newstr.append('\\'); continue; /* switch */ } switch (cp) { case 'r': newstr.append('\r'); break; /* switch */ case 'n': newstr.append('\n'); break; /* switch */ case 'f': newstr.append('\f'); break; /* switch */ /* PASS a \b THROUGH!! */ case 'b': newstr.append("\\b"); break; /* switch */ case 't': newstr.append('\t'); break; /* switch */ case 'a': newstr.append('\007'); break; /* switch */ case 'e': newstr.append('\033'); break; /* switch */ /* * A "control" character is what you get when you xor its * codepoint with '@'==64. This only makes sense for ASCII, * and may not yield a "control" character after all. * * Strange but true: "\c{" is ";", "\c}" is "=", etc. */ case 'c': { if (++i == oldstr.length()) { die("trailing \\c"); } cp = oldstr.codePointAt(i); /* * don't need to grok surrogates, as next line blows them up */ if (cp > 0x7f) { die("expected ASCII after \\c"); } newstr.append(Character.toChars(cp ^ 64)); break; /* switch */ } case '8': case '9': die("illegal octal digit"); /* NOTREACHED */ /* * may be 0 to 2 octal digits following this one * so back up one for fallthrough to next case; * unread this digit and fall through to next case. */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': --i; /* FALLTHROUGH */ /* * Can have 0, 1, or 2 octal digits following a 0 * this permits larger values than octal 377, up to * octal 777. */ case '0': { if (i+1 == oldstr.length()) { /* found \0 at end of string */ newstr.append(Character.toChars(0)); break; /* switch */ } i++; int digits = 0; int j; for (j = 0; j <= 2; j++) { if (i+j == oldstr.length()) { break; /* for */ } /* safe because will unread surrogate */ int ch = oldstr.charAt(i+j); if (ch < '0' || ch > '7') { break; /* for */ } digits++; } if (digits == 0) { --i; newstr.append('\0'); break; /* switch */ } int value = 0; try { value = Integer.parseInt( oldstr.substring(i, i+digits), 8); } catch (NumberFormatException nfe) { die("invalid octal value for \\0 escape"); } newstr.append(Character.toChars(value)); i += digits-1; break; /* switch */ } /* end case '0' */ case 'x': { if (i+2 > oldstr.length()) { die("string too short for \\x escape"); } i++; boolean saw_brace = false; if (oldstr.charAt(i) == '{') { /* ^^^^^^ ok to ignore surrogates here */ i++; saw_brace = true; } int j; for (j = 0; j < 8; j++) { if (!saw_brace && j == 2) { break; /* for */ } /* * ASCII test also catches surrogates */ int ch = oldstr.charAt(i+j); if (ch > 127) { die("illegal non-ASCII hex digit in \\x escape"); } if (saw_brace && ch == '}') { break; /* for */ } if (! ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) ) { die(String.format( "illegal hex digit #%d '%c' in \\x", ch, ch)); } } if (j == 0) { die("empty braces in \\x{} escape"); } int value = 0; try { value = Integer.parseInt(oldstr.substring(i, i+j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\x escape"); } newstr.append(Character.toChars(value)); if (saw_brace) { j++; } i += j-1; break; /* switch */ } case 'u': { if (i+4 > oldstr.length()) { die("string too short for \\u escape"); } i++; int j; for (j = 0; j < 4; j++) { /* this also handles the surrogate issue */ if (oldstr.charAt(i+j) > 127) { die("illegal non-ASCII hex digit in \\u escape"); } } int value = 0; try { value = Integer.parseInt( oldstr.substring(i, i+j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\u escape"); } newstr.append(Character.toChars(value)); i += j-1; break; /* switch */ } case 'U': { if (i+8 > oldstr.length()) { die("string too short for \\U escape"); } i++; int j; for (j = 0; j < 8; j++) { /* this also handles the surrogate issue */ if (oldstr.charAt(i+j) > 127) { die("illegal non-ASCII hex digit in \\U escape"); } } int value = 0; try { value = Integer.parseInt(oldstr.substring(i, i+j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\U escape"); } newstr.append(Character.toChars(value)); i += j-1; break; /* switch */ } default: newstr.append('\\'); newstr.append(Character.toChars(cp)); /* * say(String.format( * "DEFAULT unrecognized escape %c passed through", * cp)); */ break; /* switch */ } saw_backslash = false; } /* weird to leave one at the end */ if (saw_backslash) { newstr.append('\\'); } return newstr.toString();}/* * Return a string "U+XX.XXX.XXXX" etc, where each XX set is the * xdigits of the logical Unicode code point. No bloody brain-damaged * UTF-16 surrogate crap, just true logical characters. */ public final static String uniplus(String s) { if (s.length() == 0) { return ""; } /* This is just the minimum; sb will grow as needed. */ StringBuffer sb = new StringBuffer(2 + 3 * s.length()); sb.append("U+"); for (int i = 0; i < s.length(); i++) { sb.append(String.format("%X", s.codePointAt(i))); if (s.codePointAt(i) > Character.MAX_VALUE) { i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/ } if (i+1 < s.length()) { sb.append("."); } } return sb.toString(); }private static finalvoid die(String foa) { throw new IllegalArgumentException(foa);}private static finalvoid say(String what) { System.out.println(what);} If it helps others, you’re welcome to it — no strings attached. If you improve it, I’d love for you to mail me your enhancements, but you certainly don’t have to.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3537706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108915/']}
jdg_374590
stackexchange
llm_judgeable_groundtruth_similarity
16120
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are treaties between some countries that obligate the signatories to have not more nuclear weapons than specified in the treaty. How does the US know that Russia doesn't have more weapons than specified and vice versa? What prevents any of the parties from silently producing more weapons than they are allowed to? If a country puts tanks into a certain territory, you can see it with satellites. Bombers and ships are also big enough to be seen by the satellites. But if they manufacture more nuclear bombs than allowed and store them in a basement, how will the other party ever notice that they cheated? Nuclear warheads are smaller than tanks or warships, sometimes as small as a backpack . Now provide the response and nothing else.
The New START Treaty signed by the United States and the Russian Federation in 2010 limited each side to 1,550 deployed strategic warheads. Verification measures for New START are based on the 1991 START I Treaty and were modified for the purposes of the new Treaty. These measures include national technical means (e.g. satellites), on-site inspections and exhibitions, data exchanges and notifications related to strategic offensive arms and facilities covered by the Treaty, and provisions to facilitate the use of national technical means for treaty monitoring. To increase transparency and confidence, the Treaty also provides for the annual exchange of telemetry data on a parity basis, for up to five ICBM and SLBM launches per year. Source: Nuclear Threat Initiative The treaty provides for 18 on-site inspections per year. Exclude a variety of nuances, both sides agree to let the other side remotely monitor or directly review their weapons manufacturing, testing, storage, and deployment capabilities to the extent required for verification. For example, building a "backpack" nuclear weapon still requires an industrial infrastructure and leaves a logistics trail; plus anyone wanting to rely on such a device would probably want to test it and there are systems in place to identify the seismic signatures of nuclear detonations.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/16120', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/-1/']}
jdg_374591
stackexchange
llm_judgeable_groundtruth_similarity
3235064
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that $ 2 \arctan({\csc (\arctan x) -\tan (\text{arccot }x)}) = \arctan x $ x is not equal to zero. So, to solve this I tried I made two condition $ x \gt 0 $ and $ x \lt 0 $ If $ x \gt 0 $ $= 2 \arctan({\csc(\arctan x) - \tan(\text{arccot } x)}) $ $ = 2 \arctan\left(\dfrac{\sqrt{1+x^2}}{x} - \dfrac{1}{x}\right) $ putting $ x = \tan\theta $ $ = 2 \arctan x $ if $ x \lt 0 $ putting $ x = -|x |$ $= 2 \arctan(\csc(\arctan (- x)) - \tan (\text{arccot }( - x)) $ $ = 2 \arctan\left( - {\dfrac{\sqrt{1+x^2}}{x} + \dfrac{1}{x} }\right) $ putting $ x = \tan \theta $ $ = 2 \arctan\left( {\dfrac{1-\sqrt{1+\tan ^2\theta }}{\tan \theta} }\right) $ $ =- 2 \arctan\left( { \dfrac{1-\cos \theta }{\tan \theta \cos \theta } }\right) $ $ =- 2 \arctan x $ What is wrong with it? Now provide the response and nothing else.
Formally $X_i$ are real valued (measurable) functions i.e $X_i\colon \Omega\to \mathbb{R}$ for $i=1,2$ where $\Omega$ is the sample space. So $$Y_i=e^{X_i}$$ for $i=1,2$ as an equality of functions means that $$Y_i(\omega)=e^{X_i(\omega)}$$ for all $\omega\in \Omega$ . Hence since $X_i(\omega)$ is a real number it follows using the first part of your question that $$Y_1(\omega)Y_2(\omega)=e^{X_1(\omega)}e^{X_2(\omega)}=e^{X_1(\omega)+X_2(\omega)}$$ for all $\omega$ whence as functions $$Y_1Y_2=e^{X_1+X_2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3235064', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/655093/']}
jdg_374592
stackexchange
llm_judgeable_groundtruth_similarity
653
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: Paul has some very strong words against the Galatians implying that they are returning to their former state: Formerly, when you did not know God, you were enslaved to those that by nature are not gods. But now that you have come to know God, or rather to be known by God, how can you turn back again to the weak and worthless elementary principles of the world, whose slaves you want to be once more? You observe days and months and seasons and years! I am afraid I may have labored over you in vain.—Galatians 4:8-11 ( ESV ) It seems the evidence he cites is that they are "[observing] days and months and seasons and years!" I interpret that to mean certain holidays (whether Pagan or Jewish, I don't know). The NET Bible seems to agree with that interpretation of Galatians 4:9 : You are observing religious 1 days and months and seasons and years. The note reads: 1 tn The adjective “religious” has been supplied in the translation to make clear that the problem concerns observing certain days, etc. in a religious sense (cf. NIV, NRSV “special days”). In light of the polemic in this letter against the Judaizers (those who tried to force observance of the Mosaic law on Gentile converts to Christianity) this may well be a reference to the observance of Jewish Sabbaths, feasts, and other religious days. If this is a good understanding of what Paul meant by the phrase, does that mean that he was suspicious of all holiday celebrations (such as the upcoming Thanksgiving (US) and Advent seasons)? Or was this a particular sign of trouble for these particular churches? Now provide the response and nothing else.
"Is it a good interpretation of the phrase?" In substance, yes--context shows it is the Jewish holidays being referred to. Martin Luther, in his Commentary on Galatians , agrees, commenting on "days and months and times and years" with: The Apostle Paul knew what the false apostles were teaching the Galatians: The observance of days, and months, and times, and years. The Jews had been obliged to keep holy the Sabbath Day, the new moons, the feast of the passover, the feast of tabernacles, and other feasts. The false apostles constrained the Galatians to observe these Jewish feasts under threat of damnation. Paul hastens to tell the Galatians that they were exchanging their Christian liberty for the weak and beggarly elements of the world. But in spirit, no--it is not so much the days themselves but that they show the Galatians' faith being weakened. The book of Galatians (seen as a whole) is a tirade against this church that had begun taking on Jewish custom in the belief that the Mosaic Law needed to be followed for salvation. He speaks of encountering the behaviour previously when he was in Antioch ( Galatians 2:14-16 ): (NIV quoted) When I saw that they were not acting in line with the truth of the gospel, I said to Cephas in front of them all, “You are a Jew, yet you live like a Gentile and not like a Jew. How is it, then, that you force Gentiles to follow Jewish customs? We who are Jews by birth and not sinful Gentiles know that a person is not justified by the works of the law, but by faith in Jesus Christ. So we, too, have put our faith in Christ Jesus that we may be justified by faith in Christ and not by the works of the law, because by the works of the law no one will be justified ." Paul attempts in this book to separate the idea of salvation from the idea of following the law. The promise of salvation, given to Abraham, is separate from the Law, which was much later given to Moses, and for a different reason (cf. Galatians 3:15-19 ). Since Christ has come, the purpose of the Law is fulfilled, and we can rely instead on Christ alone ( Galatians 3:23-25 ): Before the coming of this faith, we were held in custody under the law, locked up until the faith that was to come would be revealed. So the law was our guardian until Christ came that we might be justified by faith. Now that this faith has come, we are no longer under a guardian. The idea is that for those who have accepted Christ, no additional custom or law is necessary: you have already been saved by Christ, so what is putting yourself under additional restraint going to do for you? So when we ask: "Does it mean he was suspicious of all holiday celebrations, or was this a particular sign of trouble for these particular churches?" we can only say that it is the latter. Because their faith in Christ's ability to save had weakened, they took to shoring it up with observances of Jewish Law--and we see from other parts of the book (e.g. Galatians 5:1-12 ) that it was not only holidays, but circumcision as well. It is not likely that we can apply this to our holidays today. The Jewish days, we understand, were religious obligations--but our modern holidays are free celebrations, and do not promise us any justification. That we are under no obligation to keep them, and that they are not supposed to effect our salvation, puts them out of the way of at least this argument of Paul's.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/653', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/68/']}
jdg_374593
stackexchange
llm_judgeable_groundtruth_similarity
893431
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: So I have the Riemann sum. $\sum_{i=1}^{n}(1+\frac{6i}{n})^3(\frac{2}{n})$. From my understanding that turns into $(\frac{2}{n})\sum_{i=1}^{n}(1+\frac{6i}{n})^3$ and what is really perplexing me is that that summation turns into$$\left(\frac{2}{n}\right)\sum_{i=1}^{n}\left(1+\frac{6i}{n}\right)^3\rightarrow \left(\frac{2}{n^4}\right)\sum_{i=1}^{n}(n+6i)^3$$From there on out I can solve the summation, but I'm having trouble understanding how the $n$ was pulled out and the new summation was formed. If someone could explain that bit I would greatly appreciate it, thanks in advance! Now provide the response and nothing else.
If $\mu(X) \le 1$, $\mu(X)^{1/p} \le 1$. If $\mu(X) > 1$, $\mu(X)^{1/p} \le \mu(X)$. For the other direction, suppose $f \notin L^\infty$. Then for every $N$ there is a set $A$ with $\mu(A) > 0$ such that $|f| > N$ on $A$. Then $\int |f|^p \; d\mu \ge N^p \mu(A)$ and $\|f\|_p \ge N \mu(A)^{1/p}$.Take$p$ large enough that $\mu(A)^{1/p} > 1/2$...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/893431', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/159613/']}
jdg_374594
stackexchange
llm_judgeable_groundtruth_similarity
57232397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to implement a simple login/logout functionality. My scenario is this: I have 2 pages ( login page and home page), In the main.dart , I am using SharedPreferences to check if a user has already logged in or not if the user is logged in, I set a boolean value as true on click of a button. The issue I am having is, I have a routeLogin function that I created to choose between Homepage and Landingpage.And I get this error: I/flutter ( 9026): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════I/flutter ( 9026): The following assertion was thrown building MyApp(dirty):I/flutter ( 9026): type 'Future<dynamic>' is not a subtype of type 'bool'I/flutter ( 9026):I/flutter ( 9026): Either the assertion indicates an error in the framework itself, or we should provide substantiallyI/flutter ( 9026): more information in this error message to help you determine and fix the underlying cause.I/flutter ( 9026): In either case, please report this assertion by filing a bug on GitHub:I/flutter ( 9026): https://github.com/flutter/flutter/issues/new?template=BUG.md This is my code : import 'package:credit/src/pages/landing.dart';import 'package:flutter/material.dart';import 'package:credit/src/pages/credit/home.dart';import 'package:shared_preferences/shared_preferences.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { // This widget is the root of your application. bool checkValue; checkLoginValue () async{ SharedPreferences loginCheck = await SharedPreferences.getInstance(); checkValue = loginCheck.getBool("login"); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Test App', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: routeLogin()); //home: LandingPage()); } routeLogin() { print("Check value"); if (checkValue == null){ return LandingPage(); } else{ return HomePage(); } }} Please let me know where did I went wrong, I am new to Flutter. Now provide the response and nothing else.
you can use future builder to obtain this behavior easily. Future<bool> checkLoginValue() async { SharedPreferences loginCheck = await SharedPreferences.getInstance(); return loginCheck.getBool("login");}@overrideWidget build(BuildContext context) { return MaterialApp( title: 'Test App', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: FutureBuilder<bool>( future: checkLoginValue, builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { if (snapshot.data == false) { return LandingPage(); } else { return HomePage(); } }, ), );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57232397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5232341/']}
jdg_374595
stackexchange
llm_judgeable_groundtruth_similarity
339039
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 have this file that simply prints one line. I'm working on manipulating this one line with different sed commands. apple orange.5678 dog cat 009 you I'm wanting to grab 'orange.5678' and include 'you' and ignore everything else. I want it to look like below orange.5678 you I'm not sure where to start and how to exclude everything except for 'orange.5678' and 'you'. Any help would be great! Now provide the response and nothing else.
$ sed -r 's/.* ([^ ]+\.[^ ]+).* ([^ ]+)$/\1 \2/' orangeorange.5678 you Explanation -r use extended regular expressions s/old/new replace old with new .* any number of any characters (some characters) save some characters to reference later in replacement [^ ]+ some characters that are not a space \. literal dot $ end of line \1 backreference to saved pattern so s/.* ([^ ]+\.[^ ]+).* ([^ ]+)$/\1 \2/ means, match anything on the line up to a space that precedes some non-space characters up to a . and then some non space characters after it (saving those characters either side of the . ), then match any characters and save the last set of non-space characters on the line, and replace the whole match with the two saved patterns separated by a space
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/339039', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/211625/']}
jdg_374596
stackexchange
llm_judgeable_groundtruth_similarity
5367369
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As far as I know there is no such thing as named capturing groups in JavaScript. What is the alternative way to get similar functionality? Now provide the response and nothing else.
ECMAScript 2018 introduces named capturing groups into JavaScript regexes. Example: const auth = 'Bearer AUTHORIZATION_TOKEN' const { groups: { token } } = /Bearer (?<token>[^ $]*)/.exec(auth) console.log(token) // "AUTHORIZATION_TOKEN" If you need to support older browsers, you can do everything with normal (numbered) capturing groups that you can do with named capturing groups, you just need to keep track of the numbers - which may be cumbersome if the order of capturing group in your regex changes. There are only two "structural" advantages of named capturing groups I can think of: In some regex flavors (.NET and JGSoft, as far as I know), you can use the same name for different groups in your regex ( see here for an example where this matters ). But most regex flavors do not support this functionality anyway. If you need to refer to numbered capturing groups in a situation where they are surrounded by digits, you can get a problem. Let's say you want to add a zero to a digit and therefore want to replace (\d) with $10 . In JavaScript, this will work (as long as you have fewer than 10 capturing group in your regex), but Perl will think you're looking for backreference number 10 instead of number 1 , followed by a 0 . In Perl, you can use ${1}0 in this case. Other than that, named capturing groups are just "syntactic sugar". It helps to use capturing groups only when you really need them and to use non-capturing groups (?:...) in all other circumstances. The bigger problem (in my opinion) with JavaScript is that it does not support verbose regexes which would make the creation of readable, complex regular expressions a lot easier. Steve Levithan's XRegExp library solves these problems.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5367369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/519267/']}
jdg_374597
stackexchange
llm_judgeable_groundtruth_similarity
43843470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been exploring query optimizations in the recent releases of Spark SQL 2.3.0-SNAPSHOT and noticed different physical plans for semantically-identical queries. Let's assume I've got to count the number of rows in the following dataset: val q = spark.range(1) I could count the number of rows as follows: q.count q.collect.size q.rdd.count q.queryExecution.toRdd.count My initial thought was that it's almost a constant operation (surely due to a local dataset) that would somehow have been optimized by Spark SQL and would give a result immediately, esp. the 1st one where Spark SQL is in full control of the query execution. Having had a look at the physical plans of the queries led me to believe that the most effective query would be the last: q.queryExecution.toRdd.count The reasons being that: It avoids deserializing rows from their InternalRow binary format The query is codegened There's only one job with a single stage The physical plan is as simple as that. Is my reasoning correct? If so, would the answer be different if I read the dataset from an external data source (e.g. files, JDBC, Kafka)? The main question is what are the factors to take into consideration to say whether a query is more efficient than others (per this example)? The other execution plans for completeness. q.count q.collect.size q.rdd.count Now provide the response and nothing else.
I did some testing on val q = spark.range(100000000) : q.count : ~50 ms q.collect.size : I stopped the query after a minute or so... q.rdd.count : ~1100 ms q.queryExecution.toRdd.count : ~600 ms Some explanation: Option 1 is by far the fastest because it uses both partial aggregation and whole stage code generation. The whole stage code generation allows the JVM to get really clever and do some drastic optimizations (see: https://databricks.com/blog/2017/02/16/processing-trillion-rows-per-second-single-machine-can-nested-loop-joins-fast.html ). Option 2. Is just slow and materializes everything on the driver, which is generally a bad idea. Option 3. Is like option 4, but this first converts an internal row to a regular row, and this is quite expensive. Option 4. Is about as fast you will get without whole stage code generation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43843470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305344/']}
jdg_374598
stackexchange
llm_judgeable_groundtruth_similarity
62888
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given {a, b, c, ...} with $n$ elements generate a list with $2^n$ elements. For example, if the list were {a, b, c} , then the output should be {{a, b, c}, {a, b, -c}, {a, -b, c}, ..., {-a, -b, -c}} If possible, I want to use buit-in functions so that the task can be performed without looping. My own solutions using Subsets[{-1,-1,...} are very messy. Now provide the response and nothing else.
Solution f[list_] := list # & /@ Tuples[{1, -1}, Length[list]] Example f[{a, b, c, d}] {{a, b, c, d}, {a, b, c, -d}, {a, b, -c, d}, {a, b, -c, -d}, {a, -b, c, d}, {a, -b, c, -d}, {a, -b, -c, d}, {a, -b, -c, -d}, {-a, b, c, d}, {-a, b, c, -d}, {-a, b, -c, d}, {-a, b, -c, -d}, {-a, -b, c, d}, {-a, -b, c, -d}, {-a, -b, -c, d}, {-a, -b, -c, -d}} Explanation Tuples generates a list of all possible n-tuples of elements from list. Tuples[{-1, 1}, 3] {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}} Then the hieroglyphics part, list # & /@ , multiplies the list to each sublist of the combinations of 1 s and -1 s, using Map ( /@ ) and Function ( # & )
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/62888', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
jdg_374599
stackexchange
llm_judgeable_groundtruth_similarity
14901535
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 Bootstrap typeahead with an ajax function, and want to know what is the correct Json result format, to return an Id and a descripcion.I need the Id to bind the typeahead selected element with a mvc3 model. This is the code: [Html] <input id="myTypeahead" class='ajax-typeahead' type="text" data-link="myUrl" data-provide="typeahead" /> [Javascript] $('#myTypeahead').typeahead({ source: function (query, process) { return $.ajax({ url: $('#myTypeahead').data('link'), type: 'post', data: { query: query }, dataType: 'json', success: function (jsonResult) { return typeof jsonResult == 'undefined' ? false : process(jsonResult); } }); } });This works properly when I return a simple list of strings, for example:{item1, item2, item3}But I want to return a list with Id, for example:{ {Id: 1, value: item1}, {Id: 2, value: item2}, {Id: 3, value: item3}} How to process this result in the ajax "success: function()"? That is very easy with jquery Autocomplete , because I can return a Json Object list. [jquery Autocomplete process data example]... success: function (data) { response($.map(data, function (item) { return { label: item.Id, value: item.Value, id: item.Id, data: item }; })... But that doesn't work with boostrap Typeahead. Can anyone help me? Thanks. Now provide the response and nothing else.
I try for two days and finally I could it working.Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter. Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options. II used Json format, and bound the Id to a hidden html input. The code: $('#myTypeahead').typeahead({ source: function (query, process) { return $.ajax({ url: $('#myTypeahead').data('link'), type: 'post', data: { query: query }, dataType: 'json', success: function (result) { var resultList = result.map(function (item) { var aItem = { id: item.Id, name: item.Name }; return JSON.stringify(aItem); }); return process(resultList); } }); },matcher: function (obj) { var item = JSON.parse(obj); return ~item.name.toLowerCase().indexOf(this.query.toLowerCase()) }, sorter: function (items) { var beginswith = [], caseSensitive = [], caseInsensitive = [], item; while (aItem = items.shift()) { var item = JSON.parse(aItem); if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item)); else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item)); else caseInsensitive.push(JSON.stringify(item)); } return beginswith.concat(caseSensitive, caseInsensitive) }, highlighter: function (obj) { var item = JSON.parse(obj); var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) }, updater: function (obj) { var item = JSON.parse(obj); $('#IdControl').attr('value', item.id); return item.name; }});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14901535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1898594/']}
jdg_374600
stackexchange
llm_judgeable_groundtruth_similarity
23793224
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to be able to take in any array type as a parameter in a method.: public void foo(Array[] array) { System.out.println(array.length)} Is there a way where I could pass a String[] or int[] array, in the same method? Now provide the response and nothing else.
Use generics . public <T>void foo(T[] array) { System.out.println(array.length);} This will not work for array of primitive types, such as int[] , boolean[] , double[] ,... You have to use their class wrappers instead: Integer[] , Boolean[] , Double[] , ... or overload your method for each needed primitive type separately.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23793224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3105335/']}
jdg_374601
stackexchange
llm_judgeable_groundtruth_similarity
324253
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 would like to know whether there are examples where finite group theory can be directly applied to solve real world problems outside of mathematics. (Sufficiently applied mathematics such as cryptography, coding theory, or statistics still count.) Let me clarify: I am not interested in applications of elementary group theory which happen to involve finite groups (e.g. cyclic/dihedral/easy groups as molecular symmetries). I am interested in applications of topics specifically coming from finite group theory as a discipline, like one might see in Isaacs , Huppert , or Robinson . "The Schur multiplier has order $2640,$ so we should point the laser that way." "Is this computer system secure?" "No - Frobenius kernels are nilpotent." I'm aware of this MO post , but many of the applications listed there are inside mathematics or fall in the "applications of easy groups" category. It is entirely possible that what I'm looking for doesn't exist, and that finite group theory is still an untouchable, pure subject, like number theory in the days of G. H. Hardy. But perhaps not. Does anyone know of any applications of the higher level stuff? Now provide the response and nothing else.
I think I see what Alexander means. There is no shortage of group theoretic (or number theoretic) thinking in telecommunications applications, but even though the apps are hi-tech, the group theory in use does not quite have the same sheen . Let me list a few examples: The theory of cyclic (error-correcting) codes is really all about the combinatoric properties of the summands of the left regular representation of a cyclic group over the field $\mathbb{F}_2$ (or some other finite field). Harmonic analysis of the cyclic group (or of an elementary abelian 2-group) is all over the place here. Many a coding theoretical proof or performance estimation calculation simply could not be carried out without a symmetry argument: "The points of the signal constellation form an orbit of a finite group of unitary matrices meaning that the constellation `looks similar' around any one of its points. Therefore we can w.l.o.g. assume that...", "The automorphism group of this code is doubly transitive, therefore we can w.l.o.g. assume that $0$ and $1$ are contained in the support of this codeword, and reduce the number of variables from six to four." Single shot properties of specific groups occasionally come to the fore: "This 2-group of units of this Clifford algebra only have such and such representations. This allows us to prove the non-existence of certain types of desirable multiantenna signal constellations" or "The structure of Coxeter groups allows us to solve the problem of finding optimal spherical codes with that group as a group of symmetries as well as design a very efficient algorithm locating the signal point closest to the received vector." (the last one jointly due to yours truly). Edit: As another example belonging to this set I just recalled a paper, where people working at Bell Labs proposed using finite groups with fixed-point-free representations to do differential modulation in multiantenna setting. Such groups were classified by Zassenhaus (he was studying nearfields). I don't think that the idea took off. Also most of those groups are metacyclic with a few non-solvable groups completing the list. So it doesn't really change my impression very much. Suitable Molien series are use in classifying the possible self-dual codes. I will add more items to the list, if/when I think of them. My point is that group theoretic thinking is ubiquitous in coding theory/telcomm, but in most cases we don't really need what could be called deep group theoretic results. There are rare tailor-made exceptions like the connections between Mathieu-24 and the extended binary Golay code, but I'm not sure that that qualifies either, because that code, while grand, is too short for practical applications. One of the reasons for this is that the really interesting groups are few and far between, but the engineers want a scalable system with a lot of flexibility in the parameters. I once described the above mentioned use of Coxeter groups to a group of engineers. I was very excited myself about my speed-up tweaks to the length reduction algorithm (generalizing the Shell sorting algorithm), and it showed. So after my presentation one of them asked: "This looks really good, but 8 is kinda low dimensional. Does it scale?"
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/324253', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12952/']}
jdg_374602
stackexchange
llm_judgeable_groundtruth_similarity
4214773
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 make a script that gets from the user the following: 1) Process name (on linux). 2) The log file name that this process write to it. It needs to kill the process and verify that the process is down.Change the log file name to a new file name with the time and date.And then run the process again, verify that it's up in order it will continue to write to the log file. Thanks in advance for the help. Now provide the response and nothing else.
You can retrieve the process id (PID) given it name using pgrep command like this: import subprocessimport signalimport osfrom datetime import datetime as dtprocess_name = sys.argv[1]log_file_name = sys.argv[2]proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE) # Kill process.for pid in proc.stdout: os.kill(int(pid), signal.SIGTERM) # Check if the process that we killed is alive. try: os.kill(int(pid), 0) raise Exception("""wasn't able to kill the process HINT:use signal.SIGKILL or signal.SIGABORT""") except OSError as ex: continue# Save old logging file and create a new one.os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))# Empty the logging file.with open(log_file_name, "w") as f: pass# Run the process again.os.sytsem("<command to run the process>") # you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again. Hope this can help
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4214773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389892/']}
jdg_374603
stackexchange
llm_judgeable_groundtruth_similarity
89999
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: There is an example on how to run a GLM for proportion data in Stata here The IV is the proportion of students receiving free or reduced priced meals at school. The stata model looks like this.: glm meals yr_rnd parented api99, link(logit) family(binomial) robust nolog I'm interested in learning how to replicate this results in R (ideally using the same robust approach). Lets imagine that I have data about the number of students receiving free meals (Successes) and the rest of the students (Failures). I'm guessing the model in R could look something like this: fitglm <- glm(cbind(Successes,Failures) ~ yr_rnd + parented + api99, family=binomial) Also, it was pointed out to me elsewhere (Penguin_Knight) that the error message "meals has non-integer values" could be bad. I'm clueless regarding this error... Now provide the response and nothing else.
Using the R package sandwich and lmtest , you can replicate the results like that (I assume that you've already downloaded the dataset or access it over the internet): #-----------------------------------------------------------------------------# Load the required packages#-----------------------------------------------------------------------------require(foreign)require(sandwich)#-----------------------------------------------------------------------------# Load the data#-----------------------------------------------------------------------------dat <- read.dta("MyPath/proportion.dta")#-----------------------------------------------------------------------------# Inspect dataset#-----------------------------------------------------------------------------str(dat)#-----------------------------------------------------------------------------# Fit the glm#-----------------------------------------------------------------------------fitglm <- glm(meals ~ yr_rnd + parented + api99, family = binomial(logit), data = dat)#-----------------------------------------------------------------------------# Output of the model#-----------------------------------------------------------------------------summary(fitglm)#-----------------------------------------------------------------------------# Calculate robust standard errors by hand#-----------------------------------------------------------------------------cov.m1 <- vcovHC(fitglm, type = "HC1")std.err <- sqrt(diag(cov.m1))q.val <- qnorm(0.975)r.est <- cbind( Estimate = coef(fitglm) , "Robust SE" = std.err , z = (coef(fitglm)/std.err) , "Pr(>|z|) "= 2 * pnorm(abs(coef(fitglm)/std.err), lower.tail = FALSE) , LL = coef(fitglm) - q.val * std.err , UL = coef(fitglm) + q.val * std.err)r.est The model output using robust standard errors is: Estimate Robust SE z Pr(>|z|) LL UL(Intercept) 6.801682703 0.0724029936 93.942009 0.000000e+00 6.659775443 6.943589963yr_rndYes 0.048252657 0.0321827112 1.499335 1.337868e-01 -0.014824298 0.111329612parented -0.766259824 0.0390852844 -19.604816 1.406590e-85 -0.842865573 -0.689654074api99 -0.007304603 0.0002156354 -33.874790 1.566480e-251 -0.007727241 -0.006881966 A much more convenient way is using the coeftest and coefci functions from the lmtest package (output not shown but is identical to output above): coeftest(fitglm, vcov. = vcovHC(fitglm, type = "HC1"))coefci(fitglm, vcov. = vcovHC(fitglm, type = "HC1")) The estimates and standard errors are fairly similar to those calculated using Stata but not exactly. The reason is that Stata uses a finite-sample adjustment (see this post ). The Stata-output is (caution: I enter the variable yr_rnd as categorical variable to replicate R's behaviour, unlike the UCLA page): ------------------------------------------------------------------------------ | Robust meals | Coef. Std. Err. z P>|z| [95% Conf. Interval]-------------+---------------------------------------------------------------- yr_rnd | Yes | .0482527 .0321714 1.50 0.134 -.0148021 .1113074 parented | -.7662598 .0390715 -19.61 0.000 -.8428386 -.6896811 api99 | -.0073046 .0002156 -33.89 0.000 -.0077271 -.0068821 _cons | 6.801683 .0723775 93.98 0.000 6.659825 6.94354------------------------------------------------------------------------------ To exactly replicate Stata's standard errors, we have to use @AchimZeileis' function: sandwich1 <- function(object, ...) sandwich(object) * nobs(object) / (nobs(object) - 1)coeftest(fitglm, vcov. = sandwich1) Estimate Std. Error z value Pr(>|z|) (Intercept) 6.80168270 0.07237747 93.9751 <2e-16 ***yr_rndYes 0.04825266 0.03217137 1.4999 0.1336 parented -0.76625982 0.03907151 -19.6117 <2e-16 ***api99 -0.00730460 0.00021556 -33.8867 <2e-16 *** There are several methods available for the function vcovHC . Consult the help file of vcovHC for the details. Note that if you use the option family = quasibinomial(logit) , there will be no error message (see here ).
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/89999', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41784/']}
jdg_374604
stackexchange
llm_judgeable_groundtruth_similarity
98867
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to measure some battery voltage in a range 0V-4.2V with MCP3008(VDD=VREF=3.3V). I used a voltage divider with R1=2.7MOhm and R2=8.2MOhm, but it didn't return correct value, I used resistors too high? How I calculate the resistors value to save the maximum amount of battery charge? Thanks :) Now provide the response and nothing else.
Question Use MCP3008 to measure voltage of range 0V to 4.2V. Use a voltage divider with 2.7MΩ / 8.2MΩ to step down value for Rpi but not working. Resistor values too high? How to calculate the resistor values? Short Answer MCP3008 ADC operation is indeed very complicated. You need to go through the long answer below a couple of times, and skimmed through the references, before you can get a rough idea of what is going on in the following over simplified operation diagram. Long Answer Well, @Ghanima's answer is very good, but a bit too professional. The suggestion of using buffer amplifier is also newbie scary. @Ghanima refers to MCP3008 datasheet Fig 4.1, 4.2. So let us first look at these two figures. As Fig 4.1 illustrates: The analog voltage to be converted (0V to 4.2V) charges the sample capacitor (20pf), in 1.5 clock cycles. The problem now is that if the clock frequency is too high (in order to get high sample rate), the 1.5 cycle time is not long enough to "fully" charge the sample capacitor (20pF), before conversion starts, with the result that the converted result would be lower than it should be. Of course we can lower the clock frequency (longer time to "fully“ charge the sample capacitor), but then the sample rate (which is proportional to clock frequency) is also lowered. Thus we need to make an engineering trade off, on in newbie language, a balance between "sample rate" and "accuracy" balance. The other thing is that the charge time depends on the "source resistance", which is "more or less" the same, or of the same order (MΩ or kΩ) as the OP's voltage divider resistors. It needs newbie scary mathematics (calculus, differential equations!) to calculate/analyse the appropriate range of resistors for different sample rate ranges Of course the lazy engineers won't do the tedious calculations every time. They just use a very rough chart to get the resistor range from the sample rate range. This is Fig 4.2. Sorry for the long winding stuff. Actually what we need to do is just looking at Fig 4.2, select your sample rate, and find the resistor range in no time, well, less than 3 seconds. For example, if you want a sample rate of 200ksps, then use 1kΩ range. For 75ksps, use 10kΩ to 100kΩ range. If you find the above explanation confusing, forget it, and just use Fig 4.2 to get the resistor range 1k, 10k or 100k. Or even forget Fig 4.2, just use 1k to 10k. You won't be too wrong, and MCP3008 won't explode, ... :) References How to get MCP3008 Sampling Rage - Rpi Forum Discussion Appendices Appendix A - MCP3008 ADC sample capacitor charging timing diagram Appendix B - Why ADC results becomes not accurate again, if clock frequency goes "too low"? Once upon a time I was a humble MCP3008 newbie. I dared not use high sample rate by setting SPI/clock too high. I used 100kHz, and even down to 50kHz, 10kHz. But then I surprisingly found that, after reaching a certain frequency value, the lower the frequency goes, the less accurate is the ADC result. I thought hard, read the SAR algorithm, and finally found the reason. I also solved the puzzle of why the ADC SAR circuit can output the MSB of the results so fast (only 2 pulses after collecting sample). I was no longer a humble newbie. I upgraded myself to a MCP3008 ninja, ... :) Understanding SAR ADCs: Their Architecture and Comparison with Other ADCs - Maxim Integrated Appendix C - Over simplified MCP3008 sample time and convert Time
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/98867', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/103969/']}
jdg_374605
stackexchange
llm_judgeable_groundtruth_similarity
32083170
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 trouble writing the query to retrieve the last object of the Comments array embedded inside the Story document. My collection currently looks like this when I do db.stories.find(): {"_id" : ObjectId("55d3a39565698bbc68079e31"),"author" : "Steven Chen","link" : "COCO","title" : "COCO","date" : ISODate("2015-08-18T21:28:53.629Z"),"comments" : [ { "author" : "Steven", "text" : "Major", "_id" : ObjectId("55d3a39565698bbc68079e32"), "date" : ISODate("2015-08-18T21:28:53.632Z") }, { "text" : "Canada", "author" : "Steven", "_id" : ObjectId("55d3a39a65698bbc68079e33"), "date" : ISODate("2015-08-18T21:28:58.001Z") }, { "text" : "Usa", "author" : "Steven", "_id" : ObjectId("55d3a39c65698bbc68079e34"), "date" : ISODate("2015-08-18T21:29:00.877Z") }],"__v" : 0} I want to get retrieve the last comment based on the date given the _id of the Story document. The context of my code is that there is a Story post with a list of comments and I want to retrieve the last comment and send it to my client JS as a JSON using ajax so the view can be updated with the newest/latest comment. In this case, the comment with "text: "Usa" should be the one getting retrieved. Can someone provide the proper way to do this and it would be even better if you can explain why? Thank you! Now provide the response and nothing else.
Your "latest" document will always be at the end of your array unless you modify somehow. Adding items into arrays will always go to the "end" or "append" to the existing items when used with the $push operator or added using array manipulation methods in client code. Only operators like $addToSet or explicitly using modifiers to the $push operation will change this. As such, when at the end of an array, what you typically want to do is use $slice , with a negative index to get items from the "end" of the array: Model.findById("55d3a39565698bbc68079e31") .select({ "comments": { "$slice": -1 }}) .exec(function(err,doc) { }) If you have actually modfied the array as mentioned earlier where the latest date is not the last element in the array then you should be using the $sort modifier on updates. It would generally only be "out of place" if you asked for the $position modifier or you used $addToSet . The $position would be deliberate and you cannot also sort, but you can always sort the array after an $addToSet operation like this, which places the alls the dates in order without changing any other content of the array: Model.findByIdAndUpdate("55d3a39565698bbc68079e31", { "$push": { "comments": { "$each": [], "$sort": { "date": 1 } } } }) With the array modified the same $slice operation applies to queries as the array is now in the order by date. If however your intention is leave the array in your documents out of order, or in the other order you want, but you also want to get the latest date, then you can use .aggregate() to $sort and retrieve the $last array entry: Model.aggregate( [ { "$match": { "_id": ObjectID("55d3a39565698bbc68079e31") } }, { "$unwind": "$comments" }, { "$sort": { "comments.date": 1 } }, { "$group": { "_id": "$_id", "author": { "$first": "$author" }, "link": { "$first": "$link" }, "title": { "$first": "$title" }, "date": { "$first": "$date" }, "comments": { "$last": "$comments" } }} ]) Noting that when using the aggregation framework with mongoose, the _id "autocasting" that happens in other queries does not happen ( this is by design ), so it is necessary to cast to an ObjectId value yourself, if the data is not already available in that form and has come in as a string. Those are your ways of getting the last element ( optionally explicitly sorted ) from an array.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32083170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/991668/']}
jdg_374606
stackexchange
llm_judgeable_groundtruth_similarity
42867407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list of data frames, organized by year. I am using lapply to get the summary for a single variable in each data frame. The output follows the list and gives a summary for each year, one by one. However, I want the output in the form of a single table with years for rows. How do I do this? An example using the iris dataset shows my problem: x <- split(iris$Sepal.Length, iris$Species)lapply(x, summary) And the output is: $setosa Min. 1st Qu. Median Mean 3rd Qu. Max. 4.300 4.800 5.000 5.006 5.200 5.800 Similarly for the other two. I want the output organized as a single table like with: > sapply(x, summary) setosa versicolor virginicaMin. 4.300 4.900 4.9001st Qu. 4.800 5.600 6.225Median 5.000 5.900 6.500Mean 5.006 5.936 6.5883rd Qu. 5.200 6.300 6.900Max. 5.800 7.000 7.900 But with setosa, versicolor, virginica (or years in my case) on the left and Min... Max up top. I can flip the axes around in ggplot, but reading the table as-is is more intuitive with the years on the left. I came across a number of discussions about converting lapply output but the ones I came across were all measuring a single stat like mean or median. Thanks. Now provide the response and nothing else.
Find here a complete solution on how to display an image on hover events. It uses a 'motion_notify_event' to detect when the mouse is over a scatter point (hovering). If this is the case, it displays an image annotation with a corresponding image next to the hovered scatter point. import matplotlib.pyplot as pltfrom matplotlib.offsetbox import OffsetImage, AnnotationBboximport numpy as np; np.random.seed(42)# Generate data x, y for scatter and an array of images.x = np.arange(20)y = np.random.rand(len(x))arr = np.empty((len(x),10,10))for i in range(len(x)): f = np.random.rand(5,5) arr[i, 0:5,0:5] = f arr[i, 5:,0:5] =np.flipud(f) arr[i, 5:,5:] =np.fliplr(np.flipud(f)) arr[i, 0:5:,5:] = np.fliplr(f)# create figure and plot scatterfig = plt.figure()ax = fig.add_subplot(111)line, = ax.plot(x,y, ls="", marker="o")# create the annotations boxim = OffsetImage(arr[0,:,:], zoom=5)xybox=(50., 50.)ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data', boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->"))# add it to the axes and make it invisibleax.add_artist(ab)ab.set_visible(False)def hover(event): # if the mouse is over the scatter points if line.contains(event)[0]: # find out the index within the array from the event ind, = line.contains(event)[1]["ind"] # get the figure size w,h = fig.get_size_inches()*fig.dpi ws = (event.x > w/2.)*-1 + (event.x <= w/2.) hs = (event.y > h/2.)*-1 + (event.y <= h/2.) # if event occurs in the top or right quadrant of the figure, # change the annotation box position relative to mouse. ab.xybox = (xybox[0]*ws, xybox[1]*hs) # make annotation box visible ab.set_visible(True) # place it at the position of the hovered scatter point ab.xy =(x[ind], y[ind]) # set the image corresponding to that point im.set_data(arr[ind,:,:]) else: #if the mouse is not over a scatter point ab.set_visible(False) fig.canvas.draw_idle()# add callback for mouse movesfig.canvas.mpl_connect('motion_notify_event', hover) plt.show()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42867407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5007180/']}
jdg_374607
stackexchange
llm_judgeable_groundtruth_similarity
2105508
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 new to Cython and I'm trying to use Cython to wrap a C/C++ static library. I made a simple example as follow. Test.h: #ifndef TEST_H#define TEST_Hint add(int a, int b);int multipy(int a, int b);#endif Test.cpp #include "test.h"int add(int a, int b){ return a+b;}int multipy(int a, int b){ return a*b;} Then I used g++ to compile and build it. g++ -c test.cpp -o libtest.oar rcs libtest.a libtest.o So now I got a static library called libtest.a . Test.pyx: cdef extern from "test.h": int add(int a,int b) int multipy(int a,int b)print add(2,3) Setup.py: from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extext_modules = [Extension("test", ["test.pyx"], language='c++', include_dirs=[r'.'], library_dirs=[r'.'], libraries=['libtest'] )]setup( name = 'test', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules) The I called: python setup.py build_ext --compiler=mingw32 --inplace The output was: running build_extcythoning test.pyx to test.cppbuilding 'test' extensioncreating buildcreating build\temp.win32-2.6creating build\temp.win32-2.6\ReleaseC:\Program Files\pythonxy\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -I. -IC:\Python26\include -IC:\Python26\PC -c test.cpp -o build\temp.win32-2.6\Release\test.owriting build\temp.win32-2.6\Release\test.defC:\Program Files\pythonxy\mingw\bin\g++.exe -mno-cygwin -mdll -static --entry _DllMain@12 --output-lib build\temp.win32-2.6\Release\libtest.a --def build\temp.win32-2.6\Release\test.def -s build\temp.win32-2.6\Release\test.o -L. -LC:\Python26\libs -LC:\Python26\PCbuild -ltest -lpython26 -lmsvcr90 -o test.pydg++: build\temp.win32-2.6\Release\libtest.a: No such file or directoryerror: command 'g++' failed with exit status 1 I also tried to use libraries=['test'] instead of libraries=['libtest'] . It gave me the same errors. Any clue about this? Now provide the response and nothing else.
If your C++ code is only used by the wrapper, another option is to let the setup compile your .cpp file, like this: from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extext_modules = [Extension("test", ["test.pyx", "test.cpp"], language='c++', )]setup( name = 'test', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules) For linking to a static library you have to use the extra_objects argument in your Extension : from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extext_modules = [Extension("test", ["test.pyx"], language='c++', extra_objects=["libtest.a"], )]setup( name = 'test', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2105508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/150324/']}
jdg_374608
stackexchange
llm_judgeable_groundtruth_similarity
21578544
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 code: #include <algorithm>#include <cctype>#include <string>int main(){ std::string str; str.erase(std::remove_if(str.begin(), str.end(), std::isspace), str.end());} MSVC-11.0 compiles this code without any error, but gcc 4.7.2 gives me the following errors: main.cpp: In function ‘int main()’:main.cpp:8:66: error: no matching function for call to ‘remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)’main.cpp:8:66: note: candidate is:In file included from /usr/include/c++/4.7/algorithm:63:0, from main.cpp:1:/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note: template<class _FIter, class _Predicate> _FIter std::remove_if(_FIter, _FIter, _Predicate)/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note: template argument deduction/substitution failed:main.cpp:8:66: note: couldn't deduce template parameter ‘_Predicate’ I found this question about it, but according to the cppreference , there isn't any version of this function that takes two arguments. I found this question too, but according to the cppreference (yep, again) I see that there's only one std::isspace function overload. Who's right? What am I doing wrong? How can I fix it? Now provide the response and nothing else.
There is another overload of std::isspace , so you need to specify which one to use. An easy way is to use a lambda (or write your own one-line function if you don't have C++11 support): std::remove_if(str.begin(), str.end(), [](char c){ return std::isspace(static_cast<unsigned char>(c)); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21578544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1608835/']}
jdg_374609
stackexchange
llm_judgeable_groundtruth_similarity
865470
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We know that $H_n = \sum_{j=1}^{n}{1 \over j}$. Article in The Sum of Certain Series Related To Harmonic Numbers of Omran Kolba, we have proof of this identity which involves some advanced concepts. I tried to turn the sum into a definite integral and could not. I appreciate any help. $$\sum_{n=1}^{\infty}(-1)^{n-1} \dfrac{H_n}{n} = \sum_{n=1}^{\infty}\dfrac{(-1)^{n-1}}{n}\sum_{i=2}^{n+1}\dfrac{1}{i+1} = \sum_{n=1}^{\infty}\dfrac{(-1)^{n-1}}{n}\sum_{i=2}^{n+1}\int_{0}^{1}x^{i}dx = ?$$ Now provide the response and nothing else.
You may consider the standard identity $$\sum_{n=1}^{\infty}H_n x^{n-1} = -\dfrac{\ln(1-x)}{x(1-x)} \quad -1 < x<1,\,x\neq0.$$ Then integrate from $x=-1$ to $x=0$ to obtain easily$$\sum_{n=1}^{\infty}(-1)^{n-1} \dfrac{H_n}{n} \!= -\! \int_{-1}^{0}\dfrac{\ln(1-x)}{x(1-x)} dx = -\!\int_{-1}^{0}\left(\dfrac{\ln(1-x)}{x}\! + \!\dfrac{\ln(1-x)}{1-x}\right) \! dx=\dfrac{\pi^2}{12} - \dfrac{1}{2}\ln^2 2.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/865470', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12624/']}
jdg_374610
stackexchange
llm_judgeable_groundtruth_similarity
24489384
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 see the values which are in the slice. How can I print them? projects []Project Now provide the response and nothing else.
You can try the %v , %+v or %#v verbs of go fmt : fmt.Printf("%v", projects) If your array (or here slice ) contains struct (like Project ), you will see their details. For more precision, you can use %#v to print the object using Go-syntax, as for a literal: %v the value in a default format. when printing structs, the plus flag (%+v) adds field names%#v a Go-syntax representation of the value For basic types, fmt.Println(projects) is enough. Note: for a slice of pointers, that is []*Project (instead of []Project ), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address). See this play.golang example .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24489384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3771173/']}
jdg_374611
stackexchange
llm_judgeable_groundtruth_similarity
17167754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As I progress on my little math library I'm stumbling upon certain aspects of C# and the .NET Framework that I'm having some trouble understanding. This time it's operator overloading and specifically the term overloading itself. Why is it called overloading ? Do all objects by default have an implementation of all operators? That is, is: public static object operator +(object o1, object o2) predefined somewhere and somehow? If so, why then if I try o1 + o2 I get the compile time error Operator '+' cannot be applied to operands of type 'object' and 'object' ? This would somehow imply that by default objects do not have predefined operators so then how come the term overloading ? I ask this, because in my math library, working with 3D geometry elements, I have the following structs: Vector and Point . Now, internally I want to allow the following construct to create vectors: static Vector operator -(Point p1, Point p2) {...} As this is not mathematically 100% correct but very useful internally to reduce code clutter, I don't want to expose this operator publicly, so my initial intention was to simply do: internal static Vector operator -(Point p1, Point p2) {...} Surprisingly (for me) I got the following compile time error: User-defined operator 'Geometry.operator +(Geometry.Vector, Geometry.Vector)' must be declared static and public ". Now this restriction that all operators must be public does seem to make some sense with the whole overloading aspect of operators but it seems that it is all kind of inconsistent: Objects by default do not have predefined operators: I can't do object + object by default or myTpye + myType without explicitly defining the + operator beforehand. Defining operators is not described as creating an operator, it's described as overloading which somehow is inconsistent (to me) with point 1. You cannot restrict access modifier of an operator , they have to be public , which does not make sense considering point 1. but sort of makes sense considering point 2. Can somebody explain the mess I'm making of all this in simple terms? Now provide the response and nothing else.
Why is it called overloading? It's called "overloading" because it is overloading. We "overload" a thing when we give two possible implementations for that thing and then must decide which to use (which is called overload resolution ). When we overload methods we give two or more implementations of a method with a given name. When we overload operators we give two or more possible implementations for an operator with a given syntax. It's the same thing. Make sure you're not confusing overloading with overriding . Overloading is simply the existence of two methods/operators with the same name/syntax in the same declaration space. Overriding deals with how the content of a virtual method slot is filled in at runtime. Do all objects by default have an implementation of all operators? No. Is public static object operator +(object o1, object o2) predefined somewhere and somehow? No. This would somehow imply that by default objects do not have predefined operators so then how come the term overloading ? I don't understand the question. Of course C# has predefined operators. I don't want to expose this operator publicly Then don't use an operator; make a private, internal or protected method. The design of C# is that an operator is always part of the public surface area of a type. It is very confusing to have operators that have a meaning that depends on what accessibility domain the usage occurs in. C# has been carefully designed to be a "pit of quality" language, where the choices of the language designers lead you away from writing confusing, buggy, hard-to-refactor programs. Requiring that user-defined operators be public and static is one of those subtle design points. (1) Objects by default do not have predefined operators Sure they do; there are hundreds of predefined operators on a variety of objects. For addition, for example, there are the following predefined overloads of operator + : int + intuint + uintlong + longulong + ulongdouble + doublefloat + floatdecimal + decimalenum + underlying (for any enum type)underlying + enumint? + int?uint? + uint?long? + long?ulong? + ulong?double? + double?float? + float?decimal? + decimal?enum? + underlying?underlying? + enum?string + stringobject + stringstring + objectdelegate + delegate (for any delegate type) Consult the C# specification for a list of all the predefined overloads of all the other operators. Note that overload resolution for operators has two phases: first, overload resolution attempts to find a user-defined overload that is the unique best; only if doing so finds no applicable candidates are the predefined overloads considered by overload resolution. (2) Defining operators is not described as creating an operator, it's described as overloading which somehow is inconsistent (to me) with point 1. I don't understand why you find it inconsistent, or, for that matter, what you find inconsistent. The term "overload" is used consistently to describe both operators and methods; in both cases it means to use the same syntax to refer to two or more different things, and that ambiguity is then resolved via "overload resolution". The exact details of the method and operator overload resolution algorithms are different but they are similar in the overall algorithm: first a candidate set is identified, then inapplicable candidates are removed, then a betterness algorithm eliminates applicable candidates that are worse than another, then a bestness algorithm determines the unique best candidate that is left, if any. (3) You cannot restrict access modifier of an operator, they have to be public, which does not make sense considering point 1. but sort of makes sense considering point 2. I don't understand what point (3) has to do with points (1) or (2) at all. The restriction that operators must be part of the public surface area is to prevent the confusing situation of being able to add a Fruit to an Animal when you're inside class Apple but not when you're inside class Giraffe . Operators are declared inside a class or struct and therefore "belong" to said type, they don't float "belonging" to no given type. So what am I overloading exactly when I declare an operator in a class? You're overloading the operator. That the same operator exists between ints does not mean I am overloading anything as that operator belongs to int. To me its the same as saying the Foo.Hello() and Bar.Hello(string hello) are overloads of Hello . They are not as they are declared in two separate types. What is the difference with operators? You've just accurately described the difference. Method overloading and operating overloading differ in many of their details. If you want to take the position that Foo.Hello() and Bar.Hello(string) are "overloads" of Hello , that's not a common position to take but it is logically consistent. I was under the impression that you cannot change the access modifier when overloading. Your impression is mistaken; you cannot change access modifiers when overriding a virtual method . You've confused that with overloading . (And I note that there is one scenario in which you are required to change the access modifier when overriding a virtual method; can you deduce what it is?) I was also under the impression that you can not declare an operator without at least one of the operands being of the type in which you declare the operator. That's almost correct. A user-defined operator must have an operand of type T , where T is the enclosing class or struct type, or T? if T is a struct type. So how can a third class have access to a given operator while another third class can't unless one belongs to an external assembly and the other doesn`t in which case I do not find it confusing at all and even useful? You've mischaracterized my example, which could have been more clear. This is illegal: public class Fruit { protected static Shape operator +(Fruit f, Animal a) { ... } } Because this is bizarre: public class Apple : Fruit{ ... Shape shape = this + giraffe; // Legal!}public class Giraffe : Animal{ ... Shape shape = apple + this; // Illegal!} This is just one example. In general it is a strange thing to do, to make overload resolution of an operator depend on the accessibility domain , so the language designers ensured that this never happens by requiring user-defined operators to be public. I simply find overloading confusing in the context of operators. Many people do, including compiler writers. The user-defined operators portion of the specification is extremely difficult to parse, and the Microsoft implementation is a rich source of compiler bugs, many of which were my fault. I don't see why simply declaring operators in a type has to described differently from how you would describe declaring any other static method. Well, different things are different; operators are different than methods in many ways, including their overload resolution algorithms. I have never particularly liked that C# has overloadable operators. The C# feature is a somewhat better designed version of the same feature in C++, but in both languages the feature in my opinion entails far larger costs than the corresponding user benefits. Thank goodness at least C# does not thoroughly abuse the << operator the way idiomatic C++ does -- though of course it does abuse + and - for delegates.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17167754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/767890/']}
jdg_374612
stackexchange
llm_judgeable_groundtruth_similarity
7937245
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Linux work queues are meant to be kernel level threads with process context. I was trying to use it as an alternative to kthread which has no specific process context. But how do I pass data to work queue? work_struct has a data field which is of type atomic_long_t. I could not pass pointer to this field. How do I do it? Also I could not find a single concrete example of work queue. Can you suggest one? Now provide the response and nothing else.
If you want to pass data to your work queue function, just embed the work_struct structure inside your own data structure and use container_of inside your work function to retrieve it. As for a simple example, the kernel is full of it - just git grep work_struct . You can look at drivers/cpufreq/cpufreq.c ( handle_update function) for a simple example. The article below also embeds an example at the end, but it does not use container_of and instead relies on the fact that the first member of a structure has the same address as its parent: http://www.ibm.com/developerworks/linux/library/l-tasklets/index.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7937245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114708/']}
jdg_374613
stackexchange
llm_judgeable_groundtruth_similarity
712633
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: How much energy can be added to a small volume of space? Perhaps like the focal point of a very high power femtosecond laser for a short time, or are there other examples like the insides of neutron stars that might be the highest possible energy density? Is there any fundamental limit? Now provide the response and nothing else.
There is a limit to how much energy that can be contained in a finite volume, after which the energy density becomes so high that the region collapses into a black hole . We also know that matter and energy are equivalent according to the Einstein equation $$E=mc^2\tag1$$ So if we can determine the greatest amount of matter that can fit into a volume just before it collapses into a black hole, the corresponding energy should also indicate the greatest energy confined in the volume just before it becomes a black hole. The maximum amount of matter, mass $M$ , that can be contained in a given volume before it collapses into a black hole, is given by the Schwarzschild radius $$r_s=\frac{2GM}{c^2}\tag2$$ Using (1) we can then write $$M=\frac{E}{c^2}$$ so that equation (2) becomes $$r_s=\frac{2GE}{c^4}$$ or $$E=\frac{r_sc^4}{2G}$$ Note that this is still energy, and to get to energy density we need to define the volume which is of course $$V=\frac 43 \pi r_s^3$$ so that the energy density is $$\epsilon =\frac{3c^4}{8\pi Gr_s^2}$$ This computation is based on not much more than the equivalence of matter and energy. It represents a bound on the maximum amount of matter, and therefore energy, in a spherical volume of radius $r_s$ before the volume containing the matter collapses into a singularity, which of course has no properly defined volume.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/712633', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/293269/']}
jdg_374614
stackexchange
llm_judgeable_groundtruth_similarity
790379
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 you please give me a hint for the following exercise:$$(\cos x+i\sin x)(\cos 2x+i\sin 2x)(\cos 5x+i\sin 5x)={i+1\over \sqrt 2 }$$ Thank you! Now provide the response and nothing else.
Note that the top is given by $e^{ix}\cdot e^{2ix}\cdot e^{5ix} = e^{8ix} = \frac{1+i}{\sqrt{2}}$ and so $\cos(8x) = \sin(8x) = 1/\sqrt{2}$ implies $8x = \pi/4$ implies $x = \pi/32 + \pi\cdot n/4$ where $n \in \mathbb{Z}$. This was edited to consider less trivial solutions - if your goal is a complete solution set.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/790379', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123499/']}
jdg_374615
stackexchange
llm_judgeable_groundtruth_similarity
3032246
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 open from c# an application (standalone flashplayer) and set it position to (0,0) on the screen. How can I do this? So far I've managed to open flashplayer: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;namespace swflauncher{ class Program { static void Main(string[] args) { Process flash = new Process(); flash.StartInfo.WindowStyle = ProcessWindowStyle.Normal; flash.StartInfo.FileName = "D:\\development\\flex4\\runtimes\\player\\10\\win\\FlashPlayer.exe"; flash.Start(); } }} Now provide the response and nothing else.
thanks guys, it's working now! :) using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Runtime.InteropServices;using System.Threading;namespace swflauncher{ class Program { static void Main(string[] args) { Process flash = new Process(); flash.StartInfo.WindowStyle = ProcessWindowStyle.Normal; flash.StartInfo.FileName = "D:\\development\\flex4\\runtimes\\player\\10\\win\\FlashPlayer.exe"; flash.Start(); Thread.Sleep(100); IntPtr id = flash.MainWindowHandle; Console.Write(id); Program.MoveWindow(flash.MainWindowHandle, 0, 0, 500, 500, true); } [DllImport("user32.dll", SetLastError = true)] internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3032246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365670/']}
jdg_374616
stackexchange
llm_judgeable_groundtruth_similarity
25534335
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 looked at various answers on SO that answer similar questions, but none have really answered what I'm looking for. Examples here: jQuery prototype and constructor function chaining How does basic object/function chaining work in javascript? I'd like to be able to chain methods from a function, but also use that function as a namespace. You can use the jquery object as a function like so: $('selector'); but you can also reach methods straight from the $ variable, like so: $.ajax( How is this achieved? I've tried looking into the jquery source but it's near impossible to follow. Now provide the response and nothing else.
From Xcode release notes: If you set a Swift subclass of NSValueTransformer as a binding’s value transformer, the XIB or storyboard will contain an invalid reference to the class, and the binding will not work properly at runtime. You can either enter a mangled class name into the Value Transformer field or add the @objc(…) attribute to the NSValueTransformer subclass to solve this problem. (17495784) From Swift guide: To make your Swift class accessible and usable back in Objective-C, make it a descendant of an Objective-C class or mark it with the @objc attribute. To specify a particular name for the class to use in Objective-C, mark it with @objc(<#name#>), where <#name#> is the name that your Objective-C code will use to reference the Swift class. For more information on @objc, see Swift Type Compatibility. Solution: Declare your class as @objc(myTransformer) class myTransformer: NSValueTransformer and then you can use "myTransformer" as name...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25534335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_374617
stackexchange
llm_judgeable_groundtruth_similarity
10791968
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 change the "term" field that is set to that by default with the jquery ui autocomplete feature. Is it possibly to easily change it to "q" (query) without going and changing it in the "core" file? JavaScript: <script> $(function() { $( "#spotify_song_search" ).autocomplete({ source: "http://ws.spotify.com/search/1/track.json", data: { q: request.term }, dataType: "getjson", minLength: 3, select: function( event, ui ) { alert('select'); } }); });</script> Now provide the response and nothing else.
Yes, it's possible by making your own AJAX request. Assume you have the following setup: $("#myfield").autocomplete({ source: '/my_url/myservice.xyz'}); Autocomplete by default (as you noticed) sends requests that look like: myservice.xyz?term=abc" You can supply a function reference to the source option of autocomplete. Inside that function you can make your own AJAX request, which would look like this: $("#myfield").autocomplete({ source: function (request, response) { // request.term is the term searched for. // response is the callback function you must call to update the autocomplete's // suggestion list. $.ajax({ url: "/my_url/myservice.xyz", data: { q: request.term }, dataType: "json", success: response, error: function () { response([]); } }); });}); This should generate a request looking more like: myservice.xyz?q=abc
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10791968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648865/']}
jdg_374618
stackexchange
llm_judgeable_groundtruth_similarity
295346
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: Non-renormalizable theories, when regarded as an effective field theory below a cut-off $\Lambda$, is perfectly meaningful field theory. This is because non-renormalizable operators can be induced in the effective Lagrangian while integrating out high energy degrees of freedom. But as far as modern interpretation is concerned, renormalizable theories are also effective field theories. Then why the renormalizability of field theories is still an important demand? For example, QED, QCD or the standard model is renormalizable. What would be wrong if they were not? Now provide the response and nothing else.
In the modern effective field theory point of view, there's nothing wrong with non-renormalizable theories. In fact, one may prefer a non-renormalizable theory inasmuch they tell you the point at which they fail(the energy cut-off). To be concrete, consider an effective lagrangian expanded in inverse powers of the energy cut-off $\Lambda$: \begin{equation} \mathcal{L}_\mathrm{eff}(\Lambda)=\mathcal{L}_\mathrm{renorm}+ \sum_\mathcal{\alpha}\frac{g_\alpha}{\Lambda^{ \operatorname{dim}\mathcal{O}_\alpha-4}}\mathcal{O}_\alpha\end{equation} where $\mathcal{L}_\mathrm{renorm}$ doesn't depend on $\Lambda$, $\mathcal{O}_\alpha$ are non-renormalizable operators (dim. > 4) and $g_\alpha$ arethe corresponding coupling constants. So at very low energies $E\ll \Lambda$ the contributions from the non-renormalizable operatorswill be supressed by powers of $E/\Lambda$. That's why the Standard Model is renormalizable, we're just unable to see the non-renormalizable terms because we're looking at too low energies. Notice also that as we increase the energy, the first operators to become important will be the ones with the lower dimension. In general, contributions from non-renormalizable operators will become importantin order given by their dimension. So you can see that, although there are infinite possible non-renormalizable coupling constants, you can make the approximation of cutting the expansion of the effective lagrangian at some power of the cut-off and get a finite number of parameters.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/295346', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/36793/']}
jdg_374619
stackexchange
llm_judgeable_groundtruth_similarity
16551354
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 Python it is possible to split a string and assign it to variables: ip, port = '127.0.0.1:5432'.split(':') but in Go it does not seem to work: ip, port := strings.Split("127.0.0.1:5432", ":")// assignment count mismatch: 2 = 1 Question: How to split a string and assign values in one step? Now provide the response and nothing else.
Two steps, for example, package mainimport ( "fmt" "strings")func main() { s := strings.Split("127.0.0.1:5432", ":") ip, port := s[0], s[1] fmt.Println(ip, port)} Output: 127.0.0.1 5432 One step, for example, package mainimport ( "fmt" "net")func main() { host, port, err := net.SplitHostPort("127.0.0.1:5432") fmt.Println(host, port, err)} Output: 127.0.0.1 5432 <nil>
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16551354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2383156/']}
jdg_374620
stackexchange
llm_judgeable_groundtruth_similarity
13144280
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 Python snippet that I would like to reproduce using C++: from itertools import count, imapsource = count(1)pipe1 = imap(lambda x: 2 * x, source)pipe2 = imap(lambda x: x + 1, pipe1)sink = imap(lambda x: 3 * x, pipe2)for i in sink: print i I've heard of Boost Phoenix , but I couldn't find an example of a lazy transform behaving in the same way as Python's imap . Edit: to clarify my question, the idea is not only to apply functions in sequence using a for , but rather to be able to use algorithms like std::transform on infinite generators. The way the functions are composed (in a more functional language like dialect) is also important, as the next step is function composition. Update: thanks bradgonesurfing, David Brown, and Xeo for the amazing answers! I chose Xeo's because it's the most concise and it gets me right where I wanted to be, but David's was very important into getting the concepts through. Also, bradgonesurfing's tipped Boost::Range :). Now provide the response and nothing else.
Employing Boost.Range : int main(){ auto map = boost::adaptors::transformed; // shorten the name auto sink = generate(1) | map([](int x){ return 2*x; }) | map([](int x){ return x+1; }) | map([](int x){ return 3*x; }); for(auto i : sink) std::cout << i << "\n";} Live example including the generate function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13144280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434305/']}
jdg_374621
stackexchange
llm_judgeable_groundtruth_similarity
17310831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: casionwoo@casionwoo-desktop:~/mystore$ bundle installUpdating https://github.com/spree/spree_gateway.gitUpdating https://github.com/spree/spree_auth_devise.gitFetching gem metadata from https://rubygems.org/.......Fetching gem metadata from https://rubygems.org/..Resolving dependencies...Bundler could not find compatible versions for gem "rails": In Gemfile: spree (= 2.0.3) ruby depends on rails (~> 3.2.8) ruby rails (4.0.0) i am installing spree for setting i don't know why this error occured Now provide the response and nothing else.
Let's first separate interfaces from classes. Interfaces are great for mocking (thus allowing for testing your app without the need for the sluggish GWTTestCase ): IsWidget : when all you need is a handle on a widget, without depending on the Widget class. This is typically used with MVP as a way to represent the view . AcceptsOneWidget : when you need a placeholder for a single widget (in the form of an IsWidget ). This is typically used with Activities, to insert the view ( IsWidget ) into the given slot ( AcceptsOneWidget ). The classes you list all extend Widget , so they rely on JSNI and (most of the time) need to run in a GWT environment (for unit tests, that means a GWTTestCase ): Widget : the base of all widgets. Implements IsWidget returning itself from asWidget() . Composite : a base class when you need to create a widget built from other widgets while hiding their implementation. While you could extend an existing widget, it's generally better to hide it inside a Composite so you only expose the API you need/want to expose. Composite is about "composition rather than inheritance" and encapsulation . Examples of composites in standard widgets include TabPanel (built from a TabBar and DeckPanel ), DateBox (built from a TextBox and DatePicker in a PopupPanel ), ValueListBox that wraps a ListBox or ValuePicker that wraps a CellList . In many cases, given that panels accept IsWidget children, you could simply implement IsWidget rather extend Composite , but it's sometimes useful to have a true Widget . SimplePanel a panel that implements AcceptsOneWidget , useful as a slot when using activities (but you could also easily implement AcceptsOneWidget to insert into any kind of panel) That being said, Google recently open-sourced GWT-Mockito that plugs Mockito into GWT.create() and uses classloader magic to rewrite JSNI methods and remove final modifiers so you can directly use widgets in tests without the need for GWTTestCase or MVP. So, all in all, it depends how you approach your code, how you architecture your app. If you use MVP, stick to depending on interfaces only ( IsWidget , AcceptsOneWidget ) in your presenter so you can easily mock your view in your tests. Otherwise, or if you want a "simplified MVP" where the view is a UiBinder template, try GWT-Mockito for your tests and directly use widgets. Of course, you can mix both approaches in the same application. And in any case, build your own widgets as Widget s for low-level things (rarely needed), and Composite s or IsWidget s for everything else, rather than extending existing widgets.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17310831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2051246/']}
jdg_374622
stackexchange
llm_judgeable_groundtruth_similarity
3528182
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 attempting to make an x64 build of a project with Visual Studio 2005. It's currently failing with linker error C1905, 'Front end and back end not compatible (must target same processor).' From what I gather, this is essentially saying that my x64 build is attempting to link with x86 modules. Unfortunately, this project links with a lot of different libraries. I'm not sure which is the one causing the problem. Is there any way to get more information out of Visual Studio? Now provide the response and nothing else.
First, check Configuration Manager (Build > Configuration Manager...) to ensure that you're building all of your projects for the same platform. If that doesn't help, then from the Visual Studio Command Prompt (available from the Start menu), you can use dumpbin to determine the architecture of your .lib and .obj files by doing the following: C:\Foo> dumpbin /headers Foo.lib | moreMicrosoft (R) COFF/PE Dumper Version 10.00.30319.01Copyright (C) Microsoft Corporation. All rights reserved.Dump of file Foo.libFile Type: LIBRARYFILE HEADER VALUES 14C machine (x86) 3 number of sections 4C6CB9B6 time date stamp Wed Aug 18 21:57:26 2010 113 file pointer to symbol table 8 number of symbols 0 size of optional header 100 characteristics 32 bit word machine The first line under the header values tells you which architecture the .lib/.obj was compiled for (in this case, x86). If you have a lot of linked intermediates, you could automate this a bit by just looking for x86 (or x64) files: for /R %f in (*.obj *.lib) do @echo %f && dumpbin /headers %f | findstr /c:"machine (x86)"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3528182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214796/']}
jdg_374623
stackexchange
llm_judgeable_groundtruth_similarity
32000562
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't really reproduce the issue, but no highlighting or intellisense is working in .js files, it works just fine in .json files however. The default editor for .js files is JSON Editor. I tried safe-mode, disabling all extensions, resetting all settings, and I even reinstalled the IDE (repair), but the issue still persists. I will add, that when I launch the IDE and a JS file is open on scope, I get the following error message (highlighting and intellisense don't work anyway): The 'JavaScriptWebExtensionPackage' package did not load correctly. The problem may have been caused by a configuration change or by the installation of another extension. You can get more information examining the file 'C:\Users\Shimmy\AppData\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml'. Restarting Visual Studio could help resolve the issue. Continue to show this error message? Here you can view the ActivityLog.xml file, I pasted in some of the recent lines I think might be relevant: <entry> <record>188</record> <time>2015/08/14 13:00:57.332</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [JavaScriptWebExtensionsPackage]</description> <guid>{30DB8F9B-EC9F-44D6-B377-83C7C27A1A8B}</guid></entry><entry> <record>189</record> <time>2015/08/14 13:00:57.394</time> <type>Error</type> <source>VisualStudio</source> <description>SetSite failed for package [JavaScriptWebExtensionsPackage]</description> <guid>{30DB8F9B-EC9F-44D6-B377-83C7C27A1A8B}</guid> <hr>80131500</hr> <errorinfo>Expected 1 export(s) with contract name "Microsoft.VisualStudio.JavaScript.Web.Extensions.ReferenceAutoSync.IReferencesFilePathProvider" but found 0 after applying applicable constraints.</errorinfo></entry><entry> <record>190</record> <time>2015/08/14 13:00:57.394</time> <type>Error</type> <source>VisualStudio</source> <description>End package load [JavaScriptWebExtensionsPackage]</description> <guid>{30DB8F9B-EC9F-44D6-B377-83C7C27A1A8B}</guid> <hr>80131500</hr> <errorinfo>Expected 1 export(s) with contract name "Microsoft.VisualStudio.JavaScript.Web.Extensions.ReferenceAutoSync.IReferencesFilePathProvider" but found 0 after applying applicable constraints.</errorinfo></entry> Now provide the response and nothing else.
I found answer here: Visual Studio 2015 RTM - Lost JavaScript support after update TypeSript Tools These are the steps to fix it: If the “Universal Windows App Development Tools” are still installed: Go to Programs and Features, select Visual Studio 2015, click Change. In Visual Studio setup, click Modify. Deselect the feature “Universal Windows App Development Tools” Select “Universal Windows App Development Tools” again, and click Update. If you have already uninstalled the “Universal Windows App Development Tools”: Reinstall “Universal Windows App Development Tools” Or, take the following steps to reinstall the JavaScript project system and language service: Download the installer for your edition of Visual Studio, e.g., vs_community.exe. Open a CMD window, and run the following command: vs_community.exe /modify /installselectableitems JavaScript_Hidden /passive I've followed the first steps and got back Javascript support. Hope this helps -UPDATED- After I did the above steps, almost everything was working, except that I got an error message every time I opened a .js file, the following did the trick: My guess is that only reinstalling the SDK didn't update the MEF cache. You can do this manually by following these steps: Open a command prompt as administrator CD into C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE Run devenv /updateconfiguration Run devenv /clearcache That got rid of the last error, and everything is working fine. Source: https://github.com/Microsoft/TypeScript/issues/4238
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32000562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75500/']}
jdg_374624
stackexchange
llm_judgeable_groundtruth_similarity
5556977
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 determine if a MKMapView was dragged around? I want to get the center location every time a user drags the map using CLLocationCoordinate2D centre = [locationMap centerCoordinate]; but I'd need a delegate method or something that fires as soon as the user navigates around with the map. Thanks in advance Now provide the response and nothing else.
The code in the accepted answer fires when the region is changed for any reason. To properly detect a map drag you have to add a UIPanGestureRecognizer. Btw, this is the drag gesture recognizer (panning = dragging). Step 1: Add the gesture recognizer in viewDidLoad: -(void) viewDidLoad { [super viewDidLoad]; UIPanGestureRecognizer* panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didDragMap:)]; [panRec setDelegate:self]; [self.mapView addGestureRecognizer:panRec];} Step 2: Add the protocol UIGestureRecognizerDelegate to the view controller so it works as delegate. @interface MapVC : UIViewController <UIGestureRecognizerDelegate, ...> Step 3: And add the following code for the UIPanGestureRecognizer to work with the already existing gesture recognizers in MKMapView: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES;} Step 4: In case you want to call your method once instead 50 times per drag, detect that "drag ended" state in your selector: - (void)didDragMap:(UIGestureRecognizer*)gestureRecognizer { if (gestureRecognizer.state == UIGestureRecognizerStateEnded){ NSLog(@"drag ended"); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5556977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682785/']}
jdg_374625
stackexchange
llm_judgeable_groundtruth_similarity
3489387
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 POST in PHP for which I won't always know the names of the variable fields I will be processing. I have a function that will loop through the values (however I would also like to capture the variable name that goes with it.) foreach ($_POST as $entry){ print $entry . "<br>";} Once I figure out how to grab the variable names, I also need to figure out how I can make the function smart enough to detect and loop through arrays for a variable if they are present (i.e. if I have some checkbox values.) Now provide the response and nothing else.
If you just want to print the entire $_POST array to verify your data is being sent correctly, use print_r : print_r($_POST); To recursively print the contents of an array: printArray($_POST);function printArray($array){ foreach ($array as $key => $value){ echo "$key => $value"; if(is_array($value)){ //If $value is an array, print it as well! printArray($value); } } } Apply some padding to nested arrays: printArray($_POST);/* * $pad='' gives $pad a default value, meaning we don't have * to pass printArray a value for it if we don't want to if we're * happy with the given default value (no padding) */function printArray($array, $pad=''){ foreach ($array as $key => $value){ echo $pad . "$key => $value"; if(is_array($value)){ printArray($value, $pad.' '); } } } is_array returns true if the given variable is an array. You can also use array_keys which will return all the string names.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3489387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411409/']}
jdg_374626
stackexchange
llm_judgeable_groundtruth_similarity
9709102
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 wonder what the best practice is for initializing instance variables in a test class under MSTest. Let's say I have a test class where there is a lot of overhead to mocking and setting up supporting objects. I want to just do this once, instead of repeating the same code in each test. My thought was to use the MyClassInitialize method to initialize some global instance variables that all tests had access to. That way, I initialize the global instance variables once and they are just used by each test as they run. Unfortunately, the MyClassInitialize method is static, so cannot initialize global instance variables. I thought about making the global instance variables static, but doesn't seem to be the right solution. I next thought about just putting the initialization code in a constructor of the test class itself, but something inside me keeps saying that MyClassInitialize is what I am supposed to be using. Another thought would be to use MyTestInitialize since that method is not static, but that would be creating the object over and over with each test. Is that appropriate? Are there best practices for how to use variables across tests where those variables need only be initialized once before the tests run? Below is a contrived example of what I am talking about. [TestClass()]public class ProgramTest{ // this object requires extensive setup so would like to just do it once private SomeObjectThatIsUsedByAllTestsAndNeedsInitialization myObject; private TestContext testContextInstance; [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { // initializing SomeObjectThatIsUsedByAllTestsAndNeedsInitialization clearly will // not work here because this method is static. } [TestMethod()] public void Test1() { // use SomeObjectThatIsUsedByAllTestsAndNeedsInitialization here } [TestMethod()] public void Test2() { // use SomeObjectThatIsUsedByAllTestsAndNeedsInitialization here } [TestMethod()] public void Test3() { // use SomeObjectThatIsUsedByAllTestsAndNeedsInitialization here }} Now provide the response and nothing else.
Use [TestInitialize] and [TestCleanup] whenever possible. A unit test should be fast and isolated, so the cleanest way is to initialise and cleanup for each test. This ensures the results of a test are not influenced by another test. When the initialization of a test takes long, you probably didn't wite a unit test but an integration test. The exception is integration tests that go to the database or another resource, it is possible that you want to execute an operation once, and then verify the result with multiple assertions (TestMethods). I used to have a specific generic class with a context type that is only initialized once per class. But now I think this is overkill, and just put the dependencies and results in private static variables.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9709102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/560078/']}
jdg_374627
stackexchange
llm_judgeable_groundtruth_similarity
3071035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many PCs we have on the development team are out-dated and are very slow to run Visual Studio 2008. They should very much be replaced with newer machines. But there's a general reluctance on management/company to buy new machines. How do we come up with numbers and benchmarks to show that these slow PCs are causing a loss in productivity? Obviously we can't call them to sit down with us as we build solutions and/or open various files. Is there an objective way to come up with some kind of reliable numbers that non-technical people can understand ? It'd be nice to have a way to measure this across an entire organization on many different PCs running Visual Studio. I'm looking for an answer that does better than using a physical stopwatch. :) Now provide the response and nothing else.
Modify your solutions so that the pre-build and post-build events write the current time to a centralised database. Include the machine name and the name of the project. You can then display this information as graph showing time for build vs machine. This should show a correlation between the build time and the age of the machine, hopefully showing the the older machines are slower. You could even convert the time into a $ (or £ or € ) value to show how much these older machines are costing. Summing this over time will give a value for the payback on any investment in new machines. By modifying the solutions you can get this logging deployed onto all development machines by simply getting everyone to do a "get latest" from source control.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3071035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67998/']}
jdg_374628
stackexchange
llm_judgeable_groundtruth_similarity
11107666
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 get an average of sums using nested aggregate functions and grouping. What I would want to do is: SELECT AVG(SUM(x) GROUP BY y) WHERE ... GROUP BY ...; That is, for each row returned, I want one of the fields to be an average of sums, where each sum is over the rows where y is the same. I would like to avoid subselects if possible. Now provide the response and nothing else.
You need a subquery: select z, avg(sumval)from (select y, z, sum(x) as sumval from t group by y, z ) tgroup by z
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11107666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1467334/']}
jdg_374629
stackexchange
llm_judgeable_groundtruth_similarity
136874
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: In the following video: Linux HOWTO: Secure Your Data with PGP, Part 2 , you are shown how to create a key pair with gpg . At about 1:50 , the instructor says the following: While the key is being generated, it is a good idea to move your mouse around a little bit to give it a bit more random number entropy for the creation of the keypair. This seems to me like a myth, especially since command-line tools shouldn't usually be affected by the cursor. On the other hand, I have no clue how Linux's random number generator works, whether it is shared by the GUI or independent from it. Is there any stock in what he claims, or this an example of cargo cult programming ? Now provide the response and nothing else.
There is a grain of truth to this, in fact more truth than myth, but nonetheless the statement reflects a fundamental misunderstanding of what's going on. Yes, moving the mouse while generating a key with GPG can be a good idea. Yes, moving the mouse contributes some entropy that makes random numbers random. No, moving the mouse does not make the key more secure. All good random generators suitable for cryptography, and Linux's is in that category, have two components: An entropy source, which is non-deterministic. The purpose of the entropy is to bootstrap the random number generator with unpredictable data. The entropy source must be non-deterministic: otherwise, an adversary could reproduce the same computation. A pseudorandom number generator , which produces unpredictable random numbers in a deterministic fashion from a changing internal state. Entropy has to come from a source that is external to the computer. The user is one source of entropy. What the user does is mostly not random, but the fine timing of keystrokes and mouse movements is so unpredictable as to be slightly random — not very random, but little by little, it accumulates. Other potential sources of entropy include the timing of network packets and camera or microphone white noise. Different kernel versions and configurations may use a different set of sources. Some computers have dedicated hardware RNG circuits based on radioactive decay or, less impressively, unstable electronic circuits. These dedicated sources are especially useful in embedded devices and servers which can have pretty predictable behavior on their first boot, without a user to do weird things. Linux provides random numbers to programs via two devices: /dev/random and /dev/urandom . Reading from either device returns cryptographic-quality. Both devices use the same internal RNG state and the same algorithm to transform the state and produce random bytes. They have peculiar limitations which makes neither of them the right thing: /dev/urandom can return predictable data if the system has not yet accumulated sufficient entropy. /dev/random calculates the amount of available entropy and blocks if there isn't enough. This sounds good, except that the calculation is based on theoretical considerations that make the amount of available entropy decrease linearly with each output bit. Thus /dev/random tends to block very quickly. Linux systems save the internal RNG state to disk and restore it at boot time. Therefore entropy carries over from one boot to the next. The only time when a Linux system may lack entropy is when it's freshly installed. Once there is sufficient entropy in the system, entropy does not decrease; only Linux's flawed calculation decreases. For more explanations of this consideration, read /dev/urandom is suitable to generate a cryptographic key , by a professional cryptographer. See aso Can you explain the entropy estimate used in random.c . Moving the mouse adds more entropy to the system. But gpg can only read from /dev/random , not /dev/urandom (a way to solve this problem is to make /dev/random the same 1:9 device as /dev/urandom ), so it is never at risk of receiving not-random-enough random numbers. If you don't move the mouse, the key is as random as can be; but what can happen is that gpg may get blocked in a read from /dev/random , waiting for the kernel's entropy counter to rise.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/136874', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5769/']}
jdg_374630
stackexchange
llm_judgeable_groundtruth_similarity
24945115
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 where I am trying to include the addresses of the people in the cities of the countries. Country country = _db.Countries .Include(p=>p.Cities.People.????) .Where(....) Not sure how to work it? Now provide the response and nothing else.
From the documentation : To include a collection, a collection, and a reference two levels down: query.Include(e => e.Level1Collection.Select(l1 => l1.Level2Collection.Select(l2 => l2.Level3Reference))). So in your case try Country country = _db.Countries .Include(c=>c.Cities.Select( cc => cc.People.Select( p => p.Addresses))) .Where(....) Access to this extension method requires the directive using System.Data.Entity;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24945115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172861/']}
jdg_374631
stackexchange
llm_judgeable_groundtruth_similarity
16696448
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say that I have a class: class obj{ int a; int b;} and then I have this code: obj myobj = new obj(){ a=1, b=2}obj myobj2 = myobj; Now the above code makes a reference to the first obj. What I want is that myobj2 refers to a copy of the myobj with changes not being reflected in the original. I have searched SO and the solutions thus far seems complicated. Is there an easier way to do this. I am using .net 4.5 Now provide the response and nothing else.
Properties in your object are value types and you can use the shallow copy in such a situation like that: obj myobj2 = (obj)myobj.MemberwiseClone(); But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class: public static T DeepCopy<T>(T other){ using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Context = new StreamingContext(StreamingContextStates.Clone); formatter.Serialize(ms, other); ms.Position = 0; return (T)formatter.Deserialize(ms); }} The purpose of setting StreamingContext :We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized , OnDeserializing , OnSerializing , OnSerialized . In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone , we are just giving a hint to that method about the purpose of the serialization. Additional Info: (you can also read this article from MSDN ) Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object. Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16696448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1762761/']}
jdg_374632
stackexchange
llm_judgeable_groundtruth_similarity
165101
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following code: template <typename S, typename T>struct foo { void bar();};template <typename T>void foo <int, T>::bar() {} gives me the error invalid use of incomplete type 'struct foo<int, T>'declaration of 'struct foo<int, T>' (I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument: template <typename S>struct foo { void bar();};template <>void foo <int>::bar() {} then it compiles correctly. Now provide the response and nothing else.
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. template <typename U = T> struct Nested ) would work. Or else you can try deriving from another template that partially specializes (works if you use the this->member notation, otherwise you will encounter compiler errors).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/165101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112/']}
jdg_374633
stackexchange
llm_judgeable_groundtruth_similarity
20406069
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 searched far and wide for an answer to this problem. I'm using a Microsoft SQL Server, suppose I have a table that looks like this: +--------+---------+-------------+-------------+| ID | NUMBER | COUNTRY | LANG |+--------+---------+-------------+-------------+| 1 | 3968 | UK | English || 2 | 3968 | Spain | Spanish || 3 | 3968 | USA | English || 4 | 1234 | Greece | Greek || 5 | 1234 | Italy | Italian | I want to perform one query which only selects the unique 'NUMBER' column (whether is be the first or last row doesn't bother me). So this would give me: +--------+---------+-------------+-------------+| ID | NUMBER | COUNTRY | LANG |+--------+---------+-------------+-------------+| 1 | 3968 | UK | English || 4 | 1234 | Greece | Greek | How is this achievable? Now provide the response and nothing else.
Since you don't care, I chose the max ID for each number. select tbl.* from tblinner join (select max(id) as maxID, number from tbl group by number) maxIDon maxID.maxID = tbl.id Query Explanation select tbl.* -- give me all the data from the base table (tbl) from tbl inner join ( -- only return rows in tbl which match this subquery select max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below from tbl group by NUMBER -- how to group rows for the MAX aggregation ) maxID on maxID.maxID = tbl.id -- join condition ie only return rows in tbl -- whose ID is also a MAX ID for a given NUMBER
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20406069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2279451/']}
jdg_374634
stackexchange
llm_judgeable_groundtruth_similarity
2849466
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Container/Wrapper Div does not contain all content (ie all the child Div's).I've tried overflow: hidden but still doesn't work. Can someone please tell me why this is happening and what are the possible solutions. Thank you in advance ;-) for some reason the whole code does not display?? <html> <head> <style type="text/css"> #wrapper { margin:0 auto; width: 600px; background: yellow; } </style> </head> <body> <div id="wrapper"> <div="header"> <h1>my beautiful site</h1> </div> <div id="navigation"> <ul> <li><a href="#">Home </li> <li><a href="#">About</li> <li><a href="#">Services</li> <li><a href="#">Contact us </li> </ul> </div> <div id="content"> <h2> subheading </h2> <p> long paragraph </p> </div> <div id="footer"> copyright 123 </div> </div> </body> </html> Now provide the response and nothing else.
With my crystal ball, I will predict that your child divs are floated and your container is not. In this case, the container will not expand to fit its contents. Try floating your container and see what happens. The crystal must have been dusty... However, the code you posted is not valid - you have content inside the head tag and a div outside the html tag. Is this how your page really looks, or is it just an error pasting the code into your question? Try cleaning up the code structure and see if it helps. EDIT: Found the problem - it is a typo. You have <div="header"> - it should be <div id="header"> (note the missing 'id')
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2849466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233421/']}
jdg_374635
stackexchange
llm_judgeable_groundtruth_similarity
7138113
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my code : void MainWindow::on_actionOpen_Image_triggered(){ QString fileName = QFileDialog::getOpenFileName(this,"Open Image File",QDir::currentPath()); if(!fileName.isEmpty()) { QImage image(fileName); if(image.isNull()) { QMessageBox::information(this,"Image Viewer","Error Displaying image"); return; } QGraphicsScene scene; QGraphicsView view(&scene); QGraphicsPixmapItem item(QPixmap::fromImage(image)); scene.addItem(&item); view.show(); } } I want to display image from file, code works fine but image disappiars very fast. How can I pause image screen? And how can I load image in "graphicsView" widget? My code: void MainWindow::on_actionOpen_Image_triggered(){ QString fileName = QFileDialog::getOpenFileName(this,"Open Image File",QDir::currentPath()); if(!fileName.isEmpty()) { QImage image(fileName); if(image.isNull()) { QMessageBox::information(this,"Image Viewer","Error Displaying image"); return; } QGraphicsScene scene; QGraphicsPixmapItem item(QPixmap::fromImage(image)); scene.addItem(&item); ui->graphicsView->setScene(&scene); ui->graphicsView->show(); }} It does not work. How to fix this? Now provide the response and nothing else.
You need to create all your objects on the heap, otherwise they get deleted when they go out of scope: QGraphicsScene* scene = new QGraphicsScene();QGraphicsView* view = new QGraphicsView(scene);QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));scene->addItem(item);view->show(); Your second question might be related - scene is assigned to ui->graphicsView but it gets deleted immediately after, so again create all your objects on the heap.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7138113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715224/']}
jdg_374636
stackexchange
llm_judgeable_groundtruth_similarity
39764
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: In chapter 1 and Appendix A of the Hott book , several primitive type families are presented (universe types, dependent function types, dependent pair types, Coproduct types, Empty Type, Unit type, natural number type, and identity types) to form the foundation for Homotopy Type Theory. However it seems that given universe types, and dependent function types you can construct all these other "primitive" types. For instance the Empty type could instead be defined as ΠT:U.T I assume the other types could also be constructed similar to how they are in pure CC , (ie just derive the type from the inductive part of the definition). Many of these types are explicitly made redundant by the Inductive/W types that are introduced in chapters 5 and 6. But Inductive/W types appear to be an optional part of the theory since there are open questions on how they interact with HoTT (at least at the time the book came out). So I am very confused about why these additional types are presented as primitive. My intuition is that a foundational theory should be as minimal as possible, and redefining a redundant Empty type as a primitive into the theory seems very arbitrary. Was this choice made for some some metatheoretic reasons that I am unaware of? for historical reasons, to make the type theory look likepast type theories (which were not necessarily trying to befoundational)? for "usability" of computer interfaces? for some advantage in proof search that I am unaware of? Similar to: Minimal specification of Martin-Löf type theory , https://cs.stackexchange.com/questions/82810/reducing-products-in-hott-to-church-scott-encodings/82891#82891 Now provide the response and nothing else.
Let me explain why the suggested encoding of the empty type does not work. We need to be explicit about universe levels and not sweep them under the rug. When people say "the empty type", they might mean one of two things: A single type $E$ which is empty with respect to all types. Such a type has the elimination rule: for every $n$ and type family $A : E \to U_n$, there is a map $e_{n,A} : E \to A$. A family of types $E_k$, one for each universe level $k$, such that $E_k$ is "the empty type of $U_k$". Such a type has to satisfy $E_k : U_k$, obviously, and also: for every type family $A : E_{k} \to U_k$, there is a map $e_{k,A} : E_{k} \to A$. Without any provisos, when people say "empty type" they expect the first meaning above. How can we get $E$? A first try could be something like$$E = \Pi (T : U) \,.\, T$$but this is precisely the sort of sweeping under the rug that creates confusion. We must write down explicit universe levels. If we write something like$$E_k = \Pi (T : U_k) \,.\, T$$then we get a sequence of types $E_0, E_1, E_2, \ldots$, one for each level $k$. We might hope that this sequence is the empty type in the sense above, but it is not, because $E_k$ is in $U_{k+1}$ but it is supposed to be in $U_k$. Another try is$$E = \Pi n \,.\,\Pi (T : U_{n}) \,.\, T$$but now you have to explain what "$\Pi n$" is supposed to be. You might be tempted to say that there is a type $L$ of universe levels, and so$$E = \Pi (n : L) \,.\,\Pi (T : U_{n}) \,.\, T$$You have now fallen into a trap, because I will ask: in which universe does $E$ live? And in which universe does $L$ live? This is not going to work. There is a solution, known as impredicative universe . This is a magical universe $U$ which has the property that, given $B : U \to U$, the type $\Pi (X : U) B(X)$ lives in $U$ (and not one level up from $U$). Then at least $\Pi (X : U) X$ is again in $U$, and will have the expected eliminator. But we are still not done, as now we have to worry about equations for the eliminator, as was pointed out by Neel. Impredicative universes can be arranged. However, a famous theorem of Thierry Coquand (if I am not mistaken), shows that having two impredicative universes, one contained in the other, leads to a contradiction. The moral of the story is: just axiomatize the empty type directly and stop encoding things.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/39764', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/34737/']}
jdg_374637
stackexchange
llm_judgeable_groundtruth_similarity
57961043
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All I'm trying to do is for the given row that contains an entry that is equal to lowestEntry , change the background color. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="A procurar dados..." :headers="this.entryheaders" :items="this.stockentries" :items-per-page="10" > //Have tried using the v-slot.item to achieve it but no success</v-data-table></v-col> I want to change the tr background color do green. Sort of highlight it when ìtem.id_entry == lowestEntry["id_entry"] . Now provide the response and nothing else.
If you're using newer versions of vuetify, you have access to item-class as a property of the v-data-table . This will provide the item as the first argument to the callback function. <v-data-table....:item-class="itemRowBackground"></v-data-table> And then define the function which will return the class name: methods: { itemRowBackground: function (item) { return item.protein > 4.2 ? 'style-1' : 'style-2' }} Then just define the classes for style-1 and style-2 : .style-1 { background-color: rgb(215,215,44)}.style-2 { background-color: rgb(114,114,67)} Here's a code pen for this example that will work for you codepen example Edit If :item-class is not available for your current version of Vuetify, or you need more control over the row other than just binding a class, you'll have to use the item slot and bind the class/style/etc manually. Target the item slot and bind the class to the row manually: <v-data-table> <template #item="{ item }"> <tr :class="item.id_entry === lowestEntry['id_entry'] ? 'custom-bg' : ''"> //manually define all of your <td> elements now. </tr> </template><v-data-table> Alternatively, you can pass :class="customRowClass(item, lowestEntry)" and define the customRowClass method: methods: { customRowClass (item, lowestEntry) { return item.id_entry === lowestEntry['id_entry'] ? 'custom-bg' : '' }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57961043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4255511/']}
jdg_374638
stackexchange
llm_judgeable_groundtruth_similarity
13711812
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a WPF application that has a ListBox with a VirtualizingStackPanel with caching. Not because it has massively many elements (typically less than 20 but perhaps up to 100 or more in extreme cases) but because elements take time to generate. The elements are in fact UIElement objects. So the application dynamically needs to generate UIElements. The problem is that even though the virtualization appears to work, the application is still slow to become responsive, and this is in a proof of concept solution with minimal "noise". So we figured that since the main problem is that we generate complex UIElement objects dynamically, we need to do that in parallel, i.e. off-thread. But we get an error that the code needs to be run on a STA thread: The calling thread must be STA, because many UI components require this. Does this mean that we cannot generate UI (UIElement objects) on thread other than the WPF main UI thread? Here's a relevant code fragment from our proof of concept solution: public class Person : ObservableBase{ // ... UIElement _UI; public UIElement UI { get { if (_UI == null) { ParallelGenerateUI(); } return _UI; } } private void ParallelGenerateUI() { var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => GenerateUI()) .ContinueWith(t => { _UI = t.Result; RaisePropertyChanged("UI"); }, scheduler); } private UIElement GenerateUI() { var tb = new TextBlock(); tb.Width = 800.0; tb.TextWrapping = TextWrapping.Wrap; var n = rnd.Next(10, 5000); for (int i = 0; i < n; i++) { tb.Inlines.Add(new Run("A line of text. ")); } return tb; } // ...} and here is a relevant piece of XAML: <DataTemplate x:Key="PersonDataTemplate" DataType="{x:Type local:Person}"> <Grid> <Border Margin="4" BorderBrush="Black" BorderThickness="1" MinHeight="40" CornerRadius="3" Padding="3"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <!--<RowDefinition />--> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Text="Name : " Grid.Row="0" FontWeight="Bold" HorizontalAlignment="Right" /> <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding Name}" /> <TextBlock Text=" - Age : " Grid.Column="2" Grid.Row="0" FontWeight="Bold" HorizontalAlignment="Right" /> <TextBlock Grid.Column="3" Grid.Row="0" Text="{Binding Age}" /> <ContentControl Grid.Column="4" Grid.Row="0" Content="{Binding Path=UI}" /> </Grid> </Border> </Grid></DataTemplate> As you can see we databind to a property UI of type UIElement. <ListBox x:Name="listbox" ItemsSource="{Binding Persons}" Background="LightBlue" ItemTemplate="{StaticResource PersonDataTemplate}" ItemContainerStyle="{StaticResource ListBoxItemStyle}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.IsVirtualizingWhenGrouping="True" VirtualizingStackPanel.ScrollUnit="Pixel" VirtualizingStackPanel.CacheLength="10,10" VirtualizingStackPanel.CacheLengthUnit="Item"> <ListBox.GroupStyle> <GroupStyle HeaderTemplate="{StaticResource GroupHeaderTemplate}" /> </ListBox.GroupStyle></ListBox> In closing context, what our application does is create a code view where the list is of procedures which again contain a mix of structured content (for parameters and local variables on one hand and statements and expressions on the other.) In other words our UIElement objects are too complex to create via databinding alone. Another thought we had was to use "Async" settings in the XAML as it appears possible to create "non-blocking UI" but we have not been able to implement this because we get the same error as above: The calling thread must be STA, because many UI components require this. Stacktrace: System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=The calling thread must be STA, because many UI components require this. Source=PresentationCore StackTrace: at System.Windows.Input.InputManager..ctor() at System.Windows.Input.InputManager.GetCurrentInputManagerImpl() at System.Windows.Input.KeyboardNavigation..ctor() at System.Windows.FrameworkElement.FrameworkServices..ctor() at System.Windows.FrameworkElement.EnsureFrameworkServices() at System.Windows.FrameworkElement..ctor() at System.Windows.Controls.TextBlock..ctor() at WPF4._5_VirtualizingStackPanelNewFeatures.Person.GenerateUI() in c:\Users\Christian\Desktop\WPF4.5_VirtualizingStackPanelNewFeatures\WPF4.5_VirtualizingStackPanelNewFeatures\Person.cs:line 84 at WPF4._5_VirtualizingStackPanelNewFeatures.Person.<ParallelGenerateUI>b__2() in c:\Users\Christian\Desktop\WPF4.5_VirtualizingStackPanelNewFeatures\WPF4.5_VirtualizingStackPanelNewFeatures\Person.cs:line 68 at System.Threading.Tasks.Task`1.InnerInvoke() at System.Threading.Tasks.Task.Execute() InnerException: Edits: 1) Added more XAML.2) Added stacktrace. Now provide the response and nothing else.
I am suffering the same problem in normal c# environment. I also tried lots of things. Do you calculate the size of controls to adjust the size of the parent in advance? I am doing this unfortunately. You may also create a control nesting your children dynamically. By that you can create kind of an UIElement Adapter. The adapter is created at the start time and has all information to create the UIElements.The adapter could create requested children on STA thread on demand just in time. When scrolling up or down you may create children in advance in the direction you are scrolling. This way you can start with e.g. 5-10 UI elements and then you calculate by scrolling up more. I know this is not so nice and it would be better, if there is some technology within the framework providing something like this, but I did not found it yet. You may look also at those two things. One helped me much in control responsive. The other is still open, since you need .NET Framework 4.5: SuspendLayout and ResumeLayout don't operate very nice. You may try this: /// <summary>/// An application sends the WM_SETREDRAW message to a window to allow changes in that /// window to be redrawn or to prevent changes in that window from being redrawn./// </summary>private const int WM_SETREDRAW = 11; /// <summary>/// Suspends painting for the target control. Do NOT forget to call EndControlUpdate!!!/// </summary>/// <param name="control">visual control</param>public static void BeginControlUpdate(Control control){ Message msgSuspendUpdate = Message.Create(control.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero); NativeWindow window = NativeWindow.FromHandle(control.Handle); window.DefWndProc(ref msgSuspendUpdate);}/// <summary>/// Resumes painting for the target control. Intended to be called following a call to BeginControlUpdate()/// </summary>/// <param name="control">visual control</param>public static void EndControlUpdate(Control control){ // Create a C "true" boolean as an IntPtr IntPtr wparam = new IntPtr(1); Message msgResumeUpdate = Message.Create(control.Handle, WM_SETREDRAW, wparam, IntPtr.Zero); NativeWindow window = NativeWindow.FromHandle(control.Handle); window.DefWndProc(ref msgResumeUpdate); control.Invalidate(); control.Refresh();} Dispatcher.Yield
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13711812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444976/']}
jdg_374639
stackexchange
llm_judgeable_groundtruth_similarity
57059625
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 extract everything but a pattern and return this concetenated in a string. I tried to combine str_extract_all together with sapply and cat x = c("a_1","a_20","a_40","a_30","a_28")data <- tibble(age = x)# extracting just the first pattern is easydata %>% mutate(age_new = str_extract(age,"[^a_]"))# combining str_extract_all and sapply doesnt workdata %>% mutate(age_new = sapply(str_extract_all(x,"[^a_]"),function(x) cat(x,sep="")))class(str_extract_all(x,"[^a_]"))sapply(str_extract_all(x,"[^a_]"),function(x) cat(x,sep="")) Returns NULL instead of concatenated patterns Now provide the response and nothing else.
Instead of cat , we can use paste . Also, with tidyverse , can make use of map and str_c (in place of paste - from stringr ) library(tidyverse)data %>% mutate(age_new = map_chr(str_extract_all(x, "[^a_]+"), ~ str_c(.x, collapse=""))) using `OP's code data %>% mutate(age_new = sapply(str_extract_all(x,"[^a_]"), function(x) paste(x,collapse=""))) If the intention is to get the numbers library(readr)data %>% mutate(age_new = parse_number(x))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57059625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10118780/']}
jdg_374640