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
|
54245541
|
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 REST API, I want to send event to the client via websocket.How to inject websocket instance in controller or another component?
Now provide the response and nothing else.
|
class Gateway can be injected in another component, and use the server instance. @Controller()export class AppController { constructor( private readonly appService: AppService, private readonly messageGateway: MessageGateway ) {} @Get() async getHello() { this.messageGateway.server.emit('messages', 'Hello from REST API'); return this.appService.getHello(); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54245541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6536240/']}
|
jdg_371941
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2709832
|
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:
Cantor set See the link, I am referring to cantor set on the real line. I wish to show that it is compact. I am doing this by pointing following arguments. I am not sure if this is enough. Cantor set is bounded by definition in the region $[0,1]$ Cantor set is the union of closed intervals, and hence it is a closed set. Since the Cantor set is both bounded and closed it is compact by Heine-Borel Theorem.
Now provide the response and nothing else.
|
Cantor set is defined as $C=\cap_n C_n$ where $C_{n+1}$ is obtained from $C_n$ by dropping 'middle third' of each closed interval in $C_n$ As you have noted, Cantor set is bounded. Since each $C_n$ is closed and $C$ is an intersection of such sets, $C$ is closed (arbitrary intersection of closed sets is a closed set). As $C$ is closed and bounded, it is compact by Heine-Borel theorem. PS: You cannot say that Cantor set is a union of closed intervals. Rudin is giving Cantor set as an example for a perfect set that contains no open interval!
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2709832', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477581/']}
|
jdg_371942
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8433176
|
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 use the MAX function of MySQL to retrieve the latest dates from my table. $_updates = Mage::getModel('ticket/updates')->getCollection(); $_updates->getSelect()->columns('MAX(created) as max_created')->group(array('status_id')); This is the resulting query: SELECT `main_table`.*, MAX(created) AS `max_created` FROM `em_ticket_updates` AS `main_table` GROUP BY `status_id` The problem with this is that if all the fields are included ( main_table.* ) it does not function correctly. Is there a way to remove main_table.* from the query and only use specific fields? Thanks.
Now provide the response and nothing else.
|
A Zend trick can be used here. $_updates->getSelect() ->reset(Zend_Db_Select::COLUMNS) ->columns('MAX(created) as max_created') ->group(array('status_id')); NOTE: For EAV collection you must re-add the entity_id or you will have an error when the collection is loaded. $collection = Mage::getModel('catalog/product') ->getCollection(); $collection->getSelect() ->reset(Zend_Db_Select::COLUMNS) ->columns(array('entity_id')); $collection ->addAttributeToSelect(array('image','small_image','thumbnail')) ->addFieldToFilter('entity_id', array('in' => $simple_ids));
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8433176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1087606/']}
|
jdg_371943
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
643542
|
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 very puzzled about this code: var closures = [];function create() { for (var i = 0; i < 5; i++) { closures[i] = function() { alert("i = " + i); }; }}function run() { for (var i = 0; i < 5; i++) { closures[i](); }}create();run(); From my understanding it should print 0,1,2,3,4 (isn't this the concept of closures?). Instead it prints 5,5,5,5,5 . I tried Rhino and Firefox.Could someone explain this behavior to me?
Now provide the response and nothing else.
|
Fixed Jon's answer by adding an additional anonymous function: function create() { for (var i = 0; i < 5; i++) { closures[i] = (function(tmp) { return function() { alert("i = " + tmp); }; })(i); }} The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function. After the loop terminates, the function-level variable i has the value 5 , and that's what the inner function 'sees'. As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/643542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3506/']}
|
jdg_371944
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39732
|
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 always thought that, even in darkness, there would still be some light, making complete darkness, i.e. complete absence of photons as far as I know, just a theoretical thing. When I tried looking up whether or not this view was actually correct, I didn't find any clear information, however. Am I wrong?
Now provide the response and nothing else.
|
No, you are right. Anywhere you can go, you're surrounded by some kind of matter at some nonzero temperature. Though most matter is not quite a blackbody , it still does radiate when at finite temperature. However, at low temperatures the intensity of this radiation in the visible range vanishes proportional to $e^{-\frac1T}$ , which means you normally have only few visible photons around, typically much less than those reflected in some indirect way from the sun or artificial light sources. You definitely can't see these photons with your eyes, because they are at a higher temperature as the surrounding and therefore have more thermal noise intensity.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/39732', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11212/']}
|
jdg_371945
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
87242
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In the proof, the author consider the normalization $\tilde{A}$ of $A$ and show $\tilde{A}/t \tilde{A}$ is a integral domain. He showed that the localizations at points of Spec $A$ are domains, but we know a non-domain ring can have integral localizations. How should I understand the proof? Thanks a lot.
Now provide the response and nothing else.
|
Let me give an easier (sketch of an) answer to the part of the question about proving Con(ZFC) in MK. Unlike Emil's answer, the following does not cover the case of arbitrary finitely axiomatized subtheories of MK. Intuitively, there's an "obvious" argument for the consistency of ZFC: All its axioms are true when the variables are interpreted as ranging over arbitrary sets. (The universe is a model of ZFC, except that it isn't a set.) And anything deducible from true axioms is true, so you can't deduce contradictions from ZFC. The trouble with this argument is that it relies on a notion of "truth in the universe" that can't be defined in ZFC. What goes wrong if you try to define, in the language of ZFC, this notion of truth (or satisfaction) in the universe? Just as in the definition of truth in a (set-sized) model, you'd proceed by induction on formulas, and there's no problem with atomic formulas and propositional connectives. Quantifiers, though, give the following problem: The truth value of $\exists x\ \phi(x)$ depends on the truth values of all the instances $\phi(a)$, and there are a proper class of these. In showing that definitions by recursion actually define functions, one has to reformulate the recursion in terms of partial functions that give enough evidence for particular values of the function being defined. (For example, the usual definition of the factorial can be made into an explicit definition by saying $n!=z$ iff there is a sequence $s$ of length $n$ with $s_1=1$ and $s_k=ks_{k-1}$ for $2\leq k\leq n$ and $s_n=z$.) If you use the same method to make the definition of "truth in the universe" explicit, you find that the "evidence" (analogous to $s$ for the factorial) needs to be a proper class. So ZFC can't handle that (and it's a good thing it can't, because otherwise it would prove its own consistency). But MK can; it's designed to deal nicely with quantification of proper classes. So in MK, one can define what it means for a formula to be true in the ZFC universe. Then one can prove that all the ZFC axioms are true in this sense and truth is preserved by logical deduction (here one uses induction over the number of steps in the deduction). Therefore deduction from ZFC axioms can never lead to contradictions.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/87242', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3525/']}
|
jdg_371946
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
480555
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Why do I get a segmentation fault when writing to a string? I want to write a function that reverses the given string passed into it.But, I can not. If I supply the doReverse function (see code below) with a character array, my code works well. I can't figure out why this does not work.I am able to access str[0] in doReverse , but I can't change any value of the array by using a char pointer. Any ideas? void doReverse(char *str) { str[0] = 'b';}void main(void) { char *str = "abc"; doReverse(str); puts(str);} Update: I know how to do write a reverse function by passing a character array to it: void reverse1(char p[]) { int i, temp, y; for (i = 0, y = strlen(p); i < y; ++i, --y) { temp = p[y-1]; p[y-1] = p[i]; p[i] = temp; }} But, I want to write another version that gets a char pointer as a parameter.
Now provide the response and nothing else.
|
The simplest solution is to change the declaration of str to char str[] = "abc"; This makes str an array of char that is initialized to the string "abc". Currently you have str as a pointer-to-char initialized to point to a string described by a string literal. There is a key difference: string literals are read-only to give the compiler maximum flexibility on where to store them; it is UB to modify them. But arrays of char are mutable, and so it's okay to modify those. PS. main() returns an int .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/480555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_371947
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5451597
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When you run Google's PageSpeed plugin for Firebug/Firefox on a website it will suggest cases where an image can be losslessly compressed, and provide a link to download this smaller image. For example: Losslessly compressing http://farm3.static.flickr.com/2667/4096993475_80359a672b_s.jpg could save 33.5KiB (85% reduction). Losslessly compressing http://farm2.static.flickr.com/1149/5137875594_28d0e287fb_s.jpg could save 18.5KiB (77% reduction). Losslessly compressing http://cdn.uservoice.com/images/widgets/en/feedback_tab_white.png could save 262B (11% reduction). Losslessly compressing http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/images/ui-bg_flat_75_ffffff_40x100.png could save 91B (51% reduction). Losslessly compressing http://www.gravatar.com/avatar/0b1bccebcd4c3c38cb5be805df5e4d42?s=45&d=mm could save 61B (5% reduction). This applies across both JPG and PNG filetypes (I haven't tested GIF or others.) Note too the Flickr thumbnails (all those images are 75x75 pixels.) They're some pretty big savings. If this is really so great, why aren't Yahoo applying this server-side to their entire library and reducing their storage and bandwidth loads? Even Stackoverflow.com stands for some very minor savings: Losslessly compressing http://sstatic.net/stackoverflow/img/sprites.png?v=3 could save 1.7KiB (10% reduction). Losslessly compressing http://sstatic.net/stackoverflow/img/tag-chrome.png could save 11B (1% reduction). I've seen PageSpeed suggest pretty decent savings on PNG files that I created using Photoshop's 'Save for Web' feature. So my question is, what changes are they making to the images to reduce them by so much? I'm guessing there are different answers for different filetypes. Is this really lossless for JPGs? And how can they beat Photoshop? Should I be a little suspicious of this?
Now provide the response and nothing else.
|
If you're really interested in the technical details, check out the source code: png_optimizer.cc jpeg_optimizer.cc webp_optimizer.cc For PNG files, they use OptiPNG with some trial-and-error approach // we use these four combinations because different images seem to benefit from// different parameters and this combination of 4 seems to work best for a large// set of PNGs from the web.const PngCompressParams kPngCompressionParams[] = { PngCompressParams(PNG_ALL_FILTERS, Z_DEFAULT_STRATEGY), PngCompressParams(PNG_ALL_FILTERS, Z_FILTERED), PngCompressParams(PNG_FILTER_NONE, Z_DEFAULT_STRATEGY), PngCompressParams(PNG_FILTER_NONE, Z_FILTERED)}; When all four combinations are applied, the smallest result is kept. Simple as that. (N.B.: The optipng command line tool does that too if you provide -o 2 through -o 7 ) For JPEG files, they use jpeglib with the following options: JpegCompressionOptions() : progressive(false), retain_color_profile(false), retain_exif_data(false), lossy(false) {} Similarly, WEBP is compressed using libwebp with these options: WebpConfiguration() : lossless(true), quality(100), method(3), target_size(0), alpha_compression(0), alpha_filtering(1), alpha_quality(100) {} There is also image_converter.cc which is used to losslessly convert to the smallest format.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5451597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24874/']}
|
jdg_371948
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9834143
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a page that displays messages and I want it to work just like Facebook, but without the lazy loader. Messages are displayed in chronological order, most recent last. My message list is initially populated x number of most recent messages, and the window is scrolled to the bottom. When the user starts to read the thread, they read from bottom to top. If they get to the top, they can load more messages... I make them click a button... facebook has a lazy loader. New messages are prepended to the list. Problem: As the new messages are prepended, the existing messages are pushed down, causing the user to lose their "viewing" place. How can I keep the user's current view position as I add the new messages? For an example, open a long message thread in facebook, scroll to the top causing new messages to be added... your view location doesn't change even though the scroll position does.
Now provide the response and nothing else.
|
Store a reference to the first message before you prepend new messages, and after you prepend, set the scroll to the offset of that message: $(document).on('scroll', function() { var scroll = $(document).scrollTop(); if (scroll < 1) { // Store eference to first message var firstMsg = $('.message:first'); // Prepend new message here (I'm just cloning...) $('body').prepend(firstMsg.clone()); // After adding new message(s), set scroll to position of // what was the first message $(document).scrollTop(firstMsg.offset().top); }}); Demo: http://jsfiddle.net/GRnQY/ Edit : I noticed you wanted it with a button. You might have to do a little more math: $(document).on('click', '#loadMore', function() { var firstMsg = $('.message:first'); // Where the page is currently: var curOffset = firstMsg.offset().top - $(document).scrollTop(); // Prepend firstMsg.before(firstMsg.clone()); // Offset to previous first message minus original offset/scroll $(document).scrollTop(firstMsg.offset().top-curOffset);}); Demo: http://jsfiddle.net/GRnQY/5/
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9834143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591736/']}
|
jdg_371949
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21177415
|
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 facing this issue, but I don't know why. How do I fix this? Failed to load resource: the server responded with a status of 404 (Not Found) http://www.xxx/res.ashx/areas/manager/content/css/style.min.cssFailed to load resource: the server responded with a status of 404 (Not Found) http://www.xxx/res.ashx/areas/manager/content/js/ext/jquery-1.7.2.min.jsFailed to load resource: the server responded with a status of 404 (Not Found) http://www.xxx/res.ashx/areas/manager/content/js/jquery.manager.js Installed Piranha: https://github.com/nickvee/Piranha.Bootstrap/tree/master/Piranha.Bootstrap on the server Original location is: http://www.xxx/content/css/style.min.css
Now provide the response and nothing else.
|
The resource could be being blocked by an extension (AdBlock in my case). The message is there because the request to retrieve that resource was never made, so the headers being shown are not the real thing. As explained in the issue you referenced, the real headers are updated when the server responds, but there is no response if the request was blocked. The way I found about the extension that was blocking my resource was through the net-internals tool in Chrome: For Latest Versions of chrome Type chrome://net-export/ in the address bar and hit enter. Start Recording. And save Recording file to local. Open the page that is showing problems. Go back to net-internals You can view Recorded Log file Here https://netlog-viewer.appspot.com/#import click on events (###) and use the textfield to find the event related to your resource (use parts of the URL). Finally, click on the event and see if the info shown tells you something. For Older Versions of chrome Type chrome://net-internals in the address bar and hit enter. Open the page that is showing problems. Go back to net-internals, click on events (###) and use the textfield to find the event related to your resource (use parts of the URL). Finally, click on the event and see if the info shown tells you something.
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/21177415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1460692/']}
|
jdg_371950
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35363194
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In this article I saw Bootstrap 4 Spacing Utility Classes, and he uses m-b-lg in className . <div class="row"> <div class="col-sm-6 m-b-lg"> <!-- column-small-50%, margin-bottom-large --> </div></div> But when I use it on meteorjs with react nothing happens. Am I missing something or missing a plugin? <div className="container-fluid"> <div className="col-xs-6 col-xs-offset-3 m-t-lg"> <h1 className="text-xs-center"> Login </h1> <form> <div className="form-group"> <input type="email" className="form-control" id="inputEmail" placeholder="Email"/> </div> <div className="form-group"> <input type="password" className="form-control" id="inputPassword" placeholder="Password"/> <p className="text-xs-center"><a href="/signup"> Forgot your email or password?</a></p> </div> <div className="form-group"> <button className="btn btn-primary btn-block" type="submit"> Login </button> <p className="text-xs-center"> New to Arcademy? <a href="/signup"> Sign up now.</a></p> </div> </form> </div></div>
Now provide the response and nothing else.
|
Bootstrap 5 beta - update 2021 Now that Bootstrap 5 has RTL support, the concept of left and right have change to start and end . Therefore the *l- and *r- spacing utilities have changed pl-* = ps-* pr-* = pe-* ml-* = ms-* pr-* = me-* Bootstrap 4 -update 2020 The Bootstrap 4 spacing utils have changed since the original answer (for v4 alpha). Now the syntax is simply: margins: m{sides}-{size} padding: p{sides}-{size} Examples.. mb-2 = margin bottom 2 spacing units m-0 = no margins pt-3 = padding top 3 spacing units p-1 = padding all sides 1 spacing unit There are now 6 sizes (0-5) that represent a portion of the standard .5rem spacer unit. Additionally, x-axis (left/right) and y-axis (top/bottom) utils have been added: my-2 = margin top & bottom 2 spacing units mx-0 = no margins left & right px-3 = padding left & right 3 spacing units And, the spacing utils are now responsive. The smallest xs breakpoint is implied when no breakpoint is used. margins: m{sides}-{breakpoint}-{size} padding: p{sides}-{breakpoint}-{size} mt-md-2 = margin top 2 spacing units, on md (and up) py-sm-0 = no padding top & bottom, on sm (and up) Bootstrap 4 Spacing Utils Demo Related: Bootstrap 4 spacing bug?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35363194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3792482/']}
|
jdg_371951
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4298387
|
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 django-registration, and just set it up. {{user.is_authenticated }} is true, even though i went already to /accounts/logout/ and logged the user out. {{user.is_anonymous }} returns true also. According to django docs, those two should be different: is_anonymous: Always returns False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated() to this method. and is_authenticated: Always returns True. This is a way to tell if the user has been authenticated. This does not imply any permissions, and doesn't check if the user is active - it only indicates that the user has provided a valid username and password. I am using the standard views that come with django-registration and haven't touched them yet. In the tempalate i have the following code: {% if user.is_authenticated %}{% user }}{% if user.is_anonymous %} is anonymous{% endif $}{% else %} gotta login{% endif %} Where would the problem be? I will be really thankful! UPDATE:i have noticed that on the homepage, it both is_authenticated and id_anonymous return True, while if i go to /accounts/login before loging in, only is_anonymous returns true as it should be. And also, on the homepage, i have the following view if that helps: def home(request): return render_jinja(request, 'index.html', blah = 'ga') UPDATE 2:print(request.user.is_authenticated()) gives False. Then, i have: return render_jinja(request, 'index.html', blah = 'ga') and in the template, user.is_authenticated returns FALSE. UPDATE 3:If i use render_to_response, instead of render_jinja, all is good. still don't know how to fix this though :(
Now provide the response and nothing else.
|
It seems like you are trying to figure out two things at once; what is the correct way to use jinja templates and what is the deal with User/AnonymousUser. Maybe try to figure out these problems one at a time. I have no experience with jinja but you may want to check and make sure that you are taking differences between jinja and django template syntax into account. The biggest difference I know of is that a method call requires explicit parenthesis. So the is_authenticated and is_anonymous calls in your example need parenthesis. Jinja style {{ user.is_authenticated() }}Django style {{ user.is_authenticated }} If that does not solve the problem, try installing django-debug-toolbar and take a look at the context for your template. Check and see if user is None or an object (User or AnonymousUser). You can also read up on AnonymousUser and see an example of checking for an authenticated user in the docs. In a nutshell, for an AnonymousUser object is_anonymous() always returns True instead of False and is_authenticated() always returns False instead of True.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4298387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/522337/']}
|
jdg_371952
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54327556
|
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 UITests that rely on showing the software keyboard. Since the CI launches the tests every time on clean new simulator, the simulator has hardware keyboard connected, hence the software one is not being presented. Is it possible to set some settings (maybe in schema?) to force-disable connecting hardware keyboard by the simulator. I am running tests using cucumber/appium.
Now provide the response and nothing else.
|
You have to distingiush among all the requests. For example you don't want to intercept your login request and also not the refresh token request. SwitchMap is your best friend because you need to cancel some calls to wait for your token is getting refreshed. So what you do is check first for error responses with status 401 (unauthorized): return next.handle(this.addToken(req, this.userService.getAccessToken())) .pipe(catchError(err => { if (err instanceof HttpErrorResponse) { // token is expired refresh and try again if (err.status === 401) { return this.handleUnauthorized(req, next); } // default error handler return this.handleError(err); } else { return observableThrowError(err); } })); In your handleUnauthorized function you have to refresh your token and also skip all further requests in the meantime: handleUnauthorized (req: HttpRequest<any>, next: HttpHandler): Observable<any> { if (!this.isRefreshingToken) { this.isRefreshingToken = true; // Reset here so that the following requests wait until the token // comes back from the refreshToken call. this.tokenSubject.next(null); // get a new token via userService.refreshToken return this.userService.refreshToken() .pipe(switchMap((newToken: string) => { // did we get a new token retry previous request if (newToken) { this.tokenSubject.next(newToken); return next.handle(this.addToken(req, newToken)); } // If we don't get a new token, we are in trouble so logout. this.userService.doLogout(); return observableThrowError(''); }) , catchError(error => { // If there is an exception calling 'refreshToken', bad news so logout. this.userService.doLogout(); return observableThrowError(''); }) , finalize(() => { this.isRefreshingToken = false; }) ); } else { return this.tokenSubject .pipe( filter(token => token != null) , take(1) , switchMap(token => { return next.handle(this.addToken(req, token)); }) ); } } We have an attribute on the interceptor class which checks if there is already a refresh token request running: this.isRefreshingToken = true; because you don't want to have multiple refresh request when you fire multiple unauthorized requests. So everthing within the if (!this.isRefreshingToken) part is about refreshing your token and try the previous request again. Everything which is handled in else is for all requests, in the meantime while your userService is refreshing the token, a tokenSubject gets returned and when the token is ready with this.tokenSubject.next(newToken); every skipped request will be retried. Here this article was the origin inspiration for the interceptor: https://www.intertech.com/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/ EDIT: TokenSubject is actually a Behavior Subject: tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null); , which means any new subscriber will get the current value in the stream, which would be the old token from last time we call this.tokenSubject.next(newToken) . With next(null) every new subscriber does not trigger the switchMap part, thats why filter(token => token != null) is neccessary. After this.tokenSubject.next(newToken) is called again with a new token every subscriber triggers the switchMap part with the fresh token. Hope it is more clearly now EDIT 21.09.2020 Fix link
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54327556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3466016/']}
|
jdg_371953
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
234404
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Denote by $\mathbb C^\infty $ the Hilbert space $\ell^2 (\mathbb C)$. Fix $1\leq N,M \leq \infty$, and let $U$ be an open subset of $\mathbb C^N $. Following Mujica's book "complex analysis in Banach spaces", a function $f:U\to \mathbb C ^M $ is called $holomorphic$ if for every $p \in U$ there is a bounded linear map $A:\mathbb C^N \to \mathbb C^M$ such that $\displaystyle \lim_{h\to 0} \frac{||f(p+h)-f(p)-Ah||}{||h||}=0$. In Mujica's book, theorem 8.12 says that a function $f:U\to \mathbb C^M $ is holomorphic if and only if, for every bounded linear map $\psi : \mathbb C^M \to \mathbb C$, the function $\psi \circ f$ is holomorphic. Denote $\pi_j:\mathbb C^M \to \mathbb C$ the map that to every $z\in \mathbb C^M$ associates its $j$-th component. Then $\pi_j $ is a bounded linear map, so $f^j := \pi_j \circ f$ is holomorphic for every $j$. My question is: is the converse true? I.e. is it true that if every $f^j$ is holomorphic then $f$ is holomorphic? The answer is obviously yes if $M$ is finite. I think that, if $f$ is continuous, then the answer is yes also in the infinite-dimensional case. Can we drop the continuity hypotesis? Thank you. EDIT2: I add my proof attempt of the fact that it suffices to assume $f$ continuous. So, let $f:U\to \mathbb C^\infty$ (with $U\subseteq \mathbb C^N$ and $N\leq \infty$) continuous such that, for every $j$, $f^j$ is holomorphic. Let $\psi:\mathbb C^\infty \to \mathbb C$ be a bounded linear map: then $\psi$ acts like $z\mapsto <z,u>$ for some $u\in \mathbb C^\infty$, so $f$ is holomorphic if and only if the map $z\mapsto <f(z),u> $ from $U$ to $\mathbb C$ is holomorphic for every $u\in \mathbb C^\infty$. Now, select $u\in \mathbb c^\infty$ and denote $g_n (z) = \sum _{j=1}^{n} f^j (z) \overline u^j $ and $g=\lim_n g_n $: since every $g_n $ is holomorphic because every $f^j$ is, it suffices to prove that $g_n \to g$ uniformly on compact subsets. But, if $K$ is a compact of $U$, then $\|g_n (z) -g(z)\|\leq \|<f(z),u^{>n}>\|\leq \|f(z)\|\|u^{>n}\|\leq R_K \|u^{>n}\|$ for $z\in K$, where $u^{>n}$ is the vector of $\mathbb C^\infty$ with $j$-th component equal to $0$ if $j\leq n$, and equal to $u^j$ if $j>n$, and $R_K$ is a positive constant that bounds $\|f\|$ on $K$. Since $\|u^{>n}\|\to 0$ for $n\to \infty$, by generality of $u$, we have the thesis. EDIT3: following this question , I found a counterexample in the case $N=\infty$ and $M=\infty$. Define $f:\mathbb C^\infty \to \mathbb C^\infty$ by setting $f^1 (z) = z^1$; $f^2 (z) = f^3 (z) = \frac{1}{\sqrt 2} (z^2 + z^3)$; $f^4 (z) = f^5 (z) = f^6 (z) = \frac{1}{\sqrt 3} (z^4 + z^5 + z^6)$; and so on. Then the Jacobian matrix of $f$ is the one given in this example , and does not represent a bounded linear operator. However, the question still remains unanswered for finite $N$ and infinite $M$.
Now provide the response and nothing else.
|
No. There are non-holomorphic functions $f:\mathbb D\to \ell^2$ such that all components $f_n=\pi_n\circ f$ are holomorphic. This follows from a general result of Arendt and Nikolski [Vector-valued holomorphic functions revisited. Math. Z. 234 (2000), no. 4, 777–805]: Theorem 1.5 Let $X$ be a Banach space and $W$ a subspace of $X'$ whichdoes not determine boundedness. Then there exists a function $f : \mathbb D \to X$which is not holomorphic such that $\varphi \circ f$ is holomorphic for all $\varphi\in W$. Here, a subspace $W\subseteq X'$ is said to determine boundedness if, for all subsets $B\subseteq X$, the condition $\sup\lbrace |\varphi(x)|: x\in B\rbrace <\infty$ for all $\varphi\in W$ implies that $B$ is bounded. This theorem is applied to $X=\ell^2$ and the linear span $W$ of all projections $\pi_n$. It does not determine boundedness by considering $B=\lbrace ne_n:n\in\mathbb N\rbrace$ with the unit vectors $e_n\in\ell^2$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/234404', 'https://mathoverflow.net', 'https://mathoverflow.net/users/83937/']}
|
jdg_371954
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22724883
|
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 mostly using programming languages like Scala and JavaScript. I'm trying to understand the similarities and differences in how async reactive programming is used in both languages. Can you help me? I'm not taking any particular Js Promise framework because it seems many implement the similar specifications (like Promise/A). I've only used Q so far. It seems that in Javascript we call a Deferred the object we resolve to complete a Promise .In Scala, it seems the Promise is the object you resolve to get a Future monad. Can someone tell me if this is right? Is there any good reason for a different usage of the term Promise between Js and Scala? Also, in Scala we usually chain Future monads with further computations using operators like map and flatMap (also called bind in Haskell). What is the equivalent of these in Js? I may be wrong but it appears to me that in Js the then on a Promise kind of handle both map and flatMap operators right? If so, is it possible to obtain a promise of promise of result in Js? Like we can get a Future[Future[Result]] in Scala (which can be flattened to a Future[Result] anyway). Is Js Promise a monad? It kind of seems so even if the method names do not really match those we find on monad literature.
Now provide the response and nothing else.
|
Yes, and no. While extremely similar. With JavaScript Promises that comply to the Promises/A+ spec .then is not really a monadic bind and does .map and .flatMap both. Inside a .then handler when you return a promise it will recursively unwrap it. Promise.delay(1000).then(function() { return Promise.delay(1000).then(function () { return Promise.delay(2000); }).then(function () { return Promise.delay(5000) });}).then(function () { alert("This is only shown after 8 seconds and not one");}); (fiddle) You are correct that the standard JS promise libraries and the A+ spec does not feature monadic promises. They have been discussed, and implementations like fantasy-promises exist. They follow a differnet spec and have little adoption. Also see this . There has been ongoing discussion about it in the language design discussion forum - esdiscuss and a monadic .chain method that does not flatmap and allows for monadic promises is considered but unlikely to make it. This is for pragmatic reasons. The current way promises are implemented is immensely useful. Rare are the cases you actually want a Future[Future and normally you want continuations to just work in the language. Promises 'borrow' from monads and are 'monadic' in a sense themselves. .then is very close to bind and in my head I use them interchangeably :) It is impossible to have a Promise[Promise[Value]] like a Future[Future[Value]] in Scala with most promise libraries. You'd have to wrap it in an object and have Promise[Container[Promise[Value]]] . Promise.delay(1000).then(function () { return Promise.delay(1000).then(function () { return { wrap: Promise.delay(2000).then(function () { return Promise.delay(5000); }) }; });}).then(function () { alert("This logs after 1 second"); // I've also not seen a really solid use case // except TypeScript type inference which is meh}); (fiddle) There are also a number of other smaller differences between the two, but generally you are correct in your assertions.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22724883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82609/']}
|
jdg_371955
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6589005
|
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 N eigenvalues in column vector form.Thus there are N eigenvectors corresponding to these eigenvalues, forming an eigenvector matrix. Now, the problem I am working on requires me to sort the eigenvalues column vector in descending order. How do I sort the eigenvectors matrix in the same order as their eigenvalues in order to preserve correspondence?
Now provide the response and nothing else.
|
For example, m = RandomReal[{0, 1}, {5, 5}];{evals, evecs} = Eigensystem[m];SortBy[Transpose[{evals, evecs}], First] or if you want them in the same form, replace the last line by Transpose@SortBy[Transpose[{evals, evecs}], First] EDIT: while I used {evals,evecs}=Eigensystem[m] , that's not necessary. I could just have used s=Eigensystem[m] and then used s wherever I currently have {evals,evecs} .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6589005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830469/']}
|
jdg_371956
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45112
|
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Q: how do I prevent mu4e from automatically checking mailwhen the internet's down? Problem I use mu4e and offlineimap to handle my email. When on alaptop, I have to deal with the fact that I sometimes have spottywifi connections. offlineimap freaks out when it gets calledwithout an internet connection. Problem as it relates to mu4e I have mu4e invoke offlineimap automatically every 5 minutesor so: (setq mu4e-get-mail-command "offlineimap -o" mu4e-update-interval 300) Unfortunately, that means it doesn't check if I've actually got aninternet connection. So... How do I tell mu4e not to invoke offlineimap if there's nointernet connection?
Now provide the response and nothing else.
|
Use wrapper shell script. Below please find trivial sample script checking connection status as reported by Unix/Linux NetworkManager. #!/bin/sh# exit if there is no internet connection/usr/bin/nm-online || exit /usr/bin/offlineimap -o Emacs fix (use wrapper instead of directly using offlineimap): (setq mu4e-get-mail-command "/home/me/bin/offlineimap-wrapper.sh" mu4e-update-interval 300)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/45112', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/253/']}
|
jdg_371957
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2852249
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my function: (defun MyFunction(input) (let ((NEWNUM (find input num))) (if (find input num) //if this (setq num NEWNUM) (FUNCT2) //then execute both of these (list 'not found)))) //else output this So after the if statement I want to be able to execute (setq num NEWNUM) followed by (FUNCT2) in order to set a new variable and then call a function. Any ideas on how to do this?
Now provide the response and nothing else.
|
To do several things in sequence, you want progn . (defun MyFunction(input) (let ((NEWNUM (find input num))) (if (find input num) //if this (progn (setq num NEWNUM) (FUNCT2)) //then execute both of these (list 'not found)))) //else output this
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2852249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128860/']}
|
jdg_371958
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
126897
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It is an exercise in a book on discrete mathematics.How to prove that in the decimal expansion of the quotient of two integers, eventually some block of digits repeats.For example:$\frac { 1 }{ 6 } =0.166\dot { 6 } \ldots$ and $\frac { 217 }{ 660 } =0.328787\dot { 8 } \dot { 7 } \ldots$ How to think of this?I just can't find the point to use the Pigeonhole Principle.Thanks for your help!
Now provide the response and nothing else.
|
Let's proceed to the actual division : $\begin{array} {r|l}\boxed{217}\hphantom{000\;} & 660\\\hline2170\hphantom{000} & 0.3287\\-1980\hphantom{000} & \\\boxed{190}\hphantom{00\;} & \\1900\hphantom{00} & \\-1320\hphantom{00} & \\\boxed{580}\hphantom{0\;} & \\5800\hphantom{0} & \\-5280\hphantom{0} & \\\boxed{520}\hphantom{\;} & \\5200 & \\-4620 & \\\boxed{580} & \\\end{array}$ The important point is that the remainders must be smaller than the quotient $660$ so that, after a finite number of operations, you must get $0$ or a remainder you got before. What will the next digit of the quotient be? And the next remainder? Hoping it clarified,
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/126897', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21834/']}
|
jdg_371959
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33192062
|
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 SQLAlchemy docs: nullable – If set to the default of True, indicates the column will be rendered as allowing NULL, else it’s rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements. I thought setting nullable=True for a Column basically made that Column required. For example: class Location(db.Model): __tablename__ = 'locations' id = db.Column(db.Integer, primary_key=True) latitude = db.Column(db.String(50), nullable=False) ... However, when I create a Location instance without a latitude field, I do not get an error! Python 2.7.8 (default, Oct 19 2014, 16:02:00)[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> Location(latitude=None)<app.models.Location object at 0x10dce9dd0> What is going on?
Now provide the response and nothing else.
|
The doc you reference explains the issue: This parameter is only used when issuing CREATE TABLE statements. If you originally created your database without nullable=False (or created it in some other way, separate from SQLAlchemy, without NOT NULL on that column), then your database column doesn't have that constraint information. This information lives in reference to the database column, not to a particular instance you are creating/inserting. Changing the SQLAlchemy table creation, without rebuilding your tables, means changes will not be reflected. As a link in a comment explains, SQLAlchemy is not doing the validation at that level (you would need to use the @validates decorator or some other such thing).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33192062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3624201/']}
|
jdg_371960
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12409572
|
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 started to wrap my head around it, and rather like using it for simple situations in which I can essentially pipe the values from one output to one input. A simple example of a pointfree composition I'm comfortable with would be: let joinLines = foldr (++) "" . intersperse "\n" While playing with GHCI today, I wanted to see if I could compose not and (==) to replicate (/=) , but I wasn't really able to reason it out. (==) take two inputs, and not takes one. I thought that this might work: let ne = not . (==) With the assumption that the single Bool output of (==) would go to not , but it won't compile, citing the following error: <interactive>:1:16: Couldn't match expected type `Bool' with actual type `a0 -> Bool' Expected type: a0 -> Bool Actual type: a0 -> a0 -> Bool In the second argument of `(.)', namely `(==)' In the expression: not . (==) I wish I could say it meant much to me, but all I'm getting is that maybe the second argument that's passed to (==) is mucking things up for not ? Can anybody help me understand a little better the logic behind this composition?
Now provide the response and nothing else.
|
If you start to remove one argument at the time, you get ne x y = not (x == y) = (not . (x ==)) yne x = not . (x ==) = not . ((==) x) = ((not .) . (==)) xne = (not .) . (==) basically, for every argument you need one (.) , properly associated. The type of (==) is Eq a => a -> a -> Bool . So if you write whatever . (==) , and pass a value x to that, you get whatever ((==) x) , but (==) x is a function a -> Bool (where a is the type of x , and an instance of Eq ). So the whatever must accept arguments of function type.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12409572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303940/']}
|
jdg_371961
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14341798
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two vectors, idx1 and idx2 , and I want to obtain the values between them. If idx1 and idx2 were numbers and not vectors, I could do that the following way: idx1=1;idx2=5;values=idx1:idx2 % Result % values = % % 1 2 3 4 5 But in my case, idx1 and idx2 are vectors of variable length. For example, for length=2: idx1=[5,9];idx2=[9 11]; Can I use the colon operator to directly obtain the values in between? This is, something similar to the following: values = [5 6 7 8 9 9 10 11] I know I can do idx1(1):idx2(1) and idx1(2):idx2(2) , this is, extract the values for each column separately, so if there is no other solution, I can do this with a for-loop, but maybe Matlab can do this more easily.
Now provide the response and nothing else.
|
Your sample output is not legal. A matrix cannot have rows of different length. What you can do is create a cell array using arrayfun : values = arrayfun(@colon, idx1, idx2, 'Uniform', false) To convert the resulting cell array into a vector, you can use cell2mat : values = cell2mat(values); Alternatively, if all vectors in the resulting cell array have the same length, you can construct an output matrix as follows: values = vertcat(values{:});
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14341798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508451/']}
|
jdg_371962
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9219971
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to this reddit comment thread , it is undefined if an attempt is made to read memory before it has been written to. I'm referring to normal heap memory which has been succesfully malloc ed. ... note that this is not strictly valid C: the compiler/runtime system is allowed to initialize uninitialized memory with so-called trap representations, which cause undefined behavior on access. I find this hard to believe. Is there a Standard quote? Of course, I understand that there is no guarantee that the memory has been zeroed out. The values in this uninitialized memory are essentially pseudo-random or arbitrary. But I can't really believe that the Standard would refer to this as undefined behaviour (in the sense that it might segfault, or delete all your files, or whatever). The rest of the reddit thread there didn't cast any more light on this issue.
Now provide the response and nothing else.
|
If accessing through a char* , this is defined. But otherwise, this is undefined behavior. (C99, 7.20.3.3) "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate." on indeterminate value: (C99, 3.17.2p1) "indeterminate value: either an unspecified value or a trap representation" on trap representation reading through a non-character type being undefined behavior: (C99, 6.2.6.1p5) "Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...] Such a representation is called a trap representation."
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9219971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146041/']}
|
jdg_371963
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
106325
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The Cayley projective plane can be realized as the compact homogeneous space $F_4/\mathrm{Spin}(9)$. In this way one can compute the curvature of this symmetric space in terms of a suitable orthonormal basis and the Lie brackets of the basic vectors. But is there any elegant expression for the curvature of $\mathbb{OP}^2$ which is independent of this homogeneous description due to the fact that $\mathbb{OP}^2$ is a rank one symmetric space?
Now provide the response and nothing else.
|
I'm not sure what you'll count as 'elegant' or as a 'description', but here's something you may find interesting or useful: Recall that the space of curvature tensors $\mathcal{K}(V)$ on an inner product space $V$ is essentially the kernel of the natural map $S^2\bigl(\Lambda^2(V^\ast)\bigr)\to \Lambda^4(V^\ast)$. Now let $V$ be the $16$-dimensional spin representation of $\mathrm{Spin}(9)$. It is well known (and easy to see via highest weights) that one has$$\Lambda^2(V^\ast) = \Lambda^2(W)\oplus\Lambda^3(W)$$where $W$ is the standard $9$-dimensional representation of $\mathrm{Spin}(9)$ (which, of course, factors through $\mathrm{SO}(9)$). Each of these summands is irreducible. It follows that, as $\mathrm{Spin}(9)$-representations $$S^2\bigl(\Lambda^2(V^\ast)\bigr) = S^2\bigl(\Lambda^2(W)\bigr)\oplus \bigl(\Lambda^2(W)\otimes\Lambda^3(W)\bigr) \oplus S^2\bigl(\Lambda^3(W)\bigr),$$ and hence it has two trivial summands, i.e., the space of curvature tensors fixed under $\mathrm{Spin}(9)$ has dimension $2$. (You don't lose either of these in the map to $\Lambda^4(V^\ast)$ since this latter space has no trivial summands under $\mathrm{Spin}(9)$.) These represent the Ricci curvature (the Cayley plane is an Einstein manifold) and the Weyl curvature of the Cayley plane. To get explicit formulae, you just need to make the above decomposition of $\Lambda^2(V^\ast)$ explicit. The first summand is obvious, since it is the Lie algebra of $\mathrm{Spin}(9)$, for the second, you need a model of how to see the wedge product of two elements in $V$ as the sum of a $2$-form and a $3$-form on $W$. Of course, this can be done by using the Clifford algebra, which can be studied using the octonions. I think that's probably as explicit as you can make it.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/106325', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15654/']}
|
jdg_371964
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18137662
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does this give me an error: angular.module('app') .config(function($routeProvider, $locationProvider, $httpProvider, $location) { Uncaught Error: Unknown provider: $location from app But this line doesn't? angular.module("app") .factory("SomeResource", function($q, $resource, $http, $location, AuthenticationService, Base64) { It's the same app. Can config only get providers and factory only get non-providers?
Now provide the response and nothing else.
|
Only providers and constants may be injected into configuration blocks. From the angularjs documentation on configuration blocks Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time. Essentially the configuration block is where you configure providers before they are injected into controller, services, factories and so on. angular.module('myModule', []). config(function(injectables) { // provider-injector // This is an example of config block. // You can have as many of these as you want. // You can only inject Providers (not instances) // into the config blocks. }). run(function(injectables) { // instance-injector // This is an example of a run block. // You can have as many of these as you want. // You can only inject instances (not Providers) // into the run blocks });
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18137662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61624/']}
|
jdg_371965
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
505527
|
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:
When the CPU is in user mode, the CPU can't execute privileged instructions and can't access kernel space memory. And when the CPU is in kernel mode, the CPU can execute all instructions and can access all memory. Now in Linux, a user mode program can access all memory (using /dev/mem ) and can execute the two privileged instructions IN and OUT (using iopl() I think). So a user mode program in Linux can do most things (I think most things) that can be done in kernel mode. Doesn't allowing a user mode program to have all this power defeats the purpose of having CPU modes?
Now provide the response and nothing else.
|
So a user mode program in Linux can do most things (I think most things) that can be done in kernel mode. Well, not all user mode programs can, only those with the appropriate privileges. And that's determined by the kernel. /dev/mem is protected by the usual filesystem access permissions, and the CAP_SYS_RAWIO capability. iopl() and ioperm() are also restricted through the same capability. /dev/mem can also be compiled out of the kernel altogether ( CONFIG_DEVMEM ). Doesn't allowing a user mode program to have all this power defeats the purpose of having CPU modes? Well, maybe. It depends on what you want privileged user-space processes to be able to do. User-space processes can also trash the whole hard drive if they have access to /dev/sda (or equivalent), even though that defeats the purpose of having a filesystem driver to handle storage access. (Then there's also the fact that iopl() works by utilizing the CPU privilege modes on i386, so it can't well be said to defeat their purpose.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/505527', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/341099/']}
|
jdg_371966
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9954937
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two questions concerning @JoinFormula and @OneToMany annotations: How can I limit the number of result with @JoinFormula and @OneToMany annotations? How can I define that id in expression author = id refers to Author.id ? Author { @Id private Long id; @OneToMany @JoinFormula(value = "SELECT a FROM Article a WHERE author = id AND schedule < CURRENT_TIMESTAMP()") // limit = 15 private List<Article> pastArticles;} Like this, I keep having the pastArticles empty, even when I remove the schedule < part of the clause. Thanks!
Now provide the response and nothing else.
|
Answer 1 : @Size(max=10)private List<Comment> commentList; Answer 2 :(just example like that) public class A{ @Id @GeneratedValue private Integer id; private String uuid; ... } other class public class B{ @Id @GeneratedValue private Integer id; private String uuidOfA; @ManyToOne @JoinColumnsOrFormulas({ @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id FROM A a WHERE a.uuid = uuid)", referencedColumnName="id")), @JoinColumnOrFormula(column = @JoinColumn("uuidOfA", referencedColumnName="uuid"))}) private A a; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9954937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/922584/']}
|
jdg_371967
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20927368
|
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 calculated a confusion matrix for my classifier using confusion_matrix() from scikit-learn. The diagonal elements of the confusion matrix represent the number of points for which the predicted label is equal to the true label, while off-diagonal elements are those that are mislabeled by the classifier. I would like to normalize my confusion matrix so that it contains only numbers between 0 and 1. I would like to read the percentage of correctly classified samples from the matrix. I found several methods how to normalize a matrix (row and column normalization) but I don't know much about maths and am not sure if this is the correct approach.
Now provide the response and nothing else.
|
I'm assuming that M[i,j] stands for Element of real class i was classified as j . If its the other way around you are going to need to transpose everything I say. I'm also going to use the following matrix for concrete examples: 1 2 34 5 67 8 9 There are essentially two things you can do: Finding how each class has been classified The first thing you can ask is what percentage of elements of real class i here classified as each class. To do so, we take a row fixing the i and divide each element by the sum of the elements in the row. In our example, objects from class 2 are classified as class 1 4 times, are classified correctly as class 2 5 times and are classified as class 3 6 times. To find the percentages we just divide everything by the sum 4 + 5 + 6 = 15 4/15 of the class 2 objects are classified as class 15/15 of the class 2 objects are classified as class 26/15 of the class 2 objects are classified as class 3 Finding what classes are responsible for each classification The second thing you can do is to look at each result from your classifier and ask how many of those results originate from each real class. Its going to be similar to the other case but with columns instead of rows. In our example, our classifier returns "1" 1 time when the original class is 1, 4 times when the original class is 2 and 7 times when the original class is 3. To find the percentages we divide by the sum 1 + 4 + 7 = 12 1/12 of the objects classified as class 1 were from class 14/12 of the objects classified as class 1 were from class 27/12 of the objects classified as class 1 were from class 3 -- Of course, both the methods I gave only apply to single row column at a time and I'm not sure if it would be a good idea to actually modify your confusion matrix in this form. However, this should give the percentages you are looking for.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20927368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1372560/']}
|
jdg_371968
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
127579
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.For instance, the Wikipedia example : public class TestAdder { public void testSum() { Adder adder = new AdderImpl(); assert(adder.add(1, 1) == 2); assert(adder.add(1, 2) == 3); assert(adder.add(2, 2) == 4); assert(adder.add(0, 0) == 0); assert(adder.add(-1, -2) == -3); assert(adder.add(-1, 1) == 0); assert(adder.add(1234, 988) == 2222); }} I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be assert(adder.add(a, b) == (a+b)); but then this is just coding the function itself in the test.Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)
Now provide the response and nothing else.
|
Unit tests, if you're testing small enough units, are always asserting the blindingly obvious. The reason that add(x, y) even gets mention of a unit test, is because sometime later somebody will go into add and put special tax logic handling code not realizing that add is used everywhere. Unit tests are very much about the associative principle: if A does B, and B does C, then A does C. "A does C" is a higher-level test. For instance, consider the following, completely legitimate business code: public void LoginUser (string username, string password) { var user = db.FetchUser (username); if (user.Password != password) throw new Exception ("invalid password"); var roles = db.FetchRoles (user); if (! roles.Contains ("member")) throw new Exception ("not a member"); Session["user"] = user;} At first glance this looks like an awesome method to unit test, because it has a very clear purpose. However, it does about 5 different things. Each thing has a valid and invalid case, and will make a huge permutation of unit tests. Ideally this is broken down further: public void LoginUser (string username, string password) { var user = _userRepo.FetchValidUser (username, password); _rolesRepo.CheckUserForRole (user, "member"); _localStorage.StoreValue ("user", user);} Now we're down to units. One unit test does not care what _userRepo considers valid behavior for FetchValidUser , only that it's called. You can use another test to ensure exactly what a valid user constitutes. Similarly for CheckUserForRole ... you've decoupled your test from knowing what the Role structure looks like. You've also decoupled your entire program from being tied strictly to Session . I imagine all the missing pieces here would look like: class UserRepository : IUserRepository{ public User FetchValidUser (string username, string password) { var user = db.FetchUser (username); if (user.Password != password) throw new Exception ("invalid password"); return user; }}class RoleRepository : IRoleRepository{ public void CheckUserForRole (User user, string role) { var roles = db.FetchRoles (user); if (! roles.Contains (role)) throw new Exception ("not a member"); }}class SessionStorage : ILocalStorage{ public void StoreValue (string key, object value) { Session[key] = value; }} By refactoring you have accomplished several things at once. The program is way more supportive of tearing out underlying structures (you can ditch the database layer for NoSQL), or seamlessly adding locking once you realize Session isn't thread-safe or whatever. You've also now given yourself very straightfoward tests to write for these three dependencies. Hope this helps :)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/127579', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/44000/']}
|
jdg_371969
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
86560
|
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 user defined function which takes multidimensional input, e.g a function that takes two algebraic variables a and b as well as a matrix m and computes some rule function as: f[a_,b_,m_] := {a :> m[[1,1]]*a + m[[2,1]]*b, b :> m[[1,2]]*a + m[[2,2]]*b} Now if I had a similar function over just single variables, e.g g[a,b,c,d] I could perform said function using the syntax g @@ vec where vec = {a,b,c,d} . What I would like achieve is something like: v = {a,b}m = {{p,q},{r,s}}f @@ {v,m} but doing so produces f[{a, b}, {{p, q}, {r, s}}] since the braces encompassing the {a,b} variable have been retained. This problem also occurs for the use of Slot , producing identical output for f[#1,#2] &[v,m] and even just f[#, m] &[v] . Neither Join[v,m] or Catenate[{v,m}] produce a useful list to apply. How can pass a function a list and then a matrix and have it evaluated in the correct manner?
Now provide the response and nothing else.
|
[Edit notice: Updated to allow the setting of the vertical direction of the plot and to fix an error.] Here is a slight generalization of my answer to Isometric 3d Plot . To get an isometric view, we need to construct a ViewMatrix that will rotate a vector of the form {±1, ±1, ±1} to {0, 0, 1} and project orthogonally onto the first two coordinates. ClearAll[isometricView];isometricView[ g_Graphics3D, (* needed only for PlotRange *) v_ /; Equal @@ Abs[N@v] && 1. + v[[1]] != 1., (* view point {±1, ±1, ±1} *) vert_: {0, 0, 1}] := (* like ViewVertical; default: z-axis *) {TransformationMatrix[ RescalingTransform[ EuclideanDistance @@ Transpose[Charting`get3DPlotRange@ g] {{-1/2, 1/2}, {-1/2, 1/2}, {-1/2, 1/2}}]. RotationTransform[{-v, {0, 0, 1}}]. RotationTransform[{vert - Projection[vert, v], {0, 0, 1} - Projection[{0, 0, 1}, v]}]. RotationTransform[Mod[ArcTan @@ Most[v], Pi], v]. TranslationTransform[-Mean /@ (Charting`get3DPlotRange@ g)]], {{0, 1, 0, 0}, {1, 0, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}};foo = Graphics3D[Cuboid[{-.5, -.5, -.5}, {1., 2., 4}]];Show[foo, ViewMatrix -> isometricView[foo, {1, 1, 1}, {0, 0, 1}], ImagePadding -> 20, Axes -> True, AxesLabel -> {x, y, z}]Show[foo, ViewMatrix -> isometricView[foo, {-1, 1, 1}, {1, 1, 0}], ImagePadding -> 20, Axes -> True, AxesLabel -> {x, y, z}] All combinations of viewpoints and vertical axes: Notes: Getting an accurate plot range that includes the padding is important to computing the correct view matrix. There are alternatives to the undocumented internal function Charting`get3DPlotRange .Alexey Popkov has a method here: How to get the real PlotRange using AbsoluteOptions? I used PlotRange /. AbsolutOptions[g, PlotRange] and multiplied by 1.02 (I don't recall why not something like 1.04 ) to approximate the padding in my answer to Isometric 3d Plot . My go-to resource for understanding ViewMatrix has been especially Heike's answer to Extract values for ViewMatrix from a Graphics3D . This update is in response to Yves' comment. Working with the axes made me realize that the coordinate system is flipped (from "right-handed" to "left-handed). Hence I changed the projection from IdentityMatrix[4] to one that flips the x & y coordinates. It might be a good idea to Deploy the graphics to prevent rotation by the mouse. When the graphics are rotated, the front end resets the ViewMatrix in a rather ugly way.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/86560', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26807/']}
|
jdg_371970
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2567133
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working with the following piece; def index @user = User.find(params[:id]) rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') else flash[:notice] = "OK" redirect_to(:action => 'index')end Now I either case whether I have a correct ID or not, I am always getting "OK" in my view, what am I doing wrong? I need that when I have no ID in the DB to show "ERROR". I have also tried to use rescue ActiveRecord::RecordNotFound but same happens. All help is appreciated.
Now provide the response and nothing else.
|
All code after the end of the rescue block is interpreted only if there are no returns in the rescue block. So you can call return at the end of your rescue block. def index begin @user = User.find(params[:id]) rescue flash[:notice] = "ERROR" redirect_to(:action => 'index') return end flash[:notice] = "OK" redirect_to(:action => 'index')end or def index @user = User.find(params[:id]) # after is interpret only if no exception before flash[:notice] = "OK" redirect_to(:action => 'index')rescue flash[:notice] = "ERROR" redirect_to(:action => 'index')end But in your case the better is to use rescue_from or rescue_in_public like class UserController < ApplicationController def rescue_in_public(exception) flash[:notice] = "ERROR" redirect_to(:action => 'index') end def index @user = User.find(params[:id]) flash[:notice] = "OK" redirect_to(:action => 'index') endend But the using of rescue_in_public is not really good advice
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2567133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/222159/']}
|
jdg_371971
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3421606
|
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 come from a c++ background and I find myself constantly doing this in java: SomeClass sc=new SomeClass();if(null!=sc){ sc.doSomething();} What I want to know is what will be in the variable sc if the constructor fails for some reason (like maybe not enough memory). I can't find a straight answer, and I am worried that I am just wasting my time because maybe if the new operator fails would the program just crash anyway?
Now provide the response and nothing else.
|
The Java Specification Language 3rd Edition covers your question thoroughly: 12.5 Creation of New Class Instances Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError . Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure: [...] So it's simply not possible for a new expression to return null . Whatever is returned, if the execution completes normally, will always be a valid instanceof whatever class was instantiated. Handling exceptions Generally speaking, possible exceptions are usually handled with a try-catch block: String someString = askFromUser();try { int num = Integer.parseInt(someString); doSomethingWith(num);} catch (NumberFormatException e) { complainAboutIt();} In your case, you may consider putting new SomeClass() in a try block with a corresponding catch (OutOfMemoryError e) , but this is highly atypical. Unless you plan to do something meaningful when this happens, in most typical scenarios it's best to not catch any Error that may occur during your program execution. From the documentation: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch . Most such errors are abnormal conditions. A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. Related questions Catching java.lang.OutOfMemoryError When to catch java.lang.Error? Is it possible to catch out of memory exception in java? Can the JVM recover from an OutOfMemoryError without a restart How to handle OutOfMemoryError in Java? See also Java Tutorials/Exceptions
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3421606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/412723/']}
|
jdg_371972
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
128597
|
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:
In Wolfram Workbench it used to be possible to generate HTML Documentation pages. Now when I build, using Mathematica 10.4+ and Workbench 2 or 3 on Windows 8.1, the HTML build fails (the notebook documentation build still works). The error I receive in the AntLog is: *** Output file test failed *** . Which means that the HTML files are not Exported. Tracing a bit further in ExportDocumentation I found the function Transmogrify , which should have exported the HTML but does not.
Now provide the response and nothing else.
|
Partial Solution Wolfram Workbench 2 and 3 are not able to launch the front end (Mathematica 10+) to create the final HTML. The solution is to use the new (Eclipse-plugin) version, downloadable from: https://www.wolfram.com/workbench/ . Which is also free when you have purchased a Mathematica license. Some issues with the HTML edit: I took the time to document the steps bellow in more detail here . I encountered some issues with the generated HTML (my best guess is that the HTML for local viewing, as Wolfram is calling it, is not updated). Not sure if I fixed this in the right place, so please if you have a better solution let me know. These fixes should be done in the in fonts.css (either in the minimal or standard folder) the font SourceSansPro-Semibold.woff seems to have an incorrect path replace all: /fonts/sourcesanspro/v8/fonts/SourceSansPro with /fonts/sourcesanspro/v8/SourceSansPro the folder: images/mathematicaIncludes does not seem to be copied for local viewing. It is not possible to click to code to copy (like on the Mathematica site). Change the jquery version to 1.7.2 (already in the export), and add the clipboards.js from Wolfram: http://reference.wolfram.com/2013/javascript/clipboard.js , The styling can be fixed by: http://reference.wolfram.com/2013/css/clipboard.css . Don't forget to also include the two images: http://reference.wolfram.com/2013/images/clipboard@2x.png and http://reference.wolfram.com/2013/images/check-mark@2x.png The collapsed pages (like Scope and options) do not show the code sniplets but the text Click code to copy . Apparently the sub-pages.js is outdated, i looked up which they used on their site: http://reference.wolfram.com/2013/javascript/sub-pages.js . This fixes the problem. Links on the top right corner (see also) relative path is not correct, leading to a dead page.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/128597', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/40756/']}
|
jdg_371973
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
232670
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am learning Fritzing, and looking to create my first pcb. The components are fairly simple: 10x DS18B20, 1x resistor, 1x Konekt Dash. I plan to have headers to connect the Dash so it can be easily removed. When it comes to connecting the 10x temp sensors, I do not know where to start with choosing a connector. The prototype that I have up and running uses a full size breadboard where I used 3.5mm screw terminal blocks for each of the 3 wires for the temp sensors. Lots of wasted space... How do you go about choosing a connector to maximize space used but ensure it is a simple choice when it comes time to solder to the board and wire up the sensors?
Now provide the response and nothing else.
|
Connectors often seem the hardest choice. If this is for maker or small volumes, I would use something simple, cheap, and easy to get. I like 0.1inch (0.1") pitch, through-hole header pins and sockets. An advantage of using 0.1" pitch is it's easy to make adapters to both attach cabled devices and also plug into breadboard. So, in your example, you could wire and test your sensors on the existing breadboard or make simple test rigs using stripboard. Invest in a (modest cost) crimp tool. Then put all of your sensors on crimped connectors. There are an astronomical number of different connectors. I'd suggest looking at a low cost supplier, with a smaller range like rapidonline . I reason that the stuff they carry is popular, and its easier to see the costs of connectors, crimps and lower-cost crimp tools. If you use one of the well known, popular, brands (e.g. Molex KK , but there are alternatives and compatible parts) you'll be able to get the connectors from almost any distributer. You could go for lowest-possible cost 0.1inch pitch pin headers , which can be bought from internet sales sites at quite a low cost (estimate under 0.02 GBP per pin or less). Each wire crimp will be a similar cost, and then the connector socket. However, it is worth using the more expensive connectors which have polarised connections (extra pieces of plastic which prevent the plug and socket being connected the wrong way round). These reduce the ways that connections can go wrong by plugging in the wrong way round, or shifted sideways. Further, the extra plastic gives a little extra protection from accidentally shorting connections. These types of connectors aren't as flexible as screw-terminals, but can be much more compact. They come in vertical orientated so many connectors can be packed closely, like servos into a radio control receiver. They are also available in right-angle so they can be arranged around a PCBs edge, and made accessible through the walls of a case. Edit: Another consideration is footprints for PCBs. For example, Eagle PCB CAD has libraries of 0.1" pitch connectors, that have been tried and tested, so you won't have to spend time designing footprints. Further, Sparkfun have a useful library which slightly offsets the PCBs holes from an 0.1" grid. The effect is to 'grip' the pins in the PCB while it is being soldered. AFAICT, this took them several iterations to get right. So by using a popular connector you may get some extra unforeseen benefits. Edit2: Most of these simple plug and socket systems come in many sizes For example Molex KK headers, sockets and receptacles are available in 2pin to 36pin connectors. Another small advantage of using a 0.1" pitch system is you can make a prototype connection on a PCB, veroboard, or breadboard using ordinary 0.1" strip header (which can be broken down to any size) without having the correct pin-size housing to hand. It's feasible to make the wire connectors from a combination of housings because the crimp connector housings stack side-by-side on a 0.1" pitch. So you could make a temporary 5-pin connector using a 2-pin and a 3-pin connector housing. Also it's possible to disassemble a connector by removing the crimped connections from the housing. So it's feasible to alter the sequence of connections in a housing, add or remove connections, and repair connectors. It's handy technology.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/232670', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8301/']}
|
jdg_371974
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
715254
|
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:
Imagine we have the first Maxwell Equation: $$\nabla \cdot \mathbf E = \frac{\rho}{\varepsilon_0} \\\mathbf E = -\nabla \phi \\\nabla \cdot (-\nabla\phi) = \frac{\rho}{\varepsilon_0} \\\nabla^2 \phi = -\frac{\rho}{\varepsilon_0}$$ We arrive to an equation for finding the potential of an Electric field, given a charge density, $\rho$ . Assuming that: $\phi$ and $\rho$ only depends on the $\mathbf r$ , coordinate, we have the following: $$\nabla^2 \phi = \frac{\partial^2 \phi}{\partial r^2} + \frac{1}{r} \frac{\partial \phi}{\partial r} = \frac{\rho(r)}{\varepsilon_0}$$ For zero charge density we have the following: $$\frac{\partial \phi}{\partial r} \equiv u(r)\\0 = u'(r) + \frac{u(r)}{r} \rightarrow u'(r) = - \frac{u(r)}{r} \\\frac{du}{u} = -\frac{dr}{r} \rightarrow u(r) = \frac{C_1}{r} \\\phi(r) = C_1\log(r) + \phi_0$$ But, this mean there exists a potential. I don't quite understand this because there is not charge density, hence, no electric field. But how is there an electric potential, did I derive it wrong?
Now provide the response and nothing else.
|
You can have a non-zero potential -- as long as it is constant in space. This will always generate a zero electric field, since in this case $\mathbf{E} = -\nabla\phi = 0$ , which is indeed expected for a zero charge density. Mathematically, you could notice that since the point $r=0$ is part of your domain, you must have $C_1 = 0$ to avoid divergences in the potential. This generates $\phi = \phi_0$ , i.e., a constant potential, as expected. EDIT: As jensen paull said, you have the wrong Laplacian operator for spherical coordinates, making your final solution wrong. Nevertheless, as the correct solution is $\phi = C_1/r + \phi_0$ , the above analysis still hold.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/715254', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/281431/']}
|
jdg_371975
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48399741
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My component has: class Search extends Component { constructor(props) { super(props); this.state = { searchTerm: typeof this.props.match.params.searchTerm !== "undefined" ? this.props.match.params.searchTerm : "" }; } and the test is: test("Search should render correct amount of shows", () => { const component = shallow(<Search shows={preload.shows} />); expect(component.find(ShowCard).length).toEqual(preload.shows.length);}); I get TypeError: Cannot read property 'params' of undefined How can I fix that or how to set query params in my test?
Now provide the response and nothing else.
|
It seems like when outside the test, the Search component receives the match props correctly. You could pass it as props when shallow rendering it in the test: test("Search should render correct amount of shows", () => { const match = { params: { searchTerm: 'foo' } } const component = shallow(<Search shows={preload.shows} match={match}/>); expect(component.find(ShowCard).length).toEqual(preload.shows.length);}); And in that case, you're not changing the component under test in a bad way, your test case just found a bug, which is good and should be aimed in tests, and you improved the component by implementing a default props, making it more robust.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48399741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7866671/']}
|
jdg_371976
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12259622
|
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 going to start the new question. I posed the question yesterday and wanted to know what's the problem in my program. The program is given below and you people pointed out that this following program does only one pass of the sorting and needs an outer loop as well. At that time I was good like OK. But again when I looked the program I got confused and need to ask Why we need Outer loop as well for the sort since only a single loop can do the sorting(In my opinion). First see program below then I present my logic at the end of the program. #include <iostream.h>#include <conio.h>using namespace std;main(){ int number[10]; int temp = 0; int i = 0; cout << "Please enter any ten numbers to sort one by one: " << "\n"; for (i = 0; i < 10; i++) { cin >> number[i]; } i = 0; for (i = 0; i < 9; i++) { if (number[i] > number[i + 1]) { temp = number[i + 1]; number[i + 1] = number[i]; number[i] = temp; } } i = 0; cout << "The sorted numbers are given below:" << "\n"; for (i = 0; i < 10; i++) { cout << number[i] << "\n"; } getch();} I think the ONLY loop with the bubble condition should do the sorting. Look at the following loop of the program: for (i=0;i<9;i++)if(number[i]>number[i+1]){ temp=number[i+1]; number[i+1]=number[i]; number[i]=temp;} Now I explain what I am thinking what this loop "should" do. It will first compare number[0] with number[1]. If the condition is satisfied it will do what is in IF statement's body. Then i will be incremented by 1(i++). Then on next iteration the values compared will be number[1] with number[2]. Then why it does not happen and the loop exits after only pass? In other words may be I'm trying to ask IF statement does not repeat itself in for loop? In my opinion it does. I'm very thankful for help and views, my question might be of small level but that is how I will progress.
Now provide the response and nothing else.
|
Let me give you an example let's only take 3 numbers. So you input 13, 3 ,1 Now you start sorting how you did it. so it compares 13 and 3 13 > 3 so switch both of them.now we have. 3, 13, 1 Now it'll compare as you said the next pair = 13 and 1 13 > 1 so the new order would be 3, 1, 13 now your loop is finished and you missed to compare 3 and 1Actually the first loop only sorts the greatest number!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12259622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1643568/']}
|
jdg_371977
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3812669
|
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 run a simple code for web crawler written in this page . every thing is fine and I tried the program on several sites and it works fine but there is one site instead of returning the html content in its pages it generates a srtange error : DotNetNuke Error: - Version 04.05.01 Return to main page and the html returned is : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en-US"><head> <title id="Title">Error</title> <link id="StyleSheet" href="/Install/Install.css" type="text/css" rel="stylesheet"></link></head><body> <form name="Form" method="post" action="ErrorPage.aspx?tabid=186&error=Object+reference+not+set+to+an+instance+of+an+object.&content=0&language=ar-SY" id="Form"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNTkzNjY2ODU2D2QWBAIDDxYCHgRocmVmBRQvSW5zdGFsbC9JbnN0YWxsLmNzc2QCBQ9kFgICAg8PFgIeBFRleHQFRDxpbWcgc3JjPSIvaW1hZ2VzL2x0LmdpZiIgYm9yZGVyPSIwIiAvPiDYsdis2YjYuSDYp9mE2Ykg2KfZhNmF2YjZgti5ZGRk2aDp+vZbUIDHSd3beGBaLQrJ6yk=" /> <table cellspacing="5" cellpadding="5" border="0" class="Error"> <tr> <td><img id="Image1" src="logo.gif" alt="DotNetNuke" border="0" /></td> </tr> <tr style="height:100%;"> <td valign="top" style="width:650px;"> <h2>DotNetNuke Error: - Version 04.05.01</h2> <hr /> <p><table border="0" cellspacing="0" cellpadding="4"> <tr> <td valign="top" align="left"><img id="ctl00_imgIcon" src="images/red-error.gif" border="0" /></td> <td valign="middle" align="left"><span id="ctl00_lblHeading" class="NormalRed">an error has been occurred<br/></span><span id="ctl00_lblMessage" class="Normal">return to the site.</span></td> </tr></table><hr noshade size="1"/></p> </td> </tr> <tr> <td align="right"><a id="hypReturn" class="WizardButton" href="Default.aspx"><img src="/images/lt.gif" border="0" /> return to the site</a></td> </tr> <tr><td height="10px"></td></tr> </table> </form></body></html> so what is DotNetNuke Error and what is the problem...BTW the error occurred in an Arabian site and I tried on another Arabian sites and there were no errors.
Now provide the response and nothing else.
|
Well the best way to do this is to create the associated record when you create the primary one: class User < ActiveRecord::Base has_one :preference_set, :autosave => true before_create :build_preference_setend That will set it up so whenever a User is created, so is a PreferenceSet . If you need to initialise the the associated record with arguments, then call a different method in before_create which calls build_preference_set(:my_options => "here") and then returns true . You can then just normalise all existing records by iterating over any that don't have a PreferenceSet and building one by calling #create_preference_set . If you want to only create the PreferenceSet when it is absolutely needed, then you can do something like: class User < ActiveRecord::Base has_one :preference_set def preference_set_with_initialize preference_set_without_initialize || build_preference_set end alias_method_chain :preference_set, :initializeend
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3812669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396744/']}
|
jdg_371978
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2734690
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the Generating Function from the sequence (0,1,0,3,0,5,...) I can't conceptualize this one and I know it should be easy because it is just odds, but I am having a hard time figuring out how to cancel the even terms. I was thinking like k$x^k$ but that doesn't cancel the evens. Any help would be much appreciated.
Now provide the response and nothing else.
|
$G(x)=x+3x^3+5x^5+...=x(1+3x^2+5x^4+...)= xF'(x),$where $$F(x)=x+x^3+x^5+...=\frac{x}{1-x^2}$$I'm sure you can finish from here.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2734690', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/528887/']}
|
jdg_371979
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9924029
|
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 this, and experimenting with a Django site that has both a main folder and a static media folder. I'm trying to install django-bootstrap, but not sure how to go about it. I'm using the instructions in this Django Bootstrap page . First, do I run pip install -e git+git://github.com/earle/django-bootstrap.git#egg=bootstrap from the terminal in the main folder, or static media folder? Second, where do I insert the usage code? from bootstrap.forms import BootstrapForm, Fieldsetclass LoginForm(BootstrapForm): class Meta: layout = ( Fieldset("Please Login", "username", "password", ), ) username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(), max_length=100) The above is obviously only for login fields, but will I need to include that import language in many files, or just one main one? EDIT for clarity: My host is WebFaction, which uses a Domain + Webapp = Website structure for site hosting. One of their recommended methods for Django installs is to set up the main Django site in one webapp, and a static media folder in another: see here for details. I am not the site creator or installer, but have copied the site over into a test version so I can mess with its design while the programmer is unavailable for an extended period. I'm looking into Django Bootstrap as a way to make it easier to redesign the site. My skills are obviously limited, but I'm willing to read/learn!
Now provide the response and nothing else.
|
Django-bootstrap is a Django "app", installed as a python package. Since webfaction doesn't do virtualenv, you should be ok* to just ssh in and run pip install -e git+git://github.com/earle/django-bootstrap.git#egg=bootstrap from wherever. This will install django-bootstrap to your global python site-packages folder. Next, you'll need to make sure django knows about it, which you do by editing the settings file and adding it to INSTALLED_APPS, e.g. INSTALLED_APPS = (# ... other things'bootstrap',# ... maybe more things) Any python file that uses the BootstrapForm and Fieldset classes, will require the import statement at the top of it. A python module (file) will only know about a) what you declare directly in it, and b) what you explicitly import. I don't know how you got anywhere using python without knowing that, because it's pretty important. Consider reading up on the subject.* Anyhow, the only thing django-bootstrap seems to do is change django's form-rendering code to output HTML that is more compatible with Bootstrap. You will still need get twitter-bootstrap yourself, and make sure that you use the media, i.e. the css, js and images, from it. Put the bootstrap media in your static app. http://twitter.github.com/bootstrap/ *Edit: I just read the last bit of your post and now I feel like a big meanie. So, here are some extra resources that I recommend you read through. Python samples: http://wiki.python.org/moin/SimplePrograms Django's Tutorial: https://docs.djangoproject.com/en/1.3/intro/tutorial01/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9924029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/918216/']}
|
jdg_371980
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
359757
|
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How we handle plagiarism has been on my mind for a while and I feel that the way we do things at the moment seems to be less than optimal. Plagiarised posts seem to get left on the site for too long. With plagiarism there are two goals: Get the information copied from elsewhere either properly attributed or deleted. Stop people plagiarising. The first goal is relatively easy to achieve. If you find a plagiarised post check the licencing on the source and if it allows copying with attribution just edit the reference link into the post. That's it. There's nothing more you need to do. If the licence doesn't allow copying with attribution then flag the post so that we can delete it. In the past I have said that it's the copyright owners responsibility to request that copied material be taken down, but plagiarism is different to a copied image (for example) and needs to be dealt with as soon as it's found. If you discover that the same user has plagiarised more than this one post then raise a flag as the moderators can then determine whether there's anything more we need to do. One concern has been that when a plagiarised post garners sufficient up-votes the user gets to "keep" the reputation if the post is eventually deleted. However, our goal as moderators is to stop the plagiarism. Hopefully we can do this with a comment on the post or, in more serious cases, a moderator message. If they reform, the fact that the user gets to keep some "ill-gotten" reputation is really a side issue. However, if steps fail and the user continues to plagiarise then we can take more drastic action by suspending the user or even deleting their account. In cases where all, or nearly all, of a users posts are plagiarised then we should probably be deleting their account pretty much straight away. They are clearly not interested in participating in our community. What I'd like to ensure is that these things happen as efficiently as possible with the minimum number of flags being raised. So, is what I propose workable?
Now provide the response and nothing else.
|
Personally, I don't think we should place the burden on anyone other than the post author to check licensing terms before using off-site material. The handful of us who serve as moderators have too much on our plates, already, and so do those members who are active (and competent) in the review queues. If something is plagiarized, my personal practice is to delete it immediately, without wasting time looking for copyright notices and terms of use. If a user edits in proper attribution later, I will consider undeleting the post. A Counterproposal My experience is that users who plagiarize once tend to do it nearly all the time. So, when we find a user with one plagiarized post, odds are that nearly all of their other material --- whether that's 1 other post or 100 --- is also plagiarized. Plagiarism is easy, so it's fairly common to find dozens of plagiarized posts by a single author. The solution I would like to see is an automated plagiarism-checker in the mod tools. It wouldn't need to run on every post on the site, which would be overwhelming. Rather, it would look like this: User flags post as plagiarized by user 1337ContentThief. Mod handles flag and sees that the post really is plagiarized. Mod clicks a link (just like others in the mod tools) labeled "plagiarism check". SO servers queue up a task for each of 1337ContentThief's posts. For each post: 2-3 sample phrases are checked against a major search engine. Any exact matches result in the system raising an automatic flag for further investigation, with a link to the search engine results . Any user with 3+ hits also gets flagged as a serial plagiarist. In the event of user deletion/destruction, all of these flags would just be automatically marked as helpful. In this world, when a mod sees a true, serial plagiarist, the default action would just be "nuke from orbit." I agree 100% with this statement: In cases where all, or nearly all, of a users posts are plagiarised then we should probably be deleting their account pretty much straight away. They are clearly not interested in participating in our community. I think automating all of this investigation would allow us to get rid of these non-productive users (and their misappropriated content) very quickly. This could, in theory, also be done via scripting (i.e., the mods doing it for ourselves), but it would be better and more reliable if SO sanctioned it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/359757', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/59303/']}
|
jdg_371981
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33321751
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering how can a function issue a compile-time warning? This came to my mind because when we supply wrong format specifier in the first argument of printf (scanf) for the variable matched with that type specifier and compile with gcc with -Wall option on, compiler issues a warning. Now, printf and scanf are regularly implemented variadic functions as I understand and I dont know any way to check the value of the string at the compile-time, let alone issue a warning if something doesnt match. Can someone explain me how I get compiler warning then?
Now provide the response and nothing else.
|
Warnings are implementation (i.e. compiler & C standard library ) specific. You could have a compiler giving very few warnings (look into tinycc ...), or even none... I'm focusing on a recent GCC (e.g. 4.9 or 10 ...) on Linux. You are getting such warnings, because printf is declared with the appropriate __attribute__ (see GCC function attributes ) (With GCC you can likewise declare your own printf -like functions with the format attribute...) BTW, a standard conforming compiler is free to implement very specially the <stdio.h> header. So it could process #include <stdio.h> without reading any header file but by changing its internal state. And you could even add your own function attributes, e.g. by customizing your GCC with your GCC plugin
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33321751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1635881/']}
|
jdg_371982
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9582320
|
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 one has confused me a little... Attempting to dispose of an XmlReader XmlReader reader = XmlReader.Create(filePath);reader.Dispose(); Provides the following error: 'System.Xml.XmlReader.Dispose(bool)' is inaccessible due to its protection level however the following is fine: using(XmlReader reader = XmlReader.Create(filePath)){} When I look at the definition in Reflector I can't understand why I can't call Dispose Implementation of Dispose: Can anyone point out what I'm missing?
Now provide the response and nothing else.
|
The problem is that XmlReader uses explicit interface implementation to implement IDisposable . So you can write: XmlReader reader = XmlReader.Create(filePath);((IDisposable)reader).Dispose(); However, I'd strongly suggest using a using statement anyway. It should be very rare that you call Dispose explicitly, other than within another Dispose implementation. EDIT: As noted, this is "fixed" in .NET 4.5, in that it exposes a public parameterless Dispose method as of .NET 4.5 as well as the explicit interface implementation. So presumably you're compiling against .NET 4.0 or earlier (perhaps .NET 2.0 given your tags) but using Reflector against .NET 4.5?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9582320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21061/']}
|
jdg_371983
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10814481
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting the following error: events.js:48 throw arguments[1]; // Unhandled 'error' event ^Error: socket hang up at createHangUpError (http.js:1091:15) at Socket.onend (http.js:1154:27) at TCP.onread (net.js:363:26) In node v0.6.6, my code has multiple http.request and .get calls.Please suggest ways to track what causes the socket hang up, and on which request/call it is.Thank you
Now provide the response and nothing else.
|
Quick and dirty solution for development : Use longjohn , you get long stack traces that will contain the async operations. Clean and correct solution :Technically, in node, whenever you emit an 'error' event and no one listens to it, it will throw . To make it not throw, put a listener on it and handle it yourself. That way you can log the error with more information. To have one listener for a group of calls you can use domains and also catch other errors on runtime. Make sure each async operation related to http(Server/Client) is in different domain context comparing to the other parts of the code, the domain will automatically listen to the error events and will propagate it to it's own handler. So you only listen to that handler and get the error data. You also get more information for free. (Domains are depreceated). As Mike suggested you can also set NODE_DEBUG=net or use strace . They both provide you what is node doing internally.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10814481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971956/']}
|
jdg_371984
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
378330
|
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 C# winforms app, I have a datagrid. When the datagrid reloads, I want to set the scrollbar back to where the user had it set. How can I do this? EDIT: I'm using the old winforms DataGrid control, not the newer DataGridView
Now provide the response and nothing else.
|
You don't actually interact directly with the scrollbar, rather you set the FirstDisplayedScrollingRowIndex . So before it reloads, capture that index, once it's reloaded, reset it to that index. EDIT: Good point in the comment. If you're using a DataGridView then this will work. If you're using the old DataGrid then the easiest way to do that is to inherit from it. See here: Linkage The DataGrid has a protected GridVScrolled method that can be used to scroll the grid to a specific row. To use it, derive a new grid from the DataGrid and add a ScrollToRow method. C# code public void ScrollToRow(int theRow){ // // Expose the protected GridVScrolled method allowing you // to programmatically scroll the grid to a particular row. // if (DataSource != null) { GridVScrolled(this, new ScrollEventArgs(ScrollEventType.LargeIncrement, theRow)); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/378330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3047/']}
|
jdg_371985
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31460347
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a standalone map to test this out for myself. I took a heap snapshot, using Chrome Developer Tools, of the page upon loading it and found it was using 882MB of memory. I'm looking to plot about an hours worth of lightning data and I would like for the user to be able to interact with it so Openlayers makes sense here. However its taking up a ton of memory and need a solution that is much more memory efficient. Below is the code I used to do this: <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"> </head> <body> <div class="container"> <div class="row"> <div class="md-12"> <div id="map" class="map"></div> </div> </div> <div id="span12"> </div> </div> <script>var iconInfo = [{ points: 4, radius: 3, radius2: 0, angle: 0}, { points: 4, radius: 3, radius2: 0, angle: 0}, { points: 4, radius: 3, radius2: 0, angle: 0}, { points: 4, radius: 3, radius2: 0, angle: 0}];var i;var iconCount = iconInfo.length;var icons = new Array(iconCount);for (i = 0; i < iconCount; ++i) { var info = iconInfo[i]; icons[i] = new ol.style.RegularShape({ points: info.points, radius: info.radius, radius2: info.radius2, angle: info.angle, fill: new ol.style.Fill({color: 'rgba(0, 0, 0, 0.9)'}), stroke: new ol.style.Stroke({width: 2, color: 'rgba(0, 0, 0, 0.9)'}), });}var featureCount = 350000;var features = new Array(featureCount);var feature, geometry;var e = 25000000;for (i = 0; i < featureCount; ++i) { geometry = new ol.geom.Point( [2 * e * Math.random() - e, 2 * e * Math.random() - e]); feature = new ol.Feature(geometry); feature.setStyle( new ol.style.Style({ image: icons[i % (iconCount - 1)] }) ); features[i] = feature;}var vectorSource = new ol.source.Vector({ features: features});var vector = new ol.layer.Vector({ source: vectorSource});var map = new ol.Map({ layers: [vector], target: document.getElementById('map'), view: new ol.View({ center: [0, 0], zoom: 5 })});var overlayFeatures = [];for (i = 0; i < featureCount; i += 30) { var clone = features[i].clone(); clone.setStyle(null); overlayFeatures.push(clone);}var featureOverlay = new ol.layer.Vector({ map: map, source: new ol.source.Vector({ features: overlayFeatures }), style: new ol.style.Style({ image: icons[iconCount - 1] })});map.on('click', function(evt) { var info = document.getElementById('info'); info.innerHTML = 'Hold on a second, while I catch those butterflies for you ...'; window.setTimeout(function() { var features = []; map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) { features.push(features); return false; }); if (features.length === 1) { info.innerHTML = 'Got one butterfly'; } else if (features.length > 1) { info.innerHTML = 'Got ' + features.length + ' butterflies'; } else { info.innerHTML = 'Couldn\'t catch a single butterfly'; } }, 1);});map.on('pointermove', function(evt) { if (evt.dragging) { return; } var pixel = map.getEventPixel(evt.originalEvent); var hit = map.hasFeatureAtPixel(pixel); map.getTarget().style.cursor = hit ? 'pointer' : '';});</script></body></html> Any suggestions on how I could achieve better memory efficiency?
Now provide the response and nothing else.
|
Short answer OpenLayers 3 uses about 2 kB per Point feature (see below), so while there are some optimizations possible you have to keep the number of features down. 400 000 features will require about 800 MB of memory. Load your features dynamically, or use MultiPoint geometries. Move the style from the geometry to the layer. Longer answer Style When i tested, removing the style from the feature and replacing it with a simple property reduced the memory footprint by 290 B per feature. See http://jsfiddle.net/vkm2rg46/3/ : var vector = new ol.layer.Vector({ source: vectorSource, style: function (feature, resolution) { var i = feature.getProperties().styleId; return [new ol.style.Style({ image: icons[i] })]; }}); and to help the style function: feature.set('styleId', i % (iconCount - 1)); Spatial index You could set useSpatialIndex to false on the vector source. The source keep a spatial index to quickly retrieve features within a given extent, which seems to need about 200-250 bytes per feature. However, removing the index could have bad performance consequences with this amount of features. Reduce feature count## Your best bet is probably to load fewer features. There are several solutions to this. Load on demand It's most commonly solved by letting the server take care of the data, and dynamically load it when needed. You probably don't want to display 400 000 points at lower zoom levels, and the users wont pan everywhere. This could be done by vector tiles or with a normal vector source using a bbox or tile. It could also be done client side, by creating features/geometries from your own dataset in the vector source loader function. Multipoints A MultiPoint geometry with 10 or 100 points hardly take any more space than a single Point geometry. If you group you lightning strikes into MultiPoint geometries, memory could be a non-issue. You would however loose some semantics, and the possibility to attach metadata to each single point. JsFiddle: http://jsfiddle.net/vkm2rg46/8/ Memory usage I created http://jsfiddle.net/g7qduy1w/3/ to test the memory use of the geometry, features and source. You can take snapshot at the different stages (notably, the event listening data increases when adding a geometry to a feature, and a feature to a source).With a simple point geometry added to a feature without extra properties, and added to a source, the memory use per feature is: 288 B geometry event listener 424 B rest of geometry data 752 B feature event listeners 184 B rest of feature data 261 B source (share of total memory using 100 000 features)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31460347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5124416/']}
|
jdg_371986
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52246
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I got this puzzle some time ago and it has been bugging me since, I cant solve it - but it is supposedly solvable, I am interested in a solution or any tips on how to proceed. In front of you is an entity named Adam. Adam is a solid block with a single speaker, through which he hears and communicates. For all propositions (statements that are either true or false) $p$, if $p$ is true and logically knowable to Adam, then Adam knows that $p$ is true. Adam is confined to his physical form, cannot move, and only has the sense of hearing. The only sounds Adam can make are to play one of two pre-recorded audio messages. One message consists of a very high note played for one second, and the other one a very low note played for one second. Adam has mentally chosen a specific subset of the Universe of ordinary mathematics. The Universe of ordinary mathematics is defined as follows: Let $S_0$ be the set of natural numbers: $$S_0 = \{1,2,3,\ldots\}$$ $S_0$ has cardinality $\aleph_0$, the smallest and only countable infinity. The power set of a set $X$, denoted $2^X$, is the set of all subsets of $X$. The power set of a set always has a cardinality larger than the set itself, $$|2^X| = 2^{|X|}$$ Let $S_1 = S_0 \cup 2^{S_0}$. $S_1$ has cardinality $2^{\aleph_0} = \beth_1$. Let $S_2 = S_1 \cup 2^{S_1}$. $S_2$ has cardinality $2^{\beth_1} = \beth_2$. In general, let $S_{n+1} = S_n \cup 2^{S_n}$. $S_{n+1}$ has cardinality $2^{\beth_n} = \beth_{n+1}$. The Universe of ordinary mathematics is defined as $$\bigcup_{i=0}^\infty S_i$$ This Universe contains all sets of natural numbers, all sets of real numbers, all sets of complex numbers, all ordered $n$-tuples for all $n$, all functions, all relations, all Euclidean spaces, and virtually anything that arises in standard analysis. The Universe of ordinary mathematics has cardinality $\beth_\omega$. Your goal is to determine the subset Adam is thinking of, while Adam is trying to prevent you from doing so. You are only allowed to ask Adam yes/no questions in trying to accomplish your task. Adam must respond to each question, and does so by playing a single note. After Adam hears your question, he either chooses the low note to mean yes and the high note to mean no, or the high note to mean yes and the low note to mean no, for that question only. He also decides to either tell the truth or lie for each question after hearing it. If at any time you ask a question which cannot be answered by Adam without him contradicting himself, Adam will either play the low note or the high note, ignoring the question entirely. Adam has given you an infinite amount of time to accomplish your task. More specifically, the set of both questions asked by you and notes played by Adam can be of any cardinality. If in your strategy this set is uncountably large, for any number of possibilities of Adam's chosen subset, you must describe the order that the elements of this set take place in as completely as possible. During your questioning, you are keeping track of the following numbers: $B_1 = $ The number of questions in which Adam had the option of truthfully responding in the affirmative. (This number and the following numbers can of course be cardinal numbers.) $B_2 = $ The number of questions in which Adam had the option of truthfully responding in the negative. $B_3 = $ The number of questions in which Adam had the option of falsely responding in the affirmative. $B_4 = $ The number of questions in which Adam had the option of falsely responding in the negative. $B_5 = $ The number of questions in which Adam responded with the high note. $B_6 = $ The number of questions in which Adam responded with the low note. $B_7 = $ The number of questions. Let $C = B_1+B_2+B_3+B_4+B_5+B_6+B_7$ A strategy exists which will eventually allow you to determine Adam's chosen subset. Describe such a strategy in which $C$ is as small as possible, for all possibilities of Adam's chosen subset.
Now provide the response and nothing else.
|
First, observe that you can get around the difficulty thatyou don't know if high means yes or low in the followingway. If you really want to ask the question $\varphi$, youshould instead ask the question "high means yes for this round if andonly if $\varphi$" . If high means yes, then this is thesame as asking $\varphi$. But if high means no, then it is like asking $\neg\varphi$, and so we may interpret a high anwer to this question as yes to $\varphi$. Thistransformation therefore ensures that we can in effect knowthat high means yes. (I mentioned a similar trick in thisMOanswer about guessing a number, when there can be wrong answers.) For the lying issue, let me assume that by lying, you meanthat Adam first decides whether to lie or tell the truth,and then calculates what a truthful answer would be, andthen when telling the truth plays the appropriate tone, but if lyingplays the opposite tone. With this interpretation, asimilar trick allows us to extract the desired information.Namely, if you want to ask $\psi$, instead ask "you have decided to be truthful for this question iff $\psi$" . If Adam decides tobe truthful, then this question is answered the same as$\psi$. If he decides to lie, then he calculates what atruthful answer would be, given that he has already decidedto lie, which is the opposite of $\psi$, and so he says theopposite of this. In this way, the double negation of thetransformation allows us to get the desired information. Combining the two transformations allows us to get answersto any desired question. Now, we simply proceed as follows. Since it seemspermissible in the world of your question, let us enumerateall the elements of what you call the universe of ordinarymathematics, and ask of each such element whether it is inAdam's set, using the transformations above. In this way,we find out exactly the set of which he is thinking. The end result is $\beth_\omega$ many questions. This is the optimal in the sense that any smaller bound on the number of questions would be less than $\beth_n$ for some $n$, with only $\beth_{n+1}$ many possible patterns of answers, but there are $\beth_{\omega+1}$ many sets that Adam might be considering. Incidently, what you call the universe of ordinary mathematicsis closely related to what is known in set theory as$V_{\omega+\omega}$, which is a model of the Zermelo axiomsof set theory, one of the first axiomatizations of set theory. The $V$ hierarchy begins with $V_0$ beingthe empty set, and $V_{\alpha+1}=P(V_\alpha)$ and$V_\lambda=\bigcup_{\alpha\lt\lambda} V_\alpha$ for limitordinals $\lambda$. Your universe is contained within$V_{\omega+\omega}$, but is actually missing huge parts of$V_{\omega+1}$, because you started only with the naturalnumbers, rather than the hereditary finite sets. Forexample, the set $\{\ a_k\mid k\in\mathbb{N}\ \}$, where$a_k=\{\{\{\cdots\}\}\}$ has depth $k$, is missingfrom your universe, but exists in $V_{\omega+1}$. It follows that your world of mathematics does not have the set HF consisting of all hereditary finite sets, or any similar set with unbounded finite depths. From this, it follows that your world does not satisfy some of the very elementary axioms of set theory, which would allow you to construct HF from the natural numbers. For example, the set mentioned above is the result of a very simple induction on finite-depth finte sets. The fact that $V_{\omega+\omega}$ itself has no sets of size $\beth_\omega$ is precisely what led to the realization that the Zermelo axioms are too weak to prove even that $\beth_\omega$ exists. This realization led directly to the addition of the Replacement axiom to the axioms of set theory, resulting in the theory now known as ZFC.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/52246', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12249/']}
|
jdg_371987
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31493663
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Situation: Just installed linux, Trying to learn to code c. Gets set up with sudo apt-get install build-essential. Open nano type in my code #include <stdio.h>int main(int argc, char *argv[]){ puts("Hello World.\n"); return 0;} open another console tab, types in make ex1then my world spins downward into the darkest abyss i have yet to experience on my first linux distro. ragnar@ragnar:~/Documents/C$ make ex1cc -Wall -g ex1.c -o ex1ex1.c:7:1: fatal error: error closing /tmp/cc8d7Oap.s: No space left on device } ^compilation terminated.make: *** [ex1] Error 1ragnar@ragnar:~/Documents/C$ df -hFilesystem Size Used Avail Use% Mounted on/dev/sdb5 4.0G 3.8G 0 100% /none 4.0K 0 4.0K 0% /sys/fs/cgroupudev 7.9G 8.0K 7.9G 1% /devtmpfs 1.6G 1.4M 1.6G 1% /runnone 5.0M 0 5.0M 0% /run/locknone 7.9G 8.1M 7.9G 1% /run/shmnone 100M 28K 100M 1% /run/user/dev/sdb2 96M 29M 68M 30% /boot/efi/dev/sdb7 11G 248M 9.5G 3% /home all help is appreciated.
Now provide the response and nothing else.
|
The partition containing the root folder ( / ) is 100% full. The root folder currently also contains the /tmp folder, which is used during compilation to store temporary files. As the root folder and with this the tmp folder is full, this fails. To get around this either add more space, or reorganise the existing one. As a workaround do mkdir ~/tmpexport TMPDIR=~/tmp and retry compilation. A flexible way to organise a file system is using seperate partitions for //usr/home/var/tmp A lazy approach would be to link /tmp/ to /var/tmp . This however might cause issues as in terms of clean-up the OS might handle the content in /var/tmp different from the content in /tmp . That is the content of /tmp/ would get deleted on each boot where as /var/tmp wouldn't.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31493663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3299732/']}
|
jdg_371988
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6490
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This question title might seem a little vague, and I apologize for that. Let me just begin by stating I'm an engineering psychologist—not an IT security or computer guru by trade. As luck would have it, my employer (a very, very big one) has placed me on a small team where I work on a mission critical server that can (ideally) never fail and has to have the utmost security. I do web design, accessibility analysis, user experience stuff — all front-end. Without really thinking about it and without any regard to my skills or background, someone up the chain unwittingly placed me in charge of also making sure the entire system is secure, as at one point our website was listed on senderbase.org with a poor reputation rating. One of my co-workers seems to think that unix's Sendmail is the root of the problem. Concordantly, we blocked all traffic on port 25 and stopped running sendmail. But because of that, my contact forms using php mail() don't work (requires sendmail). I was told that "there is no way to use SMTP on a server and have a secure server." But I'm less certain of this. On a clean, uninfected system with ideal security, could sendmail be targeted from the outside and used to send spam email? In other words, are there any secure ways to send emails server side? Or will I have to convert all my contact forms to "mailto:" links, etc? To be clear: the location of the mail is to a support email we use. It is hardcoded; all email gets sent to this email address and the user cannot change this (unless there are hacking techniques I'm unaware of, which is really my question). The only fields the user can type in are Subject, Message, and From. There obviously has to be some solution because I see email contact forms all the time on huge, powerful websites. If it was a security weakness, you'd think google, yahoo, facebook, cnn, times, and all those other popular websites would have stopped using it long ago, right?
Now provide the response and nothing else.
|
There is a difference between a mail server that sends emails and a mail server that receives emails from outside. In your case you do not need to receive emails from the outside, so the mail server does not need to listen on port 25 . It is true that sendmail has a long history of security issues and a extremely complex configuration language (there is even a macro language to make configuration simpler). sendmail is not used on current Linux distribution anymore but there is a number of drop in replacements such as qmail, exim or postfix that will provide a compatible interface and a symlink called /usr/bin/sendmail. If that symlink is used, they will parse the common command line parameters the same wayas the original sendmail did. On Windows you need to edit the [mail function] section of php.ini to point to an external email server. Since you are sending emails to a fix target domain, it can be the mail exchange server that is responsible to receive emails for that domain. Use host -t mx example.com to learn the name.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/6490', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/4451/']}
|
jdg_371989
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
382365
|
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:
There are several introductory textbooks which define a ring without any reference to a unity. However, nearly all of the rings one encounters in various branches of mathematics are endowed with a $1$.Thus, I'm wondering if some of you could prove me wrong and show me some examples of rings without unity arising naturally in a mathematical theory. (Two-sided ideals don't count as an example, because normally, they aren't considered as rings in their own right, but as modules or equivalence classes, allowing you to pass to a quotient ring (with $1$).)
Now provide the response and nothing else.
|
I once thought it was the case that in number theory basically all the relevant rings were commutative with identity. But this is not so! In the theory of automorphic forms and representations, the Hecke algebras which act on representations of various groups (the groups of points of reductive groups over local and global fields, valued in the field, or in the global case, in its completions or its adele ring) are generally non-commutative and do not have multiplicative identities (although there are interesting subalgebras, e.g. the spherical Hecke algebras, which are commutative and do have identities). In the local case, the rings are convolution algebras of locally profinite (meaning totally disconnected and locally compact) groups. Specifically, for $G$ locally profinite, the space $C_c^\infty(G)$ of smooth (meaning locally constant) and compactly supported complex-valued functions is a ring under convolution (for a choice of Haar measure on $G$) and acts on smooth representations of $G$. In fact, smooth representations of $G$ are literally the same as smooth representations of $C_c^\infty(G)$, so it plays the role of the group algebra $\mathbf{C}[G]$ for $G$ finite. But unlike the group algebra, this ring won't usually have a multiplicative identity.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/382365', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50527/']}
|
jdg_371990
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
702665
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The problem says to find a basis of the null space of A, A being the matrix: $\begin{bmatrix}1 & 0 & 0\\1 & 0 & 1\end{bmatrix}$ So I need to solve the equation $Ax = 0$ to find the null space of A. $\begin{bmatrix}1 & 0 & 0 \\1 & 0 & 1\end{bmatrix}$ reduces to $\begin{bmatrix}1 & 0 & 0\\0 & 0 & 1\end{bmatrix}$ and I end with $x_1 = 0, x_3 = 0$ so this tells me the solution vector is $\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}$ = $\begin{bmatrix}0\\0\\0\end{bmatrix}$ Which is the zero vector. However the book the tells me the solution is: $\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}$ = $\begin{bmatrix}0\\1\\0\end{bmatrix}$ I do not know where they got the 1 from since $x_2$ was not a part of the system at all. If I had to take a guess I would say that because $x_2$ isn't included at all it can be anything since the result of the multiplication will always end up with $0$. Can anyone enlighten me on this? Am I close? Thanks!
Now provide the response and nothing else.
|
This is a very common mistake. You have no equation telling you about $x_2$. Lots of people assume this means $x_2$ must be zero. On the contrary, since you have no information about $x_2$, it could be anything! So the solution is$$x_1=0\ ,\quad x_2=t\ ,\quad x_3=0$$and the nullspace is$$\left\{t\pmatrix{0\cr1\cr0\cr}\ :\ t\in{\Bbb R}\right\}\ ,$$which has a basis$$\left\{\pmatrix{0\cr1\cr0\cr}\right\}$$as claimed.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/702665', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/133681/']}
|
jdg_371991
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
97575
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a quick definition of the tangent space $T_p M$, where $p$ is a point of a smooth manifold $M$. I mean a definition that allows easily to prove that: (1) $T_p M$ is a vector space of the same dimension of $M$; (2) if $x^1, x^2, \ldots,x^d$ are local coordinates functions then $\partial / \partial x^i|_p$ is a basis of $T_p M$; (3) The elements of $T_p M$ are the same thing of derivations of functions definited on a neighborhood of $p$ (W. Warner, Foundations of Differentiable Manifolds, called them "germs" and denoted their set by $\tilde{F}_p$). Surely the old-style definition of $T_p M$ by equivalence classes of curves which passes through $p$ is inadequate. The definition of $T_p M$ like the vector space of derivations of germs is, obviously, OK for the point (3) but seems to me that points (2) and (1) require to look at the cotangent space $T_p^* M$. I do not like to talk about the cotangent space before I have finished to talk about the tangent space. I saw that someone defines the cotangent space first and then the tangent space, however the Warner definition of cotangent space like $\tilde{F}_p / \tilde{F}_p^2$, where $\tilde{F}_p^2$ is the ideal of finite linear combinations of product of two germs, I think it is rather artificial, and justifiable only in retrospect. In conclusion I really appreciate any advice on how to define $T_p M$ so that (1), (2) and (3) are easy to prove. Thanks.
Now provide the response and nothing else.
|
I think the description of tangent space $T_pM$ you're looking for is one defined entirely locally by "pushing forward" tangent spaces of $\mathbb{R}^n$ via local coordinate charts. ie. the tangent space $T_pM$ at a point $p$ in a trivial neighborhood $U$ of the manifold $M$ is described via a coordinate chart $\phi: (\mathbb{R}^n, 0) \to (U,x)$ as simply the image of $T_0 \mathbb{R}^n$ under the differential $d\phi$. This yields your (1), (2) immediately, while (3) follows once one understands why its true on $\mathbb{R}^n$. The basic point of smooth manifolds, I think, is that there is no calculus on manifolds, but only calculus on $\mathbb{R}^n$ and pushforwards and pullbacks. When I was first learning the basics of smooth manifolds I found Warner's book to be very helpful. He demonstrates very clearly the formalism of (co)tangent spaces and how to actually perform differential computations.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/97575', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21706/']}
|
jdg_371992
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6124
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have three 1TB drives in a software RAID-5 configuration with LVM running on top of it. Each drive is partitioned into 2 500GB partitions. So as far as mdadm knows, it has 6 devices. Currently the raid array has 2.5TB of space; I'm assuming one of the 500GB partitions is being used for parity? Or maybe 500GB is being used throughout the array, I'm not exactly sure. My question is: with this configuration, am I safe if any one of the drives fail? Or, do I need to add a fourth drive with another 500GB partition as a spare? Or do I need to add another 500GB partition from a fourth drive and somehow specify it to be used for parity?
Now provide the response and nothing else.
|
No, you're not safe. The idea with RAID 5 is to have N+1 disks (providing total storage equivalent to N disks), with enough redundancy to recover if one disk fails. (The parity is actually distributed over all the disks with RAID 5.) However, by partitioning each of your 3 physical disks into 2 partitions, you've set up 5+1 500 GB partitions (providing 5*500 GB space), with protection if one partition fails. However if one drive fails completely, you will lose the two partitions that are on it, and you don't have enough redundancy to recover from that. The usual trick with RAID 5 is to leave your physical devices unpartitioned (or with only one partition each), create the RAID array, and then partition the resulting device if necessary. Even if you add another 500 GB partition, you still won't be safe if you still use RAID 5, because the extra partition won't add more redundancy, only more capacity. You would have to switch to something like RAID 6, which provides protection against losing two drives.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/6124', 'https://serverfault.com', 'https://serverfault.com/users/53971/']}
|
jdg_371993
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
168199
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If you take this code: echo -e '\t\t\tString' | grep '^[\t]*String' the result is blank because it doesn't match, yet this: echo -e '\t\t\tString' | grep $'^[\t]*String' works. I swear that I must have used the first line's code a hundred times in my scripts and in the terminal, without ever using the "$" character like that, and it's always seemed to work. Has there been some recent change? Why does it need the "$" character? Or am I doing something wrong?
Now provide the response and nothing else.
|
ANSI-C Quoting According to the Bash manual, this is called ANSI-C quoting . The manual says: Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. In practice, this means that '\t' will not be expanded into a tab character, but $'\t' will. The output should be equivalent to using echo -e , but can be used anywhere you'd use a string without requiring command substitution . Utilities like GNU sed perform their own expansion of escape characters, but GNU grep doesn't. The Bash shell, not grep, expands escaped characters within ANSI-C quoted strings. Without the ANSI-C quoting, the regular expression you posted contains no tab characters to match the input.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/168199', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/91667/']}
|
jdg_371994
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6749022
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible somehow to achieve this behavior in C#: public interface IReadOnly{ Data Value { get; }}internal interface IWritable : IReadOnly { Data Value { get; set; }} I want to be able to expose a readonly interface to outside assemblies, but use a writable interface internally (which I could also implement in different ways). I know I can use an abstract class which implements IReadOnly but adds setters, but that forces me to derive all internal implementations from that class.
Now provide the response and nothing else.
|
This isn't a problem: public interface IReadOnly { Data Value { get; }}internal interface IWritable : IReadOnly { new Data Value { get; set; }}internal class Impl : IWritable { public Data Value { get; set; }} The Impl.Value property implementation takes care of both IReadOnly.Value and IWritable.Value, as demonstrated in this test snippet: var obj = new Data(); var target = new Impl(); var irw = (IWritable)target; irw.Value = obj; var iro = (IReadOnly)target; System.Diagnostics.Debug.Assert(Object.ReferenceEquals(iro.Value, obj));
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6749022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852232/']}
|
jdg_371995
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13502247
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone tell me which one is lighter between ref and out . I know the exact difference between ref and out keyword and usage as well. In my case I can use both ref and out , but wondering the lighter one. If some one needs to refer please go here and let me know the lighter ones. Thanks in advance..
Now provide the response and nothing else.
|
The only difference is a compiler hint. ... out ... public static void TestOut(out int test){ test = 1;}.method public hidebysig static void TestOut([out] int32& test) cil managed{ // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stind.i4 IL_0003: ret} // end of method Program::TestOut ... ref ... public static void TestRef(ref int test){ test = 1;}.method public hidebysig static void TestRef(int32& test) cil managed{ // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: stind.i4 IL_0003: ret} // end of method Program::TestRef ... out and ref are effectively the same. The only real difference being that out tells the compiler to expect the value to be set before the method is returned. You could send a value to a function that has an out flag but again the compiler will treat it as an unassigned variable. The runtime doesn't really care. Both will be created as a pointer to the variable. You are best to use the keyword that describes the functionality you expect with your function. Any optimization that "may" take place in the JITer below this will have near 0 impact on the application.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13502247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1762515/']}
|
jdg_371996
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41518494
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
any way to loop in a json file and print all keys and values like a dictionary? Example foreach (string item in result.Data.Keys) { Debug.LogError("KEY:"+item); Debug.LogError("Value:" + result.Data[item]); } I have tried JsonUtility and simple json , but i cant print the KEY value yet Any solution? thanks
Now provide the response and nothing else.
|
The type of data[Items] isn't Array but actually Array<[String: Any]> . You could probably squeeze this into fewer steps, but I prefer the clarity of multiple steps: var data: [String: Any] = [ "key1": "example value 1", "key2": "example value 2", "items": []]for index in 1...3 { let item: [String: Any] = [ "key": "new value" ] // get existing items, or create new array if doesn't exist var existingItems = data["items"] as? [[String: Any]] ?? [[String: Any]]() // append the item existingItems.append(item) // replace back into `data` data["items"] = existingItems}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41518494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6771754/']}
|
jdg_371997
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54758232
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just replaced the js pipeline in my Rails app with webpacker . Most things work correctly, however controllers that render js no longer work as expected. def action format.js { render "javascript_partial" }end Normally, the above would execute a file in my view called javascript_partial.js.erb or action.js.erb if not specified in render . The problem seems to be that these files have no connection to the webpacker pipeline and thus cannot access global libraries like jquery or explicitly manage their own imports . This code now causes client-side syntax errors because it cannot access the jquery $ function: $("#element").html(<= j render partial: 'partial', locals: { object: @object } %> I have a related problem with in-line js in my views. Something like the following, <%= form.collection_select ... onchange: 'Rails.fire(this.form, "submit")' %> no longer works, because in-line js cannot access global objects such as Rails . This seems to be a straightforward problem but I cannot find documentation anywhere. Does anyone how to harmonize webpacker with historically expected Rails/js behavior? Do I need to bring back sprockets ? If it helps, my javascript/packs/application.js file looks something like, import Rails from 'rails-ujs';import Turbolinks from 'turbolinks';Rails.start();Turbolinks.start();$(document).on("turbolinks:load", () => { // initial setup ...}); The above works perfectly fine, and has access to jquery because I've exported it in config/webpack/environment.js , environment.plugins.append('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: 'jQuery'}));
Now provide the response and nothing else.
|
Figured it out thanks to this wonderful article ! Use expose-loader to expose key libraries to vanilla JavaScript sprinkled throughout your app. 1) Install dependency, yarn add expose-loader --dev 2) Configure config/webpack/environment.js , const { environment } = require('@rails/webpacker');environment.config.merge({ module: { rules: [ { test: require.resolve('jquery'), use: [{ loader: 'expose-loader', options: '$' }, { loader: 'expose-loader', options: 'jQuery' }] }, { test: require.resolve('rails-ujs'), use: [{ loader: 'expose-loader', options: 'Rails' }] } ] }});module.exports = environment;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54758232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408136/']}
|
jdg_371998
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27676404
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
with str(data) I get the head of the levels (1-2 values) fac1: Factor w/ 2 levels ... :fac2: Factor w/ 5 levels ... :fac3: Factor w/ 20 levels ... :val: num ... with dplyr::glimpse(data) I get more values, but no infos about number/values of factor-levels. Is there an automatic way to get all level informations of all factor vars in a data.frame? A short form with more info for levels(data$fac1)levels(data$fac2)levels(data$fac3) or more precisely a elegant version for something like for (n in names(data)) if (is.factor(data[[n]])) { print(n) print(levels(data[[n]])) } thxChristof
Now provide the response and nothing else.
|
Here are some options. We loop through the 'data' with sapply and get the levels of each column (assuming that all the columns are factor class) sapply(data, levels) Or if we need to pipe ( %>% ) it, this can be done as library(dplyr)data %>% sapply(levels) Or another option is summarise_each from dplyr where we specify the levels within the funs . data %>% summarise_each(funs(list(levels(.))))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27676404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2156916/']}
|
jdg_371999
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26170279
|
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 possible to create a big circle around a hyperlink using CSS? I'm trying to achieve it but my circle is very small. I would like that circle size were similar to hyperlink size. If i put the hyperlink inside a div, it's not being centralized inside the circle. Here is what i'm doing: <html><head> <style> .circle { border-radius: 1000%; width: 40px; height: 40px; background: green; } </style></head><body> <a href="#" class="circle">Test test test test</a></body></html>
Now provide the response and nothing else.
|
The problem with your code is that the a element is an inline element and thus accepts no height. Change it to a block level element to give it a specified height: .circle { border-radius: 100%; background: green; display:inline-block; line-height:100px;} To have the text appear in the middle, use line-height instead of height . Working sample: http://jsfiddle.net/7qfbopqj/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26170279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_372000
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17224270
|
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 allow CDI injection of resources into restful web service resources? I am running on standard java using weld 2 (cdi), jersey (jaxrs), and grizzly (web server). Here is my simple web resource: import training.student.StudentRepository;import javax.inject.Inject;import javax.ws.rs.*;@Path("student")public class StudentWebResource { @Inject private StudentRepository studentRepository; @GET @Path("count") @Produces(MediaType.TEXT_PLAIN) public Integer getCount() { return studentRepository.studentCount(); }} And here is how I've got weld starting my simple web server: public class Main { public static void main(String[] args) throws Exception { startCdiApplication(); } public static void startCdiApplication() throws Exception { Weld weld = new Weld(); try { WeldContainer container = weld.initialize(); Application application = container.instance().select(WebServer.class).get(); application.run(); } finally { weld.shutdown(); } }} And the code that I suspect will need to be modified to inform jersey to use weld for CDI inject resolution: ...import org.glassfish.grizzly.http.server.HttpServer;import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;import org.glassfish.jersey.jackson.JacksonFeature;import org.glassfish.jersey.server.ResourceConfig;public class WebServer implements Application { /* * startup the grizzly http server to make available the restful web services */ private void startWebServer() throws IOException, InterruptedException { final ResourceConfig resourceConfig = new ResourceConfig().packages("training.webservice").register(new JacksonFeature()); final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(), resourceConfig); server.start(); Thread.currentThread().join(); } ... @Override public void run() throws IOException, InterruptedException { startWebServer(); }}
Now provide the response and nothing else.
|
After seeing this stackoverflow post , I implemented the following solution. Not sure if it is the best route to take, but it worked. I created an hk2 Binder and registered the Binder: public class WebServiceBinder extends AbstractBinder { @Override protected void configure() { BeanManager bm = getBeanManager(); bind(getBean(bm, StudentRepository.class)) .to(StudentRepository.class); } private BeanManager getBeanManager() { // is there a better way to get the bean manager? return new Weld().getBeanManager(); } private <T> T getBean(BeanManager bm, Class<T> clazz) { Bean<T> bean = (Bean<T>) bm.getBeans(clazz).iterator().next(); CreationalContext<T> ctx = bm.createCreationalContext(bean); return (T) bm.getReference(bean, clazz, ctx); }} Then modified the ResourceConfig instantiation from above to: final ResourceConfig resourceConfig = new ResourceConfig() .packages("training.webservice") .register(new JacksonFeature()) .register(new WebServiceBinder());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17224270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225217/']}
|
jdg_372001
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4612708
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a scheme (or just a topological space) and $F$ and $G$ be two sheaves on them. If $F_x=G_x$ for all $x \in X$ i.e $F$ and $G$ are equal at stalks at every point, is $F \cong G$ ?
Now provide the response and nothing else.
|
The summand is the coefficient of $x^{i-j}$ from the following expression: $$(1+x)^{n+1}\left(1+\frac{1}{x}\right)^{n}=\frac{(1+x)^{2n+1}}{x^{n}}$$ Since $i-j>1$ , we just need to sum the coefficients of $x^{n+1},...,x^{2n+1}$ from the numerator on RHS. $$\binom{2n+1}{n+1}+\binom{2n+1}{n+2}+...+\binom{2n+1}{2n+1}=2^{2n}$$ Seems like all the options are correct except (B)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4612708', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/454200/']}
|
jdg_372002
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
517759
|
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 learning how to create services with systemd. I get this error: .service: Start request repeated too quickly. I can't start the service any more; it was working yesterday. What am I doing wrong? (root@Kundrum)-(11:03:19)-(~)$nano /lib/systemd/system/swatchWATCH.service 1 [Unit] 2 Description=Monitor Logfiles and send Mail reports 3 After=syslog.target network.target 4 5 [Service] 6 Type=simple 7 ExecStart=/usr/bin/swatch --config-file=/home/kristjan/.swatchrc --input-record-separator="\n \n " --tail-file=/var/log/snort/alert --daemon 8 Restart=on-failure 9 StartLimitInterval=310 StartLimitBurst=1001112 [Install]13 WantedBy=multi-user.target StartLimitInterval and StartLimitBurst I added after trying to fix it. My system is Debian 9.8 Stretch all updates.
Now provide the response and nothing else.
|
First, if this is a custom service, it belongs in /etc/systemd/system . /lib/systemd is intended for package-provided files. Second, the service is likely crashing and systemd is attempted to restart it repeatedly, so you need to figure out why it's crashing. Check the service logs with: journalctl -e -u swatchWATCH It's possible there will be some extra detail in the main journal: journalctl -e Finally, check to see it runs directly on the CLI ok: /usr/bin/swatch --config-file=/home/kristjan/.swatchrc --input-record-separator="\n \n " --tail-file=/var/log/snort/alert --daemon I see you are using a --daemon option. That's often a mistake with systemd. Systemd daemonizes for you. Try removing this option. If all else fails, review what changed since yesterday when it was working.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/517759', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/36440/']}
|
jdg_372003
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49266469
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
while building crud app in angular 5 I've come across with a question, how can I use the same form builder but change what form controls I get depending on what I want, adding or updating users thru form... Here's some simple code, I will try not to complicate things, since I have pretty big form with lot of attributes... So in my app.component.html i have form <form class="form-horizontal" [formGroup]="form" #myForm="ngForm" (ngSubmit)="save()"> <div class="form-group"> <label for="firstName" class="control-label required">First name</label> <input type="text" id="firstName" class="form-control" formControlName="firstName"> </div> <div class="form-group"> <label for="lastName" class="control-label required">Last name</label> <input type="text" id="lastName" class="form-control" formControlName="lastName"> </div> and in my app.component.ts in my constructor i have this.form = this.formBuilder.group({ firstName: ['', [Validators.required, Validators.minLength(2), Validators.pattern(/^[a-zA-Z]+$/)]], lastName: ['', [Validators.required, Validators.minLength(2), Validators.pattern(/^[a-zA-Z]+$/)]], }); and save() function for submiting the form save() { let formModel = this.form.value; formModel.id = this.Id; if (this.Id == null) { this._usermanagementservice.addEmployee(formModel).subscribe(() => { //function that reloads table with employees this.LoadAllEmployees(); }); } else { this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => { this.LoadAllEmployees(); }); }} Noted that everything works, I've not included other fields, but here's the question, how can I include only form for first name field on adding user, and have ONLY last name for updating? (to simplfy things, I'm using this example first and last name) Thanks, If you need more info, I'll gladly provide itPs. english is my secondary language, so terms like fields, forms and etc. are for sure incorrect, hopefully you'll get the point
Now provide the response and nothing else.
|
The FormGroup API exposes methods such as addControl and removeControl which you can use to add or remove controls from your form group after it has been initialized. An example using these methods might look like: formMode: 'add' | 'update';userForm: FormGroup;ngOnInit() { this.form = this.formBuilder.group({ firstName: [''], lastName: [''] });}changeMode(mode: 'add' | 'update') { if (mode === 'add') { if (!this.form.get('firstName')) { this.form.addControl('firstName'); } this.form.removeControl('lastName'); } else { if (!this.form.get('lastName')) { this.form.addControl('lastName'); } this.form.removeControl('firstName'); }}onChange(event: 'add' | 'update') { this.changeMode(event);} You'll probably want your DOM to reflect the state of your form by adding *ngIf checks based on the existence of a given control: <input *ngIf="form.get('lastName')" formControlName="lastName">
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49266469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9280600/']}
|
jdg_372004
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30708
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to figure out why this is true: $$ \lim_{p \to 0}\frac{1}{2p}\left((1+p)e^{-\frac{y}{1+p}} - (1-p)e^{-\frac{y}{1-p}}\right) = e^{-y} + ye^{-y}$$ I have already tried L'Hopital's Rule, but it gave me something that I couldn't simplify. The problem seems to be the $\frac{1}{2p}$ term never seems to go away. I know the exponential function can be represented as: $e^x = \lim_{n\to\infty} (1+\frac{x}{n})^n$, but it doesn't seem immediately obvious how that would apply in this situation. Thanks.
Now provide the response and nothing else.
|
HINT $\ $ It has form $\displaystyle\rm\ \lim_{x\to 0}\ \frac{f(x)-f(-x)}{x - (-x)}\:.\ $ Relate that to a derivative. Note that this solution by recognizing the limit as a derivative employs only knowledge of the definition of the derivative and the basic rules for calculating derivatives of polynomials and powers. It does not require knowledge of more advanced techniques such as power series or Taylor series, l'Hôpital's rule, the mean-value theorem, etc. As I often remark here, limits exercises are frequently of this form (e.g. see this prior question or this or this or this or this ) so it is worthwhile to be familiar with this technique, which - when it applies - is often much simpler than alternatives.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/30708', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8140/']}
|
jdg_372005
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17377337
|
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 not find them under ~/Library/Application Support/Google/Chrome/; Where are they? Mac Pro 10.8.4 Chrome Version 26.0.1410.65
Now provide the response and nothing else.
|
The default locations of Chrome's profile directory are documented in the User Data Directory article on Googlesource.com. (When this article was written in 2013, the User Data Directory article was at chromium.org .) It says there, To determine the user data directory for a running Chrome instance: Navigate to chrome://version Look for the Profile Path field. This gives the path to the profile directory. The user data directory is the parent of the profile directory. For Chrome on Mac, it's ~/Library/Application\ Support/Google/Chrome/Default The actual location can be different, by setting the --user-data-dir=path/to/directory flag. If only one user is registered in Chrome, look in the Default/Extensions subdirectory. Otherwise, look in the <profile user name>/Extensions directory. If that didn't help, you can always do a custom search. Go to chrome://extensions/ , and find out the ID of an extension (32 lowercase letters) (if not done already, activate "Developer mode" first). Open the terminal, cd to the directory which is most likely a parent of your Chrome profile (if unsure, try ~ then / ). Run find . -type d -iname "<EXTENSION ID HERE>" , for example: find . -type d -iname jifpbeccnghkjeaalbbjmodiffmgedin Result:
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17377337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316334/']}
|
jdg_372006
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8514
|
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My wife was just rear-ended by some woman who was "tired" (her claim—in fact she was more probably texting) and not paying attention. This did a lot of damage to the rear end of our Honda Pilot. This is the third accident my wife has been in in a year where someone else was not paying attention, and I want to take some preventative action. Grill guards (and rear bumper guards—I'm using the term generically since a search for "grill guards" will bring up both) give the appearance of being strong and solid pieces of metal that add extra protection for the body of your car, but I'm wondering if that appearance is deceiving. Here are some examples: http://www.amazon.com/2009-2013-Honda-Bumper-Protector-Stainless/dp/B00D6940S0 http://www.amazon.com/Custom-Bumper-Mounting-Hardware-included/dp/B00D30S970 One reason for my skepticism is from the blurb here , which says Honda Pilot 2004, 2.5" Ultimate Bull Bar by Westin®, with Removable Stainless Steel Skid Plate. The secret of living a peaceful life in the asphalt jungle is to add a scary edge to your looks. The Ultimate Bull Bar is perfect for the purpose.... The fact that they focus exclusively on the appearance and do not even address the issue of structural protection leads me to believe perhaps they know it's all a facade, and are carefully avoiding making any claims they know could come back to haunt them, so they sell it as a way of massaging their customers' egos rather than actually protecting anything or anyone. How much protection do these actually offer? Can they in some situations eliminate body or structural damage to your car, and in others reduce it?
Now provide the response and nothing else.
|
There a several moderately complex and variable issues in this question. It is impossible to adequately adress all the variables, but here are some key points. First there are almost no after market protectors for the rear of the most vehicles. There are some companion rear bumpers sold for "brush guard" type front bumpers. While heavier than stock bumpers they are primarily geared towards providing solid points of attachment for towing and pulling. These will provide little additional protection in the case of a rear impact, and may actually lead to increases in damage ( at high speed ) as they tend to be mounted directly to the frame, so any shock absorber benefits of a stock bumper are lost. Grill guards come in two basic styles, "just for looks" and "intended for impact". As you may expect many of the chrome plated grill guards you see in your daily drive are just for looks. While shining does not always mean just for looks, the majority of "intended for impact" bumpers ( in my experience ) are painted flat black. This is because, you expect them to come into contact with; brush, rocks, trees, earth. Touch up with a can of flat black spray paint is really easy. The primary identifier of an "intended for impact" front bumper/quard is it's attachment. Let us consider the grill guard pictured in the question. The stock bumper is still in place, so it is unlikely that the "guard" is bolted to the frame, in most of these types of applications it the guard is connected using light screws to equally light body parts. In the event of a frontal impact, the attachments will pull out, tearing the parts of the body, it will then fold up into the grill of the vehicle. All of this happens before the shock absorbers in the stock bumper have the opportunity to do anything. So a collision that may have left no notable blemish on your truck, has torn out part of the lower radiator support, and smashed your grill. Bumpers/guards designed for impact ( some examples ) fully replace the stock bumper. There are bolted directly to the frame and are intended to transfer any force applied directly to the frame of the vehicle, protecting the soft parts like, fender, grills and radiators. There are a many options for brush type additions on the basic frame mounted bumper. Personal preference and expected terrain are the primary motivators in the decision. If you are going to be driving up on rocks you might want something like this. Another body protection option is for the side, often called "Nerf Bars" or "Rock Guards" these are bumpers for the side of your vehicle. These are particularly helpful when you have the possibility of having rocks or trees, impacting the side of your vehicle. As with grill guards these also come in "just for looks" and "intended for impact". If they screwed to tin rather then bolting to a steel frame, you are likely to do more damage by installing something "just for looks". Particularly if it has more impact than someone standing on it to get in the vehicle. A well constructed nerf bar, can actually be used as a fulcrum while in off road situations. So to answer your question. If you buy and properly install quality protection it can offer a lot of protection. Particularly in low speed high force events. My TJ was 10 years old and not a dent in the body when I sold it. But if you are in a highway speed accident, little additional protection is offered. These devices work by transferring forces away from light duty body parts to the stronger steel frame.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/8514', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/4318/']}
|
jdg_372007
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4025893
|
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 check if the two arrays are identical(not content wise, but in exact order). For example: array1 = [1,2,3,4,5] array2 = [1,2,3,4,5] array3 = [3,5,1,2,4] Array 1 and 2 are identical but 3 is not. Is there a good way to do this in JavaScript?
Now provide the response and nothing else.
|
So, what's wrong with checking each element iteratively? function arraysEqual(arr1, arr2) { if(arr1.length !== arr2.length) return false; for(var i = arr1.length; i--;) { if(arr1[i] !== arr2[i]) return false; } return true;}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4025893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392373/']}
|
jdg_372008
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11297825
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Okay, so I have written this script which allows me to find however it does not work correctly. I am having a programming issue - programming this to work correctly. It does not seem to be working correctly. This function is declared on each row that shows up within a database full of payments from a bank statement. The $a, $b, $c, $d is simply the type (BAC, TRS, etc), description (35 QUEENS ROAD RENT) and amount (£500.00). I am trying to create a function that will reconcile payments to a particular user, depending on what addresses/properties are connected to them, their name and how much their rent is. This is what I have so far: function reconcile($a,$b,$c,$d) { //when the user clicks on the text fild, jquery loads the various names needed from the database //when the user clicks on the selected field, the value is saved via ajax and saved on the server the reconciled field //break down the inputs into an array //create SQL query that matches all of these key words //create keywords database $keywords = $a . " " . $b . " " . $c . " " . $d; //remove commas, dashes and other keywords from database that might be a nuisance //change names like ave to avenue $keywords = str_replace("'", "", $keywords); $keywords = str_replace("-", "", $keywords); $keywords = str_replace(",", "", $keywords); $keywords = str_replace("A/C", "", $keywords); $keywords = str_replace("TO", "", $keywords); $keywords = str_replace("CALL", "", $keywords); $keywords = str_replace("REF.NO.", "", $keywords); $keywords = str_replace("TO", "", $keywords); $keywords = preg_replace("/\s+/", " ", $keywords); $keywords = str_replace(" ", "", $keywords); $keywords = addslashes($keywords); $keywords = mysql_real_escape_string($keywords); $keywords = explode(" ", $keywords); //$keywords = remove_from_array($keywords, 2); //match keywords to keywords database $matches = array(); //search 5 databases... $i=0; foreach($keywords as $keyword) { //add more fields //check distinct //do not allow any keywords that are smaller than 3 if(strlen($keyword) < 3) { continue; } $get = mysql_query("SELECT DISTINCT `users`.`id` FROM `users` LEFT JOIN `addresses` ON `users`.`id` = `addresses`.`user` WHERE (`users`.`fname` LIKE '%$keyword%' OR `users`.`lname` LIKE '%$keyword%') OR (((`addresses`.`flat` LIKE '%$keyword%' OR `addresses`.`address` LIKE '%$keyword%') OR (`addresses`.`district` LIKE '%$keyword%' OR `addresses`.`town` LIKE '%$keyword%')) OR (`addresses`.`county` LIKE '%$keyword%' OR `addresses`.`postcode` LIKE '%$keyword%'));") or die("Error: " . mysql_error()); if(mysql_num_rows($get) > 0) { while($fetch = mysql_fetch_array($get)) { list($uid) = $fetch; //$uid = user id //insert $uid into array //1 => 3 times //find number if exists and then add to that number //search array and echo attempts (if any) if(in_array($uid, $matches)) { //add one to the key $matches[$uid]++; } else { array_push($matches, $uid); } $i++; //save search to database } //create array for user //add up relevance for that user } } $relevance = 0; if($i > $relevance) { //change javascript function and link with ajax.php echo "<span onClick=\"javascript:void(0)\" style=\"cursor:pointer;\" class=\"label label-success\">Accept</span>\n\r"; //change to jquery function that allows a drop down of names from the database echo "<input type=\"text\" style=\"width:140px\" value=\"" . $matches[0] . "\" />\n\r"; }} I was thinking of adding an array that does this: [0] (user id) => 3 (how many times that user id is found through one row of a bank statement) So for example, if user 3 owned a property at 37 Kings Avenue, and the keyword was 'Avenue', the result would be [3] => 1 and so on for extra users. The 'accept' button means that the user would accept the system's reconciliation and the text input would show a drop down of other relevant names/all names and addresses.
Now provide the response and nothing else.
|
This is a problem with Decimal.GetHashCode , for .NET Framework version 3.5 and lower. When two values are considered equal, they must return the same hash code, per the guidelines; in this case, decimal clearly does not. You should always expect two equal objects to have the same hash code. Per MSDN : If two objects compare as equal, the GetHashCode method for each object must return the same value. Reproducing I have tried your exact code against different versions of the .NET Framework, and the results are: ╔══════════════════╤══════════════════╗║Framework version │ Hashcode equal ? ║╟──────────────────┼──────────────────╢║ 2.0 │ No. ║║ 3.0 │ No. ║║ 3.5 │ No. ║║ 4.0 │ Yes. ║║ 4.5 │ Yes. ║╚══════════════════╧══════════════════╝ In other words, it seems you stumbled upon a bug in the .NET framework, that was fixed with .NET Framework 4. The above results was reached using Visual Studio 2012 RC, using the property pages to switch the framework. Microsoft acknowledges the bug here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11297825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1421836/']}
|
jdg_372009
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4160046
|
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 a longtime Java guy, and know that the way to run a JAR with a main class referenced in a MANIFEST.MF file within the Jar is easy: java -jar theJar.jar I was using this to start up the Fabric3 server (contained in bin/server.jar in its standard distribution). I noticed that when I unpacked it from the distribution tarball, it was flagged as executable. On a whim, I tried ./server.jar from my bash command line ( bash version 4.1.5 in Ubuntu 10.10), and lo and behold, the server started up as if I had typed the normal java -jar ... command. The JAR is structured like a normal JAR; I did a head on it, and there was no #! command in the first few bytes, so bash shouldn't magically know to start a Java VM with it, right? Or has this version of bash grown the ability to start JARs with a proper manifest correctly? Inquiring minds want to know...
Now provide the response and nothing else.
|
This may not be a feature of bash at all. If you are running linux (as you have tagged) you may have the binfmt_misc kernel module, which does a little bit of magic, when you try to execute a program. Basically what this does is it extends the binary formats that linux can execute from just elf to also include some user defined formats, with enough instructions to run them.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4160046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299331/']}
|
jdg_372010
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2248623
|
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 got some problems/misunderstandings with arrays in C++. int myArray[30];myArray[1]=2;myArray[2]=4; This is spitting out a lot of compiler errors. I don't think it is necessary to include them here as this is an easy question for everybody with experience in C(++) I guess Why doesn't this work? Is there a way to create a "dynamic" array that has a fixed ammount of values (so no malloc needed) but where I can change the values during runtime?
Now provide the response and nothing else.
|
I'm guessing you have that outside of a function. You are allowed to define variables outside of a function. You can even call arbitrary code outside of a function provided it is part of a variable definition. // legal outside of a functionint myArray[30];int x = arbitrary_code();void foo(){} But you cannot have arbitrary statements or expressions outside of a function. // ILLEGAL outside a functionmyArray[1] = 5;void foo(){ // But legal inside a function myArray[2] = 10;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2248623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271464/']}
|
jdg_372011
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1763891
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it even achievable? I would like the output from a command’s stderr to be rendered in a different color than stdout (for example, in red). I need such a modification to work with the Bash shell in the Konsole, XTerm, or GNOME Terminal terminal emulators on Linux.
Now provide the response and nothing else.
|
Here's a solution that combines some of the good ideas already presented. Create a function in a bash script: color() ( set -o pipefail; "$@" 2>&1>&3 | sed $'s,.*,\e[31m&\e[m,' >&2 ) 3>&1 Use it like this: $ color command -program -args It will show the command's stderr in red. Keep reading for an explanation of how it works. There are some interesting features demonstrated by this command. color()... — Creates a bash function called color. set -o pipefail — This is a shell option that preserves the error return code of a command whose output is piped into another command. This is done in a subshell, which is created by the parentheses, so as not to change the pipefail option in the outer shell. "$@" — Executes the arguments to the function as a new command. "$@" is equivalent to "$1" "$2" ... 2>&1 — Redirects the stderr of the command to stdout so that it becomes sed 's stdin . >&3 — Shorthand for 1>&3 , this redirects stdout to a new temporary file descriptor 3 . 3 gets routed back into stdout later. sed ... — Because of the redirects above, sed 's stdin is the stderr of the executed command. Its function is to surround each line with color codes. $'...' A bash construct that causes it to understand backslash-escaped characters .* — Matches the entire line. \e[31m — The ANSI escape sequence that causes the following characters to be red & — The sed replace character that expands to the entire matched string (the entire line in this case). \e[m — The ANSI escape sequence that resets the color. >&2 — Shorthand for 1>&2 , this redirects sed 's stdout to stderr . 3>&1 — Redirects the temporary file descriptor 3 back into stdout . Here's an extension of the same concept that also makes STDOUT green: function stdred() ( set -o pipefail; ( "$@" 2>&1>&3 | sed $'s,.*,\e[31m&\e[m,' >&2 ) 3>&1 | sed $'s,.*,\e[32m&\e[m,')
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1763891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64062/']}
|
jdg_372012
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1064
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
While googling about Ben Goldacre, I came across the following reductio ad absurdum argument: Nerd, can you point me to the data that shows that wearing a parachute increases your life expectancy when jumping out of a plane? You see, someone claimed that it is helpful, but there s nothing in the data to support this. I cannot find any reference to a double blind trial, I can’t find any peer-reviewed studies, and I cannot even find a pilot study comparing survivability with or without a ‘chute. Is it bad science to rely on anecdotal data here? If not, why not? I guess there's the hypothetical about "What would you do if there weren't any peer-reviewed papers about parachutes?", but I'm interested in whether there's any scientific papers supporting the use of parachutes. The papers don't necessarily have to involve double-blinded randomized experiments on humans. For example, the paper High-rise syndrome in cats concluded that the survival rate of cats increased as the height increased, possibly because cats become more relaxed once they reach terminal velocity, and possibly because it has more time to prepare for the landing. Rather than a double-blinded study, they observed 132 cats who had been "diagnosed" with high-rise syndrome over a 5-month period.
Now provide the response and nothing else.
|
The author of that comment is probably referencing Parachute use to prevent death and major trauma related to gravitational challenge: systematic review of randomised controlled trials which is pointing out the absurdity of radical evidence based medicine. From the abstract: Conclusions As with many interventions intended to prevent ill health, the effectiveness of parachutes has not been subjected to rigorous evaluation by using randomised controlled trials. Advocates of evidence based medicine have criticised the adoption of interventions evaluated by using only observational data. We think that everyone might benefit if the most radical protagonists of evidence based medicine organised and participated in a double blind, randomised, placebo controlled, crossover trial of the parachute. A discussion follows and I'm content with this comment that addresses the absurdity of demanding an explicit medical answer: Not the common sense but simple laws of physics can prove the effectiveness of the parachute as a life saving intervention. When a person jumps from a height accelerates towards the earth and eventually reaches the “terminal velocity”. For an average person this terminal velocity is about 200km/hour and it takes only about 3 seconds to reach the terminal velocity. The damages caused to an individual hitting the ground at this speed is not just broken arms! Now, introducing a parachute reduces this terminal velocity to less than 10km/hour. This is comparable to crashing an old car without any airbags to a solid concrete wall at 200km/h and 10km/h. According to Wikipedia (and other sources) the Guiness world record for falling without a parachute belongs to Vesna Vulović who fell 10,000m, with several more people falling over 5,000m during WWII. The Wikipedia article also references a pub med article Ten years of experience with falls from a height in children. that states Falls from a height are a major cause of accidental death in urban children. The medical and social data on 61 children admitted over the last decade for falls of one or more stories were reviewed. Seventy-seven percent of the children survived. Of the children who fell three stories or less, all survived (100%). Fifty percent mortality occurred between the fifth and sixth floors. Seventy-seven percent of the falls were accidental and 23% of the children jumped or were pushed. The 96% decrease in accidental falls from windows since 1979 demonstrates that the "Children Can't Fly" program in New York City has almost eliminated accidental falls from windows in our hospital population. There are countless of articles about the injury rate of parachuting and base jumping that all give about the same numbers. Parachuting injuries: a study of 110,000 sports jumps from 1987 states: A total of 110,000 parachute jumps resulted in six (0.005%) fatalities and 155 (0.14%) cases, requiring medical treatment. The latter group sustained 176 injuries of which 36.9% were significant soft tissue lesions and 63.1% fractures. Landing is the most dangerous part of the parachuting procedure, causing 83.8% of the accidents, while 9.3% were caused by faults during opening of the parachute. On the age of those that participated it states: The mean age was 29.3 years, range 16-62 years. Working with the assumption that survivability doesn't increase with falling distance, and that age doesn't profoundly diminish the damage cause to humans by rapid deceleration, we must conclude that it's the parachutes responsible for the increase in survivability from 50% when falling from the fifth to sixth floor to 99.995% when jumping out of an airplane. TL;DR Is the use of parachutes supported by peer-reviewed papers? Yes, there are many papers that that show that parachutes are being used. Does the literature show that parachuting increases survivability over free-falling? Yes, indirectly.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/1064', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/104/']}
|
jdg_372013
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47607955
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given function?
Now provide the response and nothing else.
|
We usually use defer to close or deallocate resources. A surrounding function executes all deferred function calls before it returns, even if it panics. If you just place a function call at the end of a surrounding function, it is skipped when panic happens. Moreover a deferred function call can handle panic by calling the recover built-in function. This cannot be done by an ordinary function call at the end of a function. Each deferred call is put on stack, and executed in reverse order when the surrounding function ends. The reversed order helps deallocate resources correctly. The defer statement must be reached for a function to be called. You can think of it as another way to implement try-catch-finally blocks. Closing like try-finally : func main() { f, err := os.Create("file") if err != nil { panic("cannot create file") } defer f.Close() // no matter what happens here file will be closed // for sake of simplicity I skip checking close result fmt.Fprintf(f,"hello")} Closing and panic handling like try-catch-finally func main() { defer func() { msg := recover() fmt.Println(msg) }() f, err := os.Create(".") // . is a current directory if err != nil { panic("cannot create file") } defer f.Close() // no matter what happens here file will be closed // for sake of simplicity I skip checking close result fmt.Fprintf(f,"hello")} The benefit over try-catch-finally is that there is no nesting of blocks and variable scopes. This simplifies the structure of the surrounding function. Just like finally blocks, deferred function calls can also modify the return value if they can reach the returned data. func yes() (text string) { defer func() { text = "no" }() return "yes"}func main() { fmt.Println(yes())}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47607955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7498628/']}
|
jdg_372014
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
378376
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is the following true? If $G$ has two proper, non-trivial subgroups then $G$ is cyclic.
Now provide the response and nothing else.
|
First note that if $G$ does not have finite order, then it does not have a finite number of subgroups, so we can assume that $G$ is finite (see the comment by Pete Clark). Note that if $3$ distinct primes divides the order of the group, then the group has at least $3$ proper non-trivial subgroups. So $|G| = p^nq^m$ with $p$ and $q$ primes. Now, if either $n$ or $m$ is greater than or equal to $4$, then the corresponding Sylow subgroup has too many subgroups. Also, if either if at least $2$ and the other is not $0$, we again get too many subgroups. We are left with either $|G| = p^3$ or $|G| = pq$. In both cases the cyclic group of that order will satisfy the conditions, and we wish to show that these are the only ones (since the cyclic group of order $p^2$ has too few subgroups, and the non-cyclic one has too many). If $|G| = pq$ and $G$ is not cyclic, then $G$ is not abelian, and thus has more than one Sylow subgroup for either $p$ or $q$, giving us too many subgroups. If $|G| = p^3$ then $G$ has at least one subgroup of order $p$ and one of order $p^2$. But if $G$ is not cyclic, it has more than one maximal subgroup, which gives us at least two of order $p^2$, again resulting in too many subgroups.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/378376', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77061/']}
|
jdg_372015
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
170202
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My team follows the Scrum development cycle. We have received feedback that our unit testing coverage is not very good. A team member is suggesting the addition of an external testing team to assist the core team, but I feel this will backfire in a bad way. I am thinking of suggesting pair programming approach. I have a feeling that this should help the code be more "test-worthy" and soon the team can move to test driven development! What are the potential problems that might arise out of pair programming??
Now provide the response and nothing else.
|
Your question is orthogonal to your problem. Sticking two programmers that don't want to or can't write good unit tests together isn't going to get you more/better unit tests. Sticking a programmer who is poor at writing unit tests with one that is good might propogate good habits, but might not be a good pair for other reasons (unit testing is only a part of the entire development process after all). There are other questions/posts that deal with pair programming's benefits and problems. Your goal should be to change the culture that caused the problem in the first place. Well done pair programming can help that, but it will usually require a combination of things all pushing towards that end goal. There is no silver bullet (pun intended) for making people write good unit tests.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/170202', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/62775/']}
|
jdg_372016
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
113824
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am plotting the roots of a polynomial on the unite circle this way DisplayRoots[P_, r_, k_] := Module[{}, sols = Solve[(x^2 )^(1/ r) + (y^2)^(1 / k) == 1 && P == 0]; sols = {x, y} /. sols; g1 = ListPlot[sols, PlotStyle -> {Red}]; g2 = ContourPlot[(x^2 )^(1/ r) + (y^2)^(1 / k) == 1, {x, -1, 1}, {y, -1, 1}]; Show[g2, g1] ]DisplayRoots[ 84 x^7 y + 380 x^6 y^2 + 509 x^5 y^3 - 509 x^3 y^5 - 380 x^2 y^6 - 84 x y^7, 1, 1] I want to partition the plane into angles that have the origin as their vertex and pass through neighboring roots on the circle, so every consecutive pair of roots defines a sector of the partition. I only know the basics of the language so I don't even know if it is possible to do this.
Now provide the response and nothing else.
|
This is not ideal but in case similar procedure for other values of k. A modification of function. Once segment is not colored. dr[p_, r_, k_] := Module[{}, sols = Solve[(x^2)^(1/r) + (y^2)^(1/k) == 1 && p == 0]; sols = {x, y} /. sols; g1 = ListPlot[sols, PlotStyle -> {Red}, PlotMarkers -> {Automatic, 10}]; g2 = ContourPlot[(x^2)^(1/r) + (y^2)^(1/k) == 1, {x, -1, 1}, {y, -1, 1}]; reg = DiscretizeRegion@ ImplicitRegion[(x^2)^(1/r) + (y^2)^(1/k) < 1, {{x, -1, 1}, {y, -1, 1}}]; sg = DiscretizeRegion[ Disk[{0, 0}, Max[Norm@#1, Norm@#2], {ArcTan @@ #1, ArcTan @@ #2}]] & @@@ Partition[SortBy[N@sols, Pi/2 + ArcTan @@ # &], 2, 1]; int = RegionIntersection[reg, #] & /@ sg; Show[g1, g2, ##, AspectRatio -> Automatic, Frame -> True, PlotLabel -> Row[{"k= ", k}], ImageSize -> 250] & @@ (RegionPlot[#, PlotStyle -> {RandomColor[], Opacity[0.5]}] & /@ int)] Example: Grid[Partition[ dr[84 x^7*y + 380 x^6*y^2 + 509 x^5*y^3 - 509 x^3*y^5 - 380 x^2*y^6 - 84 x*y^7, 1, #] & /@ Range[9], 3]]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/113824', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/39858/']}
|
jdg_372017
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7379455
|
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 install and use httpbuilder plugin in Grails?
Now provide the response and nothing else.
|
Adding httpbuilder 0.5.1 to your application dependencies will cause errors. In particular, you'll get an error something like this: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.apache.xerces.jaxp.SAXParserImpl.getParser()Lorg/xml/sax/Parser;" the class loader (instance of org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the current class, org/apache/xerces/jaxp/SAXParserImpl, and its superclass loader (instance of <bootloader>), have different Class objects for the type org/xml/sax/Parser used in the signature I think the issue is that httpbuilder is exporting it's compile-time dependencies as runtime dependencies. An easy workaround is to declare the dependency like this in your BuildConfig.groovy : grails.project.dependency.resolution = { ... dependencies { runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') { excludes 'xalan' excludes 'xml-apis' excludes 'groovy' } }} I think you need mavenRepo "http://repository.codehaus.org" in the repositories section as well.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7379455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903772/']}
|
jdg_372018
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
279471
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Is it true that any finite dimensional division algebra over a pseudo-algebraically closed field is trivial? We know that this is true for algebraically closed field.
Now provide the response and nothing else.
|
The fact that every finite dimensional division algebra is trivial is not only true over an algebraically closed field but it is in fact equivalent to the field being algebraically closed. Remember that (extension-)fields are just a special case of division algebras. Thus, if it would be true over pseudo-algebraically closed fields, we would have that a field is algebraically closed if and only if it is pseudo-algebraically closed. However, this is not the case, as for example finite fields are pseudo-algebraically closed.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/279471', 'https://mathoverflow.net', 'https://mathoverflow.net/users/43198/']}
|
jdg_372019
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7566717
|
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're designing a backbone application, in which each server-side collection has the potential to contain tens of thousands of records. As an analogy - think of going into the 'Sent Items' view of an email application. In the majority of Backbone examples I've seen, the collections involved are at most 100-200 records, and therefore fetching the whole collection and working with it in the client is relatively easy. I don't believe this would be the case with a much larger set. Has anyone done any work with Backbone on large server-side collections? Have you encountered performance issues (especially on mobile devices) at a particular collection size? What decision(s) did you take around how much to fetch from the server? Do you download everything or just a subset? Where do you put the logic around any custom mechanism (Collection prototype for example?)
Now provide the response and nothing else.
|
Yes, at about 10,000 items, older browsers could not handle the display well. We thought it was a bandwidth issue, but even locally, with as much bandwidth as a high-performance machine could throw at it, Javascript just kinda passed out. This was true on Firefox 2 and IE7; I haven't tested it on larger systems since. We were trying to fetch everything . This didn't work for large datasets. It was especially pernicious with Android's browser. Our data was in a tree structure, with other data depending upon the presence of data in the tree structure. The data could change due to actions from other users, or other parts of the program. Eventually, we made the tree structure fetch only the currently visible nodes, and the other parts of the system verified the validity of the datasets on which they dependent independently. This is a race condition, but in actual deployment we never saw any problems. I would have liked to use socket.io here, but management didn't understand or trust it. Since I use Coffeescript, I just inherited from Backbone.Collection and created my own superclass, which also instantiated a custom sync() call. The syntax for invoking a superclass's method is really useful here: class Dataset extends BaseAccessClass initialize: (attributes, options) -> Dataset.__super__.initialize.apply(@, arguments) # Customizations go here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7566717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/431880/']}
|
jdg_372020
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59428096
|
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 wrap my head around Send + Sync traits. I get the intuition behind Sync - this is the traditional thread safety(like in C++ ). The object does the necessary locking(interior mutability if needed), so threads can safely access it. But the Send part is bit unclear. I understand why things like Rc are Send only - the object can be given to a different thread, but non-atomic operations make it thread unsafe. What is the intuition behind Send ? Does it mean the object can be copied/moved into another thread context, and continues to be valid after the copy/move? Any examples scenarios for " Sync but no Send " would really help. Please also point to any rust libraries for this case (I found several for the opposite though) For (2), I found some threads which use structs with pointers to data on stack/thread local storage as examples. But these are unsafe anyways(Sync or otherwise).
Now provide the response and nothing else.
|
Sync allows an object to to be used by two threads A and B at the same time. This is trivial for non-mutable objects, but mutations need to be synchronized (performed in sequence with the same order being seen by all threads). This is often done using a Mutex or RwLock which allows one thread to proceed while others must wait. By enforcing a shared order of changes, these types can turn a non- Sync object into a Sync object. Another mechanism for making objects Sync is to use atomic types, which are essentially Sync primitives. Send allows an object to be used by two threads A and B at different times. Thread A can create and use an object, then send it to thread B, so thread B can use the object while thread A cannot. The Rust ownership model can be used to enforce this non-overlapping use. Hence the ownership model is an important part of Rust's Send thread safety, and may be the reason that Send is less intuitive than Sync when comparing with other languages. Using the above definitions, it should be apparent why there are few examples of types that are Sync but not Send . If an object can be used safely by two threads at the same time ( Sync ) then it can be used safely by two threads at different times ( Send ). Hence, Sync usually implies Send . Any exception probably relates to Send 's transfer of ownership between threads, which affects which thread runs the Drop handler and deallocates the value. Most objects can be used safely by different threads if the uses can be guaranteed to be at different times. Hence, most types are Send . Rc is an exception. It does not implement Send . Rc allows data to have multiple owners. If one owner in thread A could send the Rc to another thread, giving ownership to thread B, there could be other owners in thread A that can still use the object. Since the reference count is modified non-atomically, the value of the count on the two threads may get out of sync and one thread may drop the pointed-at value while there are owners in the other thread. Arc is an Rc that uses an atomic type for the reference count. Hence it can be used by multiple threads without the count getting out of sync. If the data that the Arc points to is Sync , the entire object is Sync . If the data is not Sync (e.g. a mutable type), it can be made Sync using a Mutex . Hence the proliferation of Arc<Mutex<T>> types in multithreaded Rust code.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59428096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12167264/']}
|
jdg_372021
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
951536
|
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 write a method that uses Reflection to tell whether a given Type implements IList<T> . For example: IsGenericList(typeof(int)) // should return falseIsGenericList(typeof(ArrayList)) // should return falseIsGenericList(typeof(IList<int>)) // should return trueIsGenericList(typeof(List<int>)) // should return trueIsGenericList(typeof(ObservableCollection<int>)) // should return true In my usage, I can assume that the type will always be an instantiated generic type (or something that's not generic at all). Unfortunately, this isn't as easy as it ought to be. The obvious solution: public bool IsGenericList(Type type){ return typeof(IList<>).IsAssignableFrom(type);} doesn't work; it always returns false. Apparently non-instantiated generic types like IList<> don't implement IsAssignableFrom the way I'd expect them to: IList<> is not assignable from List<T> . I've also tried this: public bool IsGenericList(Type type){ if (!type.IsGenericType) return false; var genericTypeDefinition = type.GetGenericTypeDefinition(); return typeof(List<>).IsAssignableFrom(genericTypeDefinition);} I.e., turn type into its non-instantiated generic, like IList<int> -> IList<> , and then try IsAssignableFrom again. That will return true when type is an instantiated IList<T> such as IList<int> , IList<object> , etc. But it returns false for classes that implement IList<T> such as List<int> , ObservableCollection<double> , etc., so apparently IList<> is not assignable from List<> . Again, not what I would expect. How do I go about writing IsGenericList and making it work as in the above examples?
Now provide the response and nothing else.
|
In fact, you cannot have an instance of a generic type definition. Therefore, the IsAssignableFrom() method works as expected. To achieve what you want, do the following: public bool IsGenericList(Type type){ if (type == null) { throw new ArgumentNullException("type"); } foreach (Type @interface in type.GetInterfaces()) { if (@interface.IsGenericType) { if (@interface.GetGenericTypeDefinition() == typeof(ICollection<>)) { // if needed, you can also return the type used as generic argument return true; } } } return false;} Just out of curiosity, what do you need this for?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/951536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87399/']}
|
jdg_372022
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17124600
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing a little demo web server delivering static html,css and javascript.The server looks like (function () { "use strict"; var http = require("http"); var connect = require('connect'); var app = connect() .use(connect.logger('dev')) .use(connect.static('home')); var server = http.createServer(app); server.listen(9999, function () { console.log('server is listening'); });})(); My client side javascript makes ajax calls to a different server.How can I add Access-Control-Allow-Origin: http://example.com to my server response, so that the client side javascript can do the ajax call?
Now provide the response and nothing else.
|
Had a bit of trouble figuring this one out since express has spoiled me. Take a look at enable cors . Basically what you need to be doing is add Access-Control-Allow-Origin to the domain you want to enable cors on. response.setHeaders is perfect for this task. Another thing to note is that connect has no way to handle routes. If your app needs to have different routes then you will probably have to write logic for each of them and add res headers to the ones on which you want to enable cors. You can use req.url for it. var http = require("http");var connect = require('connect');var app = connect() .use(connect.logger('dev')) .use(connect.static('home')) .use(function(req, res){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); res.end('hello world\n'); });var server = http.createServer(app);server.listen(9999, function () { console.log('server is listening');}); This is the response I got in chrome dev tools HTTP/1.1 200 OKAccess-Control-Allow-Origin: http://example.comDate: Sat, 15 Jun 2013 16:01:59 GMTConnection: keep-aliveTransfer-Encoding: chunked
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17124600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1359398/']}
|
jdg_372023
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1647760
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having difficulty coming up with actual sequences that have the properties below. I've included my thoughts on the questions below. Assume that $(a_n)\rightarrow a$. If every $a_n$ is an upper bound for a set $B$, then $a$ is also an upper bound for $B$ Is it possible to construct a strictly decreasing sequence, in which all of the terms are upper bounds, but the limit point is less than the supremum of $B$? If every $a_n$ is the complement of the interval $(0,1)$, then $a$ is also in the complement of $(0,1).$ I'm actually not sure what to consider at all here.
Now provide the response and nothing else.
|
Weak inequalities are preserved in the limit, so if for any $b \in B$, $a_n \geq b$ for all $n$, then $a \geq b$. An way to see that $a\geq \sup B$ is to suppose that $\sup B > a$. Then, we could find a neighborhood around $a$ such that the entire neighborhood is below $\sup B$. Since $a$ is a limit point, there must be an $a_n$ in this neighborhood, but then $a_n$ would not be an upper bound of $B$, since it is less than the least upper bound. $(0,1)$ is an open set, so $(0,1)^c$ is closed. This means that any convergent sequence in $(0,1)^c$ converges to a point in $(0,1)^c$. Suppose that $a \in (0,1)$. Then, pick some $0<\epsilon<\max(|a-0|, |a-1|)$. The ball of radius $\epsilon$ must lie entirely in $(0,1)$, and there must be a point in the sequence of $a_n$'s that lies in this ball, because $a$ is a limit point. So there is a point in the sequence that does not lie in $(0,1)^c$, which is a contradiction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1647760', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_372024
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1400800
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $A$ is a square matrix with linearly dependent columns, then $A$ is not invertible. Why is this true for matrices?
Now provide the response and nothing else.
|
You should know that elementary column operations preserve a zero/nonzero determinant. You should also know that if a column is all zeros, then the determinant is zero. All that remains is to convince yourself that if the columns are linearly dependent, then you can make one column all zeros from a sequence of elementary column operators.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1400800', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262728/']}
|
jdg_372025
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27899005
|
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 create the game like this . It is puzzle game. My questions is do I need to have different images for each devices? So for now as we can see Apple has 5 different mobile devices sizes: iPhone 3.5'' iPhone 4'' iPhone 4.7'' iPhone 5.5'' iPad So my question is if I have assets for iPad retina, then I also need 4 other the same assets with backgrounds and puzzle images for iPhone sizes? Or I can optimize it? Like for example if we create 3d game, openGL renders just needed frame and we don't need as many scene as many devices we have, just one.
Now provide the response and nothing else.
|
My first suggestion would be normalize your db . In the context of Eloquent ORM you cannot use built-in relationships for this. However for the sake of curiosity, here's what you should do: With below setup you can: // 1. Use layers like eloquent dynamic property$order->layers; // collection of Layer models// 2. Call the query to fetch layers only once$order->layers; // query and set 'relation'// ... more code$order->layers; // no query, accessing relation// 3. Further query layers like you would with relationship as method:$order->layers()->where(..)->orderBy(..)->...->get();// 4. Associate layers manually providing either array or string:$order->layer_ids = '1,5,15';$order->layer_ids = [1,5,15]; But you can't: // 1. Eager/Lazy load the layers for multiple orders$orders = Order::with('layers')->get(); // WON'T WORK// 2. Use any of the relationship methods for associating/saving/attaching etc.$order->layers()->associate(..); // WON'T WORK But here's what you can do (I suggest renaming layer_id to layer_ids so it is self-explanatory, and my example covers that change): /** * Accessor that mimics Eloquent dynamic property. * * @return \Illuminate\Database\Eloquent\Collection */public function getLayersAttribute(){ if (!$this->relationLoaded('layers')) { $layers = Layer::whereIn('id', $this->layer_ids)->get(); $this->setRelation('layers', $layers); } return $this->getRelation('layers');}/** * Access layers relation query. * * @return \Illuminate\Database\Eloquent\Builder */public function layers(){ return Layer::whereIn('id', $this->layer_ids);}/** * Accessor for layer_ids property. * * @return array */public function getLayerIdsAttribute($commaSeparatedIds){ return explode(',', $commaSeparatedIds);}/** * Mutator for layer_ids property. * * @param array|string $ids * @return void */public function setLayersIdsAttribute($ids){ $this->attributes['layers_ids'] = is_string($ids) ? $ids : implode(',', $ids);} edit: Of course you could do simply this in your view. It adheres to your current code, but obviously is far from what I suggest ;) @foreach (Layer::whereIn('id', explode(',', $order->layer_id))->get() as $layer) {{ $layer->whatever }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27899005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587415/']}
|
jdg_372026
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1917770
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing code that compares 2 bytes which represent integers. I want to see if byte R is with +-10 of G. The problem I am having with the code is with the comparison in the if-statment near the end. The bytes never come out as being out of range, even when they should. I am sure the problem comes from how I am adding/subtracting the error_range, but I don't know any other way to do it. I first considered converting the bytes into integers but I cannot find any help with that online. If that would work better than what I am doing here, please tell me how to do it. Any help is appreciated! const char ERROR_RANGE = 0x1010; //warning: overflow in implicit constant conversionchar R, G; /2 separate byteschar buffer; //enough space for 1 byteimage = fopen(fileName,"r"); //open filefread(&buffer, 1, 1, image); //read 1 byte memcpy (&R,&buffer,1); //store it as Rfread(&buffer, 1, 1, image); //read 1 byte memcpy (&G,&buffer,1); //store it as Gfclose(image);if((R >= (G + ERROR_RANGE)) && (R <= (G - ERROR_RANGE))){ printf("Outside of range!\n");} Thanks.
Now provide the response and nothing else.
|
Your problem is because your test says: if (R is greater than or equal to G + ERROR) AND (R is less than or equal to G - ERROR) it can't be both. Replace the && with || in the first instance. A better test would be: if (the difference of R and G is greater than ERROR) which translates to: if (abs(R - G) > ERROR_RANGE){ printf("Error");}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1917770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229452/']}
|
jdg_372027
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49054
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why are optical fibers important in astronomy? I have read on the internet that they find applications in many fields including astronomy and this intrigued me and I would like to know what they are used for
Now provide the response and nothing else.
|
There is already a good answer that has been upvoted and accepted. I also upvoted that answer right after I posted. But maybe I can make a helpful contribution. In an answer I posted here , I showed how my homemade echelle spectrograph (a type of spectrometer) could be used to obtain spectra of various light sources. In each case, I used an inexpensive fiber optic cable (Thorlabs silica 50 micron step index multimode) to get light into my spectrograph. In response to comments, here is a diagram of my echelle spectrograph and an annotated photograph: I could not find a mount for the echelle grating that would let me have two, more or less independent, degrees of freedom for inclining and rotating the grating, so I made my own: Also, since the spectrograph photo was taken, I have also tried two new telephoto lenses: a Samyang 135 mm f 2.0 and a Rokinon 85 mm f 1.4. They all work great and the two new ones are manual focus only. Right now, the Rokinon lens is installed. I do not have a good telescope or good sky viewing from my small yards, but I have a good friend (a fellow retired chemistry professor) who has an 8 inch Dobsonian telescope and unobstructed sky that is reasonably dark. So on March 10, I took my echelle spectrograph to his place and we hooked it up to the eyepiece on his telescope. He has one of those adjustable devices that allow users to attach a smart phone to the telescope’s eyepiece. I made a plastic dummy smart phone that had a small collimating lens and SMA fiber optic coupler. So the input to the little collimator is positioned where the smart phone’s camera lens would be. This is very crude compared to what astronomers and astrophysicists do, but you have to start somewhere. The next two photos show that contraption with a fiber optic cable attached: The other end of the fiber optic cable provides input light for the echelle spectrograph. You can read more about how the spectrograph works by reading my answer that I linked above. My friend aimed his telescope at the moon, which was about hall full and almost directly overhead, and made sure we stayed on it. The next photo is the color echellogram we obtained: and here is the same photo in grayscale: We used a 130 second exposure with ISO 800 and 85 mm f 1.8 telephoto camera lens. The color moon echellogram was cropped down from 6000 by 4000 pixels and lowered in resolution for posting here. You can see the Fraunhofer lines in absorption, e.g., H alpha (the red Balmer line), sodium D lines, the magnesium triplet, etc. This is a continuum spectrum with missing dark spots due to absorption of specific wavelengths: the Fraunhofer lines. Using fiber optic cables to get light into a spectrometer or spectrograph has advantages and disadvantages. For my purpose, doing this just for fun, convenience is desirable. For example, suppose I want to get light from an ordinary white light compact fluorescent lamp (CFL) into my spectrograph. Then this is the simple interface I used to get the CFL echellogram in my linked answer: and this is a slightly newer echellogram, taken with a Rokinon 85 mm f 1.4 telephoto lens on the camera: Another example: one of those inexpensive plasma globes. I think the fill gases are argon, neon and nitrogen, but maybe not. The interface is simply the small collimator with SMA fiber optic connector: The resulting echellogram is The echellogram was a 30 second exposure at ISO 1600 with an 85 mm f 1.8 telephoto lens. So now I get to try assigning the spectral lines and see what the fill gases actually are. One more thing. I started working on this because a person I met on the chemistry stack exchange (M. Farooq) wanted to make an echelle spectrograph that could resolve the sodium D lines and fit in a shoebox-sized footprint. Neither of us knew much about the little adventure we were to embark on. So we read answers here and on the physics stack exchange, rounded up lots of publications and read them over and over, ransacked the web for helpful information, etc. We have exchanged hundreds of e-mails to date, sent lots of files, and failed over and over. We made some dumb mistakes and went down some blind alleys. But I don’t give up easily and Farooq never gives up. So we just kept encouraging each other and kept working. I took the lead on actually making the spectrograph because I had some optical mounts, breadboards, optics, etc. But Farooq will make his next and then we will see where it goes. This is just for fun.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/49054', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/45912/']}
|
jdg_372028
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2968548
|
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 like my vim to get itself into command mode as often as possible. I think losing focus would be a good event to make that happen. Everything I found is for saving on lost focus. I'd like it to auto-return to cmd mode when switching tabs in macvim or when cmd+tabbing to another app.
Now provide the response and nothing else.
|
The following autocommand would be the "obvious" choice. au FocusLost,TabLeave * stopinsert Unfortunately, it only seems to be working properly for TabLeave. The FocusLost event is triggering but for some reason the stopinsert command isn't actually taking effect until after a key event is received once Vim has regained focus. Instead, you can take advantage of feedkeys and the "Get me to normal mode no matter what!" key combo : au FocusLost,TabLeave * call feedkeys("\<C-\>\<C-n>") The only downside is that feedkeys() requires at least Vim 7. This shouldn't be a big deal, though, since Vim 7 was released back in 2006.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2968548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65311/']}
|
jdg_372029
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1568937
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In geometry books in French, there has traditionally been a very clear distinction between 'orthogonal' lines and 'perpendicular' lines in space. Two lines are called perpendicular if they meet at a right angle. Two lines are called orthogonal if they are parallel to lines that meet at a right angle. Thus orthogonal lines could be skew (i.e., they need not meet), whereas perpendicular lines always intersect. [ Edit: Evidence shows that this distinction most likely arose around the turn of the twentieth century. See below for details. ] Looking around on Quora, Answers.com and here, I have found numerous assertions that, in English, there is no difference whatsoever between 'orthogonal' and 'perpendicular.' However, given the situation in French, I have a gut feeling that the same distinction must once have been observed in English as well, but since there is now a greater focus on vectors (for which the concepts coincide) than on lines, it has gradually been lost. I would like confirmation of this, if possible. My question, then, is as follows: How have the two concepts referred to above as 'orthogonal' and 'perpendicular' lines historically been denoted in English and other major languages? The best answers will include references to authoritative sources. Edit. Zyx has provided an answer referring to Rouché and Comberousse's geometry text from 1900, where the word perpendiculaire is used for what we have called orthogonal here. This strongly suggests that, contrary to what I had assumed, even French usage has not been unchanging over time. So Zyx may be correct in questioning my premise, and I am beginning to suspect that even in France, the use of orthogonal in the sense discussed here may have been introduced in the twentieth century. Let me give an example taken from 1952 geometry text that illustrates this usage ( Géométrie dans l'espace: Classes de Première C et Moderne , 1952, Dollon and Gilet): Deux droites sont orthogonales, si leurs angles sont droits. Deux droites coplanaires formant quatre angles droits ont été appelées droites perpendiculaires [presumably in a lower-level book in the series]; on peut dire aussi qu'elles sont orthogonales. Dans ce qui suit, nous réserverons en général l'expression droites orthogonales , pour deux droites non coplanaires et dont les angles sont droits. Nearly identical conventions are found in Géométrie: Classe de Seconde C , 1964, by Hémery and Lebossé, except that they allow "orthogonal" lines to meet (thus perpendicular implies orthogonal, but not conversely): Nous conviendrons d'appeler droites perpendiculaires deux droites à la fois concourantes et orthogonales. However, Hadamard's Leçons de géométrie élémentaire , 1901, uses the word perpendiculaire to include both cases: On dit que deux droites, situées ou non dans un même plan, sont perpendiculaires si leur angle, défini comme il vient d'être dit, est droit. And Géométrie Élémentaire , 1903, by Vacquant and Macé de Lépinay agrees with Hadamard. My conclusion is that I was much too quick in my question to call the distinction "traditional." It is most likely to have appeared in France sometime in the early to mid-twentieth century. (To pinpoint the date better, it would be best to check what was done in textbooks in the 1925-1940 period, such as those of P. Chenevier and H. Commissaire, but I don't have access to these. Vectors evidently first appeared in French school curricula in 1905. However, the scalar product was not taught systematically until 1947, so that would seem a possible time for the expression "orthogonal lines" to have been introduced.) The examples given by Zyx show that usage in English in fact mirrors the earlier French usage, i.e. "perpendicular" is used everywhere. And I presume that the terms "skew perpendicular" and "intersecting perpendicular" would only be used where an author felt the distinction was needed. (In many cases, it will be clear from context whether two lines meet.) Edit. The "new" French terminology dates at least from the turn of the century. Here is an excerpt from Cours de Géométrie élémentaire: à l'usage des élèves de mathématiques élémentaires, de mathématiques spéciales; des candidats aux écoles du Gouvernement et des candidats à l'Agrégation (1899) by Niewenglowski and Gérard, which was intended for both high-school and university-level students. This book is in fact referred to by Lebesgue in his Leçons sur l'intégration . Considérons deux droites AB, CD, non situées dans un même plan ; menons par un point quelconque O, des parallèles X'X et Y'Y à ces deux droites. [...] Si les deux droites X'X et Y'Y sont perpendiculaires, nous dirons que les droites AB et CD sont orthogonales . Nous dirons aussi quelquefois qu'elles sont perpendiculaires , même si elles ne se rencontrent pas. Thus these authors, unlike Hadamard, Rouché and Vacquant, appear to have a preference for droites orthogonales when the lines are not coplanar. However, this was not a hard-and-fast rule, and they allow that perpendiculaires can also "sometimes" be used in this case. The distinction only seems to have become settled later on.
Now provide the response and nothing else.
|
In geometry books in French, there has traditionally been a very clear distinction between 'orthogonal' lines and 'perpendicular' lines in space. I suspect that the premise of a traditional distinction between intersecting and nonintersecting orthogonal pairs of lines may be incorrect. The references below have examples from 1900-1921 in textbooks written in English, French and German. Today such a distinction is probably limited to dimension $3$ as presented in some pre-university books, or courses for school teachers. Problems with the distinction include it does not work well for parametric families of (pairs of) lines. in higher dimension there is a clear notion of orthogonality between linear subspaces but it would be complicated to have to judge whether there is an intersection in order to choose the mot juste . there are too many words like orthocenter , orthologic , orthopole in 2-3 dimensional Euclidean geometry that are incongruous with the idea of orthogonal lines not intersecting. If the orthocenter is the intersection of some orthogonal lines (altitudes) they must be orthogonal to the sides of the triangle. To then alter the language from 2 to 3 dimensions would be strange. Search results: 1903 UK translation of Franz Hocevar's Solid Geometry book into English has examples of "perpendicular" lines in 3-d being used to include the case of skew lines. Page 10 : "prove that if a straight line be perpendicular to two intersecting lines but does not meet them, it is normal to the plane containing them" and other similar uses on the same page. This was the first old text listed at https://www.google.com/#q=solid+geometry&tbm=bks . 1921 (in USA) Charles Austin Hobbs, Solid Geometry, p271: "in solid geometry, two skew lines are either perpendicular to each other or are oblique to each other". 1900 Eugene Rouche et Ch. de Comberousse, Traite de Geometrie, V, Geometrie dans l'Espace, p.10 "on dit que deux droites non situees dans le meme plan sont perpendiculaires l'un a l'autre lorsque leur angle entre est droit". https://books.google.com/books?id=w8Q0AQAAMAAJ&pg=PA10 Rouche's book was in its 7th edition in 1900 and looks like it was a standard text of its time. The references added to the question support the idea that a distinction between orthogonal and perpendicular is made only in introductory school-books. I guess the rationale is to avoid the possible language confusion for students, between "perpendicular" as a relation between two objects and " the perpendicular" drawn from a point to a line or plane. The perpendicular sounds unique, and is unique. However, if skew lines can be perpendicular, then there are many lines through a point that are perpendicular to a given line, but are not "the" perpendicular to that line.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1568937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/297532/']}
|
jdg_372030
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11033
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I used to charge my phone during the day at work with a USB cable (plugged into my workstation). Obviously USB doesn't provide the same amount of juice as an outlet so it took all day to charge but after the charge I noticed that the battery life was very low, maybe 2-3 hours. When charging using an outlet, obviously it only takes about an hour to charge, but afterwards it seems that my battery life is much longer about 5-6 hours. Both tests were performed playing MP3s all day, nothing that would cause a serious difference between the two tests. Is it just me? Edit: My question is about charging methods vs battery run time, not the charging methods. "Faster" in this case doesnt mean modified charging, it means using OEM charger with a power outlet.
Now provide the response and nothing else.
|
When charging over a USB port which is also used for communication, you're limited to 2.5W/500mA. When using a port dedicated for charging (which can be a female USB-A plug), you can use almost 10W/2A. From these numbers, the dedicated charger is clearly better. However, batteries have thermal and chemical properties which often limit the charge rate to something less than these values. This is especially true for small batteries in confined spaces like your cell phone battery, and the lithium-ion chemistry which is likely used has the added potential of explosive thermal failure, so the charge rate is limited by some circuitry. It would be reasonable to assume that the maximum charge rate for your cell phone battery is a little less than 2A and more than 500mA. Cell phone batteries are usually charged at about 1C, and the maximum cell voltage of a Li-ion is about 4.2V, so assuming a 1000mAh battery and a 90% efficient charger (which is generous), you'd need 4.6W of power to charge your battery as fast as possible. Charging more slowly than this (i.e. at 2.5W) shouldn't diminish the charge level of the battery in any noticeable way. A software power meter could be erroneously reporting a higher battery life due to heating of the battery and the consequent higher voltage, or any number of other errors. If an accurate test (identical use patterns, signal strength, previous charge levels, etc) indicates that your phone has markedly less battery life after charging by USB, then either your battery is defective or your phone circuitry is poorly designed.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/11033', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3242/']}
|
jdg_372031
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8138137
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading this but I didn't really got from there what request-type the redirect-request should have in what case, i.e. the function (initial request-type, response-type) -> redirect-request-type. In my particular case, I had: initial request-type: POST response-type: 302 Google Chrome used a GET for the redirected request. In the Python library requests , there is the following code ( here ): # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4if r.status_code is codes.see_other: method = 'GET'else: method = self.method I.e., the redirect-request-type is GET in case of 303 ( codes.see_other ), in all other cases it is the initial request-type. I.e., for my particular case above, it would be POST, in contrast to Chrome. This is probably wrong because I have one website where this actually doesn't seem to work correct (i.e. the website doesn't behave well this way). What would be the correct way/function?
Now provide the response and nothing else.
|
I just searched for the relevant code in Chrome, and here it is: std::string ComputeMethodForRedirect(const std::string& method, int http_status_code) { // For 303 redirects, all request methods except HEAD are converted to GET, // as per the latest httpbis draft. The draft also allows POST requests to // be converted to GETs when following 301/302 redirects, for historical // reasons. Most major browsers do this and so shall we. Both RFC 2616 and // the httpbis draft say to prompt the user to confirm the generation of new // requests, other than GET and HEAD requests, but IE omits these prompts and // so shall we. // See: // https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-17#section-7.3 if ((http_status_code == 303 && method != "HEAD") || ((http_status_code == 301 || http_status_code == 302) && method == "POST")) { return "GET"; } return method;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8138137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133374/']}
|
jdg_372032
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5345380
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I had an assignment for each table to count nullable columns. Easy: SELECT table_name, count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE is_nullable='NO' GROUP BY table_name; Now I have to modify this to count "columns that have property "NOT NULL"". Will the following code do this or will it just check weather column name is not null? CREATE TEMP TABLE A AS SELECT DISTINCT column_name, table_name AS name FROM INFORMATION_SCHEMA.COLUMNSWHERE column_name IS NOT NULLGROUP BY table_name, column_name;SELECT name, count(*) FROM AGROUP BY name; If no... Any advices?
Now provide the response and nothing else.
|
No. This query SELECT DISTINCT column_name, table_nameFROM INFORMATION_SCHEMA.COLUMNSWHERE column_name IS NOT NULL will return all the rows that have a value in the column "column_name". All rows in that table will always have a value in the column "column_name". Do you just need to know how many columns are nullable and how many are non-nullable? SELECT is_nullable, COUNT(*)FROM INFORMATION_SCHEMA.COLUMNSGROUP BY is_nullable; Count by table name? I think you can use this. SELECT table_name, is_nullable, count(*)FROM INFORMATION_SCHEMA.COLUMNSGROUP BY table_name, is_nullableORDER BY table_name, is_nullable;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5345380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665127/']}
|
jdg_372033
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1145969
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an app which calls another process in a command window and that process has updating stats that output to the console window. I thought this was a fairly simple operation but I can't seem to get it to work. Am I missing something? string assemblyLocation = Assembly.GetExecutingAssembly().Location;Process process = new Process{ ProcessStart = { RedirectStandardOutput = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, Arguments = arg, FileName = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf("\\")) + "\\ffmpeg.exe", CreateNoWindow = true }};process.Start();Console.WriteLine(process.StandardOutput.ReadToEnd());process.WaitForExit(); Ideally what I would like is as the output changes within that process I hit or data comes into the reader that I get events off it. Any help would be great, I feel like this is a newbie question but seem to be missing something.
Now provide the response and nothing else.
|
I've experienced this before. Sometimes, the way in which the process you're calling outputs to the console is not compatible with this sort of output redirection. I've been fortunate enough in this case to be able to modify the external process to get around this. You might try running your code on another process that outputs to the console, and see if it works properly. It reads about right to me right now. EDIT: I went and pulled a code block I've used to do this. This is in a WPF app which redirects the process output to the window. Notice the event binding. Since this is WPF I have to invoke my call to write the data out. Since you aren't worried about blocking, ou should be able to simply replace that with: Console.WriteLine(e.Data); Hopefully it helps! private static void LaunchProcess() { Process build = new Process(); build.StartInfo.WorkingDirectory = @"dir"; build.StartInfo.Arguments = ""; build.StartInfo.FileName = "my.exe"; build.StartInfo.UseShellExecute = false; build.StartInfo.RedirectStandardOutput = true; build.StartInfo.RedirectStandardError = true; build.StartInfo.CreateNoWindow = true; build.ErrorDataReceived += build_ErrorDataReceived; build.OutputDataReceived += build_ErrorDataReceived; build.EnableRaisingEvents = true; build.Start(); build.BeginOutputReadLine(); build.BeginErrorReadLine(); build.WaitForExit(); } // write out info to the display window static void build_ErrorDataReceived(object sender, DataReceivedEventArgs e) { string strMessage = e.Data; if (richTextBox != null && !String.Empty(strMessage)) { App.Instance.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate() { Paragraph para = new Paragraph(new Run(strMessage)); para.Margin = new Thickness(0); para.Background = brushErrorBrush; box.Document.Blocks.Add(para); }); } }
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1145969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109605/']}
|
jdg_372034
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37181403
|
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 create a cross-browser Python-Selenium test script. So I need all results to be same no matter which webdriver ( Chrome or IE ) I use.I can set browser window size as follow: driver.set_window_size(1920, 1080) But following code will return different values for Chrome and IE : element = driver.find_element_by_xpath('some_xpath')element.location as viewport area (where web-content displayed) sizes are different ( Chrome - 1910x998, IE - 1904x965) despite of same window size. To get these values I used driver.execute_script('return document.documentElement.clientHeight')driver.execute_script('return document.documentElement.clientWidth') so I tried driver.execute_script('document.documentElement.clientHeight = "990px";')driver.execute_script('document.documentElement.clientWeight = "1900px";') but with no luck So the question is how to set browser viewport size in selenium ?
Now provide the response and nothing else.
|
Here is function to set the viewport size: def set_viewport_size(driver, width, height): window_size = driver.execute_script(""" return [window.outerWidth - window.innerWidth + arguments[0], window.outerHeight - window.innerHeight + arguments[1]]; """, width, height) driver.set_window_size(*window_size) Usage : from selenium import webdriverdriver = webdriver.Chrome()# set the viewport size to 800 x 600set_viewport_size(driver, 800, 600)# display the viewport sizeprint driver.execute_script("return [window.innerWidth, window.innerHeight];")
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37181403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4549554/']}
|
jdg_372035
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
139729
|
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:
American Mathematical Monthly problem 11611 essentially asks you to show that $$\lim_n\ n \int_0^1\left(\sum_{k=n}^\infty {x^k\over k}\right)^2\,dx=2\log(2).\tag1$$ This would follow easily from (2) below, which is true for small values of $n$ according to Maple. But I couldn't prove equation (2) in general, so I found a direct solution for (1) instead. $$\int_0^1\left(\sum_{k=n}^\infty {x^k\over k}\right)^2\,dx = \int_0^1 2x^{n-1}\log\left(1+{1\over\sqrt{x}}\right)\,dx.\tag2$$ But I'm still curious about (2). What am I missing? How can equation (2) be proven?
Now provide the response and nothing else.
|
One can avoid $\psi$ functions and even the expansion of the logarithm (right, for the logarithm, I am kind of cheating, try to find where...). Call $L_n$ and $R_n$ the LHS and the RHS of (2). Expand the square of the series in $L_n$ and integrate term by term the resulting double series to get$$L_n=\sum_{i\geqslant n}\sum_{j\geqslant n}\frac1{ij(i+j+1)}.$$Since $\color{red}{\dfrac{i+1}{j(j+i+1)}=\dfrac1j-\dfrac1{i+j+1}}$,$$L_n=\sum_{i\geqslant n}\frac1{i(i+1)}\sum_{j\geqslant n}\left(\frac1j-\frac1{i+j+1}\right)=\sum_{i\geqslant n}\frac1{i(i+1)}\sum_{j\geqslant n}\frac1j[i\geqslant j-n].$$Exchanging the order of summations and using the identity $\color{red}{\dfrac1{i(i+1)}=\dfrac1i-\dfrac1{i+1}}$, one gets$$L_n=\sum_{j\geqslant n}\frac1j\frac1{\max(n,j-n)}=\sum_{j=n}^{2n-1}\frac1j\frac1n+\sum_{j\geqslant2n}\frac1{j(j-n)}.$$Since $\color{red}{\dfrac{n}{j(j-n)}=\dfrac1{j-n}-\dfrac1j}$,$$L_n=\frac1n\sum_{j=n}^{2n-1}\frac1j+\frac1n\sum_{j\geqslant2n}\left(\frac1{j-n}-\frac1j\right)=\frac2n\sum_{j=n}^{2n-1}\frac1j.$$ Use the change of variables $x=t^2$ and an integration by parts to get$$nR_n=2\int_0^1\frac{1+t^{2n-1}}{1+t}\mathrm dt.$$ Compute the differences$$(n+1)L_{n+1}-nL_n=2\left(\frac1{2n+1}-\frac1{2n}\right),$$and$$(n+1)R_{n+1}-nR_n=2\int_0^1\frac{t^{2n+1}-t^{2n-1}}{1+t}\mathrm dt=2\int_0^1(t^{2n}-t^{2n-1})\mathrm dt=2\left(\frac1{2n+1}-\frac1{2n}\right).$$ Compute the initial terms $L_1=R_1=2$ and conclude that $nL_n=nR_n$ for every $n\geqslant1$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/139729', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_372036
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
979337
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With jQuery code like: $("#myid").click(myfunction);function myfunction(arg1, arg2) {/* something */} How do I pass arguments to myfunction while using jQuery?
Now provide the response and nothing else.
|
The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)... $("#myid").click(function() { myfunction(arg1, arg2);}); jsFiddle . This create an anonymous function, which is called when the click event is triggered. This will in turn call myfunction() with the arguments you provide. If you want to keep the ThisBinding (the value of this when the function is invoked, set to the element which triggered the event), then call the function with call() . $("#myid").click(function() { myfunction.call(this, arg1, arg2);}); jsFiddle . You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event object . If you do want to pass the reference, you must leverage jQuery's proxy() function (which is a cross browser wrapper for Function.prototype.bind() ). This lets you pass arguments, which are bound before the event argument. $("#myid").click($.proxy(myfunction, null, arg1, arg2)); jsFiddle . In this example, myfunction() would be executed with its ThisBinding intact ( null is not an object, so the normal this value of the element which triggered the event is used), along with the arguments (in order) arg1 , arg2 and finally the jQuery event object, which you can ignore if it's not required (don't even name it in the function's arguments). You could also use use the jQuery event object's data to pass data, but this would require modifying myfunction() to access it via event.data.arg1 (which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/979337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58954/']}
|
jdg_372037
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23470667
|
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 currently have a site created in codeigniter in a folder /ci/ I currently installed WordPress in the root directory. What I want is the site to perform as normal with CI but for the main root url (www.example.com) I want it to load the the Wordpress site (hence why i installed it in the root) I am trying in the .htaccess to IGNORE the main site from being redirected to CI with: RewriteCond %{REQUEST_URI} !^/ But as expected this means all the the other CI links (e.g. http://www.example.com/test which is http://www.example.com/ci/test ) no longer work. This is my current .htaccess file: Options -Indexes +SymLinksIfOwnerMatch RewriteEngine onRewriteBase /RewriteCond %{REQUEST_URI} !^/RewriteCond %{REQUEST_URI} !^/ci/RewriteCond %{REQUEST_URI} !^/wp-admin/?$RewriteCond %{REQUEST_URI} !^/wp-content/?$RewriteCond %{REQUEST_URI} !^/wp-includes/?$RewriteRule ^(.*)$ /ci/$1 [L]
Now provide the response and nothing else.
|
No there isn't really a better solution to this, so perhaps with an explanation. Suppose you have a document in place that has the structure as you show: { "name": "foo", "bars": [{ "name": "qux", "somefield": 1 }] } If you do an update like this db.foo.update( { "name": "foo", "bars.name": "qux" }, { "$set": { "bars.$.somefield": 2 } }, { "upsert": true }) Then all is fine because matching document was found. But if you change the value of "bars.name": db.foo.update( { "name": "foo", "bars.name": "xyz" }, { "$set": { "bars.$.somefield": 2 } }, { "upsert": true }) Then you will get a failure. The only thing that has really changed here is that in MongoDB 2.6 and above the error is a little more succinct: WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0, "writeError" : { "code" : 16836, "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: bars.$.somefield" }}) That is better in some ways, but you really do not want to "upsert" anyway. What you want to do is add the element to the array where the "name" does not currently exist. So what you really want is the "result" from the update attempt without the "upsert" flag to see if any documents were affected: db.foo.update( { "name": "foo", "bars.name": "xyz" }, { "$set": { "bars.$.somefield": 2 } }) Yielding in response: WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 }) So when the modified documents are 0 then you know you want to issue the following update: db.foo.update( { "name": "foo" }, { "$push": { "bars": { "name": "xyz", "somefield": 2 }}) There really is no other way to do exactly what you want. As the additions to the array are not strictly a "set" type of operation, you cannot use $addToSet combined with the "bulk update" functionality there, so that you can "cascade" your update requests. In this case it seems like you need to check the result, or otherwise accept reading the whole document and checking whether to update or insert a new array element in code.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23470667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3603920/']}
|
jdg_372038
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17853112
|
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 learning about the CopyOnWriteArrayList class. What is the purpose of copying a new array? Is it for other threads to read the array? So if a system has high concurrency and most of the threads' actions are reading not writing, it is better to use CopyOnWriteArrayList .
Now provide the response and nothing else.
|
As stated on this link : CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java. CopyOnWriteArrayList implements List interface like ArrayList , Vector and LinkedList but its a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class. As name suggest CopyOnWriteArrayList creates copy of underlying ArrayList with every mutation operation e.g. add or set. Normally CopyOnWriteArrayList is very expensive because it involves costly Array copy with every write operation but its very efficient if you have a List where Iteration outnumber mutation e.g. you mostly need to iterate the ArrayList and don't modify it too often. Iterator of CopyOnWriteArrayList is fail-safe and doesn't throw ConcurrentModificationException even if underlying CopyOnWriteArrayList is modified once Iteration begins because Iterator is operating on separate copy of ArrayList. Consequently all the updates made on CopyOnWriteArrayList is not available to Iterator. To get the most updated version do a new read like list.iterator(); That being said, updating this collection alot will kill performance. If you tried to sort a CopyOnWriteArrayList you'll see the list throws an UnsupportedOperationException (the sort invokes set on the collection N times). You should only use this read when you are doing upwards of 90+% reads.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17853112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2331313/']}
|
jdg_372039
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1237239
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If I define a function: $f(x) = \max[g(x),h(x)]$ What is $f'(x)$?
Now provide the response and nothing else.
|
I assume that $f$ and $g$ are differentiable. You can write $$ \max(f(x),g(x)) = \frac{f(x) + g(x) + |f(x) - g(x)|}{2}$$ and calculate the derivative of your function at those points where it exists (note that $x \mapsto |x|$ is not differentiable at $0$ , so it is not clear that the derivative exists at those points where $f(x) = g(x)$ .) Distinguishing the cases in the different regions, what we obtain is the following $$ \frac{d}{dx} \max(f(x),g(x)) = \begin{cases}f'(x) & \text{if} \quad f(x) = g(x) \text{ and } f'(x) =g'(x) \\ g'(x) & \text{if} \quad g(x) > f(x) \\ f'(x) & \text{if} \quad f(x) > g(x) \\\text{undefined} & \text{if} \quad f(x) = g(x) \text{ and } f'(x)\neq g'(x) \end{cases}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1237239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/231890/']}
|
jdg_372040
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.