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
10512
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 $G$ be a (finite?) group. By definition, the Eilenberg-MacLane space $K(G,1)$ is a CW complex such that $\pi_1(K(G,1)) = G$ while the higher homotopy groups are zero. One can consider the singular cohomology of $K(G,1)$, and it is a theorem that this is isomorphic to the group cohomologies $H^*(G, \mathbb{Z})$. According to one of my teachers, this can be proved by an explicit construction of $K(G, 1)$. On the other hand, it seems like there ought to be a categorical argument. $K(G, 1)$ is the object that represents the functor $X \to H^1(X, \mathbb{Z})$ in the category of pointed CW complexes, say, while the group cohomology consists of the universal $\delta$-functor that begins with $M \to M^G$ for $M$ a $G$-module. In particular, I would be interested in a deeper explanation of this "coincidence" that singular cohomology on this universal object happens to equal group cohomology. Is there one? Now provide the response and nothing else.
Akhil, you're thinking of this the opposite of how I think group cohomology was discovered. The concept of group cohomology originally centered around the questions about the (co)homology of $K(\pi,1)$-spaces, by people like Hopf (he called them aspherical rather than $K(\pi,1)$ spaces, and Hopf preferred homology to cohomology at that point). I think the story went that Hopf observed his formula for $H_2$ of a $K(\pi,1)$, which was a description of $H_2$ entirely in terms of the fundamental group of the space. This motivated people to ask to what extent (co)homology is an invariant of the fundamental group of a $K(\pi,1)$-space. This was resolved by Eilenberg and Maclane. Eilenberg and Maclane went the extra step to show that one can define cohomology of a group directly in terms of a group via what nowadays would be called a "bar construction" (ie skipping the construction of the associated $K(\pi,1)$-space). Bar constructions exist topologically and algebraically and they all have a similar feel to them. On the level of spaces, bar constructions are ways of constructing classifying spaces. For groups they construct the cohomology groups of a group. The latter follows from the former -- if you're comfortable with the concept of the "nerve of a category", this is how you construct an associated simplicial complex to a group (a group being a category with one object). The simplicial (co)homology of this object is your group (co)homology. Dieudonne's "History of Algebraic and Differential Topology" covers this in sections V.1.D and V.3.B. I don't think that answers all your questions but it answers some.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/10512', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/536/']}
jdg_74041
stackexchange
llm_judgeable_groundtruth_similarity
45241131
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 doing an angular(4) application, but i got a problem integrating google analytics.I'm currently to add google analytics to my single page web application. But when I try to retrieve the ga function to send the new url it seems that it don't find the function. This is the code I got: index.hbs <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'My-key', 'auto');</script> app.component.ts import { Component, OnInit } from '@angular/core';import {NavigationEnd, Router} from "@angular/router";import {WindowRef} from "./social/windowRef";@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'],})export class AppComponent { user: User; private currentRoute: string; constructor(private misc: MiscService, public router: Router) { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { console.log(event.urlAfterRedirects); WindowRef.get().ga('set', 'page', event.urlAfterRedirects); WindowRef.get().ga('send', 'pageview'); } }); }} windowRef.ts export class WindowRef{ public static get(): any{ console.log(window); return window; }} I got this error: ERROR TypeError: windowRef_1.WindowRef.get(...).ga is not a function When I do console.log(WindowRef.get()); I can see in the window the ga function but it still display the previous error when I try to use it. here and here I don't really understand I used this method to retrieve the stripe function and it worked pretty well. Have a good day :) Now provide the response and nothing else.
I've had a similar problem trying to integrate Google Analytics into my Angular 4 App. What did the trick for me was to move the google analytics code from the AppComponent's constructor to the ngAfterViewInit() lifecycle hook to ensure that the view is fully initialized first. Here's the code I got: index.html (same as you): <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject'] = r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'some code', 'auto');</script> app.component.ts: import {AfterViewInit, Component, Inject, PLATFORM_ID} from '@angular/core';import {isPlatformBrowser} from '@angular/common';import {NavigationEnd, Router} from '@angular/router';// declare google analyticsdeclare const ga: any;@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements AfterViewInit { constructor(@Inject(PLATFORM_ID) private platformId: Object, private router: Router) {} ngAfterViewInit(): void { this.router.events.subscribe(event => { // I check for isPlatformBrowser here because I'm using Angular Universal, you may not need it if (event instanceof NavigationEnd && isPlatformBrowser(this.platformId)) { console.log(ga); // Just to make sure it's actually the ga function ga('set', 'page', event.urlAfterRedirects); ga('send', 'pageview'); } }); }} Let me know if this works for you as well. Have a nice day! :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45241131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7364750/']}
jdg_74042
stackexchange
llm_judgeable_groundtruth_similarity
7095703
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to implement the new view-based OutlineView as a source list in my Mac app. I can't get values to display, though, so I made a small test app from the Core Data app template, and can't get it working right in there, either. I defined two simple classes in my data model; let's call them "Parent" and "Child". Parent has a single Attribute, "name", and a single relationship, "children". name is an optional string, and children is an optional to-many relationship to Child . Child has the same "name" attribute and a to-one "parent" relationship that is the inverse of children . I generated custom classes for both of those, and wrote a stub in Child for children that returns nil . I dragged a Source List from the Object library onto my XIB, and dropped in a Tree Controller. The Tree Controller's Children Key Path is set to "children", it's in Entity Name mode, with "Parent" as the Entity Name, Prepares Content checked, and its Managed Object Context set to the app delegate's context. The Tree Controller is the data source of the outline view, and I bound the data cell's text view to Table Cell View, with the "objectValue.name" key path. in -applicationDidFinishLaunching: I create two Parent instances, one with a Child , and assign the name property of every object. The actual problem Now, with that setup out of the way, I get rows showing up in the source list, but the text fields are empty, even though they're bound. I don't think I should need to do anything else, since I'm using bindings, and I'm fairly certain binding to the objectValue property is the right thing. What's going wrong? I can provide more detail if necessary, but I'm pretty sure that covers everything I did. Now provide the response and nothing else.
Wow, it's like me from two weeks ago is asking this question. Anyway, if you're anything like me, the problem is that, for view-based NSOutlineViews , you need to implement the - (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item; delegate method and return the NSTableCellView you set up, or they'll just give you a blank line. The easiest way to do this is to just call [outlineView makeViewWithIdentifier:@"MyCell" owner:self] replacing MyCell with whatever you typed in as the "User Interface Item Identifier" in the Identity Inspector for your NSTableCellView . Objective-C: - (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item { return [outlineView makeViewWithIdentifier:@"MyCell" owner:self];} Swift: func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { return outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("MyCell"), owner: self)} UPDATE 2018-08-02: Actually, you don't need to set the delegate. Here is how I got it working (tested with NSTreeController , but should work with NSArrayController as well): Bind each column object to arrangedObjects (without Model Key Path) Bind the inner-most custom view (e.g., label field) to objectValue.yourCustomValue Shouldn't be necessary but if this doesn't work try setting the identifier for the column and for the TableCellView . Make sure both identifiers are identical. Repeat that for the remaining columns with different identifiers. Screenshot: Bindings for View Based NSOutlineView
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7095703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105717/']}
jdg_74043
stackexchange
llm_judgeable_groundtruth_similarity
12708443
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 new iOS 6, viewDidUnload is deprecated and we have been instructed to use didReceiveMemoryWarning instead, to manage objects in UIViewController instances and subclasses. Is it equally effective to assign nils to UIView kinds inside didReceiveMemoryWarning like the way it has been done inside viewDidUnload ? I am asking this because these two methods seems to be working differently. It seems like didReceiveMemoryWarning doesn't guarantee viewDidLoad to be called again to re-instantiate any necessary UIViews. I suspect with iOS 6, memory management is done without requiring to manually deallocate UIView. Please help me to know what I have missed in understanding the lifecycle of UIViewController. Now provide the response and nothing else.
My preferred method is now the following: - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; if (self.isViewLoaded && !self.view.window) { self.view = nil; } // Do additional cleanup if necessary} Note that the test self.isViewLoaded is essential, as otherwise accessing the view causes it to load - even the WWDC videos tend to miss that. If your other references to subviews are weak references, you don't have to nil them out here, otherwise you want to set them to nil, too. You should get rid of viewDidUnload completely, and every code there should move to appropriate places. It wasn't guaranteed to be called prior to iOS 6 before anyway.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12708443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259765/']}
jdg_74044
stackexchange
llm_judgeable_groundtruth_similarity
177776
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There are plenty of popular NP-hard puzzles,for example, generalized Sudoku ( $n^2 \times n^2$ -board), Flow (I cannot give a source for this), Minesweeper, etc. Recently, I read a bit about aperiodic tilings of the plane, and it is undecidable whether a set of tiles can tile the plane or not, since there might be aperiodic tilings. I do not really consider this problem a popular game you would find in a newspaper. So, my question is this: what puzzles/games are there that are undecidable in general? The Post correspondence Problem , (PCP), is undecidable and this has a very "puzzle"-feel to it, so I would say this game could qualify. Perhaps some generalization of the board game Roborally on an infinite board,would lead to some type of undecidability, that is, there is no algorithm that given a RoboRally configuration produces the resulting configuration after all rules have been applied? As a funny note, the sand-box game Minecraft allows the user to make circuits, making the game (in theory) Turing complete. Now provide the response and nothing else.
Typing "undecidable" and "puzzle" into MathSciNet turned up a couple of candidates. Baumeister, Dorothea and Rothe, Jörg, The three-color and two-color Tantrix rotation puzzle problems are NP-complete via parsimonious reductions, Inform. and Comput. 207 (2009), no. 11, 1119–1139, MR2566946 (2011c:68052). According to the summary, the infinite variants of the 3-color and 2-color Tantrix rotation puzzle problems are undecidable. This follows work by M. Holzer and W. Holzer [Discrete Appl. Math. 144 (2004), no. 3, 345–358; MR2098189 (2005j:94043)] showing the same for the 4-color Tantrix puzzle. Demaine, Erik D. and Hearn, Robert A., Constraint logic: a uniform framework for modeling computation as games, Twenty-Third Annual IEEE Conference on Computational Complexity, 149–162, IEEE Computer Soc., Los Alamitos, CA, 2008, MR2513497 (2010d:68039). This paper introduces a simple game family and proves "a game with three players and a bounded amount of state can simulate any (infinite) Turing computation, making the game undecidable." There are applications to many existing combinatorial games and puzzles.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/177776', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1056/']}
jdg_74045
stackexchange
llm_judgeable_groundtruth_similarity
562173
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: These two files are artefacts of Office 2011 that are preventing removal the 'Contents' directory. How do I delete these? sh-3.2# ls -l -atotal 21496drwx------+ 15 Beef staff 480 Jan 14 23:32 .drwxr-xr-x+ 19 Beef staff 608 Jan 14 23:40 ..-rw-r--r--@ 1 Beef staff 10244 Jan 10 10:36 .DS_Store-rw-r--r-- 1 Beef staff 0 Dec 25 23:13 .localizeddrwxrwxrwx 47 Beef staff 1504 Jan 2 00:01 CSC119 - 1228drwxrwxrwx 7 Beef staff 224 Jan 1 22:50 Chris 1228drwxrwxr-x@ 3 Beef staff 96 Aug 25 2010 Contentsdrwxrwxrwx@ 5 Beef staff 1 sh-3.2# cd Contentssh-3.2# ls -l -atotal 0drwxrwxr-x@ 3 Beef staff 96 Aug 25 2010 .drwx------+ 15 Beef staff 480 Jan 14 23:32 .. Specifically the these to above '.' and '..' files in the Contents dir.I am using a bash shell on my Mac terminal. I am in root. Thanks! sh-3.2# ls -a -ltotal 21496drwx------+ 15 Beef staff 480 Jan 14 23:32 .drwxr-xr-x+ 19 Beef staff 608 Jan 15 00:19 ..-rw-r--r--@ 1 Beef staff 10244 Jan 10 10:36 .DS_Store-rw-r--r-- 1 Beef staff 0 Dec 25 23:13 .localizeddrwxrwxrwx 47 Beef staff 1504 Jan 2 00:01 CSC119 - 1228drwxrwxrwx 7 Beef staff 224 Jan 1 22:50 Chris 1228drwxrwxr-x@ 3 Beef staff 96 Aug 25 2010 Contentsdrwxrwxrwx@ 5 Beef staff 160 Dec 28 12:09 Lily 1228drwxrwxrwx 29 Beef staff 928 Jan 3 21:48 Old Dell Laptoplrwxr-xr-x 1 Beef staff 29 Dec 26 02:51 Relocated Items -> /Users/Shared/Relocated Items-rwxrwxrwx@ 1 Beef staff 1554944 Jan 8 2019 SanDisk Flashback.pdfdrwxrwxrwx 4 Beef staff 128 Jan 8 2019 SanDiskSecureAccess-rwxrwxrwx 1 Beef staff 8600360 Nov 4 2016 SanDiskSecureAccessV3.01_win.exedrwxr-xr-x@ 9 Beef staff 288 Jan 10 11:41 Scanned Docsdrwxrwxrwx 4 Beef staff 128 Dec 19 10:04 googlesh-3.2# rmdir Contentsrmdir: Contents: Directory not emptysh-3.2# rmdir -p Contentsrmdir: Contents: Directory not empty How do I get rid of this dir? sh-3.2# ls -a -ltotal 21496drwx------+ 15 Beef staff 480 Jan 14 23:32 .drwxr-xr-x+ 19 Beef staff 608 Jan 15 00:19 ..-rw-r--r--@ 1 Beef staff 10244 Jan 10 10:36 .DS_Store-rw-r--r-- 1 Beef staff 0 Dec 25 23:13 .localizeddrwxrwxrwx 47 Beef staff 1504 Jan 2 00:01 CSC119 - 1228drwxrwxrwx 7 Beef staff 224 Jan 1 22:50 Chris 1228drwxrwxr-x@ 3 Beef staff 96 Aug 25 2010 Contentsdrwxrwxrwx@ 5 Beef staff 160 Dec 28 12:09 Lily 1228drwxrwxrwx 29 Beef staff 928 Jan 3 21:48 Old Dell Laptoplrwxr-xr-x 1 Beef staff 29 Dec 26 02:51 Relocated Items -> /Users/Shared/Relocated Items-rwxrwxrwx@ 1 Beef staff 1554944 Jan 8 2019 SanDisk Flashback.pdfdrwxrwxrwx 4 Beef staff 128 Jan 8 2019 SanDiskSecureAccess-rwxrwxrwx 1 Beef staff 8600360 Nov 4 2016 SanDiskSecureAccessV3.01_win.exedrwxr-xr-x@ 9 Beef staff 288 Jan 10 11:41 Scanned Docsdrwxrwxrwx 4 Beef staff 128 Dec 19 10:04 googlesh-3.2# sudo rm -r -f Contentsrm: Contents: Directory not empty It still won't delete. Now provide the response and nothing else.
Your directory looks empty, but the ls output indicates that there is a file in there since the link count for the directory is 3 rather than 2 (an empty directory on an APFS filesystem should have a link count of 2). This implies that your filesystem has managed to get itself into an inconsistent state and that you should probably run fsck on it. On macOS, this is done by running the disk first aid via the "Disk Utility" app. If the issue is with your main boot disk (often called "Macintosh HD", at least by default), then you should do this from recovery mode. If this is the same issue that I encountered , then it will most likely be solved by first making sure that you are on a recent version of macOS (somewhere past March 2019) before running the first aid on the disk in recovery mode. You get into recovery mode by pressing Cmd+R as soon as you reboot the machine. Once in recovery mode, you will be presented with the opportunity to run "Disk Utility" from a menu.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/562173', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/390465/']}
jdg_74046
stackexchange
llm_judgeable_groundtruth_similarity
23905601
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The part that I can't quite get to work is the conditional as it's always failing: use Test::More tests => 2;my $regex = qr/(\d+),(\d+) (?(?{\g1<\g2})(*FAIL)) /x ; like( "(23,36)", $regex, 'should match' );unlike( "(36,23)", $regex, 'should not match' ); Output not ok 1 - should match# Failed test 'should match'# at - line 7.# '(23,36)'# doesn't match '(?^x:(\d+),(\d+)# (?(?{\g1<\g2})(*FAIL))# )'ok 2 - should not match# Looks like you failed 1 test of 2. Now provide the response and nothing else.
Your code needs the following fixes: Use the $1 and $2 variables in the experimental (?{ }) code block. Need to invert your test to match what you want to fail. You need to prevent backtracking where if the code block indicates a failure, you don't want it to match a substring that will pass, such as 6 is less then 23 in the second test. There are two methods to prevent this: Add word boundaries so the regex can't match a partial number. Use the (*SKIP) control verb to prevent backtracking explicitly. The code: use strict;use warnings;use Test::More tests => 2;my $regex = qr/(\d+),(\d+) (?(?{$1 > $2})(*SKIP)(*FAIL)) /x ; like( "(23,36)", $regex, 'should match' );unlike( "(36,23)", $regex, 'should not match' ); Outputs: 1..2ok 1 - should matchok 2 - should not match
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23905601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/133939/']}
jdg_74047
stackexchange
llm_judgeable_groundtruth_similarity
16628946
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 domain, example.com, that I want to use for my rails-app that resides at example.herokuapp.com and I'm pretty confused how to go about to do this. Heroku says "Zone apex domains (aka "naked", "bare" or "root" domains), e.g., example.com, using conventional DNS A-records are not supported on Heroku." And then they go on explaining workarounds (using ALIAS or ANAME). I have spent a good hour reading up on the subject (here on SO and elsewhere) but still don't get my head around this. Are there any alternative ways or explanations on how to acomplish this for "a dummy"? Now provide the response and nothing else.
I'll take a stab at this as it's a frequent question. Ok, so assuming you have a domain example.com and you want to use www.example.com to host your site. In traditional hosting you'd probably have a virtual server which has been assigned an IP address, in this case you would use a host record, otherwise known as an A record in DNS control panels to map www.example.com to the IP address. In this case, since you have now set www.example.com to a fixed IP address should that IP address ever change you will need to update your DNS yourself. Also, with traditional hosting you could have example.com set to the same IP address so www.example.com and example.com would work for naked domains. Ok, so what's a CNAME record. A CNAME record rather than mapping to an IP address maps the record to another DNS entry. So, www.example CNAME'd to example.herokuapp.com means that Heroku can and may move where example.herokuapp.com is pointing at but you don't have to update anything as you're using an CNAME record and Heroku are managing where example.herokuapp.com is pointing (which can and may be another CNAME or an IP address). The problem with CNAME records is that they CANNOT point to an IP address, which is fine for www.example.com but a problem with example.com. Heroku previously published IP addresses to be used for naked domains but problems ensued when they suffered DDOS attacks and couldn't replace those IPs with new ones as they were published IP addresses. For the new EU region, Heroku ARE NOT publishing IP addresses for use with naked domains. What several DNS providers (DNSsimple I know is one) have done is add their own ALIAS records to their DNS servers to allow you to use CNAME's with naked domains so both www.example.com and example.com will work as now supported by Heroku. If you DNS provider does not support ALIAS records then it's worth moving the domain to a DNS provider that does support it. DNSsimple also supports redirect records so you can have www.example.com redirect to example.com at the DNS provider level and not at your application layer.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16628946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1417223/']}
jdg_74048
stackexchange
llm_judgeable_groundtruth_similarity
2254176
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 class with an IDictionary on it. <map name="CodedExamples" table="tOwnedCodedExample"> <key> <column name="OwnerClassID"/> </key> <index type="string" column="ExampleCode"/> <many-to-many class="CodedExample" column ="CodedExampleClassID"/> </map> as you can see it uses a many-to-many to get the CodedExamples from their table using the tOwnedCodedExample table to find which are owned by the OwnerClass. I realise that this is a very basic (and hopefully standard) mapping but am struggling and can't find any documentation for it, therefore would be very grateful of any help possible. Many Thanks Stu Now provide the response and nothing else.
I have a working example, this should make it clear to you. Classes: public class Customer : Entity{ public IDictionary<string, Book> FavouriteBooks { get; set; }}public class Book : Entity{ public string Name { get; set; }} And then the map: HasManyToMany<Book>(x => x.FavouriteBooks) .Table("FavouriteBooks") .ParentKeyColumn("CustomerID") .ChildKeyColumn("BookID") .AsMap<string>("Nickname") .Cascade.All(); Resulting xml: <map cascade="all" name="FavouriteBooks" table="FavouriteBooks" mutable="true"> <key> <column name="`CustomerID`" /> </key> <index type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="`Nickname`" /> </index> <many-to-many class="Domain.Book, Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <column name="`BookID`" /> </many-to-many></map> Generated SQL: create table "Customer" ( "Id" integer, "FirstName" TEXT, primary key ("Id"))create table FavouriteBooks ( "CustomerID" INTEGER not null, "BookID" INTEGER not null, "Nickname" TEXT not null, primary key ("CustomerID", "Nickname"))create table "Book" ( "Id" integer, "Name" TEXT, primary key ("Id"))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2254176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178362/']}
jdg_74049
stackexchange
llm_judgeable_groundtruth_similarity
131013
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: Help me please to prove that matrix exponential which defined as: $e^{A}=\sum\limits_{k=0}^{\infty }\frac{A^{k}}{k!}$ converges for all matrix $A$ Thanks beforehand. Now provide the response and nothing else.
Since the space $E:=\mathcal M_n(\mathbb C)$ of all $n \times n$ complex matrices is a finite-dimensional vector space, all norms define the same topology. So we can take a sub-multiplicative norm, that is, a norm $\lVert\cdot\rVert$ such that $\lVert AB\rVert\leq \lVert A\rVert \cdot\lVert B\rVert$. (For example, we can take $\lVert\cdot\rVert$ to be the operator norm on $E$.) As a finite dimensional vector space, $E$ is complete, so it's enough to show normal convergence . We have that, for each integer $n \geq 0$, $$0\leq \lVert\frac{A^n}{n!}\rVert\leq \frac{\lVert A\rVert^n}{n!},$$and we know that, for each real number $x$, the series $\sum_{n=0}^{+\infty}\frac{x^n}{n!}$ converges (it defines the exponential function). Therefore, for any $A \in E$, the series $\sum_{n=0}^{+\infty}\frac{A^n}{n!}$ converges. (We also got the additional result that $\lVert e^A\rVert\leq e^{\lVert A\rVert}$ for any $A \in E$.)
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/131013', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28972/']}
jdg_74050
stackexchange
llm_judgeable_groundtruth_similarity
10676729
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 at the point in learning Python where I'm dealing with the Mutable Default Argument problem . # BAD: if `a_list` is not passed in, the default will wrongly retain its contents between successive function callsdef bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list# GOOD: if `a_list` is not passed in, the default will always correctly be []def good_append(new_item, a_list=None): if a_list is None: a_list = [] a_list.append(new_item) return a_list I understand that a_list is initialized only when the def statement is first encountered, and that's why subsequent calls of bad_append use the same list object. What I don't understand is why good_append works any different. It looks like a_list would still be initialized only once; therefore, the if statement would only be true on the first invocation of the function, meaning a_list would only get reset to [] on the first invocation, meaning it would still accumulate all past new_item values and still be buggy. Why isn't it? What concept am I missing? How does a_list get wiped clean every time good_append runs? Now provide the response and nothing else.
The default value of a_list (or any other default value, for that matter) is stored in the function's interiors once it has been initialized and thus can be modified in any way: >>> def f(x=[]): return x...>>> f.func_defaults([],)>>> f.func_defaults[0] is f()True resp. for Python 3: >>> def f(x=[]): return x...>>> f.__defaults__([],)>>> f.__defaults__[0] is f()True So the value in func_defaults is the same which is as well known inside function (and returned in my example in order to access it from outside. In other words, what happens when calling f() is an implicit x = f.func_defaults[0] . If that object is modified subsequently, you'll keep that modification. In contrast, an assignment inside the function gets always a new [] . Any modification will last until the last reference to that [] has gone; on the next function call, a new [] is created. In order words again, it is not true that [] gets the same object on every execution, but it is (in the case of default argument) only executed once and then preserved.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10676729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291022/']}
jdg_74051
stackexchange
llm_judgeable_groundtruth_similarity
37856155
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 upgrading my mysql-5.5 docker container database to mysql-5.6 docker container. I was able to fix all other problems. Finally my server is running with 5.6. But when i run mysql_upgrade i am getting the following error. ERROR: root@17aa74cbc5e2# mysql_upgrade -uroot -password Warning: Using a password on the command line interface can be insecure.Looking for 'mysql' as: mysqlLooking for 'mysqlcheck' as: mysqlcheckRunning 'mysqlcheck' with connection arguments: '--port=3306' '--socket=/var/run/mysqld/mysqld.sock' Warning: Using a password on the command line interface can be insecure.Running 'mysqlcheck' with connection arguments: '--port=3306' '--socket=/var/run/mysqld/mysqld.sock' Warning: Using a password on the command line interface can be insecure.mysql.columns_priv OKmysql.db OKmysql.event OKmysql.func OKmysql.general_log OKmysql.help_category OKmysql.help_keyword OKmysql.help_relation OKmysql.help_topic OKmysql.innodb_index_statsError : Table 'mysql.innodb_index_stats' doesn't existstatus : Operation failedmysql.innodb_table_statsError : Table 'mysql.innodb_table_stats' doesn't existstatus : Operation failedmysql.ndb_binlog_index OKmysql.plugin OKmysql.proc OKmysql.procs_priv OKmysql.proxies_priv OKmysql.servers OKmysql.slave_master_infoError : Table 'mysql.slave_master_info' doesn't existstatus : Operation failedmysql.slave_relay_log_infoError : Table 'mysql.slave_relay_log_info' doesn't existstatus : Operation failedmysql.slave_worker_infoError : Table 'mysql.slave_worker_info' doesn't existstatus : Operation failedmysql.slow_log OKmysql.tables_priv OKmysql.time_zone OKmysql.time_zone_leap_second OKmysql.time_zone_name OKmysql.time_zone_transition OKmysql.time_zone_transition_type OKmysql.user OKRepairing tablesmysql.innodb_index_statsError : Table 'mysql.innodb_index_stats' doesn't existstatus : Operation failedmysql.innodb_table_statsError : Table 'mysql.innodb_table_stats' doesn't existstatus : Operation failedmysql.slave_master_infoError : Table 'mysql.slave_master_info' doesn't existstatus : Operation failedmysql.slave_relay_log_infoError : Table 'mysql.slave_relay_log_info' doesn't existstatus : Operation failedmysql.slave_worker_infoError : Table 'mysql.slave_worker_info' doesn't existstatus : Operation failedRunning 'mysql_fix_privilege_tables'...Warning: Using a password on the command line interface can be insecure.ERROR 1146 (42S02) at line 62: Table 'mysql.innodb_table_stats' doesn't existERROR 1243 (HY000) at line 63: Unknown prepared statement handler (stmt) given to EXECUTEERROR 1243 (HY000) at line 64: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPAREERROR 1146 (42S02) at line 66: Table 'mysql.innodb_index_stats' doesn't existERROR 1243 (HY000) at line 67: Unknown prepared statement handler (stmt) given to EXECUTEERROR 1243 (HY000) at line 68: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPAREERROR 1146 (42S02) at line 81: Table 'mysql.slave_relay_log_info' doesn't existERROR 1243 (HY000) at line 82: Unknown prepared statement handler (stmt) given to EXECUTEERROR 1243 (HY000) at line 83: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPAREERROR 1146 (42S02) at line 110: Table 'mysql.slave_master_info' doesn't existERROR 1243 (HY000) at line 111: Unknown prepared statement handler (stmt) given to EXECUTEERROR 1243 (HY000) at line 112: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPAREERROR 1146 (42S02) at line 128: Table 'mysql.slave_worker_info' doesn't existERROR 1243 (HY000) at line 129: Unknown prepared statement handler (stmt) given to EXECUTEERROR 1243 (HY000) at line 130: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPAREERROR 1146 (42S02) at line 1896: Table 'mysql.slave_master_info' doesn't existERROR 1146 (42S02) at line 1897: Table 'mysql.slave_master_info' doesn't existERROR 1146 (42S02) at line 1898: Table 'mysql.slave_master_info' doesn't existERROR 1146 (42S02) at line 1899: Table 'mysql.slave_worker_info' doesn't existERROR 1146 (42S02) at line 1900: Table 'mysql.slave_relay_log_info' doesn't existERROR 1146 (42S02) at line 1904: Table 'mysql.innodb_table_stats' doesn't existERROR 1146 (42S02) at line 1908: Table 'mysql.innodb_index_stats' doesn't existFATAL ERROR: Upgrade failed Now provide the response and nothing else.
This is a known bug in MySQL 5.6, it is documented here . According to the replies to the bug report, you can manually create the missing tables. The structure of the missing tables is provided as attachment here . Steps to follow: Drop these tables from Mysql: innodb_index_statsinnodb_table_statsslave_master_infoslave_relay_log_infoslave_worker_info Delete *.frm and *.ibd files for the 5 tables above. Create the tables by running the following queries: CREATE TABLE `innodb_index_stats` ( `database_name` varchar(64) COLLATE utf8_bin NOT NULL, `table_name` varchar(64) COLLATE utf8_bin NOT NULL, `index_name` varchar(64) COLLATE utf8_bin NOT NULL, `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `stat_name` varchar(64) COLLATE utf8_bin NOT NULL, `stat_value` bigint(20) unsigned NOT NULL, `sample_size` bigint(20) unsigned DEFAULT NULL, `stat_description` varchar(1024) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`database_name`,`table_name`,`index_name`,`stat_name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0;CREATE TABLE `innodb_table_stats` ( `database_name` varchar(64) COLLATE utf8_bin NOT NULL, `table_name` varchar(64) COLLATE utf8_bin NOT NULL, `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `n_rows` bigint(20) unsigned NOT NULL, `clustered_index_size` bigint(20) unsigned NOT NULL, `sum_of_other_index_sizes` bigint(20) unsigned NOT NULL, PRIMARY KEY (`database_name`,`table_name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0;CREATE TABLE `slave_master_info` ( `Number_of_lines` int(10) unsigned NOT NULL COMMENT 'Number of lines in the file.', `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log currently being read from the master.', `Master_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The master log position of the last read event.', `Host` char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT 'The host name of the master.', `User_name` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The user name used to connect to the master.', `User_password` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The password used to connect to the master.', `Port` int(10) unsigned NOT NULL COMMENT 'The network port used to connect to the master.', `Connect_retry` int(10) unsigned NOT NULL COMMENT 'The period (in seconds) that the slave will wait before trying to reconnect to the master.', `Enabled_ssl` tinyint(1) NOT NULL COMMENT 'Indicates whether the server supports SSL connections.', `Ssl_ca` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Authority (CA) certificate.', `Ssl_capath` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path to the Certificate Authority (CA) certificates.', `Ssl_cert` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL certificate file.', `Ssl_cipher` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the cipher in use for the SSL connection.', `Ssl_key` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL key file.', `Ssl_verify_server_cert` tinyint(1) NOT NULL COMMENT 'Whether to verify the server certificate.', `Heartbeat` float NOT NULL, `Bind` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'Displays which interface is employed when connecting to the MySQL server', `Ignored_server_ids` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The number of server IDs to be ignored, followed by the actual server IDs', `Uuid` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The master server uuid.', `Retry_count` bigint(20) unsigned NOT NULL COMMENT 'Number of reconnect attempts, to the master, before giving up.', `Ssl_crl` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Revocation List (CRL)', `Ssl_crlpath` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path used for Certificate Revocation List (CRL) files', `Enabled_auto_position` tinyint(1) NOT NULL COMMENT 'Indicates whether GTIDs will be used to retrieve events from the master.', PRIMARY KEY (`Host`,`Port`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Master Information';CREATE TABLE `slave_relay_log_info` ( `Number_of_lines` int(10) unsigned NOT NULL COMMENT 'Number of lines in the file or rows in the table. Used to version table definitions.', `Relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the current relay log file.', `Relay_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The relay log position of the last executed event.', `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log file from which the events in the relay log file were read.', `Master_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The master log position of the last executed event.', `Sql_delay` int(11) NOT NULL COMMENT 'The number of seconds that the slave must lag behind the master.', `Number_of_workers` int(10) unsigned NOT NULL, `Id` int(10) unsigned NOT NULL COMMENT 'Internal Id that uniquely identifies this record.', PRIMARY KEY (`Id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Relay Log Information';CREATE TABLE `slave_worker_info` ( `Id` int(10) unsigned NOT NULL, `Relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `Relay_log_pos` bigint(20) unsigned NOT NULL, `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `Master_log_pos` bigint(20) unsigned NOT NULL, `Checkpoint_relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `Checkpoint_relay_log_pos` bigint(20) unsigned NOT NULL, `Checkpoint_master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, `Checkpoint_master_log_pos` bigint(20) unsigned NOT NULL, `Checkpoint_seqno` int(10) unsigned NOT NULL, `Checkpoint_group_size` int(10) unsigned NOT NULL, `Checkpoint_group_bitmap` blob NOT NULL, PRIMARY KEY (`Id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Worker Information'; Restart your MySQL server. Run the mysql_upgrade script.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37856155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1986826/']}
jdg_74052
stackexchange
llm_judgeable_groundtruth_similarity
2841
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to obtain true probabilities from Black-Scholes option pricing equation?Suppose, that we know risk adjusted discount rate for the underlying asset (the drift term in the physical measure) and risk free rate. The task is to find a real (not risk neutral) expected payoff for a call option. Now provide the response and nothing else.
The true probabilities underlying the B-S equation are actually postulated.The pricing process is assumed to follow the stochastic process $d S_t =\mu S_t d t + \sigma S_t dW_t$, where $W_t$ is the Wiener process . It means that (for simplicity, let's talk about European call) $\ln S_T$ is distributed as $N(ln(S_0)+(\mu-\frac{1}{2}\sigma^2)T, \sigma^2 T)$ Correct me if I'm wrong, you'd like to find $E_P(C) = e^{-rT} E_P[max(S_T-K,0)] $, where P is a "physical" probability measure. Just to make sure, this expected value won't represent the fair price of the option. If my calculations are correct, this expected value is equal to $S_0 N(d_1(\mu)) e^{(\mu-r)T} - K N(d_2(\mu))e^{-rT}$ the terms $d_1$ $d_2$ are from the B-S formula, with the adjustment to replace risk-free rate $r$ there with "risky" $\mu$ Now, I write down some derivation steps, please check them. Let's rewrite expectation as follows, $E_P[...]=E_P[\textbf{I}(S_T\geq K)(S_T-K)]$, where $\textbf{I}(.)$ is the indicator function. Notice that the inequality $S_T\geq K$ is equivalent to $\ln S_T \geq \ln K$ Then, $... = E_P[S_T \textbf{I}(\ln S_T \geq \ln K)]-E_P[K \textbf{I}(\ln S_T \geq \ln K)] $ $= E_P[e^{\ln S_T} \textbf{I}(\ln S_T \geq) \ln K)]- K N(d_2(\mu))$ To calculate the first term, use the following lemma: if X distributed as $N(a,s^2)$ then $E(e^X\textbf{I}(l<X))=e^{s+\frac{1}{2}s^2} N (\frac{\mu+s^2-l}{s})$ Take $\ln S_T$ as $X$ and $l$ as $\ln K$, obtain $E_P[S_T \textbf{I}(\ln S_T \geq \ln K)]=e^{\ln S_0 + (\mu - \frac{1}{2}\sigma^2)T + \frac{1}{2}\sigma^2 T}N(\frac{\ln S_0 + (\mu-\frac{1}{2}\sigma^2)T + \sigma^2 T - \ln K}{\sigma\sqrt T}) = S_0 e^\mu N(d_1(\mu))$ Finally, discount it with the risk-free rate $r$ and we get the result.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/2841', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/1960/']}
jdg_74053
stackexchange
llm_judgeable_groundtruth_similarity
1222392
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 keep seeing DDD (Domain Driven Design) being used a lot in articles - I have read the Wikipedia entry about DDD but still can't figure out what it actually is and how I would go about implementing it in creating my sites? Now provide the response and nothing else.
Firstly, if you don't know that you need it then it's possible that you don't need it. If you don't recognize the problems that DDD solves then maybe you don't have those problems. Even DDD advocates will frequently point out that DDD is only intended for large (>6 month) projects. Assuming that you're still reading at this point, my take on DDD is this: DDD is about trying to make your software a model of a real-world system or process. In using DDD, you are meant to work closely with a domain expert who can explain how the real-world system works. For example, if you're developing a system that handles the placing of bets on horse races, your domain expert might be an experienced bookmaker. Between yourself and the domain expert, you build a ubiquitous language (UL), which is basically a conceptual description of the system. The idea is that you should be able to write down what the system does in a way that the domain expert can read it and verify that it is correct. In our betting example, the ubiquitous language would include the definition of words such as 'race', 'bet', 'odds' and so on. The concepts described by the UL will form the basis of your object-oriented design. DDD provides some clear guidance on how your objects should interact, and helps you divide your objects into the following categories: Value objects, which represent a value that might have sub-parts (for example, a date may have a day, month and year) Entities, which are objects with identity . For example, each Customer object has its own identity, so we know that two customers with the same name are not the same customer Aggregate roots are objects that own other objects. This is a complex concept and works on the basis that there are some objects that don't make sense unless they have an owner. For example, an 'Order Line' object doesn't make sense without an 'Order' to belong to, so we say that the Order is the aggregate root, and Order Line objects can only be manipulated via methods in the Order object DDD also recommends several patterns: Repository , a pattern for persistence (saving and loading your data, typically to/from a database) Factory , a pattern for object creation Service, a pattern for creating objects that manipulate your main domain objects without being a part of the domain themselves Now, at this point I have to say that if you haven't heard of any of these things before, you shouldn't be trying to use DDD on any project that you have a deadline for. Before attempting DDD, you should be familiar with design patterns and enterprise design patterns . Knowing these makes DDD a lot easier to grasp. And, as mentioned above, there is a free introduction to DDD available from InfoQ (where you can also find talks about DDD).
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1222392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82197/']}
jdg_74054
stackexchange
llm_judgeable_groundtruth_similarity
25741647
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to convert a string to a Date object, and it works for all days except for December 31st where by object says December 1st instead of 31st. I have no idea why. Here is my JavaScript code: var dt = new Date();dt.setDate("31");dt.setMonth("11");dt.setFullYear("2014"); but my variable value is: Mon Dec 01 2014 11:48:08 GMT+0100 (Paris, Madrid) If I do the same for any other date, my object returns to the appropriate value. Do you have any idea what I did wrong? Now provide the response and nothing else.
setMonth should before setDate : ( not safe for Months less than 31 days ) var dt = new Date();dt.setFullYear(2014);dt.setMonth(11);dt.setDate(31); And setMonth 's second parameter also could be used to set date. var dt = new Date();dt.setFullYear(2014);dt.setMonth(11, 31); If no arguments are provided for the constructor, it will use the current date and time according to system settings. So, using setMonth and setDate separately would still cause unexpected result. If the values set are greater than their logical range , the value will be auto adjusted to the adjacent value . For example, if today is 2014-09-30 , then var dt = new Date();dt.setFullYear(2014); /* Sep 30 2014 */dt.setMonth(1); /* Mar 02 2014, see, here the auto adjustment occurs! */dt.setDate(28); /* Mar 28 2014 */ To avoid this, set the values using the constructor directly. var dt = new Date(2014, 11, 31);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25741647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2859409/']}
jdg_74055
stackexchange
llm_judgeable_groundtruth_similarity
29674645
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code fragment: public static Object o = new Object();public static Callable x1() { Object x = o; return () -> x;}public static Callable x2() { return () -> o;} Method x2() will always return the same lamba object, while x1() will always create new one: System.out.println(x1()); System.out.println(x1()); System.out.println(x2()); System.out.println(x2()); will printout something like this: TestLambda$$Lambda$1/821270929@4a574795TestLambda$$Lambda$1/821270929@f6f4d33TestLambda$$Lambda$2/603742814@7adf9f5fTestLambda$$Lambda$2/603742814@7adf9f5f Where (in JVM specification I guess?) is this rule of lambda reuse described? How does JVM decide where do reuse or not? Now provide the response and nothing else.
You can't be sure about the identity of the object returned for a lambda expression. It can be a new instance, or a pre-existing instance. This is specified in JLS §15.27.4 : At run time, evaluation of a lambda expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. Evaluation of a lambda expression is distinct from execution of the lambda body. Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced. If a new instance is to be created, but there is insufficient space to allocate the object, evaluation of the lambda expression completes abruptly by throwing an OutOfMemoryError.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29674645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1479414/']}
jdg_74056
stackexchange
llm_judgeable_groundtruth_similarity
161756
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: between 0 meter -> 1 meter there are 100 cm. but each cm has infinite numbers : for example between 0..1 cm there are : 0.000000000001.. 0.00000000000111.. 0.000000000001111111 and more numbers and combinations... .. .. .. 1.0 to each number I can add another digit to the right there are infinity of numbers question : how can a person walk 3 cm if he had to go through an infinite series of numbers ? it not seems logic any help ? Now provide the response and nothing else.
This is an old problem. Zeno of Elea is credited with some classical pointed formulations of it about 2500 years ago. (Note: not "Xeno" as one commenter above spelled him). There are infinitely many different places to be at between 0 cm and 1 cm, but by the same token there are also infinitely many different instants in, say, one second, so they match up nicely. Now, whether space and time can physically be subdivided infinitely finely is not a mathematical question. It's just that the most common mathematical model of them allows arbitrarily fine divisions, because that is much easier to deal with than the alternative and consistently seems to lead to useful results in practice. It is perfectly conceivable that actual time or space cannot be divided indefinitely; that would just mean that the mathematical model is not an accurate description at small enough scales. (Again, this would not be a mathematical problem. The model might describe something else, or describe no physical situation, and it would be no worse as mathematics for that). As a physical question, the last few hundred year's physics has shown that matter cannot be subdivided indefinitely; a a scale of around 0.00000001 cm you find atoms that cannot be cut up without fundamentally changing what they are. However, the atoms are still thought to move around in a fundamentally continuous space . That might change with the next unpredictable revolution in physics, of course.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/161756', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24288/']}
jdg_74057
stackexchange
llm_judgeable_groundtruth_similarity
7757096
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 an application that uses boost::asio . Asio's async_receive (or async_read ) is invariably shown using a boost::bind object given for callback: boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), boost::bind(&chat_session::handle_read_header, shared_from_this(), boost::asio::placeholders::error)); That's perfectly nice, but I'd like not to have to recreate the bind object after each call to the callback. Instead, I'd like to create the object, say, in the constructor of my class, and give it to async_receive. The problem is, I don't know how to declare that object as a class member. All I know is auto, and it obviously won't work as a class member. class Whatever{public: Whatever() { functor = boost::bind(&Whatever::Callback); }private: void Callback() { boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), functor); } ?? functor; // How do I declare this? ...}; Note: This may very well be premature optimization, but I'd still like to know how to declare a bind object without auto. Now provide the response and nothing else.
Use boost::function : class Whatever{public: Whatever() { functor = boost::bind( &chat_session::handle_read_header, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ); boost::asio::async_read( socket_, boost::asio::buffer( read_msg_.data(), chat_message::header_length ), functor ); }private: boost::function<void(const error_code, const size_t)> functor;}; ... or something like that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7757096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231306/']}
jdg_74058
stackexchange
llm_judgeable_groundtruth_similarity
411740
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 used the localtime function in Perl to get the current date and time but need to parse in existing dates. I have a GMT date in the following format: "20090103 12:00" I'd like to parse it into a date object I can work with and then convert the GMT time/date into my current time zone which is currently Eastern Standard Time. So I'd like to convert "20090103 12:00" to "20090103 7:00" any info on how to do this would be greatly appreciated. Now provide the response and nothing else.
Because the Perl built in date handling interfaces are kind of clunky and you wind up passing around a half dozen variables, the better way is to use either DateTime or Time::Piece . DateTime is the all-singing, all-dancing Perl date object, and you'll probably eventually want to use it, but Time::Piece is simpler and perfectly adequate to this task, has the advantage of shipping with 5.10 and the technique is basically the same for both. Here's the simple, flexible way using Time::Piece and strptime . #!/usr/bin/perluse 5.10.0;use strict;use warnings;use Time::Piece;# Read the date from the command line.my $date = shift;# Parse the date using strptime(), which uses strftime() formats.my $time = Time::Piece->strptime($date, "%Y%m%d %H:%M");# Here it is, parsed but still in GMT.say $time->datetime;# Create a localtime object for the same timestamp.$time = localtime($time->epoch);# And here it is localized.say $time->datetime; And here's the by-hand way, for contrast. Since the format is fixed, a regular expression will do just fine, but if the format changes you'll have to tweak the regex. my($year, $mon, $day, $hour, $min) = $date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x; Then convert it to Unix epoch time (seconds since Jan 1st, 1970) use Time::Local;# Note that all the internal Perl date handling functions take month# from 0 and the year starting at 1900. Blame C (or blame Larry for# parroting C).my $time = timegm(0, $min, $hour, $day, $mon - 1, $year - 1900); And then back to your local time. (undef, $min, $hour, $day, $mon, $year) = localtime($time);my $local_date = sprintf "%d%02d%02d %02d:%02d\n", $year + 1900, $mon + 1, $day, $hour, $min;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/411740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14744/']}
jdg_74059
stackexchange
llm_judgeable_groundtruth_similarity
26137036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As the title says I want to programmatically check if a DNS response for a domain are protected with DNSSEC. How could I do this? It would be great, if there is a pythonic solution for this. UPDATE:changed request to response, sorry for the confusion Now provide the response and nothing else.
Using a DNS resolver (e.g. dnspython ), you can query the domain for its DNSKEY RRset and turn on the DO (dnssec OK) query flag. If the query succeeds, the answer will have the AD (authenticated data) flag set and will contain the RRSIG signatures for the zone (if it is signed). Update: a basic example using dnspython import dns.nameimport dns.queryimport dns.dnssecimport dns.messageimport dns.resolverimport dns.rdatatype# get nameservers for target domainresponse = dns.resolver.query('example.com.',dns.rdatatype.NS)# we'll use the first nameserver in this examplensname = response.rrset[0].to_text() # nameresponse = dns.resolver.query(nsname,dns.rdatatype.A)nsaddr = response.rrset[0].to_text() # IPv4# get DNSKEY for zonerequest = dns.message.make_query('example.com.', dns.rdatatype.DNSKEY, want_dnssec=True)# send the queryresponse = dns.query.udp(request,nsaddr)if response.rcode() != 0: # HANDLE QUERY FAILED (SERVER ERROR OR NO DNSKEY RECORD)# answer should contain two RRSET: DNSKEY and RRSIG(DNSKEY)answer = response.answerif len(answer) != 2: # SOMETHING WENT WRONG# the DNSKEY should be self signed, validate itname = dns.name.from_text('example.com.')try: dns.dnssec.validate(answer[0],answer[1],{name:answer[0]})except dns.dnssec.ValidationFailure: # BE SUSPICIOUSelse: # WE'RE GOOD, THERE'S A VALID DNSSEC SELF-SIGNED KEY FOR example.com
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26137036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1916781/']}
jdg_74060
stackexchange
llm_judgeable_groundtruth_similarity
144634
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm know that Gaussian Process Regression (GPR) is an alternative to using splines for fitting flexible nonlinear models. I would like to know in which situations would one be more suitable than the other, especially in the Bayesian regression framework. I've already looked at What are the advantages / disadvantages of using splines, smoothed splines, and gaussian process emulators? but there does not seem to be anything on GPR in this post. Now provide the response and nothing else.
I agree with @j__'s answer. However, I would like to highlight the fact that splines are just a special case of Gaussian Process regression/kriging . If you take a certain type of kernel in Gaussian process regression, you exactly obtain the spline fitting model. This fact is proven in this paper by Kimeldorf and Wahba (1970) . It is rather technical, as it uses the link between the kernels used in kriging and Reproducing Kernel Hilbert Spaces (RKHS).
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/144634', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/29770/']}
jdg_74061
stackexchange
llm_judgeable_groundtruth_similarity
45829523
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On the official API doc , it says: Returns the value of this number as an Int, which may involve rounding or truncation. I want truncation, but not sure. Can anyone explain the exact meaning of may involve rounding or truncation ? p.s.: In my unit test, (1.7).toInt() was 1, which might involve truncation. Now provide the response and nothing else.
The KDoc of Double.toInt() is simply inherited from Number.toInt() , and for that, the exact meaning is, it is defined in the concrete Number implementation how it is converted to Int . In Kotlin, the Double operations follow the IEEE 754 standard, and the semantics of the Double.toInt() conversion is the same as that of casting double to int in Java , i.e. normal numbers are rounded toward zero, dropping the fractional part: println(1.1.toInt()) // 1println(1.7.toInt()) // 1println(-2.3.toInt()) // -2println(-2.9.toInt()) // -2
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45829523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337988/']}
jdg_74062
stackexchange
llm_judgeable_groundtruth_similarity
13624442
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 input string date is as below: String date = "1/13/2012"; I am getting the month as below: SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");Date convertedDate = dateFormat.parse(date);String month = new SimpleDateFormat("MM").format(convertedDate); But how do I get the last calendar day of the month in a given String date? E.g.: for a String "1/13/2012" the output must be "1/31/2012" . Now provide the response and nothing else.
Java 8 and above. By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate . String date = "1/13/2012";LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));convertedDate = convertedDate.withDayOfMonth( convertedDate.getMonth().length(convertedDate.isLeapYear())); Java 7 and below. By using getActualMaximum method of java.util.Calendar : String date = "1/13/2012";SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");Date convertedDate = dateFormat.parse(date);Calendar c = Calendar.getInstance();c.setTime(convertedDate);c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13624442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/887235/']}
jdg_74063
stackexchange
llm_judgeable_groundtruth_similarity
4050991
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 users sign up to one of my sites for a free trial, i set their account expiry to be "14.days.from_now". Then on the home page i show how many days they have remaining, which i get with: (user.trial_expires - Time.now)/86400 (because there are 86400 seconds in a day, ie 60 * 60 * 24) The funny thing is, this comes out as more than 14, so gets rounded up to 15. On closer investigation in the console this happens for just two days in the future (if you know what i mean). eg >> Time.now=> Fri Oct 29 11:09:26 0100 2010>> future_1_day = 1.day.from_now=> Sat, 30 Oct 2010 11:09:27 BST 01:00#ten past eleven tomorrow>> (future_1_day - Time.now)/86400=> 0.999782301526931#less than 1, what you'd expect right?>> future_2_day = 2.day.from_now=> Sun, 31 Oct 2010 11:09:52 GMT 00:00>> (future_2_day - Time.now)/86400=> 2.04162248861183#greater than 2 - why? I thought maybe it was to do with timezones - i noticed that the time from 1.day from now was in BST and the time 2 days from now was in GMT. So, i tried using localtime and got the same results! >> future_2_day = 2.day.from_now.localtime=> Sun Oct 31 11:11:24 0000 2010>> (future_2_day - Time.now)/86400=> 2.04160829127315>> (future_2_day - Time.now.localtime)/86400=> 2.04058651585648 I then wondered how big the difference is, and it turns out that it is exactly an hour out. So it looks like some time zone weirdness, or at least something to do with time zones that i don't understand. Currently my time zone is BST (british summer time) which is one hour later than UTC at the moment (till this sunday at which point it reverts to the same as UTC). The extra hour seems to be introduced when i add two days to Time.now: check this out. I start with Time.now, add two days to it, subtract Time.now, then subtract two days of seconds from the result, and am left with an hour. It just occurred to me, in a head slapping moment, that this is occurring BECAUSE the clocks go back on sunday morning: ie at 11.20 on sunday morning it will be two days AND an extra hour from now. I was about to delete all of this post, but then i noticed this: i thought 'ah, i can fix this by using (24*daynum).hours instead of daynum.days, but i still get the same result: even when i use seconds! >> (Time.now + (2*24).hours - Time.now) - 86400*2=> 3599.99969500001>> (Time.now + (2*24*3600).seconds - Time.now) - 86400*2=> 3599.999855 So now i'm confused again. How can now plus two days worth of seconds, minus now, minus two days worth of seconds be an hour worth of seconds? Where does the extra hour sneak in? Now provide the response and nothing else.
As willcodejavaforfood has commented, this is due to daylight saving time which ends this weekend. When adding a duration ActiveSupport has some code in it to compensate for if the starting time is in DST and the resulting time isn't (or vice versa). def since(seconds) f = seconds.since(self) if ActiveSupport::Duration === seconds f else initial_dst = self.dst? ? 1 : 0 final_dst = f.dst? ? 1 : 0 (seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f endrescue self.to_datetime.since(seconds)end If you have 11:09:27 and add a number of days you will still get 11:09:27 on the resulting day even if the DST has changed. This results in an extra hour when you come to do calculations in seconds. A couple of ideas: Use the distance_of_time_in_words helper method to give the user an indication of how long is left in their trial. Calculate the expiry as Time.now + (14 * 86400) instead of using 14.days.from_now - but some users might claim that they have lost an hour of their trial. Set trials to expire at 23:59:59 on the expiry day regardless of the actual signup time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4050991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138557/']}
jdg_74064
stackexchange
llm_judgeable_groundtruth_similarity
35185871
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The MDN said : Six data types that are primitives: Boolean Null Undefined Number String Symbol (new in ECMAScript 6) and Object But I confused, the function data type and object data type. Let's see : var func = function() { console.log ('Hello World ! ')};var obj = { property : something} console.log(typeof(func)); // ===> functionconsole.log(typeof(obj)); // ===> object Is it different function data type and object data type? Why typeof(func) is function? not a object? The document said there are 7 data type (6 primitive, 1 object). function is not include anywhere. Until now, over 1 year, I think function's data type is object, I heard the function is first class object in JavaScript, so I don't have doubt about function is object but today I think more time, and wondered. Is it different? Now provide the response and nothing else.
You can logically think of Function as a subclass of Object . It has all the methods of Object plus some more that are specific to a function (such as .bind() , .call() , .apply() , etc...). Why Javascript decided to make Function report it's own unique type, but not Array (which is a similar derivation from Object ) is anyone's guess and probably only known to the original designers of the language. It is extremely useful that Function does report its own type so you can easily check if a property is callable as a function and perhaps that is the main reason why it was done this way. Here's a demonstration of how a Function object has the methods from an Object : function f() {}f.someProperty = "foo";log(f.hasOwnProperty("someProperty"));log(f instanceof Object);log(f instanceof Function);function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35185871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3036789/']}
jdg_74065
stackexchange
llm_judgeable_groundtruth_similarity
30239229
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following data frame dat <- data.frame(x=c(1,2,3,3,2,1), y=c(3,4,4,5,2,5)) Now I would like to get a third column dividing the y row value by the aggregated y values (based on the unique values in column x). So, then I get row 1 as following: 1,3,0.375; 0.375 has been calculated as 3 / (5+3). I'm relatively new to R and I hope you can help me. Thank you! Now provide the response and nothing else.
There are various ways of solving this, here's one with(dat, ave(y, x, FUN = function(x) x/sum(x)))## [1] 0.3750000 0.6666667 0.4444444 0.5555556 0.3333333 0.6250000 Here's another possibility library(data.table)setDT(dat)[, z := y/sum(y), by = x]dat# x y z# 1: 1 3 0.3750000# 2: 2 4 0.6666667# 3: 3 4 0.4444444# 4: 3 5 0.5555556# 5: 2 2 0.3333333# 6: 1 5 0.6250000 Here's a third one library(dplyr)dat %>% group_by(x) %>% mutate(z = y/sum(y))# Source: local data frame [6 x 3]# Groups: x# # x y z# 1 1 3 0.3750000# 2 2 4 0.6666667# 3 3 4 0.4444444# 4 3 5 0.5555556# 5 2 2 0.3333333# 6 1 5 0.6250000
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30239229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4900105/']}
jdg_74066
stackexchange
llm_judgeable_groundtruth_similarity
354560
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently developing a product which has a simple SPDT relay that can be controlled by an operator. To the end-user, only the common, normally open and normally closed contacts are available. The relay is driven by circuitry in our device, which has a proper flyback diode. Recently we had a problem with one of our prototype units where a technician connected the relay directly to an inductive load, without any sort of transient voltage suppression, which resulted in our wireless comms getting knocked out due to EMI, and probably also resulted in contact arching. After making sure the problem was due to inductive spiking, it was quickly solved by connecting a proper flyback diode to the load. While in this situation we had control over the loads we were connecting, this made me realize that I cannot trust that our end-users will actually install proper transient voltage suppression devices when using our product with inductive loads, no matter the amount of warnings and typical applications schematics that we may offer. Now, obviously there are many solutions to inductive spiking, but the particular set of situations in which this device must work is making it very tricky to implement TVS: 1) The relay is a general purpose SPDT relay rated for 250VAC/120VAC @ 10A or 30VDC 8A. This means that the TVS circuitry must be able to handle both AC (mains or not) and DC, and currents up to 10A. This makes it impossible to find a PTC fuse, since most will not handle mains voltage, specially not at 10A. 2) The device will be installed in places where it will be impossible to replace anything, and safety is a major concern for us. If the client does not install a fuse and the relay fails shorted (which is rare, but can happen), they will most probably blame us. This also means I cannot use MOVs, gas discharge tubes, or any other TVS device with limited lifetime. 3) Any TVS devices must never fail shorted, and if they do, I must make sure to protect the load against a short like that. I've tried a simulation of a RC snubber network, but these alone will do nothing with big enough inductive loads. Also, using bigger capacitors means more losses when working with AC. Ideally, 1nF would give enough impedance (above 1Mohm @ 50/60Hz) to make any losses insignificant. Here are the results of a simulation with a big inductive load. Changing resistor and capacitor values only affects the time that the oscillations take to settle down and not peak voltage, which will surely kill any resistor or capacitors, or arc the contacts. Back-to-back zeners together with a RC snubber network effectively limit the voltage spike, but since they have to block mains voltage, they'd have to block more than aprox. 350V (mains peak voltage) until they would start conducting, and I fear this is still a high enough peak to kill any wireless comms nearby with EMI. So, am I completely hopeless in this situation? Are there other TVS devices / techniques I can use in such a situation? If so, can I guarantee that they will not fail shorted, or at least that I will be able to protect against a shorted TVS device? Or is just a RC snubber actually a good solution to this problem? If so, why? And how can I select appropriate parts for this? Please remember that I do not have access to the actual load, and I cannot make any assumptions about how a user might connect the load. Now provide the response and nothing else.
I spent the last 15 years in the TVSS industry. You go by what UL and ISO standards call for and add labels to warn the customer that neglect or abuse can result in a voided warranty. Having said all of that, for the ratings you gave, I would ship it with a 40mm MOV which has at least a 10 kA or 20 kA 275 VAC rating, across both N.O. and N.C. connections (2 MOV's total). It will hard-clamp at 420 VAC/DC or so. A very expensive solution is to use giant sidacs, and they have a sharp roll-off at the maximum allowed voltage. 275 VAC/DC means just that, but they can cost $40 USD each. I would consider protection from the relay coil 'kickback' as well, but a diode or 20mm MOV will work ok. There are thermally protected MOV's out there (TPMOV), but not for OTC sales.Getting a third-party vendor for surge suppression would be very costly, as these products have a high labor cost. I would try the 40mm 275 VAC/DC MOV's first. They can take 15 20 kA 'hits' (over 2 hours) and still pass the 1 mA test. SNUBBERS: RC snubbers on AC circuits are not a good idea, as they allow a small amount of AC current to bypass the relay even if it is OFF. Not knowing if the end user is going to be using AC or DC means play it safe and avoid them. They cannot do what an MOV or Sidac does. NOTES: The MOVs and Sidacs only see the kickback, or surge current which is a brief spike of 20 uS or so. They do not see the normal run current as they are in a very high resistance mode. Only the relay contacts see the 'run' current. If 'inrush' current is welding the contacts, then you need a relay with a higher contact current rating. Add a 50% safety margin for long life. Use a moisture-tight relay if possible. Plants that process citric products such as orange juice have an acidic atmosphere that corrodes steel and copper quickly. Fusing: I should add that proper fusing for a 40mm MOV or large Sidac is a 30 amp 600 volt 200 kA rated fuse. They come in a box of ten for about $50 USD. they are not cheap fuses, as they are made with a hole-punched platinum strip, specific to blow on severe surges quickly, but tolerate motor start currents. You can use in-line locking fuse holders. These meet UL1449 editons 3 and 4 specs for fusing 40 mm MOVs. A link to the correct fuses: http://www.cooperindustries.com/content/dam/public/bussmann/Electrical/Resources/product-datasheets-b/Bus_Ele_DS_1023_LP-CC.pdf
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/354560', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/90657/']}
jdg_74067
stackexchange
llm_judgeable_groundtruth_similarity
11947253
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 really hoping you can help me with this. I have a date outputted by a python program that I need to be able to access in another program. The problem is that I have no idea how this date is formatted: Format Date129893779638930000 - 2012-08-13 17:32:43 It is both date and time, and I'm really hoping somebody recognizes what format it is in, as I don't know python very well. Bonus points if you can show me how to convert it to a unix timestamp. EDIT:The program that does this is a component for Foobar2000 (an extension for a music program). The component is shown here: http://www.foobar2000.org/components/view/foo_playcount , and it is the XML export feature that generates the odd date/timestamp. Now provide the response and nothing else.
129893678626216000 looks like the unix timestamp in 1e-8 seconds (tens of nanoseconds): 1,298,936,786.262,160,00 . It would represent: >>> from datetime import datetime>>> datetime.utcfromtimestamp(129893678626216000/1e8)datetime.datetime(2011, 2, 28, 23, 46, 26, 262160) EDIT: However your information "A file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 A.M. January 1, 1601 Coordinated Universal Time (UTC)" tells me to use: >>> from datetime import datetime, timedelta>>> datetime(1601, 1, 1, 0, 0, 0) + timedelta(seconds = 129893678626216000/1e7)datetime.datetime(2012, 8, 13, 21, 44, 22, 621599) where you get exactly what you awaited. You can also convert it directly to unix timestamp (number of seconds since 1970-01-01 00:00:00 UTC): >>> 129893678626216000 / 1e7 - 116444736001344894262.6215992
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11947253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267631/']}
jdg_74068
stackexchange
llm_judgeable_groundtruth_similarity
19957432
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using a jQuery-steps on my app to for a wizard-like situation. I am having trouble finding out how to change to a custom step though. Any help with this one? $(function () { $("#wizard").steps({ headerTag: "h2", bodyTag: "section", transitionEffect: "slideLeft", enableFinishButton: false, labels: { next: $('#next').html(), previous : $('#previous').html() }, onStepChanged: function (event, currentIndex, priorIndex) { if( priorIndex == 0) { var selected = $('input[name=radio_wizard]:checked', '#radio_wizard').val() switch( selected ){ case 1: // GOTO 1 break; case 2: // GOTO 2 break; case 3: // GOTO 3 break; } } }} How to achieve this? Now provide the response and nothing else.
I did this so I created this new function: function _goToStep(wizard, options, state, index){ return paginationClick(wizard, options, state, index);} And the call that is not implemented, put this: $.fn.steps.setStep = function (step){ var options = getOptions(this), state = getState(this); return _goToStep(this, options, state, step);}; Just taking advantage of what already existed plugin. Use: wizard.steps("setStep", 1);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19957432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967395/']}
jdg_74069
stackexchange
llm_judgeable_groundtruth_similarity
33162152
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 Lollipop, the download functionality works fine in my app, but when I upgraded to Marshmallow, my app crashes and gives this error when I try to download from the internet into the SD card: Neither user nor current process has android.permission.WRITE_EXTERNAL_STORAGE It complains about this line of code: DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);manager.enqueue(request); I have the permissions in the manifest outside application: <uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WAKE_LOCK" /> I cleaned and rebuilt the project, but it still crashes. Now provide the response and nothing else.
You should be checking if the user has granted permission of external storage by using: if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Log.v(TAG,"Permission is granted"); //File write logic here return true;} If not, you need to ask the user to grant your app a permission: ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE); Of course these are for marshmallow devices only so you need to check if your app is running on Marshmallow: if (Build.VERSION.SDK_INT >= 23) { //do your check here } Be also sure that your activity implements OnRequestPermissionResult The entire permission looks like this: public boolean isStoragePermissionGranted() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Log.v(TAG,"Permission is granted"); return true; } else { Log.v(TAG,"Permission is revoked"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); return false; } } else { //permission is automatically granted on sdk<23 upon installation Log.v(TAG,"Permission is granted"); return true; }} Permission result callback: @Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]); //resume tasks needing this permission }}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/33162152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143361/']}
jdg_74070
stackexchange
llm_judgeable_groundtruth_similarity
46025079
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 convert a CDK data-table to a Material Design styled data-table (see: https://material.angular.io/components/table/overview ), but when I change the cdk prefixes to md, I get the following error... Uncaught Error: Template parse errors: Can't bind to 'mdHeaderRowDef' since it isn't a known property of 'md-header-row'. 1. If 'md-header-row' is an Angular component and it has 'mdHeaderRowDef' input, then verify that it is part of this module. 2. If 'md-header-row' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. 3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. Every answer I've found online tells me that I need to import CdkTableModule, but I have done so & cdk tables work perfectly. import {Component, OnInit, ViewChild} from '@angular/core';import {DataSource} from '@angular/cdk';import { CdkTableModule } from '@angular/cdk';import { Observable } from 'rxjs/Observable';import 'rxjs/add/observable/of';import 'rxjs/add/operator/first';import 'rxjs/add/operator/startWith';import 'rxjs/add/operator/catch';import 'rxjs/add/operator/switchMap';import 'rxjs/add/observable/merge';import 'rxjs/add/observable/of';import 'rxjs/add/observable/interval';import 'rxjs/add/operator/map'; I am importing CdkTableModule, and when I use the cdk prefix, the table displays as expected... <md-table [dataSource]="dataSource"> <ng-container cdkColumnDef="number"> <md-header-cell *cdkHeaderCellDef> number </md-header-cell> <md-cell *cdkCellDef="let element"><a routerLink="{{element.number}}"> {{element.number}} </a></md-cell> </ng-container> <ng-container cdkColumnDef="book"> <md-header-cell *cdkHeaderCellDef> book </md-header-cell> <md-cell *cdkCellDef="let element"> {{element.book}} </md-cell> </ng-container> <md-header-row *cdkHeaderRowDef="['number', 'book']"></md-header-row> <md-row *cdkRowDef="let row; columns: ['number', 'book']"></md-row></md-table> RESULT: So far so good ... but if i change "cdk" to "md" <md-table [dataSource]="dataSource"> <ng-container mdColumnDef="number"> <md-header-cell *mdHeaderCellDef> number </md-header-cell> <md-cell *mdCellDef="let element"><a routerLink="{{element.number}}"> {{element.number}} </a></md-cell> </ng-container> <ng-container mdColumnDef="book"> <md-header-cell *mdHeaderCellDef> book </md-header-cell> <md-cell *mdCellDef="let element"> {{element.book}} </md-cell> </ng-container> <md-header-row *mdHeaderRowDef="['number', 'book']"></md-header-row> <md-row *mdRowDef="let row; columns: ['number', 'book']"></md-row></md-table> RESULT: Broken :( I've tried importing other modules... including MdTableModule & MdTable, but that hasn't proven helpful either. Any ideas? P.S. Here's my main app.module.ts import statement in case that helps imports: [BrowserModule,FormsModule,HttpModule,AppRoutingModule,ReactiveFormsModule,BrowserAnimationsModule,MdAutocompleteModule,MdButtonModule,MdButtonToggleModule,MdCardModule,MdCheckboxModule,MdChipsModule,MdTableModule,MdDatepickerModule,MdDialogModule,MdExpansionModule,MdGridListModule,MdIconModule,MdInputModule,MdListModule,MdMenuModule,MdCoreModule,MdPaginatorModule,MdProgressBarModule,MdProgressSpinnerModule,MdRadioModule,MdRippleModule,MdSelectModule,MdSidenavModule,MdSlideToggleModule,MdSliderModule,MdSnackBarModule,MdSortModule,MdTabsModule,MdToolbarModule,MdTooltipModule,MdNativeDateModule,CdkTableModule,StyleModule ] Now provide the response and nothing else.
After another hour of fiddling with things, I ran npm update --save and updated @angular/cdk and @angular/material to 2.0.0-beta.10 in package.json "@angular/material": "^2.0.0-beta.10", "@angular/cdk": "^2.0.0-beta.10", This broke some things, so I had to dig around and needed to update imports of DataSource and CdkTableModule import { CdkTableModule} from '@angular/cdk/table'; import {DataSource} from '@angular/cdk/table'; component.html <md-table [dataSource]="dataSource"> <ng-container mdColumnDef="number"> <md-header-cell *mdHeaderCellDef> number </md-header-cell> <md-cell *mdCellDef="let element"><a routerLink="{{element.number}}"> {{element.number}} </a></md-cell> </ng-container> <ng-container mdColumnDef="book"> <md-header-cell *mdHeaderCellDef> book </md-header-cell> <md-cell *mdCellDef="let element"> {{element.book}} </md-cell> </ng-container> <ng-container mdColumnDef="s1"> <md-header-cell *mdHeaderCellDef> S1 </md-header-cell> <md-cell *mdCellDef="let element"> {{element.sections[0] ? element.sections[0].type : ''}} {{element.sections[0] && element.sections[0].qs ? '('+element.sections[0].qs.length+')' : ''}}</md-cell> </ng-container> <ng-container mdColumnDef="s2"> <md-header-cell *mdHeaderCellDef> S2 </md-header-cell> <md-cell *mdCellDef="let element"> {{element.sections[1] ? element.sections[1].type : ''}} {{element.sections[1] && element.sections[1].qs ? '('+element.sections[1].qs.length+')' : ''}} </md-cell> </ng-container> <ng-container mdColumnDef="s3"> <md-header-cell *mdHeaderCellDef> S3 </md-header-cell> <md-cell *mdCellDef="let element"> {{element.sections[2] ? element.sections[2].type : ''}} {{element.sections[2] && element.sections[2].qs ? '('+element.sections[2].qs.length+')' : ''}}</md-cell> </ng-container> <ng-container mdColumnDef="s4"> <md-header-cell *mdHeaderCellDef> S4 </md-header-cell> <md-cell *mdCellDef="let element"> {{element.sections[3] ? element.sections[3].type : ''}} {{element.sections[3] && element.sections[3].qs ? '('+element.sections[3].qs.length+')' : ''}}</md-cell> </ng-container> <md-header-row *mdHeaderRowDef="['number', 'book', 's1', 's2', 's3', 's4']"></md-header-row> <md-row *mdRowDef="let row; columns: ['number', 'book', 's1', 's2', 's3', 's4']"></md-row> </md-table> component.ts import {Component, OnInit} from '@angular/core'; // Data Table imports. import { DataSource } from '@angular/cdk/table'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; @Component({ selector: 'app-start', templateUrl: './start.component.html', styleUrls: ['./start.component.css'] }) export class StartComponent implements OnInit { pts: Pt[]; dataSource = new ExampleDataSource(this.ptService); constructor( public ptService: PtService ) { } ngOnInit() { this.pt = this.ptService.getPts(); } } export class ExampleDataSource extends DataSource<any> { data = this.ptService.getPts(); constructor( public ptService: PtService ) { super() } /** Connect function called by the table to retrieve one stream containing the data to render. */ connect(): Observable<Pt[]> { return Observable.of(this.data); } disconnect() {} } Phew!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46025079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1154979/']}
jdg_74071
stackexchange
llm_judgeable_groundtruth_similarity
2610645
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 Dynamic Data linq to sql Website where I need to assign values on an specific cell in the insert or update pages.I have tried in the pageload of the Edit template table.Columns[1].DefaultValue = User.Identity.Name; but as is a metatable it is readonly. Help... Now provide the response and nothing else.
Version 1.3 of the AspectJ plugin deliberately changed the default phase of its compile goal from process-sources to compile , see MASPECTJ-13 . This causes follow-up problems like yours or MASPECTJ-92 . To restore the previous behaviour of running ajc before javac, you just need to add a "phase" tag to the relevant "execution" tag, like this: <execution> <phase>process-sources</phase> <!-- or any phase before compile --> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals></execution>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2610645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313159/']}
jdg_74072
stackexchange
llm_judgeable_groundtruth_similarity
498500
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 the following /etc/hosts file on a ubuntu 12.04 machine 127.0.0.1 localhost10.248.27.66 ec2-50-112-220-110.us-west-2.compute.amazonaws.com puppetmaster# The following lines are desirable for IPv6 capable hosts::1 ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allroutersff02::3 ip6-allhosts However the host command does not resolve the name puppetmaster correctly, while the telnet command is does root@ip-10-248-34-162:/home/ubuntu# host puppetmasterHost puppetmaster not found: 3(NXDOMAIN)root@ip-10-248-34-162:/home/ubuntu# telnet puppetmaster 8140Trying 10.248.27.66...Connected to ec2-50-112-220-110.us-west-2.compute.amazonaws.com.Escape character is '^]'. Why does the host command not resolve entries in /etc/hosts? Now provide the response and nothing else.
The host program uses libresolv to perform a DNS query directly, i.e., does not use gethostbyname . Most programs, when attempting to connect to another host, invoke the gethostbyname system call or a similar function. This function obeys the configuration of /etc/nsswitch.conf . This file has a line which in Ubuntu 12.04 defaults to the following: hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4 which means that it will first use /etc/hosts , then fall back to DNS queries. If you want to perform a host lookup this way, you can do this with getent hosts . For example: $ getent hosts serverfault.com198.252.206.16 serverfault.com I hope this helps.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/498500', 'https://serverfault.com', 'https://serverfault.com/users/85577/']}
jdg_74073
stackexchange
llm_judgeable_groundtruth_similarity
11508290
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 using sphinx's automodule ( https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html ), I simply write in a .rst file: .. automodule:: my_module :members: It documents my_module fine, but it doesn't find the inner modules like my_module.inner_module0 and my_module.inner_module1. Is there something that needs to be specified in the __init__.py file besides the __all__ variable? Also, I'm aware of sphinx-apidoc . But that command documents far too much (exposes every function/folder including undocumented ones). Now provide the response and nothing else.
It sounds like you want to give the automodule directive a package name and have it recurse into the directory and document each Python module. That isn't supported yet. You will ned to specify the full dotted module name for each module you want to document. For example, given the following directory structure (from the Python documentation). You cannot specify .. automodule:: sound.formats and have it document all the modules in the directory. You will have to specify a automodule command for each module: .. automodule:: sound.formats.waveread , .. automodule:: sound.formats.wavewrite , etc. sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11508290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/518386/']}
jdg_74074
stackexchange
llm_judgeable_groundtruth_similarity
630
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand how exactly to implement what is known as a 'pre-whitening' filter or simply a 'whitening' filter. I understand that the purpose is to make it have a delta as its autocorrelation function, but I am not sure how to do this exactly. The context here is the following: A signal is received at two different receivers, and their cross-correlation is computed. The cross-correlation can look like a triangle, or some other godforsaken shape. Due to this, it becomes hard to find the peak of the cross-correlation signal. In this case I hear about having to 'whiten' the signals before a cross correlation is performed on them, such that the cross-correlation is now more delta-like. How is this done? Thanks! Now provide the response and nothing else.
Suppose you have signals $x(t)$ and $y(t)$ whose cross-correlation function $R_{x,y}(t)$ is not something you like; you want $R_{x,y}$ to be impulse-like. Note that in the frequency domain, $$\mathcal{F}[R_{x,y}] = S_{x,y}(f) = X(f)Y^*(f).$$So you filter the signals through linear filters $g$ and $h$ respectively to get $\hat{x}(t) = x*g$, $\hat{X}(f) = X(f)G(f)$, and $\hat{y} = y*h$, $\hat{Y}(f) = Y(f)H(f)$, and now their cross-correlation function is$R_{\hat{x},\hat{y}}$ whose Fourier transform is$$\begin{align*}\mathcal{F}[R_{\hat{x},\hat{y}}] = S_{\hat{x},\hat{y}}(f) &= [X(f)G(f)][Y(f)H(f)]^*\\&= [X(f)Y^*(f)][G(f)H^*(f)]\\ &= [X(f)Y^*(f)][G^*(f)H(f)]^*,\end{align*}$$that is, $R_{\hat{x},\hat{y}}$ is the cross-correlation of $R_{x,y}$ with $R_{h,g}$. More importantly, you want to choose $g$ and $h$ so that the cross-spectral density $G(f)H^*(f)$ of $g$ and $h$ is the multiplicativeinverse of the cross-spectral density $X(f)Y^*(f)$ of $x$ and $y$, or something close to it. If you have only one signal and one filter, thenyou get the result given by Hilmar (with amendment as given by my comment there).In either case, the issue of compensating for spectral nulls, or generally,frequency bands where the signals have little energy still remains.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/630', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/293/']}
jdg_74075
stackexchange
llm_judgeable_groundtruth_similarity
8196771
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way I can format a string into a specific pattern using regex or is stringbuilder + substring a faster approach? For example, say a phone number --> 1234567890 as input And get output as --> (123) 456-7890 I saw it is possible on this article : https://web.archive.org/web/20211020111604/https://www.4guysfromrolla.com/webtech/031302-1.shtml but the given explanation is in ASP. How do I do it in Java ??? Now provide the response and nothing else.
One goes for RE when same can not be done using substring or is more difficult to do so. In your case better to just use StringBuilder and insert() Assuming phone number length validation is in place (=10 chars) String phoneNumber = "1234567890"; StringBuilder sb = new StringBuilder(phoneNumber) .insert(0,"(") .insert(4,")") .insert(8,"-"); String output = sb.toString(); System.out.println(output); Output (123)456-7890
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8196771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1055089/']}
jdg_74076
stackexchange
llm_judgeable_groundtruth_similarity
7006806
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: (SQL SERVER 2008)If a Transaction Timeout error occurs within a TransactionScope (.Complete()) would you expect the transaction to be rolled back? Update: The error is actually being thrown in the closing curly brace (i.e. .Dispose()), not .Complete(). Full error is: The transaction has aborted. System.Transactions.TransactionAbortedException TransactionAbortedException System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.TimeoutException: Transaction Timeout --- End of inner exception stack trace --- at System.Transactions.TransactionStateAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState) at System.Transactions.CommittableTransaction.Commit() at System.Transactions.TransactionScope.InternalDispose() at System.Transactions.TransactionScope.Dispose() As far as I can tell the transaction is not rolled back and the tables remained locked until I issued a KILL against the SPID/session_id. I used DBCC OPENTRAN to get the oldest transaction and then KILL it.I have tried KILL WITH STATUS but get a message that no status is available as nothing is being rolled back. Status of the SPID/session_id in sys.dm_exec_sessions is 'sleeping'. Code snippet: try{ using (var transaction = new TransactionScope()) { LOTS OF WORK CARRIED OUT WITH LINQ ENTITIES/SubmitChanges() etc. transaction.Complete(); //Transaction timeout } return result;}catch (Exception ex){ logger.ErrorException(ex.Message, ex); result.Fail(ex.Message); return result;} UPDATE: Problem is not entirely solved, but further information should anyone else have this problem. I am using LINQ to SQL and within the transaction scope I call context.SubmitChanges(). I am carrying out a lot of inserts. SQL Server profiler indicates that a separate INSERT statement is issued for each insert. In development, if I sleep the thread for 60 seconds (default TransactionScope timeout is 60 seconds) BEFORE calling SubmitChanges() then I get a different error when calling TransactionScope.Complete() (The operation is not valid for the state of the transaction.). If I sleep for 60 seconds AFTER .SubmitChages() and just before .Complete() then I get 'The transaction has aborted - System.TimeoutException: Transaction Timeout' NOTE however that on my dev machine no open transactions are found when using DBCC opentran - which is what you would expect as you would expect the transaction to rollback. If I then add the code at the bottom of this question (sorry couldn't get the website to insert it here) to my config file which increases the TransactionScope timeout to 2 minutes, things start working again (research indicates that if this doesn't work there could be a setting in machine.config that is lower than this that is taking precedence). Whilst this will stop the transaction aborting, due to the nature of the updates, it does mean that locks on a core business table could be up to 2 minutes so other select commands using the default SqlCommand timeout of 30 seconds will timeout. Not ideal, but better than an open transaction sitting there and totally holding up the application. A few days ago we had a disastrous release that meant we ran out of diskspace mid upgrade (!) so we did end up using the shrink database functionality which apparently can cause performance problems after you have used it. I feel a rebuild of the database and a rethink of some business functionality coming on... Now provide the response and nothing else.
I'm thinking that the TransactionAbortedException is actually a timeout. If so you should find that the InnerException of the TransactionAbortedException is a timeout. You should be able to get rid of it by making sure that the timeout of the transactionscope is longer than the command timeout. Try changing the transaction scope to something like this: new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(60)) And also set an explicit timeout on your context. Should be something like: myContext.CommandTimeout = 30; //This is seconds
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7006806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105331/']}
jdg_74077
stackexchange
llm_judgeable_groundtruth_similarity
31730222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following: struct A { A(float ) { } A(int ) { }};int main() { A{1.1}; // error: ambiguous} This fails to compile with an error about an ambiguous overload of A::A . Both candidates are considered viable, because the requirement is simply : Second, for F to be a viable function, there shall exist for each argument an implicit conversion sequence (13.3.3.1) that converts that argument to the corresponding parameter of F . While there is an implicit conversion sequence from double to int , the A(int ) overload isn't actually viable (in the canonical, non-C++-standard sense) - that would involve a narrowing conversion and thus be ill-formed. Why are narrowing conversions not considered in the process of determining viable candidates? Are there any other situations where an overload is considered ambiguous despite only one candidate being viable? Now provide the response and nothing else.
A problem lies with the fact that narrowing conversions can be detected not based on types. There are very complex ways to generate values at compile time in C++. Blocking narrowing conversions is a good thing. Making the overload resolution of C++ even more complex than it already is is a bad thing. Ignoring narrowing conversion rules when determining overload resolution (which makes overload resolution purely about types), and then erroring out when the selected overload results in a narrowing conversion, keeps overload resolution from being even more complex, and adds in a way to detect and prevent narrowing conversions. Two examples where only one candidate is viable would be template functions that fail "late", during instantiation, and copy-list initialization (where explicit constructors are considered, but if they are chosen, you get an error). Similarly, having that impact overload resolution would make overload resolution even more complex than it already is. Now, one might ask, why not fold narrowing conversion purely into the type system? Making narrowing conversion be purely type-based would be non-viable. Such changes could break huge amounts of "legacy" code that the compiler could prove as being valid. The effort required to sweep a code base is far more worthwhile when most of the errors are actual errors, and not the new compiler version being a jerk. unsigned char buff[]={0xff, 0x00, 0x1f}; this would fail under a type-based narrowing conversion, as 0xff is of type int , and such code is very common. Had such code required pointless modification of the int literals to unsigned char literals, odds are the sweep would have ended with us setting a flag to tell the compiler to shut up about the stupid error.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31730222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2069064/']}
jdg_74078
stackexchange
llm_judgeable_groundtruth_similarity
49585885
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 only allows to get image but i want users to be able to pick documents too. Intent intent = new Intent();intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE); Now provide the response and nothing else.
First, these errors only come out in non-production builds, however they indicate a problem that should be resolved before production release. The $attrs, $listeners and other warnings are displayed if there's more than one instance of Vue loaded. As I understand it, this can happen usually for one these reasons: it is being loaded/packed into the bundle by webpack and also loaded externally (not via webpack) it is being loaded by something you include (e.g. vuetify , vue-test-utils , vue-cli-electron-builder ) one way and by your webpack config another way (e.g. absolute vs relative paths, common.js vs esm.js vue files, runtime-only vue vs compiler+runtime vue) If you click on that line (it was app.js:19302 in your output above) and put a breakpoint where the message is coming out, you can see the list of modules in the stack traceback to see if there's more than one path to Vue listed. For example, see that the top three modules have a different path below (but are all part of Vue): If you see Vue showing up in two or more different ways, it demonstrates that more than one instance of Vue is loaded. Vue only supports a single instance, and can produce these error messages if more than one is loaded. There are several links to issues included above, the Vuetify issue was the one I filed. In that case, Vuetify requires Vue and was loading it differently than I was. Usually the fix is to check your webpack config where Vue is specified (or isn't) and try to make it match the way the other copy is being included (e.g. absolute vs relative path, or packed vs external).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49585885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7190250/']}
jdg_74079
stackexchange
llm_judgeable_groundtruth_similarity
7050802
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following Ruby program: class Accessdef retrieve_publicputs "This is me when public..."endprivatedef retrieve_privateputs "This is me when privtae..."endprotecteddef retrieve_protectedputs "This is me when protected..."endendaccess = Access.newaccess.retrieve_protected When I run it, I get the following: accessor.rb:23: protected method `retrieve_protected' called for #<Access:0x3925758> (NoMethodError) Why is that? Thanks. Now provide the response and nothing else.
Because you can call protected methods directly only from within instance method of this object, or or another object of this class (or subclass) class Access def retrieve_public puts "This is me when public..." retrieve_protected anotherAccess = Access.new anotherAccess.retrieve_protected endend#testing ita = Access.newa.retrieve_public# Output:## This is me when public...# This is me when protected...# This is me when protected...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7050802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588855/']}
jdg_74080
stackexchange
llm_judgeable_groundtruth_similarity
25128723
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 creating a UITableViewHeaderFooterView from a xib file , and almost everything is working properly. The problem is that now when I try to change the background color (or if I had one configured in the xib), it will constantly output this message to the console: Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead. This means I have two problems: If I don't want to see that warning, I must get rid of the background color in the xib file.(This is undesirable because then it means my xib no longer reflects what the view will look like at runtime). When I attempt to change the background color via code, I get the contentView.backgroundColor suggestion, but when I try to follow that suggestion, nothing happens. (This is because contentView is nil .) Note: There is a similar question here, but that was mainly concerned with muting the message, not finding an alternative solution that resolves both problems above. Update: To be clear, I want to continue using a xib file for the header view, and want to be able to call dequeueReusableHeaderFooterViewWithIdentifier: so that the table can be efficient in its management of the views. Now provide the response and nothing else.
Here is the best way I've found to solve this: Reset the background color of your UITableViewHeaderFooterView to Default . Add a single view directly underneath the instance of your UITableViewHeaderFooterView , and call it Content View . (This is exactly what Apple does with a UITableViewCell , and we are just mimicking that structure.) You can now change the background color of the content view to be whatever you want in the xib file. Place any other views inside the Content View . Redefine the contentView property in an extension method, and add IBOutlet to its definition. (See code below.) Associate the property with the content view you created, just as you would with any IBOutlet. You can now change the background color using contentView.backgroundColor in code, just as the error message tells you to. .h file: @interface ABCHeaderView : UITableViewHeaderFooterView@end .m file: @interface ABCHeaderView ()@property (nonatomic, readwrite, retain) IBOutlet UIView *contentView;@end@implementation ABCHeaderView@synthesize contentView;@end This hierarchy is consistent with Apple's documentation : If you have custom content to display, create the subviews for your content and add them to the view in the contentView property.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25128723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35690/']}
jdg_74081
stackexchange
llm_judgeable_groundtruth_similarity
5168549
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between a View and widget in Android? Now provide the response and nothing else.
As is stated in the View class docs: This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other View s (or other ViewGroup s) and define their layout properties. Therefore a View is a base class for UI elements and a Widget is loosely defined as any ready to use View . Let's emphasize these concepts a little more. View A View is a base class for all UI elements. It, therefore, covers many different classes and concepts, including widgets, ViewGroup s and layouts. There is a root View attached to a Window instance which forms the basis of the View hierarchy. In general, the word View is usually used to describe UI elements in general, or to refer to abstract or base UI classes such as ViewGroup s. Widget There are various definitions for this term, but most refer to a "ready to use" UI element, be it a Button , ImageView , EditText , etc. Note that some people consider widgets to be UI elements that are complete (not abstract) and are not containers (such as ViewGroup s (layouts/ ListViews )). It's also worth noting that "widget" is a package name ( android.widget ) where the docs mention the following: The widget package contains (mostly visual) UI elements to use on your Application screen. Therefore, it is reasonable to consider non-visual UI elements to also be widgets, as well as any class defined under the widget package. See here for a full list of classes in the widget package: http://developer.android.com/reference/android/widget/package-summary.html App Widget Not to be confused with a UI element widget, an App Widget is a remote View hierarchy which is most commonly displayed on the user's home screen. As defined by the docs: App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component that is able to hold other App Widgets is called an App Widget host. ViewGroup A ViewGroup is a subclass of View and provides the ability to parent and position child View s, such as in the case of Layouts. Layout/View Containers Much as with Widgets, there is no Layout base class, therefore it could be loosely defined as any class which extends ViewGroup and provides the ability to define the positioning of child View s within it. Usually, only ViewGroup subclasses which are appended with the word "Layout" (as in LinearLayout , RelativeLayout ) are referred to as "layouts", other classes extending ViewGroup are usually just referred to as "view containers". Finally, I'd like to suggest that whenever you mention Views, widgets or any other important term, to make it clear your intended definition so that people can better understand what you're referring to. Further Reading What is the difference between Views and widgets?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5168549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/640995/']}
jdg_74082
stackexchange
llm_judgeable_groundtruth_similarity
95909
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can someone explain why taking an average of an average usually results in a wrong answer? Is there ever a case where the average of the average can be used correctly? As an example, let's say that an assessment is given to three schools and I want to find out the average score for all three schools combined and the average score per school. When I attempt to add the three individual scores and divide by three I get a number that is very close (+/- 1 percent) to the actual overall average. Now provide the response and nothing else.
If there are $n_1$ , $n_2$ , and $n_3$ students in the three schools, and the average test score for each school is $a_1$ , $a_2$ , $a_3$ , respectively, the correct average is a "weighted average:" $$\frac{n_1}{n_1+n_2+n_3}a_1+\frac{n_2}{n_1+n_2+n_3}a_2+\frac{n_3}{n_1+n_2+n_3}a_3$$ The average of the averages is: $$\frac{1}{3}a_1 + \frac{1}{3}a_2 + \frac{1}{3}a_3$$ These two values will be exactly the same if each school has exactly the same number of students, and will tend to be "close" if the schools are relatively close in size and/or the scores for the three schools are close. If a school system created a small school consisting of all the smartest students, they could bump up the second value - the "average of averages" - but they couldn't do that if they take the correct weighted average.
{}
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/95909', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5899/']}
jdg_74083
stackexchange
llm_judgeable_groundtruth_similarity
4125883
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 drew a hand that contains the Sun and the Moon from a tarot deck with $78$ cards.I want to find the probability of this occurring.I think because there are $78 \choose 6$ distinct arrangements of the $6$ other cards in the hand, and $78\choose8$ distinct hands, the probability of choosing both the Sun and the Moon is $$\frac{78 \choose 6}{78 \choose 8}=1/9.$$ But $1/9$ seems pretty high. Am I missing something? Now provide the response and nothing else.
Here is a fairly simple explicit example (I believe it is equivalent to Alex Kruckman's example, but it gives an explicit set-theoretic construction that makes it easier to see why $X$ and $Y$ are not isomorphic). For convenience I will consider the dual question with coproducts instead of products. Let $A$ be a set with $4$ elements and let $X=A^\mathbb{N}$ . Note that for each $n\in\mathbb{N}$ , we have a canonical bijection $A^n\times X\to X$ given by concatenation of sequences. If $T$ is a set, we can think of $T\times X$ as consisting of $|T|$ copies of $X$ , but we can also think of it as consisting of $4|T|$ copies of $X$ by identifying it with $T\times A\times X$ , or as consisting of $16|T|$ copies of $X$ by identifying it with $T\times A^2\times X$ , or as consisting of $4^n|T|$ copies of $X$ for any $n$ by identifying it with $T\times A^n\times X$ . Say that a copy of $X$ in $T\times X$ has depth $n$ if it is one of the $4^n|T|$ copies obtained in this way. Say that a function $f:X\to T\times X$ is good if it is the inclusion of a copy of $X$ at some depth. That is, $f$ is good if there exists $t\in T$ and a finite sequence $a\in A^n$ for some $n$ such that $f(x)=(t,ax)$ for all $x\in X$ , where $ax$ denotes the concatenation of $a$ and $x$ . Note that if we take a good function and restrict it to one of the copies of $X$ inside $X$ (identifying $X$ with $A^m\times X$ for some $m$ ), we get another good function, since this corresponds to just extending the finite sequence $a$ used. Our category has as objects the sets of the form $S\times X$ where $S$ is finite. The morphisms are the locally good functions: that is, functions that are good when restricted to each copy of $X$ in $S\times X$ of sufficiently large depth. More precisely, a function $f:S\times X\to T\times X$ is locally good if for some $n$ , if we identify $S\times X$ with $(S\times A^n)\times X$ via concatenation, then the restriction of $f$ to $\{a\}\times X$ is good for each $a\in S\times A^n$ . Since the restriction of a good function to a smaller copy of $X$ is still good, a locally good function $f$ which satisfies the definition above for some depth $n$ will also satisfy it for any larger $n$ . It follows that the composition of two locally good functions is good, since you can choose $n$ large enough for the first function such that it maps each copy of $X$ into a copy of $X$ on which the second function is also good. Since locally good functions can be defined independently on each of the copies of $X$ making up their domain, $(S\sqcup T)\times X$ is a coproduct of $S\times X$ and $T\times X$ in this category. The intuition here is that our category knows that $X\sqcup X\sqcup X\sqcup X\cong X$ via the canonical bijection $A\times X\to X$ , and only contains the morphisms that can be built out of this isomorphism by decomposing the domain and codomain using this isomorphism repeatedly and then mapping each copy of $X$ in the domain to one of the copies in the codomain via the identity. Now suppose $f:S\times X\to T\times X$ is an isomorphism in this category. Then $f$ is a bijection, and there exists $n$ such that $f$ is good on each copy of $X$ of depth $n$ in $S\times X$ . So, $f$ maps each copy of $X$ of depth $n$ in $S\times X$ to some copy of $X$ in $T\times X$ . We would like to "count" the copies of $X$ that $f$ is pairing up in order to get some relationship between $|S|$ and $|T|$ . We have $4^n|S|$ copies of $X$ of depth $n$ on which $f$ is good, but our counting is complicated by the fact that the images of these copies under $f$ might not all have the same depth in $T\times X$ . However, we can think of copies of low depth as just consisting of many copies of higher depth (since each time we increase the depth we split each copy of $X$ into $4$ copies). Picking $m$ large enough such that all our copies in $T\times X$ have depth at most $m$ , if $f$ maps a copy of $X$ to a copy of $X$ of depth $i$ , we can think of it instead as mapping it onto $4^{m-i}$ copies of depth $m$ . So we have $4^n|S|$ copies in our domain and $4^m|T|$ copies in our codomain, and each copy in the domain is mapped onto a power of $4$ number of copies in the codomain. This means that $f$ decomposes the integer $4^m|T|$ as a sum of $4^n|S|$ integers, all of which are powers of $4$ . Reducing this sum mod $3$ , this means that $|S|$ and $|T|$ must be the same mod $3$ . So, in particular, $X\not\cong X\sqcup X$ in this category. On the other hand, since $A\times X\cong X$ via concatenation, we do have $X\cong X\sqcup X\sqcup X\sqcup X$ . So taking $Y=X\sqcup X$ , each of $X$ and $Y$ is a coproduct of two copies of the other, but $X$ and $Y$ are not isomorphic. (More generally, if you take $A$ to have $N$ elements instead of $4$ , then this category will satisfy $S\times X\cong T\times X$ iff $S$ and $T$ are either both empty or both nonempty and $|S|$ and $|T|$ are the same mod $N-1$ . You are then just asking for two distinct residues mod $N-1$ which are each multiples of each other, which exist as long as $N\geq 4$ .)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4125883', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/923006/']}
jdg_74084
stackexchange
llm_judgeable_groundtruth_similarity
10589889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to get the response & the response headers from CURL using PHP, specifically for Content-Disposition: attachment; so I can return the filename passed within the header. This doesn't seem to get returned within curl_getinfo. I've tried using the HeaderFunction to call a function to read the additional headers, however, I am unable to add the contents to an array. Does anyone have any ideas please? Below is part of my code which is a Curl wrapper class: ... curl_setopt($this->_ch, CURLOPT_URL, $this->_url); curl_setopt($this->_ch, CURLOPT_HEADER, false); curl_setopt($this->_ch, CURLOPT_POST, 1); curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData); curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_userAgent); curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, 'readHeader'); $this->_response = curl_exec($this->_ch); $info = curl_getinfo($this->_ch); ... function readHeader($ch, $header) { array_push($this->_headers, $header); } Now provide the response and nothing else.
Here, this should do it: curl_setopt($this->_ch, CURLOPT_URL, $this->_url);curl_setopt($this->_ch, CURLOPT_HEADER, 1);curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);$response = curl_exec($this->_ch);$info = curl_getinfo($this->_ch);$headers = get_headers_from_curl_response($response);function get_headers_from_curl_response($response){ $headers = array(); $header_text = substr($response, 0, strpos($response, "\r\n\r\n")); foreach (explode("\r\n", $header_text) as $i => $line) if ($i === 0) $headers['http_code'] = $line; else { list ($key, $value) = explode(': ', $line); $headers[$key] = $value; } return $headers;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10589889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525290/']}
jdg_74085
stackexchange
llm_judgeable_groundtruth_similarity
242873
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to show that any open interval is homeomorphic to the real line. I know that $f(x)=a+e^x$ will work for the mapping $f:R \to (a,\infty)$ and $f(x)=b-e^{-x}$ will work for the mapping $f:R \to (-\infty,b).$ Without using two functions, how can I prove the result in general? Now provide the response and nothing else.
You've already been given two possible homeomorphisms, but how about another one? Say that you have two maps $\varphi : A \to B$ and $\psi : B \to C$, both of which are homeomorphisms. It's clear that $\psi \circ \varphi : A \to C$ is again a homeomorphism. Using this fact, choose your favorite finite open interval $(a,b)$, and prove it is homeomorphic to $\mathbb{R}$. Next up, take an arbitrary open interval $(c,d)$, and construct a homeomorphism between this an $(a,b)$, and voila, you are done. In particular, look at the interval $(0,1)$, and its image under the function $\tan(\pi(x-\frac{1}{2}))$. This is pretty clearly a homeomorphism. Now just map an open interval to $(0,1)$ (homeomorphically), and call it a day.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/242873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32145/']}
jdg_74086
stackexchange
llm_judgeable_groundtruth_similarity
16632546
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 a fresh installation of Joomla 3.1 running on my home computer. My environment is Ubuntu 12.10 with apache server, php 5.4.6 installed. Since installing the system, no I am just trying to install more languages through the language manager: As you can see, the 2 additional languages that I wanted show up in the list, but after selecting each language, and clicking "Install", I was led to a page with this message: DateTime::__construct(): Failed to parse time string (jerror) at position 0 (j): The timezone could not be found in the database With a button to just go back to the control panel. I was suprised to see these languages show up in the list. I also saw this message when I tried (and failed) to install my first component - it was a component to embed google maps in articles. Anyway, I haven't been able to find a solution for this problem online, I was wondering if anyone out there knows what the problem is. Any help is greatly appreciated! Thanks! EDIT The problem in my case turned out to be that some on my directories where un-writable. I went to the "directory permissions" tab under "System Information", and tried to make sure that all the directories were writable. When i first opened it, all the directories in the "administrator" directory were not writable, and we changed them to be writable through the shell in linux, then i was able to install the new languages without the error message above. Now provide the response and nothing else.
This is the most stupid bug in Joomla 3. I wasted 2 days trying to solve this out and I found that the problem was that the log and tmp paths were not set correctly on the configuration.php Don't worry there's nothing wrong with your Date/Time/Timezone/Localization settings. It's just a stupid silly message that doesn't relate to the actual problem. To save your time I recommend you get the full path using this script: <?php$dir = dirname(__FILE__);echo "<p>Full path to this dir: " . $dir . "</p>";?> Create a PHP file and upload it to Joomla root. It will get you the path correctly My path looked exactly the same except that there was an uppercase letter screwing everything up. Note that this error could happen if the folders doesn't have the correct permission (not writable)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16632546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959306/']}
jdg_74087
stackexchange
llm_judgeable_groundtruth_similarity
64386172
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 find a way to add a blank space while typing in a TextFormField . I found a way how to do this a while back but I cannot find it now, no matter what I search for on Google or here on StackOverflow .. Basically I want to turn the text shown in the textfield from 000011112222333 to 0000 1111 2222 3333 I'm guessing I need to use some RegExp check in the onChanged function of a TextFormField and use it to change the TextEditingController 's .text Now provide the response and nothing else.
I also faced this problem before and luckily found a way to do this somewhere.First create a class that extends TextInputFormatter customInputFormatter.dart class CustomInputFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { var text = newValue.text; if (newValue.selection.baseOffset == 0) { return newValue; } var buffer = new StringBuffer(); for (int i = 0; i < text.length; i++) { buffer.write(text[i]); var nonZeroIndex = i + 1; if (nonZeroIndex % 4 == 0 && nonZeroIndex != text.length) { buffer.write(' '); // Replace this with anything you want to put after each 4 numbers } } var string = buffer.toString(); return newValue.copyWith( text: string, selection: new TextSelection.collapsed(offset: string.length) ); }} And then add it to the list of inputFormatters[] of TextFormField inputFormatters: [ FilteringTextInputFormatter.digitsOnly, new CustomInputFormatter()],
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64386172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12140067/']}
jdg_74088
stackexchange
llm_judgeable_groundtruth_similarity
115197
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The question is, how can I run a .nb file in the kernel mode of Mathematica? I am not an expert in Mathematica, but one of our users who use this program says that in the GUI mode, he selects all the cells (CTRL+A) and then evaluates the notebook (SHIFT+ENTER). However, he wants to run the program in background. When I test with math < file.nb , the program quickly exits; however, in the GUI mode, the run time is very large actually. I read other documentation articles about that, but since I am not expert in Mathmatica, I have no idea! As an example, solve.nb file is an input to the command math -run < solve.nb . The output is also available here . I have no idea what the output means :| Update I simply tried to port the solution to Linux. So I wrote a solve.m file containing NotebookPauseForEvaluation[nb_] := Module[{},While[NotebookEvaluatingQ[nb],Pause[1]]];NotebookEvaluatingQ[nb_]:=Module[{},SelectionMove[nb,All,Notebook];Or@@Map["Evaluating"/.#&,Developer`CellInformation[nb]]];UsingFrontEnd[nb = NotebookOpen["/home/mahmood/solve.nb"];SelectionMove[nb, All, Notebook];SelectionEvaluate[nb]NotebookPauseForEvaluation[nb];NotebookSave[nb];];Quit[]; Here is the output of what I see mahmood@cluster:~$ MathKernel -noprompt -initfile solve.m mahmood@cluster:~$ LinkConnect::linkc: -- Message text not found -- (LinkObject[7wkjs_shm, 3, 1])^Cmahmood@cluster:~$ Note that I pressec ^c after several minutes. Also, the is no output file containing th results. Update 2 I tried the solution as given by selecting the cells, initialize them and then save the file as .m . I did that on a GUI machine. The saved script file contains (* ::Package:: *)a = 3; Solve[x^2 + a*x + 1 == 0, x] As you can see, the last line in the notebook file is not there in the script file. I ran the command and saw mahmood@cluster:~$ /apps/Mathematica/10.3/SystemFiles/Kernel/Binaries/Linux-x86-64/MathematicaScript -script solve3.m mahmood@cluster:~$ Is that all? There is no output file containing the result Now provide the response and nothing else.
It is not a good idea to try to run a notebook in command line mode. Whether or not it is possible, it is just not a good idea because notebooks can only be handled by the Front End, which is not a command line tool. If you go this route anyway, expect difficulties. The usual way is to extract the code you want to run into a plain text .m file and run that. Do this by marking all cells to be exported as initialization cells. Select them, then choose Cell -> Cell Properties -> Initialization Cell. Or often simpler: put them under a section header and mark the header as "Initialization Group". Then use File -> Save As... -> Wolfram Mathematica Package. When running it as a script in command line mode, use MathematicaScript -script filename.m (for some reason math -script may not work the same, so don't use that).
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/115197', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/39006/']}
jdg_74089
stackexchange
llm_judgeable_groundtruth_similarity
17333901
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 PHP form that is located on file contact.html . The form is processed from file processForm.php . When a user fills out the form and clicks on submit, processForm.php sends the email and direct the user to - processForm.php with a message on that page "Success! Your message has been sent." I do not know much about PHP, but I know that the action that is calling for this is: // Die with a success messagedie("<span class='success'>Success! Your message has been sent.</span>"); How can I keep the message inside the form div without redirecting to the processForm.php page? I can post the entire processForm.php if needed, but it is long. Now provide the response and nothing else.
In order to stay on the same page on submit you can leave action empty ( action="" ) into the form tag, or leave it out altogether. For the message, create a variable ( $message = "Success! You entered: ".$input;" ) and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?> . Like this: <?php$message = "";if(isset($_POST['SubmitButton'])){ //check if form was submitted $input = $_POST['inputText']; //get input text $message = "Success! You entered: ".$input;} ?><html><body> <form action="" method="post"><?php echo $message; ?> <input type="text" name="inputText"/> <input type="submit" name="SubmitButton"/></form> </body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17333901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2518599/']}
jdg_74090
stackexchange
llm_judgeable_groundtruth_similarity
8898807
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's a=109 or 1101101 in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1] Now provide the response and nothing else.
There's a trick for just getting the 1's out of the binary representation without having to iterate over all the intervening 0's: def bits(n): while n: b = n & (~n+1) yield b n ^= b>>> for b in bits(109): print(b)1483264
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8898807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/889530/']}
jdg_74091
stackexchange
llm_judgeable_groundtruth_similarity
7482
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: Looking for a solution on how to restore my window layout after an Ediff session, I found a blog post , where the author suggests: (winner-mode)(add-hook 'ediff-after-quit-hook-internal 'winner-undo) This seems to almost work well for me. I say almost because I invoke M-x ediff-buffers from Helm , and quiting the Ediff session brings me back to the original layout with the dead Helm menu from where I chose M-x ediff-buffers . Let me explain: At any point I have several windows open with a window layout L1. I want to ediff some buffers, so I press M-x : This re-uses one of the windows in L1 to open up a Helm autocompletion menu. So far so good. I choose ediff-buffers , and then the two buffers to compare, one after the other This takes me to an ediff session where I can check differences etc. Once I am done. I quit my ediff-session. I would like to go back to my layout L1 in step #1. However, Emacs (winner-mode) takes me back to step #2, where one of the Emacs windows in L1 was used to show the options in Helm. This is pointless since I am done with my ediff session. How can I restore windows to my original layout L1? Setup: This is all in Emacs 25.0.50.1 on OS X. More specifically, GNU Emacs 25.0.50.1 (x86_64-apple-darwin14.0.0, NS appkit-1343.16 Version 10.10.1 (Build 14B25)) Now provide the response and nothing else.
What you want can be achieved cleanly using hook provided by ediff (which if read the documentation seem to be provided for this exact purpose), advices are not needed. The relevant hooks are 1) ediff-quit-hook , from the documentation Hooks to run in the Ediff control buffer after finishing Ediff. 2) ediff-before-setup-hook Hooks to run before Ediff begins to set up windows and buffers. This hook can be used to save the previous window config, which can be restored on ediff-quit or ediff-suspend. The approach is similar to @abo-abo's approach. We save the window configuration before ediff is setup using the ediff-before-setup-hook and restore the stored window configuration in ediff-quit-hook . (defvar my-ediff-last-windows nil)(defun my-store-pre-ediff-winconfig () (setq my-ediff-last-windows (current-window-configuration)))(defun my-restore-pre-ediff-winconfig () (set-window-configuration my-ediff-last-windows))(add-hook 'ediff-before-setup-hook #'my-store-pre-ediff-winconfig)(add-hook 'ediff-quit-hook #'my-restore-pre-ediff-winconfig)
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/7482', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/6/']}
jdg_74092
stackexchange
llm_judgeable_groundtruth_similarity
37376442
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 Angular 1 all DOM manipulation should be done in directives to ensure proper testability, but what about Angular 2? How has this changed? I've been searching for good articles or any information at all about where to put DOM manipulation and how to think when doing it, but I come up empty every time. Take this component for example (this is really a directive but let's pretend that it's not): export class MyComponent { constructor(private _elementRef: ElementRef) { this.setHeight(); window.addEventListener('resize', (e) => { this.setHeight(); }); } setHeight() { this._elementRef.nativeElement.style.height = this.getHeight() + 'px'; } getHeight() { return window.innerHeight; }} Does event binding belong in a constructor for example, or should this be put in the ngAfterViewInit function or somewhere else? Should you try to break out the DOM manipulation of a component into a directive? It's all just a blur at the moment so I'm not sure that I'm going about it correctly and I'm sure I'm not the only one. What are the rules for DOM manipulation in Angular2? Now provide the response and nothing else.
Direct DOM manipulation should be avoided entirely in Angular2. Use instead bindings like: export class MyComponent { constructor() { this.setHeight(); } @HostBinding('style.height.px') height:number; @HostListener('window:resize', ['$event']) setHeight() { this.height = window.innerHeight; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37376442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4054974/']}
jdg_74093
stackexchange
llm_judgeable_groundtruth_similarity
484661
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 there a formula to calculate the number of multiplications that take place when multiplying 2 matrices? For example $$\begin{pmatrix}1&2\\3&4\end{pmatrix}\times\begin{pmatrix}5&6\\7&8\end{pmatrix} =\text{8 multiplications and 4 additions}$$ Now provide the response and nothing else.
Doing a $k\times l$ times $l\times m$ matrix multiplication in the straightforward way, every entry of the result is a scalar product of of two $l$-vectors, which requires $l$ multiplications and $l-1$ additions. Multiply that by the number $km$ of entries of the result (or don't multiply if you have sufficiently many processors to do everything in parallel).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/484661', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_74094
stackexchange
llm_judgeable_groundtruth_similarity
24754005
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 directive with a template like <div> <div ng-repeat="item in items" ng-click="updateModel(item)"><div> My directive is declared as: return { templateUrl: '...', restrict: 'E', require: '^ngModel', scope: { items: '=', ngModel: '=', ngChange: '&' }, link: function postLink(scope, element, attrs) { scope.updateModel = function(item) { scope.ngModel = item; scope.ngChange(); } }} I would like to have ng-change called when an item is clicked and the value of foo has been changed already. That is, if my directive is implemented as: <my-directive items=items ng-model="foo" ng-change="bar(foo)"></my-directive> I would expect to call bar when the value of foo has been updated. With code given above, ngChange is successfully called, but it is called with the old value of foo instead of the new updated value. One way to solve the problem is to call ngChange inside a timeout to execute it at some point in the future, when the value of foo has been already changed. But this solution make me loose control over the order in which things are supposed to be executed and I assume that there should be a more elegant solution. I could also use a watcher over foo in the parent scope, but this solution doesn't really give an ngChange method to be implmented and I have been told that watchers are great memory consumers. Is there a way to make ngChange be executed synchronously without a timeout or a watcher? Example: http://plnkr.co/edit/8H6QDO8OYiOyOx8efhyJ?p=preview Now provide the response and nothing else.
If you require ngModel you can just call $setViewValue on the ngModelController , which implicitly evaluates ng-change . The fourth parameter to the linking function should be the ngModelCtrl. The following code will make ng-change work for your directive. link : function(scope, element, attrs, ngModelCtrl){ scope.updateModel = function(item) { ngModelCtrl.$setViewValue(item); }} In order for your solution to work, please remove ngChange and ngModel from isolate scope of myDirective. Here's a plunk: http://plnkr.co/edit/UefUzOo88MwOMkpgeX07?p=preview
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24754005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1399310/']}
jdg_74095
stackexchange
llm_judgeable_groundtruth_similarity
96694
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: stdin, stdout, stderr are some integers that index into a data structure which 'knows' which I/O channels are to be used for the process. I understand this data structure is unique to every process. Are I/O channels nothing but some data array structures with dynamic memory allocation ? Now provide the response and nothing else.
In Unix-like operating systems, the standard input, output and error streams are identified by the file descriptors 0 , 1 , 2 . On Linux, these are visible under the proc filesystem in /proc/[pid]/fs/{0,1,2} . These files are actually symbolic links to a pseudoterminal device under the /dev/pts directory. A pseudoterminal (PTY) is a pair of virtual devices, a pseudoterminal master (PTM) and a pseudoterminal slave (PTS) (collectively referred to a s a pseudoterminal pair ), that provide an IPC channel, somewhat like a bidirectional pipe between a program which expects to be connected to a terminal device , and a driver program that uses the pseudoterminal to send input to, and receive input from the former program. A key point is that the pseudoterminal slave appears just like a regular terminal, e.g. it can be toggled between noncanonical and canonical mode (the default), in which it interprets certain input characters, such as generating a SIGINT signal when a interrupt character (normally generated by pressing Ctrl + C on the keyboard) is written to the pseudoterminal master or causing the next read() to return 0 when a end-of-file character (normally generated by Ctrl + D ) is encountered. Other operations supported by terminals is turning echoing on on or off, setting the foreground process group etc. Pseudoterminals have a number of uses: They allow programs like ssh to operate terminal-oriented programs on a another host connected via a network. A terminal-orientated program may be any program, which would normally be run in an interactive terminal session. The standard input, output and error of such a program cannot be connected directly socket, as sockets do not support the aforementioned terminal-related functionality. They allow programs like expect to drive a interactive terminal-orientated program from a script. They are used by terminal emulators such as xterm to provide terminal-related functionality. They are are used by programs such as screen to multiplex a single physical terminal between multiple processes. They are used by programs like script to to record all input and output occuring during a shell session. Unix98-style PTYs , used in Linux, are setup as follows: The driver program opens the pseudo-terminal master multiplexer at dev/ptmx , upon which it receives a a file descriptor for a PTM, and a PTS device is created in the /dev/pts directory. Each file descriptor obtained by opening /dev/ptmx is an independent PTM with its own associated PTS. The driver programs calls fork() to create a child process, which in turn performs the following steps: The child calls setsid() to start a new session, of which the child is session leader. This also causes the child to lose its controlling terminal . The child proceeds to open the PTS device that corresponds to the PTM created by the driver program. Since the child is a session leader, but has no controlling terminal, the PTS becomes the childs controlling terminal. The child uses dup() to duplicate the file descriptor for the slave device on it standard input, output, and error. Lastly, the child calls exec() to start the terminal-oriented program that is to be connected to the pseudoterminal device. At this point, anything the driver program writes to the PTM, appears as input to the terminal-orientated program on the PTS, and vice versa. When operating in canonical mode, the input to the PTS is buffered line by line. In other words, just as with regular terminals, the program reading from a PTS receives a line of input only when a newline character is written to the PTM. When the buffering capacity is exhausted, further write() calls block until some of the input has been consumed. In the Linux kernel, the file related system calls open() , read() , write() stat() etc. are implemented in the Virtual Filesystem (VFS) layer, which provides a uniform file system interface for userspace programs. The VFS allows different file system implementations to coexists within the kernel. When userspace programs call the aforementioned system calls, the VFS redirects the call to the appropriate filesystem implementation. The PTS devices under /dev/pts are managed by the devpts file system implemention defined in /fs/devpts/inode.c , while the TTY driver providing the the Unix98-style ptmx device is defined in in drivers/tty/pty.c . Buffering between TTY devices and TTY line disciplines , such as pseudoterminals, is provided a buffer structure maintained for each tty device, defined in include/linux/tty.h Prior to kernel version 3.7, the buffer was a flip buffer : #define TTY_FLIPBUF_SIZE 512struct tty_flip_buffer { struct tq_struct tqueue; struct semaphore pty_sem; char *char_buf_ptr; unsigned char *flag_buf_ptr; int count; int buf_num; unsigned char char_buf[2*TTY_FLIPBUF_SIZE]; char flag_buf[2*TTY_FLIPBUF_SIZE]; unsigned char slop[4];}; The structure contained storage divided into two equal size buffers.The buffers were numbered 0 (first half of char_buf/flag_buf )and 1 (second half). The driver stored data to the buffer identifiedby buf_num . The other buffer could be flushed to the line discipline. The buffer was 'flipped' by toggling buf_num between 0 and 1 .When buf_num changed, char_buf_ptr and flag_buf_ptr was set to the beginning of the buffer identified by buf_num ,and count was set to 0 . Since kernel version 3.7 the TTY flip buffers have been replaced with objects allocated via kmalloc() organized in rings . In a normal situation for an IRQ driven serial port at typical speeds their behaviour is pretty much the same as with the old flip buffer; two buffers end up allocated and the kernel cycles between them as before. However, when there are delays or the speed increases, the new buffer implementation performs better as the buffer pool can grow a bit.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/96694', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45568/']}
jdg_74096
stackexchange
llm_judgeable_groundtruth_similarity
44350401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is something wrong when I use groupby method: data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))keys = lambda x: [x.year,x.month]data.groupby(keys).mean() but it has an error: TypeError: unhashable type: 'list'.I want group by year and month, then calculate the means,why it has wrong? Now provide the response and nothing else.
list object cannot be used as key because it's not hashable. You can use tuple object instead: >>> {[1, 2]: 3}Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'>>> {(1, 2): 3}{(1, 2): 3} data = pd.Series(np.random.randn(100), index=pd.date_range('01/01/2001', periods=100))keys = lambda x: (x.year,x.month) # <----data.groupby(keys).mean()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44350401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7161679/']}
jdg_74097
stackexchange
llm_judgeable_groundtruth_similarity
686487
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: How can I show that let $n$ and $k$ be integers. $n(n+1)2^{n-2}=\sum_{k=1}^{n}k^2\dbinom{n}{k}$ It seems a bit confusing to me on the left hand side. You have a set of $n$ people on a team and you keep picking $k$ people who will play a match and you pick before that a captain $k^2$. Now provide the response and nothing else.
Both sides of the identity answer the question: "Given $n$ candidate members, how many ways are there to form a committee with a president and treasurer, if the same person is allowed to fill both roles?" For the right-hand side, you pick $k$ members, and then choose one of them to be president and one to be treasurer. This immediately gives you the sum on the right-hand side. For the left-hand side, you pick a president and a treasurer from the entire candidate pool, and then select the rest of the committee. There are two ways to do this: Pick one person to be president-and-treasurer (in $n$ possible ways). Then, for each of the other $n-1$ candidate members, decide whether they're on the committee or not (in $2^{n-1}$ possible ways). There are a total of $n2^{n-1}$ ways to do this. Pick a president (in $n$ possible ways), a treasurer distinct from the president (in $n-1$ possible ways) and decide whether each of the other $n-2$ candidates is on the committee (in $2^{n-2}$ possible ways). There are a total of $n(n-1)2^{n-2}$ ways to do this. So there are a total of $n2^{n-1}+n(n-1)2^{n-2}=n(n+1)2^{n-2}$ ways to make your choices, which completes the proof.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/686487', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37244/']}
jdg_74098
stackexchange
llm_judgeable_groundtruth_similarity
6117293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a synchronous wait function that won't tie up the UI-thread in .NET WPF? Something like: Sub OnClick(sender As Object, e As MouseEventArgs) Handles button1.Click Wait(2000) 'Ui still processes other events here MessageBox.Show("Is has been 2 seconds since you clicked the button!")End Sub Now provide the response and nothing else.
You can use a DispatcherTimer for that sort of thing. Edit: This might do as well... private void Wait(double seconds){ var frame = new DispatcherFrame(); new Thread((ThreadStart)(() => { Thread.Sleep(TimeSpan.FromSeconds(seconds)); frame.Continue = false; })).Start(); Dispatcher.PushFrame(frame);} ( Dispatcher.PushFrame documentation. ) Starting with .NET 4.5 you can use async event handlers and Task.Delay to get the same behaviour. To simply let the UI update during such a handler return Dispatcher.Yield .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6117293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/635906/']}
jdg_74099
stackexchange
llm_judgeable_groundtruth_similarity
550621
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: My question differs from these questions: When is $\Delta U=nC_V \Delta T$ true? Because here he asks to distinguish between $C_P$ and $C_V$ and not why it's always $C_V$ Work done in adiabatic process Here the answer is "just because it is always the case" Is there no mathematical proof for this? What is the real physical intuition for this being the case? Now provide the response and nothing else.
There are two criteria. First, $c_V=nC_V$ must be constant; second, we must have that $P = f(V) T$ for some function $f$ . Both criteria hold in the specific case of an ideal gas, but neither holds for a general thermodynamical system. I'll give the mathematical explanation first, and then the physical explanation second. Starting from the perspective that $U=U(S,V)$ and $T= \left(\frac{\partial U}{\partial S}\right)_V (S,V)$ , note that a small change in $S$ and $V$ will cause small changes $$dU=\left(\frac{\partial U}{\partial S}\right)_V dS + \left(\frac{\partial U}{\partial V}\right)_S dV \equiv TdS - PdV$$ and $$dT = \left(\frac{\partial T}{\partial S}\right)_V dS + \left(\frac{\partial T}{\partial V}\right)_SdV$$ Solving the second equation for $dS$ and substituting it in the first equation yields $$dU = T \frac{1}{\left(\frac{\partial T}{\partial S}\right)_V}dT- \left[T\frac{\left(\frac{\partial T}{\partial V}\right)_S}{\left(\frac{\partial T}{\partial S}\right)_V} + P\right]dV$$ $$= c_V dT+ \left[T\frac{\left(\frac{\partial P}{\partial S}\right)_V}{\left(\frac{\partial T}{\partial S}\right)_V} - P\right]dV$$ Where we've used that $\left(\frac{\partial T}{\partial V}\right)_S = \frac{\partial^2 U}{\partial V\partial S} = -\left(\frac{\partial P}{\partial S}\right)_V$ , and that the definition of the specific heat at constant volume is $c_V \equiv T \left(\frac{\partial S}{\partial T}\right)_V$ . Finally, note that $$\frac{\left(\frac{\partial P}{\partial S}\right)_V}{\left(\frac{\partial T}{\partial S}\right)_V} \equiv \left(\frac{\partial P}{\partial T}\right)_V$$ so finally $$ dU = c_V dT + \left[T\left(\frac{\partial P}{\partial T}\right)_V - P \right]dV$$ Assuming that we are not dealing with variable numbers of particles, what has been written here is completely general, so your question boils down to asking when the second term is zero. The answer is that $$\left(\frac{\partial P}{\partial T}\right)_V = \frac{P}{T} \implies P = f(V) T$$ for some function $V$ . If this is the case, then the second term on the right of the preceding equation vanishes, and we have $$dU = c_V dT \implies \Delta U = \int c_V dT = \int nC_V dT$$ since $C_V$ is the specific heat per mole . If $C_V$ is constant, then this just becomes $$\Delta U = nC_V \Delta T$$ From a physical standpoint, the answer is that the energy of an ideal gas is purely kinetic - the gas particles do not have any long-range interactions with each other at all. As a result, since the temperature can be shown to be a measure of the average kinetic energy of the ideal gas particles, the internal energy of the system is unaffected by changes in volume, as long as the temperature is fixed. This would not be the case if the particles attracted each other, for example. Putting such a system in a larger box with the same amount of kinetic energy would result in a larger average spacing, and therefore a less negative potential energy (remember that attractive potential energies are negative). Therefore, larger box $\implies$ more energy, even if the kinetic energy didn't change. As I showed, $$ dU = c_V dT + \left[T\left(\frac{\partial P}{\partial T}\right)_V - P \right]dV$$ The first term on the right describes the change in energy due to change in temperature while holding the volume fixed; the second describes the change in energy due to a change in volume while holding temperature fixed. Because of the lack of interaction between gas particles, the second term goes away, leaving only the first, and so $$dU = c_V dT = nC_V dT$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/550621', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/236734/']}
jdg_74100
stackexchange
llm_judgeable_groundtruth_similarity
52969782
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 our project we inherited Docker environment with some service stack in it. I've noticed Docker restarting stack once it faces memory limit. Unfortunately, I haven't found any info according to my questions on the Docker's website, so I'm asking here: Is this behaviour configurable? For instance, I don't want Docker torestart my stack under any circumstances. If it is configurable,then how? Is there any docker journal to keep any stack restarts as it's entries? Now provide the response and nothing else.
Is this behaviour configurable? For instance, I don't want Docker to restart my stack under any circumstances. If it is configurable, then how? With a version 3 stack, the restart policy moved to the deploy section: version: '3'services: crash: image: busybox command: sleep 10 deploy: restart_policy: condition: none # max_attempts: 2 Documentation on this is available at: https://docs.docker.com/compose/compose-file/#restart_policy Is there any docker journal to keep any stack restarts as it's entries? Depending on the task history limit (configurable with docker swarm update , you can view the previously run tasks for a service: $ docker service ps restart_crashID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS30okge1sjfno restart_crash.1 busybox:latest bmitch-asusr556l Shutdown Complete 4 minutes agopapxoq1vve1a \_ restart_crash.1 busybox:latest bmitch-asusr556l Shutdown Complete 4 minutes ago1hji2oko51sk \_ restart_crash.1 busybox:latest bmitch-asusr556l Shutdown Complete 5 minutes ago And you can inspect the state for any one task: $ docker inspect 30okge1sjfno --format '{{json .Status}}' | jq .{ "Timestamp": "2018-11-06T19:55:02.208633174Z", "State": "complete", "Message": "finished", "ContainerStatus": { "ContainerID": "8e9310bde9acc757f94a56a32c37a08efeed8a040ce98d84c851d4eef0afc545", "PID": 0, "ExitCode": 0 }, "PortStatus": {}} There's also an event history in the docker engine that you can query: $ docker events --filter label=com.docker.swarm.service.name=restart_crash --filter event=die --since 15m --until 0s2018-11-06T14:54:09.417465313-05:00 container die f17d945b249a04e716155bcc6d7db490e58e5be00973b0470b05629ce2cca461 (com.docker.stack.namespace=restart, com.docker.swarm.node.id=q44zx0s2lvu1fdduk800e5ini, com.docker.swarm.service.id=uqirm6a8dix8c2n50thmpzj06, com.docker.swarm.service.name=restart_crash, com.docker.swarm.task=, com.docker.swarm.task.id=1hji2oko51skhv8fv1nw71gb8, com.docker.swarm.task.name=restart_crash.1.1hji2oko51skhv8fv1nw71gb8, exitCode=0, image=busybox:latest@sha256:2a03a6059f21e150ae84b0973863609494aad70f0a80eaeb64bddd8d92465812, name=restart_crash.1.1hji2oko51skhv8fv1nw71gb8)2018-11-06T14:54:32.391165964-05:00 container die d6f98b8aaa171ca8a2ddaf31cce7a1e6f1436ba14696ea3842177b2e5e525f13 (com.docker.stack.namespace=restart, com.docker.swarm.node.id=q44zx0s2lvu1fdduk800e5ini, com.docker.swarm.service.id=uqirm6a8dix8c2n50thmpzj06, com.docker.swarm.service.name=restart_crash, com.docker.swarm.task=, com.docker.swarm.task.id=papxoq1vve1adriw6e9xqdaad, com.docker.swarm.task.name=restart_crash.1.papxoq1vve1adriw6e9xqdaad, exitCode=0, image=busybox:latest@sha256:2a03a6059f21e150ae84b0973863609494aad70f0a80eaeb64bddd8d92465812, name=restart_crash.1.papxoq1vve1adriw6e9xqdaad)2018-11-06T14:55:00.126450155-05:00 container die 8e9310bde9acc757f94a56a32c37a08efeed8a040ce98d84c851d4eef0afc545 (com.docker.stack.namespace=restart, com.docker.swarm.node.id=q44zx0s2lvu1fdduk800e5ini, com.docker.swarm.service.id=uqirm6a8dix8c2n50thmpzj06, com.docker.swarm.service.name=restart_crash, com.docker.swarm.task=, com.docker.swarm.task.id=30okge1sjfnoicd0lo2g1y0o7, com.docker.swarm.task.name=restart_crash.1.30okge1sjfnoicd0lo2g1y0o7, exitCode=0, image=busybox:latest@sha256:2a03a6059f21e150ae84b0973863609494aad70f0a80eaeb64bddd8d92465812, name=restart_crash.1.30okge1sjfnoicd0lo2g1y0o7) See more details on the events command at: https://docs.docker.com/engine/reference/commandline/events/ The best practice at larger scale organizations is to send the container logs to a central location (e.g. Elastic) and monitor the metrics externally (e.g. Prometheus/Grafana).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52969782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2697661/']}
jdg_74101
stackexchange
llm_judgeable_groundtruth_similarity
14580752
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 some documents which have the same content but when I try to query for these documents, I am getting different scores although the queried field contains the same text. I have explained the scores but I am not able to analyse and find the reason for different scores. My query is curl 'localhost:9200/acqindex/_search?pretty=1' -d '{ "explain" : true, "query" : { "query_string" : { "query" : "text:shimla" } } }' Search response : { "took" : 8, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 31208, "max_score" : 268.85962, "hits" : [ { "_shard" : 0, "_node" : "KOebAnGhSJKUHLPNxndcpQ", "_index" : "acqindex", "_type" : "autocomplete_questions", "_id" : "50efec6c38cc6fdabd8653a3", "_score" : 268.85962, "_source" : {"_class":"com.ixigo.next.cms.model.AutoCompleteObject","_id":"50efec6c38cc6fdabd8653a3","ad":"rajasthan,IN","category":["Destination"],"ctype":"destination","eid":"503b2a65e4b032e338f0d24b","po":8.772307692307692,"text":"shimla","url":"/travel-guide/shimla"}, "_explanation" : { "value" : 268.85962, "description" : "sum of:", "details" : [ { "value" : 38.438133, "description" : "weight(text:shi in 5860), product of:", "details" : [ { "value" : 0.37811017, "description" : "queryWeight(text:shi), product of:", "details" : [ { "value" : 5.0829277, "description" : "idf(docFreq=7503, maxDocs=445129)" }, { "value" : 0.074388266, "description" : "queryNorm" } ] }, { "value" : 101.658554, "description" : "fieldWeight(text:shi in 5860), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shi)=1)" }, { "value" : 5.0829277, "description" : "idf(docFreq=7503, maxDocs=445129)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=5860)" } ] } ] }, { "value" : 66.8446, "description" : "weight(text:shim in 5860), product of:", "details" : [ { "value" : 0.49862078, "description" : "queryWeight(text:shim), product of:", "details" : [ { "value" : 6.7029495, "description" : "idf(docFreq=1484, maxDocs=445129)" }, { "value" : 0.074388266, "description" : "queryNorm" } ] }, { "value" : 134.05899, "description" : "fieldWeight(text:shim in 5860), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shim)=1)" }, { "value" : 6.7029495, "description" : "idf(docFreq=1484, maxDocs=445129)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=5860)" } ] } ] }, { "value" : 81.75818, "description" : "weight(text:shiml in 5860), product of:", "details" : [ { "value" : 0.5514458, "description" : "queryWeight(text:shiml), product of:", "details" : [ { "value" : 7.413075, "description" : "idf(docFreq=729, maxDocs=445129)" }, { "value" : 0.074388266, "description" : "queryNorm" } ] }, { "value" : 148.2615, "description" : "fieldWeight(text:shiml in 5860), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shiml)=1)" }, { "value" : 7.413075, "description" : "idf(docFreq=729, maxDocs=445129)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=5860)" } ] } ] }, { "value" : 81.8187, "description" : "weight(text:shimla in 5860), product of:", "details" : [ { "value" : 0.55164987, "description" : "queryWeight(text:shimla), product of:", "details" : [ { "value" : 7.415818, "description" : "idf(docFreq=727, maxDocs=445129)" }, { "value" : 0.074388266, "description" : "queryNorm" } ] }, { "value" : 148.31636, "description" : "fieldWeight(text:shimla in 5860), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shimla)=1)" }, { "value" : 7.415818, "description" : "idf(docFreq=727, maxDocs=445129)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=5860)" } ] } ] } ] } }, { "_shard" : 1, "_node" : "KOebAnGhSJKUHLPNxndcpQ", "_index" : "acqindex", "_type" : "autocomplete_questions", "_id" : "50efed1c38cc6fdabd8b8d2f", "_score" : 268.29953, "_source" : {"_id":"50efed1c38cc6fdabd8b8d2f","ad":"himachal pradesh,IN","category":["Hill","See and Do","Destination","Mountain","Nature and Wildlife"],"ctype":"destination","eid":"503b2a64e4b032e338f0d0af","po":8.781970310391364,"text":"shimla","url":"/travel-guide/shimla"}, "_explanation" : { "value" : 268.29953, "description" : "sum of:", "details" : [ { "value" : 38.52957, "description" : "weight(text:shi in 14769), product of:", "details" : [ { "value" : 0.37895453, "description" : "queryWeight(text:shi), product of:", "details" : [ { "value" : 5.083667, "description" : "idf(docFreq=7263, maxDocs=431211)" }, { "value" : 0.07454354, "description" : "queryNorm" } ] }, { "value" : 101.67334, "description" : "fieldWeight(text:shi in 14769), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shi)=1)" }, { "value" : 5.083667, "description" : "idf(docFreq=7263, maxDocs=431211)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=14769)" } ] } ] }, { "value" : 66.67524, "description" : "weight(text:shim in 14769), product of:", "details" : [ { "value" : 0.49850821, "description" : "queryWeight(text:shim), product of:", "details" : [ { "value" : 6.6874766, "description" : "idf(docFreq=1460, maxDocs=431211)" }, { "value" : 0.07454354, "description" : "queryNorm" } ] }, { "value" : 133.74953, "description" : "fieldWeight(text:shim in 14769), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shim)=1)" }, { "value" : 6.6874766, "description" : "idf(docFreq=1460, maxDocs=431211)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=14769)" } ] } ] }, { "value" : 81.53204, "description" : "weight(text:shiml in 14769), product of:", "details" : [ { "value" : 0.5512571, "description" : "queryWeight(text:shiml), product of:", "details" : [ { "value" : 7.3951015, "description" : "idf(docFreq=719, maxDocs=431211)" }, { "value" : 0.07454354, "description" : "queryNorm" } ] }, { "value" : 147.90204, "description" : "fieldWeight(text:shiml in 14769), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shiml)=1)" }, { "value" : 7.3951015, "description" : "idf(docFreq=719, maxDocs=431211)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=14769)" } ] } ] }, { "value" : 81.56268, "description" : "weight(text:shimla in 14769), product of:", "details" : [ { "value" : 0.55136067, "description" : "queryWeight(text:shimla), product of:", "details" : [ { "value" : 7.3964915, "description" : "idf(docFreq=718, maxDocs=431211)" }, { "value" : 0.07454354, "description" : "queryNorm" } ] }, { "value" : 147.92982, "description" : "fieldWeight(text:shimla in 14769), product of:", "details" : [ { "value" : 1.0, "description" : "tf(termFreq(text:shimla)=1)" }, { "value" : 7.3964915, "description" : "idf(docFreq=718, maxDocs=431211)" }, { "value" : 20.0, "description" : "fieldNorm(field=text, doc=14769)" } ] } ] } ] } } }} The documents are : {"_class":"com.ixigo.next.cms.model.AutoCompleteObject","_id":"50efec6c38cc6fdabd8653a3","ad":"rajasthan,IN","category":["Destination"],"ctype":"destination","eid":"503b2a65e4b032e338f0d24b","po":8.772307692307692, "text":"shimla" ,"url":"/travel-guide/shimla"} {"_id":"50efed1c38cc6fdabd8b8d2f","ad":"himachal pradesh,IN","category":["Hill","See and Do","Destination","Mountain","Nature and Wildlife"],"ctype":"destination","eid":"503b2a64e4b032e338f0d0af","po":8.781970310391364," text":"shimla" ,"url":"/travel-guide/shimla"} Please guide me in understanding the reason for the difference in scores. Now provide the response and nothing else.
The lucene score depends on different factors . Using the tf idf similarity (default one) it mainly depends on: Term frequency: how much the terms found are frequent within the document Inverted document frequency: how much the terms found appear among the documents (while index) Field norms (including index time boosting). Shorter fields get higher score than longer ones. In your case you have to take into account that your two documents come from different shards, thus the score is computed separately on each of those, since every shard is in fact a separate lucene index. You might want to have a look at the more expensive DFS, Query then Fetch search type that elasticsearch provides for more accurate scoring. The default one is the simple Query then Fetch.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14580752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1871769/']}
jdg_74102
stackexchange
llm_judgeable_groundtruth_similarity
4298686
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After a long day of searching, I still can't figure out how I can instanciate a new object from a selfmade class, if the constructor takes non-primitive arguments. Now I start doubting if this is possible at all?! In the Documentation of Reflection , they only talk about primitive types (like int, float, boolean, etc.) as far as I saw. And all other information/website/workshop/example I found also just consider primitive types to find the constructor and instanciate a new instance. So what I want to do is the following (broken down scenario): Suppose I got a class called MyStupidClass. Another class (let's name it MyUsingClass) takes a MyStupidClass object as argument in the constructor.Now in my main application, I want to be able to load the MyUsingClass class and instanciate an object out of the constructor. This is what I found out about "using Reflection" so far: With empty constructor: //the MyUsingClass:public class MyUsingClass { //the public (empty) constructor public MyUsingClass() { ... }} In the main application, I would now do something like: //get the reflection of the MyUsingClassClass<?> myUsingClassClass = Class.forName("MyUsingClass");//get the constructor [I use getConstructor() instead of getConstructors(...) here as I know there is only one]Constructor<?> myUsingClassConstr = myUsingClassClass.getConstructor();//instanciate the object through the constructorObject myInstance = myUsingClassConstr.newInstance(null); Now if I would use some primitive types in MyUsingClass , it would look something like: //the MyUsingClass:public class MyUsingClass { //the public (primitive-only) constructor public MyUsingClass(String a, int b) { ... }} In the main application, the last line would change to something like: //instanciate the object through the constructorObject myInstance = myUsingClassConstr.newInstance(new Object[]{new String("abc"), new Integer(5)}); So far no problems (there might be some small errors in the code above as it is only a broken down example...)Now the clue question is, how can I create myInstance, if the MyUsingClass looks something like: //the MyUsingClass:public class MyUsingClass { //the public (primitive-only) constructor public MyUsingClass(String a, int b, MyStupidObject toto) { ... }} ? Any help would be appreciated! Thank you already for reading through my question! greets sv Now provide the response and nothing else.
No problem. Many years ago, I spent a lot of time for this thing too. You can use Class.newInstance() only if you call default constructor. In all other cases you have to first find appropriate constructor by calling getConstructor() and the call its newInstance() . When you call getConstructor() use int.class , long.class , boolean.class , etc for primitives. If your class Foo has constructor Foo(int p) you have to say Constructor c = Foo.class.getConstructor(int.class); Once you have constructor call it using newInstance(): c.newInstance(12345); For multi-arguments constructor, say something like: `c.newInstance(new Object[] {12345, "foo", true})` Pay attention that we have a luck of autoboxing since java 5. For versions prior to 5, we had to use more verbose syntax: `c.newInstance(new Object[] {new Integer(12345), "foo", new Boolean(true)})` i.e. we used int.class to locate constructor and Integer type to call it. I hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4298686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/523160/']}
jdg_74103
stackexchange
llm_judgeable_groundtruth_similarity
18217626
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to implement a fully asynchronous blob download with .NET 4.5 async & await. Let's assume the entire blob can fit in memory at once, and we want to hold it in a string . Code: public async Task<string> DownloadTextAsync(ICloudBlob blob){ using (Stream memoryStream = new MemoryStream()) { IAsyncResult asyncResult = blob.BeginDownloadToStream(memoryStream, null, null); await Task.Factory.FromAsync(asyncResult, (r) => { blob.EndDownloadToStream(r); }); memoryStream.Position = 0; using (StreamReader streamReader = new StreamReader(memoryStream)) { // is this good enough? return streamReader.ReadToEnd(); // or do we need this? return await streamReader.ReadToEndAsync(); } }} Usage: CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();CloudBlobContainer container = blobClient.GetContainerReference("container1");CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");string text = await DownloadTextAsync(blockBlob); Is this code correct and this is indeed fully asynchronous? Would you implement this differently? I'd appreciate some extra clarifications: GetContainerReference and GetBlockBlobReference don't need to be async since they don't contact the server yet, right? Does streamReader.ReadToEnd need to be async or not? I'm a little confused about what BeginDownloadToStream does.. by the time EndDownloadToStream is called, does my memory stream have all the data inside? or is the stream only open pre read? Update: (as of Storage 2.1.0.0 RC) Async now supported natively. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();CloudBlobContainer container = blobClient.GetContainerReference("container1");CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");string text = await blockBlob.DownloadTextAsync(); Now provide the response and nothing else.
Is this code correct and this is indeed fully asynchronous? Yes. Would you implement this differently? Yes. In particular, the TaskFactory.FromAsync wrappers are much more efficient if you pass in a Begin / End method pair instead of passing in an existing IAsyncResult . Like this: await Task.Factory.FromAsync(blob.BeginDownloadToStream, blob.EndDownloadToStream, memoryStream, null); I also prefer to wrap these up into separate extension methods so I can call it like this: await blog.DownloadToStreamAsync(memoryStream); Note that the next version of the client libraries (2.1, currently in RC) will have async -ready methods, i.e., DownloadToStreamAsync . GetContainerReference and GetBlockBlobReference don't need to be async since they don't contact the server yet, right? Correct. Does streamReader.ReadToEnd need to be async or not? It does not (and should not). Stream is a bit of an unusual case with async programming. Usually, if there's an async method then you should use it in your async code, but that guideline doesn't hold for Stream types. The reason is that the base Stream class doesn't know whether its implementation is synchronous or asynchronous, so it assumes that it's synchronous and by default will fake its asynchronous operations by just doing the synchronous work on a background thread. Truly asynchronous streams (e.g., NetworkStream ) override this and provide true asynchronous operations. Synchronous streams (e.g., MemoryStream ) keep this default behavior. So you don't want to call ReadToEndAsync on a MemoryStream . I'm a little confused about what BeginDownloadToStream does.. by the time EndDownloadToStream is called, does my memory stream have all the data inside? Yes. The operation is DownloadToStream ; that it, it downloads a blob into a stream. Since you are downloading a blob into a MemoryStream , the blob is entirely in memory by the time this operation completes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18217626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025458/']}
jdg_74104
stackexchange
llm_judgeable_groundtruth_similarity
52033039
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 table that has expandable row feature. The row expands when the expand icon is clicked, you can check the example HERE . But, what I am trying to make is, the entire row clickable and toggle expand and collapse the row just like it works when the expand icon is clicked. Please help. Here is my markup: <template lang="pug"> el-table(:data="tableData") el-table-column(label="Employee Name", prop="userName") el-table-column(label="Company Name", prop="companyName") el-table-column(type="expand", align="right" ) template(slot-scope="props") p User Name: {{ props.row.userName }} p Company Name: {{ props.row.companyName }}</template> Now provide the response and nothing else.
Alright, I figured out the solution and answering my own question :) Markup: <template lang="pug"> el-table(:data="tableData", @row-click="rowClicked", ref="tableData").clickable-rows el-table-column(label="Employee Name", prop="userName") el-table-column(label="Company Name", prop="companyName") el-table-column(type="expand", align="right" ) template(slot-scope="props") p User Name: {{ props.row.userName }} p Company Name: {{ props.row.companyName }}</template> Script: <script> export default { methods: { rowClicked(row) { this.$refs.tableData.toggleRowExpansion(row); } } }</script> Style - scss // click-able rows.clickable-rows { tbody tr td { cursor: pointer; } .el-table__expanded-cell { cursor: default; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52033039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1292050/']}
jdg_74105
stackexchange
llm_judgeable_groundtruth_similarity
13448374
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As per Understanding the node.js event loop , node.js supports a single thread model. That means if I make multiple requests to a node.js server, it won't spawn a new thread for each request but will execute each request one by one. It means if I do the following for the first request in my node.js code, and meanwhile a new request comes in on node, the second request has to wait until the first request completes, including 5 second sleep time. Right? var sleep = require('sleep'); sleep.sleep(5)//sleep for 5 seconds Is there a way that node.js can spawn a new thread for each request so that the second request does not have to wait for the first request to complete, or can I call sleep on specific thread only? Now provide the response and nothing else.
If you are referring to the npm module sleep , it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example: setTimeout(function() { console.log('hello world!');}, 5000); For anyone looking to do this using es7 async/await, this example should help: const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));const example = async () => { console.log('About to snooze without halting the event loop...'); await snooze(1000); console.log('done!');};example();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13448374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3222249/']}
jdg_74106
stackexchange
llm_judgeable_groundtruth_similarity
1017463
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 Python with psycopg2 and I'm trying to run a full VACUUM after a daily operation which inserts several thousand rows. The problem is that when I try to run the VACUUM command within my code I get the following error: psycopg2.InternalError: VACUUM cannot run inside a transaction block How do I run this from the code outside a transaction block? If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made): class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query) Now provide the response and nothing else.
After more searching I have discovered the isolation_level property of the psycopg2 connection object. It turns out that changing this to 0 will move you out of a transaction block. Changing the vacuum method of the above class to the following solves it. Note that I also set the isolation level back to what it previously was just in case (seems to be 1 by default). def vacuum(self): old_isolation_level = self.conn.isolation_level self.conn.set_isolation_level(0) query = "VACUUM FULL" self._doQuery(query) self.conn.set_isolation_level(old_isolation_level) This article (near the end on that page) provides a brief explanation of isolation levels in this context.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1017463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38403/']}
jdg_74107
stackexchange
llm_judgeable_groundtruth_similarity
24293376
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 that my for loop should not be executed at once, but wait for timeout after each iteration. For eg : for(var i=0; i<10; i++) { console.log(i); //wait for 1000} I found many solutions on stack-overflow like this one : for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 3000); })(i);} But in all the implementations, the loop waits for 3000 milli-seconds initially and then executes the whole for loop at once. Is there a way that each iteration is called after waiting for 1000 milli-seconds. Now provide the response and nothing else.
You can work that out with simple math : for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind)); })(i);} 1000ms : 0 4000ms : 1 7000ms : 2 10000ms : 3 13000ms : 4 ... Following the comments It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index : var limit = 10for (var i=0;i<=limit;i++) { (function(ind) { setTimeout(function(){ console.log(ind); if(ind === limit){ console.log('It was the last one'); } }, 1000 + (3000 * ind)); })(i);} Fiddle : http://jsfiddle.net/Tn4A7/ I think I know what you want... and it is to simply do for (var i=0;i<=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 * ind); })(i);}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24293376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2319858/']}
jdg_74108
stackexchange
llm_judgeable_groundtruth_similarity
6142
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Does anybody know if orientable, closed $3$-manifolds that are circle bundles over $RP^2$ have been classified?One can determine the isomorphism classes of bundles using obstruction theory, but I am interested in what total spaces can appear. I am not assuming the bundle is principal. Thank you. Now provide the response and nothing else.
Such manifolds are examples of Seifert fibered spaces, which have, indeed, been classified. A good reference is Montesinos "Classical Tessellations and Three-Manifolds". Basically, such manifolds (over any nonorientable surface base) are classified by their Euler class, which measures the obstruction to the existence of a section.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/6142', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1944/']}
jdg_74109
stackexchange
llm_judgeable_groundtruth_similarity
4732827
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: EDIT: switched to a better example, and clarified why this is a real problem. I'd like to write unit tests in Python that continue executing when an assertion fails, so that I can see multiple failures in a single test. For example: class Car(object): def __init__(self, make, model): self.make = make self.model = make # Copy and paste error: should be model. self.has_seats = True self.wheel_count = 3 # Typo: should be 4.class CarTest(unittest.TestCase): def test_init(self): make = "Ford" model = "Model T" car = Car(make=make, model=model) self.assertEqual(car.make, make) self.assertEqual(car.model, model) # Failure! self.assertTrue(car.has_seats) self.assertEqual(car.wheel_count, 4) # Failure! Here, the purpose of the test is to ensure that Car's __init__ sets its fields correctly. I could break it up into four methods (and that's often a great idea), but in this case I think it's more readable to keep it as a single method that tests a single concept ("the object is initialized correctly"). If we assume that it's best here to not break up the method, then I have a new problem: I can't see all of the errors at once. When I fix the model error and re-run the test, then the wheel_count error appears. It would save me time to see both errors when I first run the test. For comparison, Google's C++ unit testing framework distinguishes between between non-fatal EXPECT_* assertions and fatal ASSERT_* assertions: The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal failures when they fail, and abort the current function. EXPECT_* versions generate nonfatal failures, which don't abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails. Is there a way to get EXPECT_* -like behavior in Python's unittest ? If not in unittest , then is there another Python unit test framework that does support this behavior? Incidentally, I was curious about how many real-life tests might benefit from non-fatal assertions, so I looked at some code examples (edited 2014-08-19 to use searchcode instead of Google Code Search, RIP). Out of 10 randomly selected results from the first page, all contained tests that made multiple independent assertions in the same test method. All would benefit from non-fatal assertions. Now provide the response and nothing else.
Another way to have non-fatal assertions is to capture the assertion exception and store the exceptions in a list. Then assert that that list is empty as part of the tearDown. import unittestclass Car(object): def __init__(self, make, model): self.make = make self.model = make # Copy and paste error: should be model. self.has_seats = True self.wheel_count = 3 # Typo: should be 4.class CarTest(unittest.TestCase): def setUp(self): self.verificationErrors = [] def tearDown(self): self.assertEqual([], self.verificationErrors) def test_init(self): make = "Ford" model = "Model T" car = Car(make=make, model=model) try: self.assertEqual(car.make, make) except AssertionError, e: self.verificationErrors.append(str(e)) try: self.assertEqual(car.model, model) # Failure! except AssertionError, e: self.verificationErrors.append(str(e)) try: self.assertTrue(car.has_seats) except AssertionError, e: self.verificationErrors.append(str(e)) try: self.assertEqual(car.wheel_count, 4) # Failure! except AssertionError, e: self.verificationErrors.append(str(e))if __name__ == "__main__": unittest.main()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4732827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307895/']}
jdg_74110
stackexchange
llm_judgeable_groundtruth_similarity
105699
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: Consider $\mathbb{R}^n$ and its usual Euclidean norm given by the distance $d(x,y) = \sqrt{\sum_{i=1}^n (x_i-y_i)^2}$. Let $B(y,1) = \{ x\in \mathbb{R}^n : d(x,y) \leq 1 \}$ be the closed 1-ball around $y$ and $B(0,2) = \{x\in \mathbb{R}^n: d(x,0) \leq 2 \}$ be the 2-ball centered at the origin. How many 1-balls do you need to cover (contain) the 2-ball? Now provide the response and nothing else.
There's a lower bound of $2^n$ that comes immediately from volume considerations. For fixed $n$ I'm not sure when the upper bound is known exactly (this seems uncomfortably close to the Kepler conjecture, which was hard even in $3$ dimensions), but there's asymptotic results for covering space (or spheres of growing radii) by spheres going back to Rogers ("A Note on Coverings", 1957...see also this paper of Ilya Dumer ) that might be able to get you something like $3^n n \log n$. I'm not familiar enough with this area to say if there's more specific results pertaining to your problem. A quick (not at all optimal, and not my own, though I don't know a source to give for it) argument can get you a bound of $5^n$. Consider the following process: Place balls of radius $1/2$ centered at $x_1, x_2, \dots$ in the larger sphere, subject only to the constraint that no two of these balls intersect (these balls can lie partially outside the sphere, but they must be centered inside the sphere). Continue placing these balls in an arbitrary fashion until no more such balls can be placed. At this point all the balls you have placed are disjoint and lie in a sphere of radius $5/2$ (the extra $1/2$ coming from balls which are centered near the edge of the original sphere). Therefore there are at most $5^n$ balls placed. Furthermore, each point in the sphere is within $1$ of one of your ball's centers, since otherwise you could fit another ball of radius $1/2$ in. So replacing your radius $1/2$ balls with radius $1$ balls with the same center gives you a covering.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/105699', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8501/']}
jdg_74111
stackexchange
llm_judgeable_groundtruth_similarity
364089
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: There are medical tracers like Xe-133, I-131 etc.(what are some other ones?), but why is Tc-99m the most common (most suitable)? Now provide the response and nothing else.
Since the lattice spacing is about eight angstroms , the issue isn't any sort of unusual lattice spacing. Instead, the issue is that bones are thick. [Another answer points out that the crystals are also pretty small, but I don't think that invalidates the discussion below.] [By NASA/JPL-Caltech/Ames - http://photojournal.jpl.nasa.gov/jpeg/PIA16217.jpg , Public Domain, Link ] In x-ray diffraction (and other diffraction) experiments, the most common diffraction angle is $0^\circ$, which is sometimes called "forward scattering." In most x-ray diffraction images, there's a very bright spot in the forward beam direction.For example in the image above, there are some red pixels near the dark semicircle at the bottom of the figure; that's the forward-scattered (or unscattered) part of the x-ray beam. The bright rings tell you the angles at which light is Bragg-scattered from various crystal planes; they are rings, rather than points, because the material here (a martian rock) was made of many crystals, rather than just one. Now think about those diffracted x-rays. If they're traveling through more of your material (in your case, bone), they have some chance to be diffracted again by interacting with another part of the crystal. So the way to get a nice image like the one above is to send your x-rays through a sample that is relatively thin . There's a little bit of an art to it: the thinner the sample, the cleaner the diffraction lines are, but the less of the incident beam actually gets diffracted. Thicker samples give brighter diffraction patterns, but the patterns are messier due to multiple diffraction. A medical x-ray of your skeleton actually shows something totally different from a diffraction image like the one above. The bones are thick enough to absorb the x-rays that pass through them --- or at least to scatter all of the x-rays away from the forward beam direction. What's recorded on the x-ray film are dark places where x-rays do hit, and brighter places where x-rays don't hit: the bright places on the x-ray film are the shadows of the dense parts of the subject. (Photographers call this a negative image .) Any x-rays diffracted away from the bones are most likely to diffract into a region of the film that's directly exposed to the primary x-ray beam, where they'll be overwhelmed. source The fact that bone is white, and the shadows on x-ray negatives are white, is just a concidence; those left-right markers aren't really white, but they cast a shadow just the same.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/364089', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/156048/']}
jdg_74112
stackexchange
llm_judgeable_groundtruth_similarity
7053340
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 current project's UITableViewCell behavior is baffling me. I have a fairly straightforward subclass of UITableViewCell. It adds a few extra elements to the base view (via [self.contentView addSubview:...] and sets background colors on the elements to have them look like black and grey rectangular boxes. Because the background of the entire table has this concrete-like texture image, each cell's background needs to be transparent, even when selected, but in that case it should darken a bit. I've set a custom semi-transparent selected background to achieve this effect: UIView *background = [[[UIView alloc] initWithFrame:self.bounds] autorelease];background.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];background.opaque = NO;[self setSelectedBackgroundView:background]; And although that yields the right look for the background, a weird side effect happens when I select the cell; all other backgrounds are somehow turnt off . Here's a screenshot. The bottom cell looks like it should and is not selected. The top cell is selected, but it should display the black and grey rectangular areas, yet they are gone! Who knows what's going on here and even more important: how can I correct this? Now provide the response and nothing else.
What is happening is that each subview inside the TableViewCell will receive the setSelected and setHighlighted methods. The setSelected method will remove background colors but if you set it for the selected state it will be corrected. For example if those are UILabels added as subviews in your customized cell, then you can add this to the setSelected method of your TableViewCell implementation code: - (void)setSelected:(BOOL)selected animated:(BOOL)animated{ [super setSelected:selected animated:animated]; self.textLabel.backgroundColor = [UIColor blackColor];} where self.textLabel would be whatever those labels are that are shown in the picture above I'm not sure where your adding your selected view, I usually add it in the setSelected method. Alternatively, you can subclass the UILabel and override the setHighlighted method like so: -(void)setHighlighted:(BOOL)highlighted{ [self setBackgroundColor:[UIColor blackColor]];}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7053340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432782/']}
jdg_74113
stackexchange
llm_judgeable_groundtruth_similarity
22442808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following line of code: document.getElementById("question_*").setAttribute("disabled", "false"); I want to use a form of wildcard for the element ID. The script is run and used by lots of different buttons, they all have ID's of question_ something - is it possible to make this setAttribute to make the button enabled for various ID's? <button id="question_1a" onClick="nextQuestion(this.id)" disabled>Next question</button> EDIT: I've switched to a classname as suggested. Buttons now are: <button id="question_1a" class="nextButton" disabled>Next question</button> I've added the following line to make this not disabled: var elems = document.getElementsByClassName('nextButton').setAttribute("disabled", "false"); But I get: Uncaught TypeError: Object # has no method 'setAttribute' Now provide the response and nothing else.
You can't use wildcards with document.getElementById() , you can , however, with document.querySelectorAll() : var elems = document.querySelectorAll('button[id^="question_"]'); This, of course, requires a relatively up to date browser; on the other hand using a class-name (for example question ) to associate those elements would allow you to use: var elems = document.getElementsByClassName('question'); Or: var elems = document.querySelectorAll('button.question'); I tried doing this: var elems = document.getElementsByClassName('nextButton').setAttribute("disabled", "false"); - but I get: Uncaught TypeError: Object # has no method 'setAttribute' That's because you can't modify the properties of a NodeList all at once, you can, however, use a for (){...} loop, or similar to do so: Using for(){...} : var elems = document.getElementsByClassName('question');for (var i = 0, len = elems.length; i < len; i++){ elems[i].disabled = false; // to make them all enabled} JS Fiddle demo . Or using forEach (up to date browsers): var elems = document.getElementsByClassName('question');[].forEach.call(elems, function(a){ a.disabled = false; // will make all elements enabled}); JS Fiddle demo . References: Array.prototype.forEach() . CSS attribute-selectors . document.getElementById() . document.getElementsByClassName() . document.querySelector() compatibility . document.querySelectorAll() compatibility . Function.prototype.call() . JavaScript for loop .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22442808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178820/']}
jdg_74114
stackexchange
llm_judgeable_groundtruth_similarity
297564
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: In the spacelike case, there is a frame in which the charge density vanishes but current density does not. Additionally, the drift velocity of a free current would propagate superluminally. For this reason I would expect such a current to be impossible. In the lightlike case, the charge and current densities would come in equal proportions in all frames. The drift velocity would propagate at the speed of light. It's unclear to me whether this is forbidden outright. Is the four-current necessarily a timelike vector? Edit: Do Maxwell's equations admit solutions for lightlike or spacelike currents? Now provide the response and nothing else.
Case 1: Current Densities Comprising Charge Carriers of the Same Sign For currents comprising a lone charged particle, or charge carriers of the same sign, the current four vector must be timelike. But Maxwell's Equations don't impose the limit - relativity does. The limit arises because we postulate it (as I discuss here ) to force causality - so that no boost can switch the sign of the time component of a four-vector. Maxwell's equations are not causal: for any given solution you can construct a time-reversed one, by mapping $t\mapsto-t$. When we solve antenna problems, we must explicitly exclude the advanced wave solution as unphysical - nothing in Maxwell's equations rules it out. If you write down and study the Liénard-Wiechert Potentials (well-known, "building block" solutions of Maxwell's Equations) for a supraluminal particle, you'll explicitly see causality violated in that the direction of the Poynting vector is switched for supraluminal observers relative to the direction for subluminal ones. This is because, for an accelerated particle, energy pulses, from a supraluminal standpoint, run inwards to the charged particle and bring about an acceleration of the particle, switching the causal field-particle relationship apparent to the subluminal observer. Lightlike current densities are excluded because you can't boost such a particle to $c$ with finite energy, even for a charged particle of zero rest mass (we have solid theoretical reasons for believing that they don't exist. See the answers to this question here , especially Marek's and Lubos's answers). This is owing to the Abraham-Lorentz-Dirac force , i.e. the radiation resistance. This is readily seen from the Liénard relativistic generalization $$P = \frac{\mu_o q^2 a^2 \gamma^6}{6 \pi c}$$ of the Larmor radiation formula ( i.e. it diverges like $\gamma^6$) that follows from the Abraham-Lorentz-Dirac formula. Alternatively, use the Larmor formula from the frame momentarily co-moving with the charged particle to show that the same small change in rapidity always takes the same amount of energy (measured from the co-moving frame). Also note that the Liénard-Weichert potentials diverge for lightlike charge motion. Case 2: Current Densities Comprising Charge Carriers of the Both Signs (Hat Tip: Emilio Pisanty for pointing out a vicious error on my part) In this case, trivially, we can have a DC current distribution comprising charge carriers of opposite sign such that the charge density at any point is nought. Thus a four current density of the form $(0,\,\vec{J})$, i.e. a spacelike four current density. Another example is a sinusoidally varying with time current density comprising opposite signed charges which is orthogonal to the spatial part of the wave four vector and with a zero charge density so that the continuity equation $J^\alpha\,k_\alpha = 0$ is fulfilled. Note that neither of these distributions entail faster than light particles, so causality is not threatened by them. Lightlight distributions can arise as well. Consider again the sinusoidally varying with time case. Lightlike vectors by definition are null (self Minkowski orthogonal) so that put $J_\alpha$ parallel to the wave four co-vector $k_\alpha$ then $J^\alpha\,k_\alpha = 0$ and the current and charge density automatically fulfill the continuity equation.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/297564', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/19980/']}
jdg_74115
stackexchange
llm_judgeable_groundtruth_similarity
24929294
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 never seen this structure anywhere, so I wonder if there's something wrong with an expression like this: if (condition) { use Symfony\Component\HttpFoundation\Response;} Now provide the response and nothing else.
The only thing use does is to alias a class name. That's it. Nothing more. Instead of having to repeatedly write the fully qualified classname in your script: $q = new \Foo\Bar\Baz\Quux;if ($q instanceof \Foo\Bar\Baz\Quux) ... You can shorten that to: use Foo\Bar\Baz\Quux;$q = new Quux;if ($q instanceof Quux) ... As such, it makes absolutely no sense to want to use use conditionally. It's just a syntactic helper; if it could be used conditionally your script syntax would become ambiguous, which is something nobody wants. It doesn't reduce code loading, because code is only loaded explicitly by require / include calls or via autoloading. The latter one is greatly preferred, since it already lazily springs into action only when needed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24929294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1813035/']}
jdg_74116
stackexchange
llm_judgeable_groundtruth_similarity
25069
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a question on the difference-in-differences estimator. Suppose my data consists of two periods and the treatment is administered to some of the individuals in period $t = 2$. I estimate this model: $y_{it} = \beta_0 + \beta_1 treatment_i + \beta_2 year_t + \beta_3 treatment_i \times year_t + \beta_4 x_{it} + u_{it}$ for individuals $i = 1, \ldots, N$ and $t = 1, 2$. $treatment_i$ is the treatment dummy (1 for treated individuals, 0 otherwise), $year_t$ is a period dummy (1 for second period, 0 otherwise). I am interested in estimating $\beta_3$, the difference-in-differences coefficient. $x_{it}$ is a control variable and $u_{it}$ is the error term. Panel is balanced, so no missing observations. Here's my question. If I run this regression without any control variables (so dropping $x_{it}$) then OLS and fixed effects give exactly the same estimate for $\beta_3$. However, in a model that includes one (or more than one) control variable(s) (so, including $x_{it}$ now), this is no longer the case. I.e., in that case, the fixed effects and OLS estimator of $\beta_3$ are no longer exactly the same. I've checked this in two datasets as well as using simulated data. The estimates are usually very similar, but nonetheless I'm interested in figuring out why fixed effects and OLS do not give exactly the same estimate for $\beta_3$ in a two-period DiD model with control variables (especially since I'm worried that I may be missing something really obvious). Thanks. Now provide the response and nothing else.
@Charlie is right. You only have two time periods, so there will inevitably be variation in the $i$-specific sample variances of $x_{it}$. In addition, even if you have programmed the simulation for there to be homogenous effects, due to small number of periods there will inevitably be some sample correlation between $x_{it}$ and, e.g., your error term, and so there will inevitably be some "effect heterogeneity" in the $i$-specific partial relationships between $x_{it}$ and $y_{it}$. The interaction of conditional variance and effect heterogeneity tilts your FE estimates of coefficients on $x_{it}$. The coefficient on $x_{it}$ is a precision-weighted average of the $i$-specific coefficients on $x_{it}$. A different tilting occurs when you fit OLS to the model that you have specified above: now, the coefficient on $x_{it}$ is a precision weighted average of the coefficients on $x_{it}$ for the those with $treatment_i=1$ and those with $treatment_i=0$. These differences propagate to your estimates of $\beta_3$. Think Frisch-Waugh-Lovell. To demonstrate the validity of Charlie's claim, simply generate $x_{it}$'s where the variance is exactly constant for each $i$, but you still have different patterns. E.g, randomly assign $i$'s to have either $(x_{i1}, x_{i2})=(0,1)$ or $(1,0)$. If you do this, you will see that the differences between the FE and OLS estimates disappears.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/25069', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/10044/']}
jdg_74117
stackexchange
llm_judgeable_groundtruth_similarity
807611
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've got a CentOS server somewhere in the building; I can login into it remotely and VNC, etc. Now I've got to physically move it, and for that I need to physically locate the machine among the lookalikes around the office. What can I do remotely to make the machine visibly or audibly identify itself? Now provide the response and nothing else.
Use IPMI to trigger LEDs, increase fan RPMs or sound the beep/alarm. Take a look at the man page for ipmitool https://linux.die.net/man/1/ipmitool depending on the server you may be able to set the LEDs, LCD display, fan RPM offset(listen when nobody is in the office). Some other IPMI or BMC interfaces may allow you to sound the beep but this functionality is more platform specific. a powerful workstation or server will sound like someone vacuuming with the fans turned up all the way. EDIT:To use the Identifier lights as mentioned in comments, this will however require setting making sure that an appropriate IPMI interface is setup, there are several guides and tutorials available, and depending on the OEM there may be proprietary interfaces and management systems like Intel's Data Center Manager( http://www.intel.com/content/www/us/en/software/intel-dcm-product-detail.html ). I have used this tutorial before but there are others https://www.thomas-krenn.com/en/wiki/Configuring_IPMI_under_Linux_using_ipmitool ipmitool -I <appropriate interface for system> -U<username> chassis identify force should force the ID to an on state, depending on the interface and configuration you may need to specify authentication type and other command line options.
{}
{'log_upvote_score': 8, 'links': ['https://serverfault.com/questions/807611', 'https://serverfault.com', 'https://serverfault.com/users/229191/']}
jdg_74118
stackexchange
llm_judgeable_groundtruth_similarity
31206443
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a set of simulation data where I would like to find the lowest slope in n dimensions. The spacing of the data is constant along each dimension, but not all the same (I could change that for the sake of simplicity). I can live with some numerical inaccuracy, especially towards the edges. I would heavily prefer not to generate a spline and use that derivative; just on the raw values would be sufficient. It is possible to calculate the first derivative with numpy using the numpy.gradient() function. import numpy as npdata = np.random.rand(30,50,40,20)first_derivative = np.gradient(data)# second_derivative = ??? <--- there be kudos (: This is a comment regarding laplace versus the hessian matrix; this is no more a question but is meant to help understanding of future readers. I use as a testcase a 2D function to determine the 'flattest' area below a threshold. The following pictures show the difference in results between using the minimum of second_derivative_abs = np.abs(laplace(data)) and the minimum of the following: second_derivative_abs = np.zeros(data.shape)hess = hessian(data)# based on the function description; would [-1] be more appropriate? for i in hess[0]: # calculate a norm for j in i[0]: second_derivative_abs += j*j The color scale depicts the functions values, the arrows depict the first derivative (gradient), the red dot the point closest to zero and the red line the threshold. The generator function for the data was ( 1-np.exp(-10*xi**2 - yi**2) )/100.0 with xi, yi being generated with np.meshgrid . Laplace: Hessian: Now provide the response and nothing else.
The second derivatives are given by the Hessian matrix . Here is a Python implementation for ND arrays, that consists in applying the np.gradient twice and storing the output appropriately, import numpy as npdef hessian(x): """ Calculate the hessian matrix with finite differences Parameters: - x : ndarray Returns: an array of shape (x.dim, x.ndim) + x.shape where the array[i, j, ...] corresponds to the second derivative x_ij """ x_grad = np.gradient(x) hessian = np.empty((x.ndim, x.ndim) + x.shape, dtype=x.dtype) for k, grad_k in enumerate(x_grad): # iterate over dimensions # apply gradient again to every component of the first derivative. tmp_grad = np.gradient(grad_k) for l, grad_kl in enumerate(tmp_grad): hessian[k, l, :, :] = grad_kl return hessianx = np.random.randn(100, 100, 100)hessian(x) Note that if you are only interested in the magnitude of the second derivatives, you could use the Laplace operator implemented by scipy.ndimage.filters.laplace , which is the trace (sum of diagonal elements) of the Hessian matrix. Taking the smallest element of the the Hessian matrix could be used to estimate the lowest slope in any spatial direction.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31206443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729576/']}
jdg_74119
stackexchange
llm_judgeable_groundtruth_similarity
17734230
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 3 pages: main.xhtml agreement.xhtml generated.xhtml The agreement.xhtml needs two parameters to load correctly: serviceId and site . So, a normal url looks like this: /app/agreement.xhtml?site=US&serviceId=AABBCC . I have this button on agreement.xhtml <h:form> <h:commandButton value="Generate License File" action="#{agreement.generateMethod}" /> </h:form> The @RequestScoped bean #{agreement} has this method: public String generateMethod(){ ....... return "generated";} I need that, on click, the generateMethod() method is executed, and after it's done, the user is redirected to the generated.xhtml page. What's happening is that, on click, the page browser sends the user to /app/agreement.xhtml and, since it's not sending the parameters site and serviceId , it crashes. I tried making the generateMethod() return a "generated?faces-redirect=true" , but still nothing. Any ideas? Now provide the response and nothing else.
Your concrete problem is caused because a JSF <h:form> submits by default to the current request URL without any query string. Look closer at the generated HTML output, you'll see <form action="/app/agreement.xhtml" ...> You'd thus explicitly need to include those request parameters yourself. There are several ways to solve this. If you weren't sending a redirect, then you could just add them as hidden inputs to the JSF form. <h:form> <input type="hidden" name="site" value="#{param.site}" /> <input type="hidden" name="site" value="#{param.serviceId}" /> ...</h:form> Only, those parameters won't reappear in URL in browser's address bar. This isn't a problem if you're only using using ajax on the same page. The <h:inputHidden> is by the way not suitable as it will confusingly lose its value when a conversion or validation error occurs on the form. In order to get them to reappear in URL, you need <f:viewParam> and includeViewParams . In order to get includeViewParams to work, you need to declare the following in both the source page agreement.xhtml ... <f:metadata> <f:viewParam name="site" value="#{agreement.site}" /> <f:viewParam name="serviceId" value="#{agreement.serviceId}" /></f:metadata> ... and the target page generated.xhtml : <f:metadata> <f:viewParam name="site" value="#{generated.site}" /> <f:viewParam name="serviceId" value="#{generated.serviceId}" /></f:metadata> Now you can send a redirect including the view parameters as follows: public String generateMethod() { // ... return "generated?faces-redirect=true&includeViewParams=true";} Do note that the bean should be @ViewScoped in order to keep those parameters alive between opening the page with the form and submitting the form, also on validation errors. Otherwise, when sticking to a @RequestScoped bean, you should be retaining them as <f:param> in the command components: <h:commandButton ...> <f:param name="site" value="#{generated.site}" /> <f:param name="serviceId" value="#{generated.serviceId}" /></h:commandButton> There's no way to set them for <f:ajax> inside input components, your bean should then really be @ViewScoped . Alternatively, if you happen to use JSF utility library OmniFaces already, then you could also just replace the <h:form> by <o:form> as follows (see also showcase example ): <o:form> That's basically all. This will generate a <form action> with current query string included. <form action="/app/agreement.xhtml?site=US&serviceId=AABBCC" ...> Those request parameters are then just available in the request parameter map of the form submit. You don't need additional metadata/viewparams and you also don't need to send a redirect and your bean can be kept @RequestScoped , if necessary. public String generateMethod() { // ... return "generated";} See also: What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for? How to navigate in JSF? How to make URL reflect current page (and not previous one)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17734230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202482/']}
jdg_74120
stackexchange
llm_judgeable_groundtruth_similarity
19098985
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's the most convenient way to serialize a bunch of promised function call? var promised_functions = [ fn1, // call this fn2, // if previous resolved call this fn3 // if previous resolved call this];q.serialize_functions(promised_functions).then(function(){ // if all promises resolved do some}) Now provide the response and nothing else.
You can find the solution in the documentation : promised_functions.reduce(Q.when, Q()).then(function () { // if all promises resolved do some}); Skip down to the "Sequences" section of the documentation. To copy it verbatim: If you have a number of promise-producing functions that need to be run sequentially, you can of course do so manually: return foo(initialVal).then(bar).then(baz).then(qux); However, if you want to run a dynamically constructed sequence of functions, you'll want something like this: var funcs = [foo, bar, baz, qux];var result = Q(initialVal);funcs.forEach(function (f) { result = result.then(f);});return result; You can make this slightly more compact using reduce: return funcs.reduce(function (soFar, f) { return soFar.then(f);}, Q(initialVal)); Or, you could use th ultra-compact version: return funcs.reduce(Q.when, Q()); There you have it. Straight from the horse's mouth.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19098985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1455910/']}
jdg_74121
stackexchange
llm_judgeable_groundtruth_similarity
6250685
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 simple input field for an int variable. I want to add validation to it but, but i see no need to create my own validator for it, since the only thing i need is to avoid negative values and characters other than numbers. So this is what i did: <h:inputText id="price" value="#{placeAddControler.price}"> <f:validateLongRange minimum="0"/></h:inputText> <h:outputText value="€" /><br/><span style="color: red;"><b><h:message for="price"showDetail="true" /></b></span> When i try how it works this is the result for negative values: And this is the result for characters: Where in my project can i customize the text of those validation messages? Now provide the response and nothing else.
To change these values you basically have to define your own Resources file, override the properties you want custom messages for and register it in web.xml. This link seems to explain it well, so I've included this rather than try and rewrite the content. For a simpler solution and as you are JSF 2 you can also use these attributes of the inputText component: requiredMessage="I am a custom message"converterMessage="I am a custom message"validatorMessage="I am a custom message" This will override any message which the validator itself spits out. But I'd prefer the Resource bundle, as that promotes consistency of user visible error messages across your application.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6250685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/614141/']}
jdg_74122
stackexchange
llm_judgeable_groundtruth_similarity
31042827
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 found the following construct today in someone elses code: try: True, Falseexcept NameError: True = 1==1; False = 1==0 As I understand this, it defines True and False if they are not defined already. So if they are defined it shouldn't throw the NameError -Exception, right? I have tryed this for myself in a shell and it shows me SyntaxError: can't assign to keyword My question is why does it even shot the syntax error if True and False are defined? If True and False are available on my system, shouldn't it just go past the exception handling and not show a syntax error? Now provide the response and nothing else.
This code is written for Python 2.x and won't work on Python 3.x (in which True and False are true keywords). Since True and False are keywords in Python 3, you'll get a SyntaxError which you cannot catch. This code exists because of very old versions of Python. In Python 2.2 (released in 2001!), True and False did not exist as predefined names, so this code would provide compatible definitions so that later code could simply use True and False . When converting your Python 2.x code to Python 3.x, remove these lines; they are historical and have no use in Python 3.x. If you see these lines in someone else's code, they are a sure sign that the program was not written or ported for Python 3.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31042827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3944421/']}
jdg_74123
stackexchange
llm_judgeable_groundtruth_similarity
3864711
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 find the maximum size of the integral $\int_0^1 f(x)f^{-1}(x)\ \mathrm dx$ for differentiable, increasing $f$ with $f(0)=0$ and $f(1)=1$ . I made up this exercise for myself and thought it would be easy, but I can't do it. I feel the answer should be $\frac 1 3$ intuitively, which comes from $f(x)=x$ . So far I've tried integration by parts but then I don't know what to do. Edit: here is the integration by parts I tried, though I think it doesn't lead anywhere: $$\int^1_0 f(x)f^{-1}(x)\ \mathrm dx=\int_0^1f^{-1}(x)\ \mathrm dx-\int_0^1f'(x)\left(\int_0^x f^{-1}(t)\ \mathrm dt\right)\ \mathrm dx\text.$$ I thought this could help because $f'(x)>0$ since $f$ is increasing and the other factor in this integral is also positive by default. Now provide the response and nothing else.
The answer is indeed 1/3, which can be proved using the Fenchel-Young inequality for Legendre transforms. Define $F(t):=\int_0^t f(x)dx$ so that $F$ is convex on $[0,1]$ . The Legendre transform of $F$ is given by $G(t)=\sup_{u\in [0,1]} (tu-F(u))=\int_0^t f^{-1}(x)dx$ for $t \in [0,1]$ . Young's inequality (also called Fenchel's inequality ) says that $ab \leq F(a)+G(b)$ for any $a,b \in [0,1]$ . Consequently we see that $f(x)f^{-1}(x)\leq F(f(x))+G(f^{-1}(x))$ . Now notice from Fubini that $$\int_0^1F(f(x))dx = \int_0^1\int_0^{f(x)}f(u)dudx $$ $$= \int_0^1 \int_0^1 f(u)1_{\{u<f(x)\}}dxdu=\int_0^1 f(u)(1-f^{-1}(u))du,$$ and symmetrically we obtain that $$\int_0^1G(f^{-1}(x))dx = \int_0^1 f^{-1}(u)(1-f(u))du.$$ Now integrating the identity $f(x)f^{-1}(x)\leq F(f(x))+G(f^{-1}(x))$ from $0$ to $1$ , we get that $$\int_0^1 f(x)f^{-1}(x)dx \leq \int_0^1 f(u)(1-f^{-1}(u))du+\int_0^1 f^{-1}(u)(1-f(u))du.$$ Since $\int_0^1f(u)du+\int_0^1 f^{-1}(u)du=1$ , the previous expression reduces to $$3\int_0^1 f(x)f^{-1}(x)dx\leq 1.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3864711', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/837080/']}
jdg_74124
stackexchange
llm_judgeable_groundtruth_similarity
2225351
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 a totally indirect way, I've proven to myself that $$\frac{1}{\sqrt{1-x}} = \frac{1}{2\pi}\int_0^{2\pi} \frac{d\theta}{1-x\cos^2\theta}.$$ The proof was by expanding the integrand as a power series in $x\cos^2\theta$, integrating term-by-term, and comparing to the binomial expansion of the left side. But I would like a direct proof. Do you know one? I would be happy either with a method based on antidifferentiation, or a contour integral, or a double integral resulting from squaring, or some other method I haven't thought of. I am just trying to avoid the power series in $x$. Now provide the response and nothing else.
$\cos^2{t}$ has period $\pi$, so the integral is the same as$$ \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} \frac{d\theta}{1-x\cos^2{\theta}} = \frac{1}{\pi}\int_{-\pi/2}^{\pi/2} \frac{\sec^2{\theta} \, d\theta}{\sec^2{\theta}-x}. $$It's pretty obvious what to do now I've written it like this: put $t=\tan{\theta}$, and the integral becomes$$ \frac{1}{\pi}\int_{-\infty}^{\infty} \frac{dt}{t^2+1-x}, $$and then we know that this evaluates to $1/\sqrt{1-x}$ in the usual way.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2225351', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13120/']}
jdg_74125
stackexchange
llm_judgeable_groundtruth_similarity
1091099
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Today I came across this question: you have a code static int counter = 0;void worker() { for (int i = 1; i <= 10; i++) counter++;} If worker would be called from two different threads, what value will counter have after both of them are finished? I know that actually it could be anything. But my internal guts tells me, that counter++ will most likely be translated into single assembler instruction, and if both threads are execute on the same core, counter will be 20. But what if those threads are run on different cores or processors, could there be a race condition in their microcode? Is one assembler instruction could always be viewed as atomic operation? Now provide the response and nothing else.
Specifically for x86, and regarding your example: counter++ , there are a number of ways it could be compiled. The most trivial example is: inc counter This translates into the following micro operations: load counter to a hidden register on the CPU increment the register store the updated register in counter This is essentially the same as: mov eax, counterinc eaxmov counter, eax Note that if some other agent updates counter between the load and the store, it won't be reflected in counter after the store. This agent could be another thread in the same core, another core in the same CPU, another CPU in the same system, or even some external agent that uses DMA (Direct Memory Access). If you want to guarantee that this inc is atomic, use the lock prefix: lock inc counter lock guarantees that nobody can update counter between the load and the store. Regarding more complicated instructions, you usually can't assume that they'll execute atomically, unless they support the lock prefix.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1091099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6258/']}
jdg_74126
stackexchange
llm_judgeable_groundtruth_similarity
11953352
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 Intel architecture IA32, instructions like movl, movw does not allow operands that are both memory locations. For example, instruction movl (%eax), (%edx) is not permitted. Why? Now provide the response and nothing else.
The answer involves a fuller understanding of RAM. Simply stated, RAM can only be in two states, read mode or write mode. If you wish to copy one byte in ram to another location, you must have a temporary storage area outside of RAM as you switch from read to write. It is certainly possible for the architecture to have such a RAM to RAM instruction, but it would be a high level instruction that in microcode would translate to copying of data from RAM to a register then back to RAM. Alternatively, it could be possible to extend the RAM controller to have such a temporary register just for this copying of data, but it wouldnt provide much of a benefit for the added complexity of CPU/Hardware interaction. EDIT: It is worth noting that recent advancements such as Hybrid Memory Cube and High Bandwidth Memory are achitectures in which the RAM topology has become more like PCI-e and direct RAM to RAM transfers are now possible, but that is due to the support logic for the technologies, not the RAM itself. In the CPU architecture, this would be in the form of huge blocks of RAM at a time, like DMA, and not in the form of a single instruction, plus the CPU cache behaves like traditional RAM so the architecture would have to abstract it as per my original explanation EDIT2: Per @PeterCordes comment, my original understanding was not entirely correct; x86 does in fact have a few memory to memory instructions. The real reason they are not available for most instructions (such as movl and movw) is to keep instruction encoding complexity low, but they could have implemented them. However, the basic idea in my original answer, that there is a temporary storage location outside of RAM in the form of a latch or register, is correct, but the idea that this is the reason why these instructions don't exist is not. Even older chips from the 1970s such as the 6502 and the 8086 have memory to memory instructions, and you could easily perform operations such as INC directly on a RAM location. This was accomplished by latching the memory fetch directly to the ALU and back out to memory again without going through a register used by the instruction set.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11953352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997505/']}
jdg_74127
stackexchange
llm_judgeable_groundtruth_similarity
1724255
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 recently discovered that 2 == [2] in JavaScript. As it turns out, this quirk has a couple of interesting consequences: var a = [0, 1, 2, 3];a[[2]] === a[2]; // this is true Similarly, the following works: var a = { "abc" : 1 };a[["abc"]] === a["abc"]; // this is also true Even stranger still, this works as well: [[[[[[[2]]]]]]] == 2; // this is true too! WTF? These behaviors seem consistent across all browsers. Any idea why this is a language feature? Here are more insane consequences of this "feature": [0] == false // trueif ([0]) { /* executes */ } // [0] is both true and false!var a = [0];a == a // truea == !a // also true, WTF? Now provide the response and nothing else.
You can look up the comparison algorithm in the ECMA-spec (relevant sections of ECMA-262, 3rd edition for your problem: 11.9.3, 9.1, 8.6.2.6). If you translate the involved abstract algorithms back to JS, what happens when evaluating 2 == [2] is basically this: 2 === Number([2].valueOf().toString()) where valueOf() for arrays returns the array itself and the string-representation of a one-element array is the string representation of the single element. This also explains the third example as [[[[[[[2]]]]]]].toString() is still just the string 2 . As you can see, there's quite a lot of behind-the-scene magic involved, which is why I generally only use the strict equality operator === . The first and second example are easier to follow as property names are always strings, so a[[2]] is equivalent to a[[2].toString()] which is just a["2"] Keep in mind that even numeric keys are treated as property names (ie strings) before any array-magic happens.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1724255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53926/']}
jdg_74128
stackexchange
llm_judgeable_groundtruth_similarity
3911400
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference? Will this suffice? void operate_on_matrix(char matrix[][20]); Now provide the response and nothing else.
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions: 1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's : #define ROWS 4#define COLS 5void func(int array[ROWS][COLS]){ int i, j; for (i=0; i<ROWS; i++) { for (j=0; j<COLS; j++) { array[i][j] = i*j; } }}void func_vla(int rows, int cols, int array[rows][cols]){ int i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { array[i][j] = i*j; } }}int main(){ int x[ROWS][COLS]; func(x); func_vla(ROWS, COLS, x);} 2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime. void func(int** array, int rows, int cols){ int i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { array[i][j] = i*j; } }}int main(){ int rows, cols, i; int **x; /* obtain values for rows & cols */ /* allocate the array */ x = malloc(rows * sizeof *x); for (i=0; i<rows; i++) { x[i] = malloc(cols * sizeof *x[i]); } /* use the array */ func(x, rows, cols); /* deallocate the array */ for (i=0; i<rows; i++) { free(x[i]); } free(x);} 3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays: void func(int* array, int rows, int cols){ int i, j; for (i=0; i<rows; i++) { for (j=0; j<cols; j++) { array[i*cols+j]=i*j; } }}int main(){ int rows, cols; int *x; /* obtain values for rows & cols */ /* allocate the array */ x = malloc(rows * cols * sizeof *x); /* use the array */ func(x, rows, cols); /* deallocate the array */ free(x);} 4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required. #include <stdio.h>#include <stdlib.h>#include <time.h>extern void func_vla(int rows, int cols, int array[rows][cols]);extern void get_rows_cols(int *rows, int *cols);extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);void func_vla(int rows, int cols, int array[rows][cols]){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { array[i][j] = (i + 1) * (j + 1); } }}int main(void){ int rows, cols; get_rows_cols(&rows, &cols); int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0])); /* error check omitted */ func_vla(rows, cols, array); dump_array("After initialization", rows, cols, array); free(array); return 0;}void dump_array(const char *tag, int rows, int cols, int array[rows][cols]){ printf("%s (%dx%d):\n", tag, rows, cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) printf("%4d", array[i][j]); putchar('\n'); }}void get_rows_cols(int *rows, int *cols){ srand(time(0)); // Only acceptable because it is called once *rows = 5 + rand() % 10; *cols = 3 + rand() % 12;} (See srand() — why call it only once? .)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3911400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459184/']}
jdg_74129
stackexchange
llm_judgeable_groundtruth_similarity
11397028
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 a sub-nav that works using jquery - A user clicks on the top level list item, for instance 'services' which triggers the dropdown. The dropdown toggles via clicking the 'service' link. I've made it so a user can click anywhere on the screen to toggle the dropdown to a closed state. But as the site is responsive i want the user to be able to click (touch) anywhere on the screen to close the dropdown but my problem is that it's not working on the touch devices. My code ive setup for the document click is: $(document).click(function(event) { if ( $(".children").is(":visible")) { $("ul.children").slideUp('slow'); }}); I'm assuming document.click might not work on touch devices, and if not, what work-around is there to achieve the same effect? Thanks Now provide the response and nothing else.
Update! In modern browsers, the click event will be fired for a tap, so you don't need to add extra touchstart or touchend events as click should suffice. This previous answer worked for a time with browsers that thought a tap was special. It originally included a "touch" event that actually was never standardised. Unless you have a problem with: $(document).on('click', function () { ... }); There is no need to change anything! Previous information, updated to remove touch ... To trigger the function with click or touch, you could change this: $(document).click( function () { To this: $(document).on('click touchstart', function () { The touchstart event fires as soon as an element is touched, so it may be more appropriate to use touchend depending on your circumstances.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11397028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1035147/']}
jdg_74130
stackexchange
llm_judgeable_groundtruth_similarity
10292
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a pair of Cisco 2960-X's in a stack configuration using stack modules. This gives me a total of 4, 10 gbps SFP+ slots. I am using interfaces Te1/0/1 and Te2/0/1 as 10 gbps uplinks to the core and previously had Te1/0/2 and Te2/0/2 open. Now I need to add a 1 gbps link coming off of one of these switches out to another device which only supports 1 gbps fiber SFP modules. I hooked up a 1 gbps SFP module to the Te2/0/2 interface, however it continued to show the type as "Not Present". After working at it for a bit I reloaded the switch to find that the list of interfaces had changed to now show a Gi2/0/49 and Gi2/0/50 while now missing Te2/0/2 . (As a side note the Gi2/0/49 interface shows "Not Present" while the Te2/0/1 interface shows the 10 gbps SFP+ module). Gi2/0/50 now shows the 1 gbps SFP and works correctly. Is there any way for the switch to perform this detection process without having to reboot it? I may have to swap these around again in the near future and I would rather not cause downtime for the other systems that are plugged into that switch if it can be avoided. Now provide the response and nothing else.
Maybe these bugs are affecting you: CSCuj74167 (Gigabyte link from WS-C2960X-48FPD-L not coming up when using GLC-SX-MM) applies to you. Fixed in software release 15.0(2)EX4. CSCul88801 (1G or 10G in uplink ports of a Catalyst 2960x stack may not come up after a reload or OIR of SFP/SFP+. 1G or 10G SFP appear as “unknown” in the output of the show int status command.). Fixed in software release 15.0(2)EX5. So before looking any further, I'd upgrade to at least 15.0(2)EX5. (Which is the latest stable available for 2960X as of this writing).
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/10292', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/5613/']}
jdg_74131
stackexchange
llm_judgeable_groundtruth_similarity
112747
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: Good Morning I have the following dataset: And I try to reach this output: key: only one row per key text: join all texts of the rows with the same key (but no duplicates) min: take the lowest value (but not empty) of the rows with the same key max: take the highest value (but not empty) of the rows with the same key I used dataInput[GroupBy[{#key} &]] but then I got stuck.I tried to apply Union , Max and Min for individual rows but somehow I don't manage to generalize it. Other attempts: dataInput[GroupBy[#key &], MaximalBy[#max &]&&MinimalBy[#min&] // Values // Flatten Query[GroupBy["key"], Catenate, "text"] @ dataInput JoinAcross[dataInput, Key[key], "Inner", KeyCollisionFunction -> Function[x, Max[x]]] Now provide the response and nothing else.
dataset = Dataset[{ <|"key" -> "abc", "text" -> "h", "min" -> 1, "max" -> 5|>, <|"key" -> "abc", "text" -> "a", "min" -> 1, "max" -> 5|>, <|"key" -> "aaa", "text" -> "h", "min" -> 2, "max" -> 3|>, <|"key" -> "aaa", "text" -> "e", "min" -> 2, "max" -> 4|>, <|"key" -> "aaa", "text" -> "a", "min" -> 1|>, <|"key" -> "aaa", "text" -> "a", "max" -> 4|>}] dataset2 = Merge[#, DeleteDuplicates] & /@ Values[GroupBy[dataset, Key["key"]]] dataset2[All, {"key" -> First, "min" -> Min, "max" -> Max}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/112747', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/39472/']}
jdg_74132
stackexchange
llm_judgeable_groundtruth_similarity
38666
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was analyzing the classifier created using a decision tree. There is a tuning parameter called max_depth in scikit's decision tree. Is this equivalent of pruning a decision tree? If not, how could I prune a decision tree using scikit? dt_ap = tree.DecisionTreeClassifier(random_state=1, max_depth=13)boosted_dt = AdaBoostClassifier(dt_ap, random_state=1)boosted_dt.fit(X_train, Y_train) Now provide the response and nothing else.
Is this equivalent of pruning a decision tree? Though they have similar goals (i.e. placing some restrictions to the model so that it doesn't grow very complex and overfit), max_depth isn't equivalent to pruning. The way pruning usually works is that go back through the tree and replace branches that do not help with leaf nodes. If not, how could I prune a decision tree using scikit? You can't through scikit-learn (without altering the source code). Quote taken from the Decision Tree documentation : Mechanisms such as pruning (not currently supported) If you want to post-prune a tree you have to do it on your own: You can read this excellent post detailing how to do so.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/38666', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/47403/']}
jdg_74133
stackexchange
llm_judgeable_groundtruth_similarity
29968130
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use the range slider from the zurb foundation framework with Ember. I want a slider next to an input field, both of them showing the same value updating each other so a user would be able to enter either a number by hand or use the slider to set a score for a game played in the past. My template looks like this: {{input type="text" id="new-game-score" value=newGameScore}}<div class="range-slider" data-slider={{newGameScore}} data-options="start: 0; end: 16;"> <span class="range-slider-handle" tabindex="0" role="slider"></span> <span class="range-slider-active-segment"></span></div> And in the controller I'm calling this.get('newGameScore'); to get the value for the creation of the model. When I open the template I get a text-input that behaves like I expect. It allows to set the score for the creation of the model. The data-slider -attribute of the slider next to it gets updated correctly, but it doesn't change how the slider looks and I can't move the slider at all.When I set newGameScore as a function returning a number in the controller both the slider and the input field start out with the set value and I can move the slider. Moving it does not change the value of the input field though, while entering a number in the text field adjusts the data-slider -value without any visible change on the slider. The number used for the creation of the new model is the one from the text input. I'm using ember-cli and installed foundation with ember install ember-cli-foundation-sass .I have var app = new EmberApp({ 'ember-cli-foundation-sass': { 'modernizr': true, 'fastclick': true, 'foundationJs': 'all' }}); in my Brocfile and the corresponding view looks like this: export default Ember.View.extend({ didInsertElement: function() { this.$().foundation(); }}); The controller is an ArrayController with the template showing all the games with their scores. I would like to keep at that way if possible. I started out using the zurb foundation documentation: http://foundation.zurb.com/docs/components/range_slider.html and found the following solution to a more complicated but closely related problem: http://danahartweg.com/foundation-5-sliders-in-dropdowns-using-emberjs but I couldn't figure out how to properly synchronise the slider with newGameScore . http://danahartweg.com/foundation-5-sliders-in-dropdowns-using-emberjs states at the beginning of the article that ember with a foundation-slider is easy to do. So I assume I don't have to write custom on-change-functions to solve my problem, but maybe someone more experienced with ember can find a solution from bottom part of the article, although it seemed to me that this is only needed for the combination of the dropdown and the slider. Thanks for reading and for any idea about this.regards,Andy Now provide the response and nothing else.
First of all it's not a Y2K issue at all! ( UPDATE: in some cases - it's related to Y2K issues, but it's not the problem here ) The correct answer is that you can't do that reliably . Does Daylight saving time apply to year 1? How many Leap Years were there? Were there any? Etc. But the answer by @Daniel will use it! UPDATE: not to mention @MattJohnson post about DST. DST in year 1, actually JS (ES5 anyway) will lie and use the current DST rule for all years So please don't fool yourself with the idea that you can reliably work with dates lower than 1970. (You will have a lot of problems and surprises even in that time range.) But if you really, really need to you can use new Date('0001-01-01') (ISO 8601 format) or @Daniel's method: var d = new Date(); d.setFullYear(1); But before you use it read this... There are 4 ways to create a Date in JS: new Date()new Date(milliseconds)new Date(dateString)new Date(year, month, day, hours, minutes, seconds, milliseconds) 1) new Date() creates current date ( in your local timezone ) so we are not interested in it for now. 2) new Date(number) creates a new date object as zero time plus the number. Zero time is 01 January 1970 00:00:00 UTC. So in this case time in JS counting from year 1970. (new Date(0)).toUTCString()"Thu, 01 Jan 1970 00:00:00 GMT If you use negative number you can go "back" it time before 1970 (new Date(-62167219200000)).toUTCString()"Sat, 01 Jan 0 00:00:00 GMT"-62167219200000 <- milliseconds-62167219200000 / 1000-62167219200 <- seconds-62167219200 / 60-1036120320 <- minutes-1036120320 / 60-17268672 <- hours-17268672 / 24-719528 <- days-719528 / 365-1971.309589041096 <- years ( this is roughly calculated value ) The problem is that it's not reliable. How many Leap Years were there? Were there any? Daylight saving time? Etc. And I don't like it because of this magic number -62167219200000 3) new Date(dateString) This is most 'reliable' way. DateString - A string representing an RFC2822 or ISO 8601 date. RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g. "Mon, 25 Dec 1995 13:30:00 GMT" The problem with it is that if you use negative number you will get an incorrect Date with NaN in a result of all methods (new Date('01 January -1 00:00:00 UTC')).getFullYear()NaN If you use year higher or equal 0 and lower then 50 then 2000 will be added automatically. (new Date('01 January 0 00:00:00 UTC')).getFullYear()2000(new Date('01 January 1 00:00:00 UTC')).getFullYear()2001(new Date('01 January 10 00:00:00 UTC')).getFullYear()2010(new Date('01 January 01 00:00:00 UTC')).getFullYear()2001(new Date('01 January 30 00:00:00 UTC')).getFullYear()2030(new Date('01 January 49 00:00:00 UTC')).getFullYear()2049 And if you use year higher or equal 50 and lower then 100 then 1900 will be added. (new Date('01 January 50 00:00:00 UTC')).getFullYear()1950(new Date('01 January 51 00:00:00 UTC')).getFullYear()1951(new Date('01 January 90 00:00:00 UTC')).getFullYear()1990(new Date('01 January 99 00:00:00 UTC')).getFullYear()1999 Years equal 100 or higher will get correct year number (new Date('01 January 100 00:00:00 UTC')).getFullYear()100(new Date('01 January 101 00:00:00 UTC')).getFullYear()101(new Date('01 January 999 00:00:00 UTC')).getFullYear()999(new Date('01 January 9999 00:00:00 UTC')).getFullYear()9999 So we can't create year 1 using RFC2822 / IETF date syntax About ISO 8601: http://www.w3.org/TR/NOTE-datetime The actual formats are Year: YYYY (eg 1997)Year and month: YYYY-MM (eg 1997-07)Complete date: YYYY-MM-DD (eg 1997-07-16)Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) We are most interested in 'Complete date' (new Date('0001-01-01')).toUTCString()"Mon, 01 Jan 1 00:00:00 GMT" Yahoo!!! ( or it is better to say Google! :) ), we can use ISO 8601 to create date with year 1 But be careful and do not try to use negative numbers or short year numbers, as parsing of those will may vary on localization or just insanity :) (new Date('-0001-01-01')).toUTCString()"Sun, 31 Dec 2000 21:00:00 GMT"(new Date('01-01-01')).toUTCString()"Sun, 31 Dec 2000 21:00:00 GMT"(new Date('02-01-01')).toUTCString()"Wed, 31 Jan 2001 21:00:00 GMT"(new Date('02-01-05')).toUTCString()"Mon, 31 Jan 2005 21:00:00 GMT" 4) new Date(year, month, day, hours, minutes, seconds, milliseconds) To use this one you have to pass two parameters ( year, and month ), all other will be optional. Be careful because here month will start from 0 to 11, not like everywhere else. WAT? o_O WARNING! This date will be created in your current time zone!!! So be careful using it! UPD: clarification by @matt-johnson ...actually the Date object always reflects the local time zone. You can't place it in another time zone, and even if you initialize it with a UTC timestamp, it will still reflect back the local time zone in most of the functions. Internally it tracks UTC by the numeric timestamp, and there are functions that expose UTC values explicitly, but everything else is local. The negative numbers will be interpreted as negative years (new Date(-1, 0)).toString()"Fri Jan 01 -1 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(-234, 0)).toString()"Wed Jan 01 -234 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)" The numbers from 0 to 99 will be incremented by 1900 automatically (new Date(0, 0)).toString()"Mon Jan 01 1900 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(1, 0)).toString()"Tue Jan 01 1901 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(11, 0)).toString()"Sun Jan 01 1911 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(50, 0)).toString()"Sun Jan 01 1950 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(99, 0)).toString()"Fri Jan 01 1999 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)" The numbers from 100 to 275760 will be interpreted as year numbers (new Date(100, 0)).toString()"Fri Jan 01 100 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(102, 0)).toString()"Sun Jan 01 102 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(2002, 0)).toString()"Tue Jan 01 2002 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)" And numbers higher then 275760 will be Invalid date (new Date(275760, 0)).toString()"Tue Jan 01 275760 00:00:00 GMT+0300 (Russia TZ 2 Standard Time)"(new Date(275761, 0)).toString()"Invalid Date" UPD: new Date(Date.UTC(1,1,1)) will safer from same symptoms as new Date(year, month, day, hours, minutes, seconds, milliseconds). Because of Date.UTC function.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29968130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827172/']}
jdg_74134
stackexchange
llm_judgeable_groundtruth_similarity
18190148
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 populate a span tag that i was to insert into my page with jquery. i tried this var span = $('<span />').attr({'className':'folder_name' , 'text':'favre' });var insert=$('<div/>', { className: "folder", html: span}); which yielded this result. <div classname="folder"><span classname="folder_name" text="favre"></span></div> then i tried this var span = $('<span />').attr({'className':'folder_name', 'html':'Elway' }); which yielded this <div classname="folder"> <span classname="folder_name" html="Elway"></span> </div> what i am trying to get is below <div classname="folder"> <span classname="folder_name" >**Elway**</span> </div> Now provide the response and nothing else.
The HTML of an object is not an attribute and needs to be supplied separately: var span = $('<span />').attr('className', 'folder_name').html('Elway'); Also, className is not a valid attribute, do you mean class instead, if so use this: var span = $('<span />').addClass('folder_name').html('Elway');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18190148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1255713/']}
jdg_74135
stackexchange
llm_judgeable_groundtruth_similarity
42754868
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 you add an event to the user's calendar, but then allow the user to choose the calendar, etc. I have this code that works, but this adds the event to the user's default calendar. How do I allow the user to change the calendar, customize the alerts etc? I have seen other apps open the calendar app and pre-fill the fields. //add to calendar let eventStore : EKEventStore = EKEventStore() eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted, error) in if granted && error == nil { let event:EKEvent = EKEvent(eventStore: eventStore) event.title = "My event: " + self.event.name event.startDate = self.event.startTime event.endDate = self.event.endTime event.notes = self.event.description event.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.saveEvent(event, span: .ThisEvent, commit: true) self.dismissViewControllerAnimated(true, completion: {}) } catch { self.dismissViewControllerAnimated(true, completion: {}) } } else { self.dismissViewControllerAnimated(true, completion: {}) } }) Now provide the response and nothing else.
You can use Apple's native calendar API. Use EKEventEditViewController in the EventKitUI framework , and the user will be able to specify the calendar when saving the event. In Swift 3: import UIKitimport EventKitimport EventKitUIclass ViewController: UIViewController { let store = EKEventStore() func createEvent() { // create the event object let event = EKEvent(eventStore: store) event.title = "Foo" event.startDate = ... event.endDate = ... // prompt user to add event (to whatever calendar they want) let controller = EKEventEditViewController() controller.event = event controller.eventStore = store controller.editViewDelegate = self present(controller, animated: true) }}extension ViewController: EKEventEditViewDelegate { func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) { controller.dismiss(animated: true) }} In Swift 2.3: import UIKitimport EventKitimport EventKitUIclass ViewController: UIViewController { let store = EKEventStore() func createEvent() { // create the event object let event = EKEvent(eventStore: store) event.title = "Foo" event.startDate = ... event.endDate = ... // prompt user to add event (to whatever calendar they want) let controller = EKEventEditViewController() controller.event = event controller.eventStore = store controller.editViewDelegate = self presentViewController(controller, animated: true, completion: nil) }}extension ViewController: EKEventEditViewDelegate { func eventEditViewController(controller: EKEventEditViewController, didCompleteWithAction action: EKEventEditViewAction) { controller.dismissViewControllerAnimated(true, completion: nil) }} This assumes that you've supplied a NSCalendarsUsageDescription in your Info.plist , that you've requested access , etc.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42754868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/406322/']}
jdg_74136
stackexchange
llm_judgeable_groundtruth_similarity
2486277
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the differences of the C# and Java implementations of the generic List class? Now provide the response and nothing else.
Well, in Java List<T> is an interface, to start with :) The most important difference between the two is the difference between C# and Java generics to start with: in Java generics basically perform compile-time checks and include some metadata in generic fields etc - but the actual object doesn't know its generic type at execution time. You can't ask a List<?> what that ? is, in other words. Any references to a generic type parameter in the implementation act as Object , basically - so a ArayList<String> is really backed by an Object[] . In C# all the information is available at execution time too - so a List<string> is backed by a string[] . Similarly C# generics allow value type type arguments, so you can have a List<int> in C# but not in Java. There are further differences in terms of variance etc - but this is moving a long way from List<T> . In terms of just ArrayList<T> (Java) and List<T> (.NET), a couple of differences: Java lists override equals/hashCode, whereas they don't in .NET ArrayList<T> grows by multiplying the current capacity by 3/2; .NET's List<T> doubles the current capacity instead Of course there are other differences in terms of the APIs exposed - if you could give more information about the kind of difference you're interested in, we could help more.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2486277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298329/']}
jdg_74137
stackexchange
llm_judgeable_groundtruth_similarity
25962595
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 implement a a progress bar to indicate the progress of a multipart file upload. I have read from a comment on this answer - https://stackoverflow.com/a/24285633/1022454 that I have to wrap the sink passed to the RequestBody and provide a callback that tracks the bytes moved. I have created a custom RequestBody and wrapped the sink with a CustomSink class, however through debugging I can see that the bytes are being written by RealBufferedSink ln 44 and the custom sink write method is only run once, not allowing me to track the bytes moved. private class CustomRequestBody extends RequestBody { MediaType contentType; byte[] content; private CustomRequestBody(final MediaType contentType, final byte[] content) { this.contentType = contentType; this.content = content; } @Override public MediaType contentType() { return contentType; } @Override public long contentLength() { return content.length; } @Override public void writeTo(BufferedSink sink) throws IOException { CustomSink customSink = new CustomSink(sink); customSink.write(content); }}private class CustomSink implements BufferedSink { private static final String TAG = "CUSTOM_SINK"; BufferedSink bufferedSink; private CustomSink(BufferedSink bufferedSink) { this.bufferedSink = bufferedSink; } @Override public void write(Buffer source, long byteCount) throws IOException { Log.d(TAG, "source size: " + source.size() + " bytecount" + byteCount); bufferedSink.write(source, byteCount); } @Override public void flush() throws IOException { bufferedSink.flush(); } @Override public Timeout timeout() { return bufferedSink.timeout(); } @Override public void close() throws IOException { bufferedSink.close(); } @Override public Buffer buffer() { return bufferedSink.buffer(); } @Override public BufferedSink write(ByteString byteString) throws IOException { return bufferedSink.write(byteString); } @Override public BufferedSink write(byte[] source) throws IOException { return bufferedSink.write(source); } @Override public BufferedSink write(byte[] source, int offset, int byteCount) throws IOException { return bufferedSink.write(source, offset, byteCount); } @Override public long writeAll(Source source) throws IOException { return bufferedSink.writeAll(source); } @Override public BufferedSink writeUtf8(String string) throws IOException { return bufferedSink.writeUtf8(string); } @Override public BufferedSink writeString(String string, Charset charset) throws IOException { return bufferedSink.writeString(string, charset); } @Override public BufferedSink writeByte(int b) throws IOException { return bufferedSink.writeByte(b); } @Override public BufferedSink writeShort(int s) throws IOException { return bufferedSink.writeShort(s); } @Override public BufferedSink writeShortLe(int s) throws IOException { return bufferedSink.writeShortLe(s); } @Override public BufferedSink writeInt(int i) throws IOException { return bufferedSink.writeInt(i); } @Override public BufferedSink writeIntLe(int i) throws IOException { return bufferedSink.writeIntLe(i); } @Override public BufferedSink writeLong(long v) throws IOException { return bufferedSink.writeLong(v); } @Override public BufferedSink writeLongLe(long v) throws IOException { return bufferedSink.writeLongLe(v); } @Override public BufferedSink emitCompleteSegments() throws IOException { return bufferedSink.emitCompleteSegments(); } @Override public OutputStream outputStream() { return bufferedSink.outputStream(); }} Does anybody have an example of how I would go about doing this? Now provide the response and nothing else.
You have to create a custom RequestBody and override writeTo method, and there you have to send your files down the sink in segments. It is very important that you flush the sink after each segment, otherwise your progress bar will fill up quickly without the file being actually sent over the network, because the contents will stay in the sink (which acts like a buffer). public class CountingFileRequestBody extends RequestBody { private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE private final File file; private final ProgressListener listener; private final String contentType; public CountingFileRequestBody(File file, String contentType, ProgressListener listener) { this.file = file; this.contentType = contentType; this.listener = listener; } @Override public long contentLength() { return file.length(); } @Override public MediaType contentType() { return MediaType.parse(contentType); } @Override public void writeTo(BufferedSink sink) throws IOException { Source source = null; try { source = Okio.source(file); long total = 0; long read; while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { total += read; sink.flush(); this.listener.transferred(total); } } finally { Util.closeQuietly(source); } } public interface ProgressListener { void transferred(long num); }} You can find a complete implementation that supports displaying progress in an AdapterView and also cancelling uploads at my gist: https://gist.github.com/eduardb/dd2dc530afd37108e1ac
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25962595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1022454/']}
jdg_74138
stackexchange
llm_judgeable_groundtruth_similarity
2452226
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Somehow my master and my origin/master branch have diverged. I actually don't want them to diverge. How can I view these differences and merge them? Now provide the response and nothing else.
You can review the differences with a: git log HEAD..origin/main# old repositoriesgit log HEAD..origin/master before pulling it (fetch + merge) (see also "How do you get git to always pull from a specific branch?" ) Note: since Git 2.28 (Q3 2020) , the default branch is configurable, and now (2021+) set to main , no longer master . The rest of the answer reflects that more recent convention. When you have a message like: "Your branch and 'origin/main' have diverged, # and have 1 and 1 different commit(s) each, respectively." Check if you need to update origin . If origin is up-to-date, then some commits have been pushed to origin from another repo while you made your own commits locally. ... o ---- o ---- A ---- B origin/main (upstream work) \ C main(your work) You based commit C on commit A because that was the latest work you had fetched from upstream at the time. However, before you tried to push back to origin , someone else pushed the commit B . Development history has diverged into separate paths. You can then merge or rebase. See Pro Git: Git Branching - Rebasing for details. Merge Use the git merge command: $ git merge origin/main# old repositories$ git merge origin/master This tells Git to integrate the changes from origin/main into your work and create a merge commit. The graph of history now looks like this: ... o ---- o ---- A ---- B origin/main (upstream work) \ \ C ---- M main (your work) The new merge, commit M , has two parents, each representing one path of development that led to the content stored in that commit. Note that the history behind M is now non-linear. Rebase Use the git rebase command: $ git rebase origin/main# old repositories$ git rebase origin/master This tells Git to replay commit C (your work) as if you had based it on commit B instead of A . CVS and Subversion users routinely rebase their local changes on top of upstream work when they update before commit. Git just adds explicit separation between the commit and rebase steps. The graph of history now looks like this: ... o ---- o ---- A ---- B origin/main (upstream work) \ C' main (your work) Commit C' is a new commit created by the git rebase command. It is different from C in two ways: It has a different history: B instead of A . Its content accounts for changes in both B and C ; it is the same as M from the merge example. Note that the history behind C' is still linear. We have chosen (for now) to allow only linear history in cmake.org/cmake.git . This approach preserves the CVS-based workflow used previously and may ease the transition. An attempt to push C' into our repository will work (assuming you have permissions and no one has pushed while you were rebasing). The git pull command provides a shorthand way to fetch from origin and rebase local work on it: $ git pull --rebase This combines the above fetch and rebase steps into one command.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/2452226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209320/']}
jdg_74139
stackexchange
llm_judgeable_groundtruth_similarity
2759933
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 tried to prove that the following rational fraction can be divided only when n=1,2,5 without using mathematical induction or function, just by using basic method. $$\frac{n^2+2}{2n-1}$$ this expression can be divided only when the remainder of $$\frac{n^2}{2n-1}$$ is $$\frac{2n-3}{2n-1}$$ and the quotient of the following expression $$\frac{n^2}{2n-1}$$ has the same quotient with the following expression, except in the case of n=1$$\frac{n^2}{2n}$$ because when some dividend is divided by these two different divisor, in order to $$2n-1$$ has much more quotient than $$2n$$ It's necessary to meet particular condition that when dividend is greater than or equal to $$2n$$ also when the dividend is greater than or equal to $$(2n)(2n-1)$$ then $$2n-1$$ can has much more quotient than $$2n$$ and when the dividend is less than $$2n$$ also when the value of the dividend is equal to the value of $$2n-1$$ then $$2n-1$$ can has much more quotient than $$2n$$ So $$n^2$$ is greater than or equal to $$2n$$ except when n=1, and when n=1, the value of $$n^2$$ is less than $$2n$$ and is equal to the value of $$2n-1$$ So when n=1, $$2n-1$$ has much more quotient than $$2n$$ and when n>1, $$n^2$$ is greater than or equal to $$2n$$ and is less than $$(2n)(2n-1)$$ So $$\frac{n^2}{2n-1}$$ has the same quotient with $$\frac{n^2}{2n}$$ except in the case of n=1. and $$\frac{n^2}{2n}=\frac{n}{2}$$ so the quotient of $$\frac{n}{2}$$ can be expressed by a formula $$\frac{n}{2}-\frac{1+(-1)^{n+1}}{4}$$ and in the following expression$$\frac{n}{2}$$ when n is even number there is no remainder and when n is odd number the remainder is always $$\frac{1}{2}$$ It also can be expressed as $$\frac{n}{2n}$$ and in the following expression $$\frac{n^2}{2n-1}$$ when n is even number the remainder of the expression is as much as Its quotient. and when n is odd number the remainder of the division is $$n+quotient$$ now I can answer the question about when the remainder become $$2n-3$$ is, by using the formula $$\frac{n}{2}-\frac{1+(-1)^{n+1}}{4}$$ when n is even number It can be expressed as $$\frac{n}{2}-\frac{1+(-1)^{n+1}}{4}=2n-3$$ this equation can be changed into $$12-(1+(-1)^{n+1})=6n$$ by multiplying both sides by 4 and by transposition. and when n is odd number, It can be expressed as $$n+\frac{n}{2}-\frac{1+(-1)^{n+1}}{4}=2n-3$$ this equation can be changed into $$12-(1+(-1)^{n+1})=2n$$ so, the following expression $$\frac{n^2+2}{2n-1}$$ is can be divided only when n=2,5 but this equation works only when n>1. and when=1 the expression can be divided. so this is what I tried to prove the question. I wanna know this proof is correct or incorrect, Could you please check my proof? roughly If you want. and I wanna know this kind of approach is proper or not when I'm gonna study advanced mathematics. Now provide the response and nothing else.
I would suggest the following approach : First consider $(2n-1)(2n+1)=4n^2-1$ hence we have $$4\cdot \frac{n^2+2}{2n-1}=\frac{4n^2+8}{2n-1}=\frac{4n^2-1}{2n-1}+\frac{9}{2n-1}=2n+1+\frac{9}{2n-1}$$ Since $2n-1$ is odd, it must divide $n^2+2$ , if it divides $4(n^2+2)$ (try to find out why), hence you only have to check for which $n$ we have $2n-1|9$. Try to solve this.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2759933', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/556999/']}
jdg_74140