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
406
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: If I have a retail store and have a way to measure how many people enter my store every minute, and timestamp that data, how can I predict future foot traffic? I have looked into machine learning algorithms, but I'm not sure which one to use. In my test data, a year over year trend is more accurate compared to other things I've tried, like KNN (with what I think are sensible parameters and distance function). It almost seems like this could be similar to financial modeling, where you deal with time series data. Any ideas? Now provide the response and nothing else.
The problem with models like KNN is that they do not take into account seasonality (time-dependent variations in trend). To take those into account, you should use Time Series analysis. For count data, such as yours, you can use generalized linear auto-regressive moving average models (GLARMA). Fortunately, there is an R package that implements them ( glarma ). The vignette is a good resource for the theory behind the tool.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/406', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/886/']}
jdg_72441
stackexchange
llm_judgeable_groundtruth_similarity
6358797
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a custom list view. I want to show a CheckBox at the custom view. There is no text for the CheckBox . I found it always have some spaces at the right of the CheckBox . Here is my layout xml file: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="wrap_content"android:orientation="horizontal" android:background="#fa9654"android:paddingTop="65dp" android:paddingBottom="65dp"><TextView android:id="@+id/bus_route_list_item_num" android:layout_height="wrap_content" android:layout_width="0dip" android:gravity="center" android:layout_gravity="center_vertical|center_horizontal" android:layout_weight="0.15"></TextView><TextView android:id="@+id/bus_route_list_item_station" android:layout_height="wrap_content" android:layout_width="0dip" android:gravity="left" android:layout_gravity="center_vertical|center_horizontal" android:layout_weight=".5"></TextView><TextView android:id="@+id/bus_route_list_item_fee" android:layout_height="wrap_content" android:layout_width="0dip" android:gravity="center" android:layout_gravity="center_vertical|center_horizontal" android:layout_weight=".15"></TextView><CheckBox android:id="@+id/bus_route_list_item_reminder" android:layout_height="wrap_content" android:layout_width="0dip" android:layout_weight=".20" android:gravity="center" android:layout_gravity="center" android:paddingRight="0dp" android:paddingLeft="0dp" android:paddingTop="0dp" android:paddingBottom="0dp" android:background="#0066ff" android:text=""/></LinearLayout> The result looks like: As you can see there are some space at the right of the checkbox. What I want is put the checkbox at the middle of the blue area. Is it possible to remove the unwanted space? thanks Now provide the response and nothing else.
You can wrap CheckBox in LinearLayout and then use android:gravity="center" on that layout. <LinearLayout android:layout_height="wrap_content" android:layout_width="0dip" android:layout_weight=".20" android:background="#ff0000" android:gravity="center"> <CheckBox android:id="@+id/bus_route_list_item_reminder" android:layout_height="wrap_content" android:layout_width="wrap_content" /></LinearLayout> As another alternative, you can use RelativeLayout . This would greatly simplify you layout and you will be able to get rid of layout_weight .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6358797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/767987/']}
jdg_72442
stackexchange
llm_judgeable_groundtruth_similarity
2285045
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: NoSQL refers to non-relational data stores that break with the history of relational databases and ACID guarantees. Popular open source NoSQL data stores include: Cassandra (tabular, written in Java, used by Cisco, WebEx, Digg, Facebook, IBM, Mahalo, Rackspace, Reddit and Twitter) CouchDB (document, written in Erlang, used by BBC and Engine Yard) Dynomite (key-value, written in Erlang, used by Powerset) HBase (key-value, written in Java, used by Bing) Hypertable (tabular, written in C++, used by Baidu) Kai (key-value, written in Erlang) MemcacheDB (key-value, written in C, used by Reddit) MongoDB (document, written in C++, used by Electronic Arts, Github, NY Times and Sourceforge) Neo4j (graph, written in Java, used by some Swedish universities) Project Voldemort (key-value, written in Java, used by LinkedIn) Redis (key-value, written in C, used by Craigslist, Engine Yard and Github) Riak (key-value, written in Erlang, used by Comcast and Mochi Media) Ringo (key-value, written in Erlang, used by Nokia) Scalaris (key-value, written in Erlang, used by OnScale) Terrastore (document, written in Java) ThruDB (document, written in C++, used by JunkDepot.com) Tokyo Cabinet/Tokyo Tyrant (key-value, written in C, used by Mixi.jp (Japanese social networking site)) I'd like to know about specific problems you - the SO reader - have solved using data stores and what NoSQL data store you used. Questions: What scalability problems have you used NoSQL data stores to solve? What NoSQL data store did you use? What database did you use prior to switching to a NoSQL data store? I'm looking for first-hand experiences, so please do not answer unless you have that. Now provide the response and nothing else.
I've switched a small subproject from MySQL to CouchDB, to be able to handle the load. The result was amazing. About 2 years ago, we've released a self written software on http://www.ubuntuusers.de/ (which is probably the biggest German Linux community website). The site is written in Python and we've added a WSGI middleware which was able to catch all exceptions and send them to another small MySQL powered website. This small website used a hash to determine different bugs and stored the number of occurrences and the last occurrence as well. Unfortunately, shortly after the release, the traceback-logger website wasn't responding anymore. We had some locking issues with the production db of our main site which was throwing exceptions nearly every request, as well as several other bugs, which we haven't explored during the testing stage. The server cluster of our main site, called the traceback-logger submit page several k times per second. And that was a way too much for the small server which hosted the traceback logger (it was already an old server, which was only used for development purposes). At this time CouchDB was rather popular, and so I decided to try it out and write a small traceback-logger with it. The new logger only consisted of a single python file, which provided a bug list with sorting and filter options and a submit page. And in the background I've started a CouchDB process. The new software responded extremely quickly to all requests and we were able to view the massive amount of automatic bug reports. One interesting thing is, that the solution before, was running on an old dedicated server, where the new CouchDB based site on the other hand was only running on a shared xen instance with very limited resources. And I haven't even used the strength of key-values stores to scale horizontally. The ability of CouchDB / Erlang OTP to handle concurrent requests without locking anything was already enough to serve the needs. Now, the quickly written CouchDB-traceback logger is still running and is a helpful way to explore bugs on the main website. Anyway, about once a month the database becomes too big and the CouchDB process gets killed. But then, the compact-db command of CouchDB reduces the size from several GBs to some KBs again and the database is up and running again (maybe i should consider adding a cronjob there... 0o). In a summary, CouchDB was surely the best choice (or at least a better choice than MySQL) for this subproject and it does its job well.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2285045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58394/']}
jdg_72443
stackexchange
llm_judgeable_groundtruth_similarity
2284446
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All, I am starting to write object-oriented R code for the first time and anticipate having multiple R files with dependencies in between. I'm new to R and have not yet wrote anything outside of a single massive script to test ideas. Are there resources online that give tips on how one ought to organize code? Short of descriptions on how to build packages, I'm failing to find such guidance. At this point, I just want to organize the code in such a way that it makes loading and interacting with the collection of routines as straightforward as possible. Appreciate any guidance you can provide. Chris Now provide the response and nothing else.
This question is very closely related to: "How to organize large R programs?" You should consider creating an R package. You can use the package.skeleton function to start with given a set of R files. I also strongly recommend using roxygen to document the package at the beginning, because it's much more difficult to do it after the fact. Read "Writing R Extensions" . The online book "Statistics with R" has a section on this subject . Also take a look at Creating R Packages: A Tutorial by Friedrich Leisch. Lastly, if you're in NY, come to the upcoming NY use-R group meeting on "Authoring R Packages: a gentle introduction with examples" . Just to rehash some suggestions about good practices: A package allows you to use R CMD check which is very helpful at catching bugs; separately you can look at using the codetools package. A package also forces you to do a minimal amount of documentation, which leads to better practices in the long run. You should also consider doing unit testing (e.g. with RUnit ) if you want your code to be robust/maintainable. You should consider using a style guide (e.g. Google Style Guide ). Use a version control system from the beginning, and if you're going to make your code open source, then consider using github or r-forge. Edit: Regarding how do make incremental changes without rebuilding and installing the full package: I find the easiest thing to do is to make changes in your relevant R file and then use the source command to load those changes. Once you load your library into an R session, it will always be lower in the environment (and lower in priority) than the .GlobalEnv, so any changes that you source or load in directly will be used first (use the search command to see this). That way you can have your package underlying and you are overwriting changes as you're testing them in the environment. Alternatively, you can use an IDE like StatET or ESS. They make loading individual lines or functions out of an R package very easy. StatET is particularly well designed to handle managing packages in a directory-like structure.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2284446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218244/']}
jdg_72444
stackexchange
llm_judgeable_groundtruth_similarity
63468346
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 I git clone the repository the following warning appears: ...warning: the following paths have collided (e.g. case-sensitive pathson a case-insensitive filesystem) and only one from the samecolliding group is in the working tree: 'components/User/index.js' 'components/user/index.js' I've been reading and it may be a windows problem since case sensitive is not enabled in the folder paths. I also tried with git config --global core.ignorecase false but it keeps failing. This problem is faced with all case-insensitive file systems, i.e Windows 10(NTFS) and macOS(APFS). Does anyone also see this problem? Now provide the response and nothing else.
Definitions case-sensitive filesystem: treats john.jpg and JOHN.jpg as two different files and this is allowed. case-insensitive filesystem: treats john.jpg and JOHN.jpg as one and the same file which is not allowed. Problem 'components/User/index.js''components/user/index.js' The problem here is that User and user are not allowed to co-exist at the same time inside the components directory on a case-insensitive filesystem (which is NTFS if you're using Windows 10). Solution for windows OS If you have recently cloned the repo and have not done any work on it yet, I recommend that you start over. So remove the clone, then enable case-sensitivity for the directory you intend to clone your repo in, and then clone it anew. The benefit of doing this ahead of the cloning process is that all directories that are created as part of the cloning process by git will be case-sensitive and git will no longer give this warning. Plus, it enables you to clean up the mess. Open a command prompt as an administrator. Go to the directory where you intend to clone your repo. In this example I will use C:\Users\Juan\Desktop . You don't have to cd to this directory to do the next step, just know what your target directory is. Enable case-sensitivity for the target directory. Command: fsutil.exe file SetCaseSensitiveInfo "C:\Users\Juan\Desktop" enable Clone your repo. In this example I will use https://github.com/torvalds/linux.git . Command: git clone https://github.com/torvalds/linux.git (optional): Remove or rename conflicting files and folders if they are the same. You need to verify this by comparing them. To remove, use git rm and to move or copy, use git mv . (optional): Commit and push up your changes to the upstream repo if you have write permission (and possibly after discussing the problem with the rest of the team). (optional): Disable case-sensitivity. Command: fsutil.exe file SetCaseSensitiveInfo "C:\Users\Juan\Desktop" disable Now you can go back to working on the project. Source: Windows Central Solution for macOS On macOS, you will have to reformat volume as case-insensitive/sensitive or make a new volume altogether. Details Reflection You probably ran into this problem because you cloned a repo that was created on a computer that runs Linux or Mac, perhaps it was created by someone else and not you personally. The lesson here is to always be consistent with the way you name things, and this applies to everyone involved in a project. This is one example of what can happen otherwise.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63468346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13302563/']}
jdg_72445
stackexchange
llm_judgeable_groundtruth_similarity
3130804
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 place various size images inside imageView of UITableViewCell. I get the image data asynch'ly, create the image, set the content mode of imageView and finally set bounds of imageView. But the code seems insensitive to any changes I made. I want the images to be centered in a 75x75 area. I wrote the below code for this purpose UIImage* image = [UIImage imageWithData:data];[holder.imageView setContentMode:UIViewContentModeCenter || UIViewContentModeRedraw];[holder.imageView setImage:image];[holder.imageView setBounds:CGRectMake(0,0,75,75)];[holder.imageView setFrame:CGRectMake(0,0,75,75)];[holder setNeedsLayout]; Where holder is the UITableViewCell. The result I get is always the same. All images have 75px height and different widths. Can someone help me solve this problem? I have realized that setting contentMode and bounds properties does not have any effect in that code. I have added an NSLog after the last line and got the results as below: NSLog(@"imageview:%@ bounds and contentMode:%@ %@",[holder imageView],[holder.imageView bounds],[holder.imageView contentMode]); imageview:<UIImageView: 0x39ab8a0; frame = (0 0; 75 75); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x39a92b0>> bounds and contentMode:(null) (null) Still no solution Now provide the response and nothing else.
Done, I finally found the solution, it cost me 3 hours though =) The solution is to change properties like bound,frame,contentMode in -(void)layoutSubviews method of the custom UITableViewCell class. The "trick" is to write layout code in this method, otherwise the code does not have any effect. Below code did the work for me. It makes rows of the table vertically aligned. - (void)layoutSubviews { [super layoutSubviews]; self.imageView.bounds = CGRectMake(0,0,75,75); self.imageView.frame = CGRectMake(0,0,75,75); self.imageView.contentMode = UIViewContentModeScaleAspectFit; CGRect tmpFrame = self.textLabel.frame; tmpFrame.origin.x = 77; self.textLabel.frame = tmpFrame; tmpFrame = self.detailTextLabel.frame; tmpFrame.origin.x = 77; self.detailTextLabel.frame = tmpFrame;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3130804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369001/']}
jdg_72446
stackexchange
llm_judgeable_groundtruth_similarity
9600888
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the case of a single perceptron - literature states that it cannot be used for seperating non-linear discriminant cases like the XOR function. This is understandable since the VC-dimension of a line (in 2-D) is 3 and so a single 2-D line cannot discriminate outputs like XOR. However, my question is why should the evaluating function in the single perceptron be a linear-step function? Clearly if we have a non-linear evaluating function like a sigmoid, this perceptron can discriminate between the 1s and 0s of XOR. So, am I missing something here? Now provide the response and nothing else.
if we have a non-linear evaluating function like a sigmoid, this perceptron can discriminate between the 1s and 0s of XOR That's not true at all. The criteria for discrimination is not the shape of the line (or hyperplane in higher dimensions), but rather whether the function allows linear separability . There is no single function that produces a hyperplane capable of separating the points of the XOR function. The curve in the image separates the points, but it is not a function. To separate the points of XOR, you'll have to use at least two lines (or any other shaped functions). This will require two separate perceptrons. Then, you could use a third perceptron to separate the intermediate results on the basis of sign.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9600888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/655757/']}
jdg_72447
stackexchange
llm_judgeable_groundtruth_similarity
400542
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: TVS diode with marker Some components that are needed to be be in a certain direction (like most diodes, and some capacitors) there is a white line over the component to show the direction. But why is this done for a P6KE43CA, Bi-Directional TVS Diode, 600W, 2-Pin DO-204AC like the picture below. Does the direction matter since it is bidirectional? TVS diode without marker This is how mine look like from P6KE15CA ; sorry for the bad picture, I do not have the TVS diodes at hand so used a screenshot crop from the page I bought them from: Now provide the response and nothing else.
In all likelihood, the site you linked to is simply using a generic picture for the entire P6KE series, which includes both unidirectional and bidirectional devices. As your second image shows, P6KExxCA devices do not have a direction marker. This excerpt from the datasheet provides further evidence of this. The unidirectional devices in the series do have a direction mark, but the bidirectional ones do not. Generally, don't trust the images on distributors' websites, especially if they appear to be CG rather than actual photographs of the product. And even photographs can lie; I've come across a part with a picture of a large contactor that was actually a mechanical hole seal! Always check the details and datasheet.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/400542', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/140343/']}
jdg_72448
stackexchange
llm_judgeable_groundtruth_similarity
4967799
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 activity which is called by few other activities. For example: I have Activity1,Activity2,Activity3.Activity1 calls Activity2 and pass parameter.Activity3 also calls Activity2 and pass parameter. Now based on the calling activity, Activity2 performs some task.But how do I know which activity is calling Activity2??can anybody plz help me?? Now provide the response and nothing else.
A. If you can use startActivityForResult As per Zain Ali's answer below: If you can start Activity with startActivityForResult() then you can get name of calling Activity class by this.getCallingActivity().getClassName(); B. If you can not use startActivityForResult If you can not use startActivityForResult(), then you can use following method: You can pass additional parameter in intent, check the value in activity and act accordingly. 1) Define an interface or constants class to define integer constants to indicate calling activity public interface ActivityConstants { public static final int ACTIVITY_1 = 1001; public static final int ACTIVITY_2 = 1002; public static final int ACTIVITY_3 = 1003;} 2) Add extra parameter in intent while calling Activity2. Intent act2 = new Intent(context, Activity2.class); act2.putExtra("calling-activity", ActivityConstants.ACTIVITY_1); // or ActivityConstants.ACTIVITY_3 if called form Activity3startActivity(act2); 3) Check the value of this extra parameter in Activity2 and act accordingly.. int callingActivity = getIntent().getIntExtra("calling-activity", 0); switch (callingActivity) { case ActivityConstants.ACTIVITY_1: // Activity2 is started from Activity1 break; case ActivityConstants.ACTIVITY_3: // Activity2 is started from Activity3 break; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4967799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574308/']}
jdg_72449
stackexchange
llm_judgeable_groundtruth_similarity
3770168
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 many distinct permutations of the string "NADAMADRID" have the word DAM appearing in them? Normally, under the Mississippi Rule, you would take the total number of characters factorial, then divide by the product of all the characters that repeat factorial. In this case however, they ask how many times a certain word will appear in the permuations of a bigger string. I was confused on how to do this problem, and how i would count these possibilites. Now provide the response and nothing else.
Just treat $DAM$ like another unique letter. Then you have 8 letters total, with two $A$ 's and two $D$ 's (after you take out those used in $DAM$ ). So the total number of arrangements is $$\frac{8!}{2!2!}$$ Note this would get more complicated if there were more than one $M$ , as then you'd have to account for instances with two $DAM$ 's by inclusion-exclusion.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3770168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/811582/']}
jdg_72450
stackexchange
llm_judgeable_groundtruth_similarity
27533386
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 multiple routes that invoke the same Controller and I would like to pass different variables to it. // Example$routeProvider. when('/a', { templateUrl: 'test.html', controller: 'MyController' // should get passed 'exampleA' }). when('/b', { templateUrl: 'test.html', controller: 'MyController' // should get passed 'exampleB'}); I know that I could use the "resolve" object: $routeProvider. when('/a', { templateUrl: 'test.html', controller: 'MyController', resolve: {test: function() { return true; }}}); To pass a value as a dependency: app.controller('MyController', ['$scope', 'test', function ($scope, test) { console.log(test); // true} My problem with that approach is that my app crashes if the resolve object is missing on other routes and I would like to pass optional params. Is there any way to pass specific params to the Controller (from the route provider)? Thank you Now provide the response and nothing else.
Routing: $routeProvider. when('/a', { templateUrl: 'test.html', controller: 'MyController', paramExample: 'exampleA' }). when('/b', { templateUrl: 'test.html', controller: 'MyController', paramExample: 'exampleB'}); Access: inject $route in your controller then use this app.controller('MyController', ['$scope', '$route', function ($scope, $route) { var paramValue = $route.current.$$route.paramExample; console.log(paramValue); }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27533386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1598840/']}
jdg_72451
stackexchange
llm_judgeable_groundtruth_similarity
34147753
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 do not quite understand the difference between the following two similar codes: def y(x): temp=[] def z(j): temp.append(j) z(1) return temp calling y(2) returns [1] def y(x): temp=[] def z(j): temp+=[j] z(1) return temp calling y(2) returns UnboundLocalError: local variable 'temp' referenced before assignment . Why + operator generates the error? Thanks Now provide the response and nothing else.
Answer to the heading, the difference between + and "append" is: [11, 22] + [33, 44,] will give you: [11, 22, 33, 44] and. b = [11, 22, 33]b.append([44, 55, 66]) will give you [11, 22, 33 [44, 55, 66]] Answer to the error This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope The problem here is temp+=[j] is equal to temp = temp +[j] . The temp variable is read here before its assigned. This is why it's giving this problem. This is actually covered in python FAQ's. For further readings, click here . :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34147753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4820266/']}
jdg_72452
stackexchange
llm_judgeable_groundtruth_similarity
971459
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 to handle both the single click and the double click of a button in a WPF application with different reaction.Unfortunately, on a doubleclick, WPF fires two click event and a double click event, so it's hard to handle this situation. It tried to solve it using a timer but without success...I hope you can help me. Lets see the code: private void delayedBtnClick(object statInfo){ if (doubleClickTimer != null) doubleClickTimer.Dispose(); doubleClickTimer = null; this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new VoidDelegate(delegate() { // ... DO THE SINGLE CLICK ACTION }));}private void btn_Click(object sender, RoutedEventArgs e){ if (doubleClickTimer == null) doubleClickTimer = new Timer(delayedBtnClick, null, System.Windows.Forms.SystemInformation.DoubleClickTime, Timeout.Infinite); } }}private void btnNext_MouseDoubleClick(object sender, MouseButtonEventArgs e){ if (doubleClickTimer != null) doubleClickTimer.Change(Timeout.Infinite, Timeout.Infinite); // disable it - I've tried it with and without this line doubleClickTimer.Dispose(); doubleClickTimer = null; //.... DO THE DOUBLE CLICK ACTION} The problem is that the 'SINGLE CLICK ACTION' called after the 'DOUBLE CLICK ACTION' on doubleclick. It's strange that I set the doubleClickTimer to null on double click but in the delayedBtnClick it's true :O I've already tried to use longer time, a bool flag and lock... Do you have any ideas? Best! Now provide the response and nothing else.
If you set the RoutedEvent 's e.Handled to true after handling the MouseDoubleClick event then it will not call the Click Event the second time after the MouseDoubleClick . There's a recent post which touches on having different behaviors for SingleClick and DoubleClick which may be useful. However, if you are sure you want separate behaviors and want/need to block the first Click as well as the second Click , you can use the DispatcherTimer like you were. private static DispatcherTimer myClickWaitTimer = new DispatcherTimer( new TimeSpan(0, 0, 0, 1), DispatcherPriority.Background, mouseWaitTimer_Tick, Dispatcher.CurrentDispatcher);private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e){ // Stop the timer from ticking. myClickWaitTimer.Stop(); Trace.WriteLine("Double Click"); e.Handled = true;}private void Button_Click(object sender, RoutedEventArgs e){ myClickWaitTimer.Start();}private static void mouseWaitTimer_Tick(object sender, EventArgs e){ myClickWaitTimer.Stop(); // Handle Single Click Actions Trace.WriteLine("Single Click");}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/971459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119991/']}
jdg_72453
stackexchange
llm_judgeable_groundtruth_similarity
139070
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 posted this question, not sure how to move that question to this stats.stackexchange.com. https://stackoverflow.com/questions/28702634/predictive-accuracy-formula-in-excel-or-r?noredirect=1#comment45695509_28702634 Recently, I have built a model and I have the output similar to this below. The output is in the Excel. I am trying to understand if prediction error can be calculated in the Excel? For example, could I write a formula (RMSE, SSE, MSE) in excel to determine the predictive accuracy for the table below? Basically, can I calculate the prediction error for the predicted sales given actual sales? pred_minus_acutal and (predicted - actual)/actual are just scenarios I tried. That may not be right way to get the prediction error. I am not sure if these ideas are right either. Thanks! customer id predicted_sales actual_sales1A 100 1502A 200 1003A 300 2561B 100 3004B 400 3906B 500 502 Now provide the response and nothing else.
This is not a bug. As we have explored (extensively) in the comments, there are two things happening. The first is that the columns of $U$ are constrained to meet the SVD requirements: each must have unit length and be orthogonal to all the others. Viewing $U$ as a random variable created from a random matrix $X$ via a particular SVD algorithm, we thereby note that these $k(k+1)/2$ functionally independent constraints create statistical dependencies among the columns of $U$ . These dependencies might be revealed to a greater or lesser extent by studying the correlations among the components of $U$ , but a second phenomenon emerges : the SVD solution is not unique. At a minimum, each column of $U$ can be independently negated, giving at least $2^k$ distinct solutions with $k$ columns. Strong correlations (exceeding $1/2$ ) can be induced by changing the signs of the columns appropriately. (One way to do this is given in my first comment to Amoeba's answer in this thread: I force all the $u_{ii},i=1,\ldots, k$ to have the same sign, making them all negative or all positive with equal probability.) On the other hand, all correlations can be made to vanish by choosing the signs randomly, independently, with equal probabilities. (I give an example below in the "Edit" section.) With care, we can partially discern both these phenomena when reading scatterplot matrices of the components of $U$ . Certain characteristics--such as the appearance of points nearly uniformly distributed within well-defined circular regions--belie a lack of independence. Others, such as scatterplots showing clear nonzero correlations, obviously depend on choices made in the algorithm-- but such choices are possible only because of the lack of independence in the first place. The ultimate test of a decomposition algorithm like SVD (or Cholesky, LR, LU, etc.) is whether it does what it claims. In this circumstance it suffices to check that when SVD returns the triple of matrices $(U, D, V)$ , that $X$ is recovered, up to anticipated floating point error, by the product $UDV^\prime$ ; that the columns of $U$ and of $V$ are orthonormal; and that $D$ is diagonal, its diagonal elements are non-negative, and are arranged in descending order. I have applied such tests to the svd algorithm in R and have never found it to be in error. Although that is no assurance it is perfectly correct, such experience--which I believe is shared by a great many people--suggests that any bug would require some extraordinary kind of input in order to be manifest. What follows is a more detailed analysis of specific points raised in the question. Using R 's svd procedure, first you can check that as $k$ increases, the correlations among the coefficients of $U$ grow weaker, but they are still nonzero. If you simply were to perform a larger simulation, you would find they are significant. (When $k=3$ , 50000 iterations ought to suffice.) Contrary to the assertion in the question, the correlations do not "disappear entirely." Second, a better way to study this phenomenon is to go back to the basic question of independence of the coefficients. Although the correlations tend to be near zero in most cases, the lack of independence is clearly evident. This is made most apparent by studying the full multivariate distribution of the coefficients of $U$ . The nature of the distribution emerges even in small simulations in which the nonzero correlations cannot (yet) be detected. For instance, examine a scatterplot matrix of the coefficients. To make this practicable, I set the size of each simulated dataset to $4$ and kept $k=2$ , thereby drawing $1000$ realizations of the $4\times 2$ matrix $U$ , creating a $1000\times 8$ matrix. Here is its full scatterplot matrix, with the variables listed by their positions within $U$ : Scanning down the first column reveals an interesting lack of independence between $u_{11}$ and the other $u_{ij}$ : look at how the upper quadrant of the scatterplot with $u_{21}$ is nearly vacant, for instance; or examine the elliptical upward-sloping cloud describing the $(u_{11}, u_{22})$ relationship and the downward-sloping cloud for the $(u_{21}, u_{12})$ pair. A close look reveals a clear lack of independence among almost all of these coefficients: very few of them look remotely independent, even though most of them exhibit near-zero correlation. (NB: Most of the circular clouds are projections from a hypersphere created by the normalization condition forcing the sum of squares of all components of each column to be unity.) Scatterplot matrices with $k=3$ and $k=4$ exhibit similar patterns: these phenomena are not confined to $k=2$ , nor do they depend on the size of each simulated dataset: they just get more difficult to generate and examine. The explanations for these patterns go to the algorithm used to obtain $U$ in the singular value decomposition, but we know such patterns of non-independence must exist by the very defining properties of $U$ : since each successive column is (geometrically) orthogonal to the preceding ones, these orthogonality conditions impose functional dependencies among the coefficients, which thereby translate to statistical dependencies among the corresponding random variables. Edit In response to comments, it may be worth remarking on the extent to which these dependence phenomena reflect the underlying algorithm (to compute an SVD) and how much they are inherent in the nature of the process. The specific patterns of correlations among coefficients depend a great deal on arbitrary choices made by the SVD algorithm, because the solution is not unique: the columns of $U$ may always independently be multiplied by $-1$ or $1$ . There is no intrinsic way to choose the sign. Thus, when two SVD algorithms make different (arbitrary or perhaps even random) choices of sign, they can result in different patterns of scatterplots of the $(u_{ij}, u_{i^\prime j^\prime})$ values. If you would like to see this, replace the stat function in the code below by stat <- function(x) { i <- sample.int(dim(x)[1]) # Make a random permutation of the rows of x u <- svd(x[i, ])$u # Perform SVD as.vector(u[order(i), ]) # Unpermute the rows of u} This first randomly re-orders the observations x , performs SVD, then applies the inverse ordering to u to match the original observation sequence. Because the effect is to form mixtures of reflected and rotated versions of the original scatterplots, the scatterplots in the matrix will look much more uniform. All sample correlations will be extremely close to zero (by construction: the underlying correlations are exactly zero). Nevertheless, the lack of independence will still be obvious (in the uniform circular shapes that appear, particularly between $u_{i,j}$ and $u_{i,j^\prime}$ ). The lack of data in some quadrants of some of the original scatterplots (shown in the figure above) arises from how the R SVD algorithm selects signs for the columns. Nothing changes about the conclusions. Because the second column of $U$ is orthogonal to the first, it (considered as a multivariate random variable) is dependent on the first (also considered as a multivariate random variable). You cannot have all the components of one column be independent of all the components of the other; all you can do is to look at the data in ways that obscure the dependencies--but the dependence will persist. Here is updated R code to handle the cases $k\gt 2$ and draw a portion of the scatterplot matrix. k <- 2 # Number of variablesp <- 4 # Number of observationsn <- 1e3 # Number of iterationsstat <- function(x) as.vector(svd(x)$u)Sigma <- diag(1, k, k); Mu <- rep(0, k)set.seed(17)sim <- t(replicate(n, stat(MASS::mvrnorm(p, Mu, Sigma))))colnames(sim) <- as.vector(outer(1:p, 1:k, function(i,j) paste0(i,",",j)))pairs(sim[, 1:min(11, p*k)], pch=".")
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/139070', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/61839/']}
jdg_72454
stackexchange
llm_judgeable_groundtruth_similarity
1443886
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to hide the base public property(a data member) in my derived class: class Program{ static void Main(string[] args) { b obj = new b(); obj.item1 = 4;// should show an error but it doent ??? }}class a{ public int item1 {get; set;} public int item2 { get; set; }}class b : a{ new private int item1;}class c : a{} i have member as public because i want the member to be inherited in c class , but want to hide the member in b class , how can i do this ? dont i have an option to selectively inherite the variable i want in my base class ??? thats really bad , i think ms should provide us with an option (may be a modifier) to perform this Edit: I found the answer myself (i heard lots of them telling this is not possible in c#, but you can kind of do it) I am including the code in case it is useful class Program{ static void Main(string[] args) { b obj = new b(); obj.item1 = 4; // shows an error : ) }}class a{ public int item1 { get; set; } public int item2 { get; set; }}class b : a{ new public static int item1 { get; private set; }} Now provide the response and nothing else.
I'm going to attempt to explain with examples why this is a bad idea, rather than using cryptic terms. Your proposal would be to have code that looks like this: public class Base{ public int Item1 { get; set; } public int Item2 { get; set; }}public class WithHidden : Base{ hide Item1; // Assuming some new feature "hide" in C#}public class WithoutHidden : Base { } This would then make the following code invalid: WithHidden a = new WithHidden();a.Item1 = 10; // Invalid - cannot access property Item1int i = a.Item1; // Invalid - cannot access property Item1 And that would be just what you wanted. However, suppose we now have the following code: Base withHidden = new WithHidden();Base withoutHidden = new WithoutHidden();SetItem1(withHidden);SetItem1(withoutHidden);public void SetItem1(Base base){ base.Item1 = 10;} The compiler doesn't know what runtime type the argument base in SetItem1 will be, only that it is at least of type Base (or some type derived from Base, but it can't tell which -- it may be obvious looking at the code snippet, but more complex scenarios make it practically impossible). So the compiler will not, in a large percentage of the cases, be able to give a compiler error that Item1 is in fact inaccessible. So that leaves the possibility of a runtime check. When you try and set Item1 on an object which is in fact of type WithHidden it would throw an exception. Now accessing any member, any property on any non-sealed class (which is most of them) may throw an exception because it was actually a derived class which hid the member. Any library which exposes any non-sealed types would have to write defensive code when accessing any member just because someone may have hidden it. A potential solution to this is to write the feature such that only members which declare themselves hideable can be hidden. The compiler would then disallow any access to the hidden member on variables of that type (compile time), and also include runtime checks so that a FieldAccessException is thrown if it is cast to the base type and tried to be accessed from that (runtime). But even if the C# developers did go to the huge trouble and expense of this feature (remember, features are expensive , especially in language design) defensive code still has to be written to avoid the problems of potential FieldAccessExceptions being thrown, so what advantage over reorganising your inheritance hierarchy have you gained? With the new member hiding feature there would be a huge number of potential places for bugs to creep into your application and libraries, increasing development and testing time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1443886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171875/']}
jdg_72455
stackexchange
llm_judgeable_groundtruth_similarity
1556264
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hey everyone, in the following code, what should the result of d be after the second expression? int d = 1; d += d++; One would assume d is 3 afterwards but the unary increment d++ doesn't seem to take effect and d retains a value of 2. Is there a name for this bug? Does it exist for other compilers that support unary increment like C#? Now provide the response and nothing else.
It's not a bug, it acts exactly as expected. The += operator expands into this: d = d + d++; That means that the change that the ++ operator causes is overwritten when the result is assigned back to the variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1556264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64/']}
jdg_72456
stackexchange
llm_judgeable_groundtruth_similarity
28060267
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 use as excerpt_separator in Jekyll and use {{post.excerpt}} to generate excerpt. It works fine except that in the final page, the "" is replace with "<!-- more -->", so the can be seen in the final pages. How to solve this problem? Now provide the response and nothing else.
Read this (your question is answered in the very last section, " The safe bool problem "). To elaborate a bit, the implementation defines an implicit conversion to void* defined for things like std::cin and std::cout , just so that code like while(std::cin>>x){...} compiles, while code like int x = std::cin; doesn't. It's still problematic because you can write stuff like in your example. C++11 solves this problem by introducing explicit conversions. An explicit conversion operator looks like this: struct A { explicit operator B() { ... } // explicit conversion to B}; When A has an explicit conversion to B, code like this becomes legal: A a;B b(a); However, code like this is not: A a;B b = a; A construct like if(std::cin) requires cin to be converted to bool , the standard states that in order for the conversion to be valid in that particular case, code like bool x(std::cin); should be "legal". Which can be achieved by adding an explicit conversion to bool . It allows cin/cout to be used in the above context, while avoiding things like int x = std::cout; . For more information, refer to Bjarne's page as well as this question .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28060267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4166008/']}
jdg_72457
stackexchange
llm_judgeable_groundtruth_similarity
197909
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 read the documentation on scope, but I'm still having trouble working this out. I've got two environments that are very similar - so I've got: modules/django-env/manifests/init.pp class django-env { package { "python26": ensure => installed } # etc ...}import "er.pp" modules/django-env/manifests/er.pp $venvname = "er"$venvpath = "/home/django/virtualenvs"class er { file { "$venvpath/$venvname" : ensure => directory } # etc ...}class er-dev { include er}class er-bce-dev { $venvname = "er-bce" include er} manifests/modules.pp import "django-env" manifests/nodes.pp node default { # etc ...}node 'centos-dev' imports default { include django-env include er-bce-dev include er-dev} The result here is that the "inheritance" works - but only the first "er-" item under the 'centos-dev' node is acted upon, I either get er-bce-dev or er-dev, but not both. There must be some basic thing I'm misunderstanding here. Is it the difference between import and include ? (not sure I understand that) Now provide the response and nothing else.
Puppet does not support this kind of configuration, but the restriction can be easily bypassed. The reason is in two basic puppet "rules": A class can be included only once (subsequent include -statements will do nothing) The order of execution is not strictly defined and can even be random er-dev and er-bce-dev both include the class er . But the class cannot be included two times, so er class is executed only with the default $venvname = "er" , or with overridden $venvname = "er-dev" , but not both. The solution: Change er class to a definition (see "Definitions" from Puppet Language Tutorial ( http://docs.puppetlabs.com/guides/language_tutorial.html )): modules/django-env/manifests/er.pp # Create new er resource definitiondefine django-env::er($vpath="/home/django/virtualenvs", $vname="er") { file { "$vpath/$vname" : ensure => directory } # etc ...} We do not need the $venvname and $venvpath variables, they are specified as default values in the definition. The name django-env::er adds the definition into django-env namespace and allows automatic import (see below). Import and Include The difference between import and include statemens is: import works with files, and does not execute classes include executes classes files must be imported before the classes can be included Note: there is a very strong exception to the last rule: Puppet module lookup . include statement does automatic imports in many situations. Here are some of them: include foo tries to import the file module_dir/foo/manifests/init.pp include foo::bar imports module_dir/foo/manifests/bar.pp With these automatic imports and the resource definition, you can define multiple virtual environments very easily. Change node 'centos-dev' : node 'centos-dev' imports default { include django-env # The er resource with default values: django-env::er { 'er-bce': } # Another er resource with different environment name: django-env::er { 'er-bce-dev': vname => 'bce-dev'}} And you can remove basically all import statements considering django-env module. Happy Puppeting!
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/197909', 'https://serverfault.com', 'https://serverfault.com/users/40104/']}
jdg_72458
stackexchange
llm_judgeable_groundtruth_similarity
22112205
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: private void button1_Click(object sender, EventArgs e){ string usernames = textBox1.Text; string passwords = textBox2.Text; string emailid = textBox5.Text; string telno = textBox6.Text; string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;"; using (SqlCeConnection con = new SqlCeConnection(connectionstring)) { con.Open(); using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (@usernames,@passwords,@emailid,@telno)", con)) { Query.Parameters.AddWithValue("@usernames", usernames); Query.Parameters.AddWithValue("@passwords", passwords); Query.Parameters.AddWithValue("@emailid", emailid); Query.Parameters.AddWithValue("@telno", telno); Query.ExecuteNonQuery(); } MessageBox.Show("QueryExecuted"); con.Close(); MessageBox.Show("Closedconnecrion"); con.Dispose(); MessageBox.Show("disposed"); this.Close(); /*string conString = "Data Source=" + Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyAppData\\database.sdf") + ";Password=yourPassword;"; even this method dosent works */ } }} on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty... I even tried refreshing database.. I didn't find problem in connectivity. Query no error executed successfully. The problem is I didn't find result or the data I gave as input in database. Please be descriptive with code eg and mail to [email protected] Now provide the response and nothing else.
It looks like some utility has created "backups" of the normal branch files ( .git/refs/heads/... ) with a trailing ~ character. This are not allowed branch names in Git as they would conflict with the suffix notation ...~N for obtaining ancestors. Commands that don't need to query all refs (such as git log master without --decorate ) are working but anything that tries to list all branches is choking on the invalid branch name. Simply delete the file ./.git/refs/heads/master~ (after backing it up) and you should be good to go.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22112205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1716693/']}
jdg_72459
stackexchange
llm_judgeable_groundtruth_similarity
482193
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 was wondering if $V=\ker(T) \oplus \mathrm{im}(T)$ if $T:V \to V$. I know the theorem that if $T:V\to W$ is linear then $\dim(V) = \dim(\ker(T)) + \dim(\mathrm{im}(T))$. This should imply $V=\ker(T) \oplus \mathrm{im}(T)$ because if $\dim(V) = \dim(\ker(T)) + \dim(\mathrm{im}(T))$ it mean that a basis of $\ker(T)$ plus a basis of $\mathrm{im}(T)$ forms a basis of $V$ which is the same like $V=\ker(T) \oplus \mathrm{im}(T)$. Is it correct? Now provide the response and nothing else.
Sometimes, it is true that $V=\ker(T)\oplus\mathrm{im}(T)$. But consider the vector space $V=\mathbb{R}^2$ and the linear map $T:V\to V$ defined by$$T(a,b)=(b,0).$$Both the kernel and the image of $T$ are $\{(t,0):t\in\mathbb{R}\}$. Thus the dimensions still add up:$$\dim(\ker(T))+\dim(\mathrm{im}(T))=1+1=2=\dim(V)$$but it is impossible for $\ker(T)$ and $\mathrm{im}(T)$ to span $V$, much less for $V$ to be the direct sum of them. It seems to me that you're (perhaps unconsciously) committing the fallacy of considering all vector spaces that have the same dimension to be the same. In my example above, it is very important to distinguish these two subspaces of $\mathbb{R}^2$:$$\{(t,0):t\in\mathbb{R}\}\quad\text{and}\quad \{(0,t):t\in\mathbb{R}\}$$ even though they are both one-dimensional (and hence isomorphic to each other).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/482193', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64098/']}
jdg_72460
stackexchange
llm_judgeable_groundtruth_similarity
3948108
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I destroy all but the newest n records using Rails' ActiveRecord? I can get the newest n records using order and limit but how do I destroy the inverse? Now provide the response and nothing else.
Either of these methods would do it: # Fetch your latest N recordsnewest_n_records = Foo.find(:all, :order => 'created_at DESC', :limit => n)# Then do:Foo.destroy_all(['id NOT IN (?)', newest_n_records.collect(&:id)])# Or:Foo.destroy_all('created_at < ?', newest_n_records.last.created_at)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3948108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312691/']}
jdg_72461
stackexchange
llm_judgeable_groundtruth_similarity
174125
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm a parent who has a parent account with my local school district so that I can log in to their website to view my child's grades etc. I clicked the "forgot password' button, and my password was emailed to me in plain text. This concerned me, so I emailed the principal, including some links from the bottom of this page . This is the reply I received from the organization's IT department: Parent passwords are not stored in plain text. They are encrypted. Not a 1 way encryption but a 2 way encryption. This is how the system is able to present it back via an email through Ariande's CoolSpool utility. For support reasons, the parent password is visible to certain staff until the parent has successfully signed in 3 times. After that, no staff can see that password. However, it is stored in such a way that the system itself can send it back to the verified email. In the future after a parent's 3 successful sign ins, if they forget their password, their verified email account will be sent a link to reset their password, this change is in the works. Does this explanation justify the plain text password being sent by email, and are my passwords secure with them? If not, what references or resources could I reply to them with? Now provide the response and nothing else.
No, this is not a good practice. There are two distinct problems. encrypting the password instead of hashing it is a bad idea and is borderline storing plain text passwords. The whole idea of slow hash functions is to thwart the exfiltration of the user database. Typically, an attacker that already has access to the database can be expected to also have access to the encryption key if the web application has access to it. Thus, this is borderline plaintext; I almost voted to close this as a duplicate of this question , because this is almost the same and the linked answer applies almost directly, especially the bit about plaintext offenders; there is another answer about plaintext offenders as well. sending the plain text password via plain text email is a bad idea. They could argue that there is no difference when no password reuse happens, but I doubt they would even know what that is and why it’s considered bad practice. Also, password reuse is so common that that wouldn’t be a good answer. Additionally, as they seem to be working on the second part (even though password reset links in plain text emails are in the same ballpark, i.e. a threat that can read the password from the plain text mail can also read the link, maybe before you can), you could explain them the problem about not hashing from my answer, also feel free to link this answer directly. Maybe even explain that encryption is one way, but can always be reversed by the inverse function of the crypto system in question, aptly named decryption. Using terms like "one way encryption" and "two way encryption" rather than "hashing" and "encryption" shows a lack of understanding. The real problem is: them implementing a password reset does not mean they will hash (correctly) in the future; there is not much you can do about this except using a password manager and create a long, strong passphrase that is unique for this site and hope for the best. This is especially true since they seem to want to keep the part of their system that tells staff your password (for absolutely no good reason). The implication being they keep not hashing properly - them saying staff can only see the password in that three login timeframe is not true; if the web app can access the key, so can the administrative staff. Maybe no longer the customer support staff but they shouldn’t be able to see it in the first place. That is horrifically bad design. Depending on your location, schools as being part of the public sector have obligations to have a CISO you can contact directly, expressing your concerns. And as usual in the public sector, there ought to be an organization that is supervising the school; they should have a CISO at least, who might be quite interested in this proceeding.
{}
{'log_upvote_score': 9, 'links': ['https://security.stackexchange.com/questions/174125', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/164408/']}
jdg_72462
stackexchange
llm_judgeable_groundtruth_similarity
45628622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to find the folder and change the current folder to one of the found ones? Something like: ls C:\Users "My folder" -recurse Then cd "My folder" from search list Now provide the response and nothing else.
I just stumbled over this and discovered a small pitfall which caused the same error you encountered: error 18 at 0 depth lookup: self signed certificate There are plenty of guides how to create a self signed client certificate, I used the following (adapted from here ): # Create the CA Key and Certificate for signing Client Certsopenssl genrsa -des3 -out ca.key 4096openssl req -new -x509 -days 365 -key ca.key -out ca.crt# Create the Client Key and CSRopenssl genrsa -des3 -out client.key 4096openssl req -new -key client.key -out client.csr# Sign the client certificate with our CA certopenssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt# Convert to .p12 so import in OSX worksopenssl pkcs12 -export -clcerts -inkey client.key -in client.crt -out client.p12 -name "MyKey" However, if you use the same Organization Name (eg, company) for both your ca and your client certificate, you will see above error! (edited: important) If openssl verify -verbose -CAfile ca.crt client.crt does not complain about a self-signed certificate, you're good to go.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45628622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8342339/']}
jdg_72463
stackexchange
llm_judgeable_groundtruth_similarity
6403055
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 exactly are objects destroyed in C++, and what does that mean? Do I have to destroy them manually, since there is no Garbage Collector? How do exceptions come into play? (Note: This is meant to be an entry to Stack Overflow's C++ FAQ . If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom , where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.) Now provide the response and nothing else.
In the following text, I will distinguish between scoped objects , whose time of destruction is statically determined by their enclosing scope (functions, blocks, classes, expressions), and dynamic objects , whose exact time of destruction is generally not known until runtime. While the destruction semantics of class objects are determined by destructors, the destruction of a scalar object is always a no-op. Specifically, destructing a pointer variable does not destroy the pointee. Scoped objects automatic objects Automatic objects (commonly referred to as "local variables") are destructed, in reverse order of their definition, when control flow leaves the scope of their definition: void some_function(){ Foo a; Foo b; if (some_condition) { Foo y; Foo z; } <--- z and y are destructed here} <--- b and a are destructed here If an exception is thrown during the execution of a function, all previously constructed automatic objects are destructed before the exception is propagated to the caller. This process is called stack unwinding . During stack unwinding, no further exceptions may leave the destructors of the aforementioned previously constructed automatic objects. Otherwise, the function std::terminate is called. This leads to one of the most important guidelines in C++: Destructors should never throw. non-local static objects Static objects defined at namespace scope (commonly referred to as "global variables") and static data members are destructed, in reverse order of their definition, after the execution of main : struct X{ static Foo x; // this is only a *declaration*, not a *definition*};Foo a;Foo b;int main(){} <--- y, x, b and a are destructed hereFoo X::x; // this is the respective definitionFoo y; Note that the relative order of construction (and destruction) of static objects defined in different translation units is undefined. If an exception leaves the destructor of a static object, the function std::terminate is called. local static objects Static objects defined inside functions are constructed when (and if) control flow passes through their definition for the first time. 1 They are destructed in reverse order after the execution of main : Foo& get_some_Foo(){ static Foo x; return x;}Bar& get_some_Bar(){ static Bar y; return y;}int main(){ get_some_Bar().do_something(); // note that get_some_Bar is called *first* get_some_Foo().do_something();} <--- x and y are destructed here // hence y is destructed *last* If an exception leaves the destructor of a static object, the function std::terminate is called. 1: This is an extremely simplified model. The initialization details of static objects are actually much more complicated. base class subobjects and member subobjects When control flow leaves the destructor body of an object, its member subobjects (also known as its "data members") are destructed in reverse order of their definition. After that, its base class subobjects are destructed in reverse order of the base-specifier-list: class Foo : Bar, Baz{ Quux x; Quux y;public: ~Foo() { } <--- y and x are destructed here,}; followed by the Baz and Bar base class subobjects If an exception is thrown during the construction of one of Foo 's subobjects, then all its previously constructed subobjects will be destructed before the exception is propagated. The Foo destructor, on the other hand, will not be executed, since the Foo object was never fully constructed. Note that the destructor body is not responsible for destructing the data members themselves. You only need to write a destructor if a data member is a handle to a resource that needs to be released when the object is destructed (such as a file, a socket, a database connection, a mutex, or heap memory). array elements Array elements are destructed in descending order. If an exception is thrown during the construction of the n-th element, the elements n-1 to 0 are destructed before the exception is propagated. temporary objects A temporary object is constructed when a prvalue expression of class type is evaluated. The most prominent example of a prvalue expression is the call of a function that returns an object by value, such as T operator+(const T&, const T&) . Under normal circumstances, the temporary object is destructed when the full-expression that lexically contains the prvalue is completely evaluated: __________________________ full-expression ___________ subexpression _______ subexpressionsome_function(a + " " + b); ^ both temporary objects are destructed here The above function call some_function(a + " " + b) is a full-expression because it is not part of a larger expression (instead, it is part of an expression-statement). Hence, all temporary objects that are constructed during the evaluation of the subexpressions will be destructed at the semicolon. There are two such temporary objects: the first is constructed during the first addition, and the second is constructed during the second addition. The second temporary object will be destructed before the first. If an exception is thrown during the second addition, the first temporary object will be destructed properly before propagating the exception. If a local reference is initialized with a prvalue expression, the lifetime of the temporary object is extended to the scope of the local reference, so you won't get a dangling reference: { const Foo& r = a + " " + b; ^ first temporary (a + " ") is destructed here // ...} <--- second temporary (a + " " + b) is destructed not until here If a prvalue expression of non-class type is evaluated, the result is a value , not a temporary object. However, a temporary object will be constructed if the prvalue is used to initialize a reference: const int& r = i + j; Dynamic objects and arrays In the following section, destroy X means "first destruct X and then release the underlying memory".Similarly, create X means "first allocate enough memory and then construct X there". dynamic objects A dynamic object created via p = new Foo is destroyed via delete p . If you forget to delete p , you have a resource leak. You should never attempt to do one of the following, since they all lead to undefined behavior: destroy a dynamic object via delete[] (note the square brackets), free or any other means destroy a dynamic object multiple times access a dynamic object after it has been destroyed If an exception is thrown during the construction of a dynamic object, the underlying memory is released before the exception is propagated.(The destructor will not be executed prior to memory release, because the object was never fully constructed.) dynamic arrays A dynamic array created via p = new Foo[n] is destroyed via delete[] p (note the square brackets). If you forget to delete[] p , you have a resource leak. You should never attempt to do one of the following, since they all lead to undefined behavior: destroy a dynamic array via delete , free or any other means destroy a dynamic array multiple times access a dynamic array after it has been destroyed If an exception is thrown during the construction of the n-th element, the elements n-1 to 0 are destructed in descending order, the underlying memory is released, and the exception is propagated. (You should generally prefer std::vector<Foo> over Foo* for dynamic arrays. It makes writing correct and robust code much easier.) reference-counting smart pointers A dynamic object managed by several std::shared_ptr<Foo> objects is destroyed during the destruction of the last std::shared_ptr<Foo> object involved in sharing that dynamic object. (You should generally prefer std::shared_ptr<Foo> over Foo* for shared objects. It makes writing correct and robust code much easier.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6403055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252000/']}
jdg_72464
stackexchange
llm_judgeable_groundtruth_similarity
36368220
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It is pretty much widely accepted that this is not 'best practise'. dim rng as rangewith thisworkbook '<~~ possibly set an external workbook with .worksheets("sheet1") set rng = .range(cells(2, 1), cells(rows.count, 1).end(xlup)) end withend with The two Range.Cells properties that define the scope of the Range object will default to the ActiveSheet property . If this is not Sheet1 (defined as the .Parent in the With ... End With statement ), the assignment will fail with, Run-tim error '1004': Application-defined or object-defined error Solution: use .Cells not Cells . Case closed. But... Is the . necessary in this Range object definition when both the Range.Cells properties inherit the .Parent worksheet property that is defined in the With ... End With statement ? How can this, dim rng as rangewith thisworkbook '<~~ possibly set an external workbook with .worksheets("sheet1") ' define rng as Sheet1!A2 to the last populated cell in Sheet1!A:A set rng = .range(.cells(2, 1), .cells(rows.count, 1).end(xlup)) '<~~ .range end withend withdebug.print rng.address(0, 0, external:=true) ... be different from this, dim rng as rangewith thisworkbook '<~~ possibly set an external workbook with .worksheets("sheet1") ' define rng as Sheet1!A2 to the last populated cell in Sheet1!A:A set rng = range(.cells(2, 1), .cells(rows.count, 1).end(xlup)) '<~~ range not .range end withend withdebug.print rng.address(0, 0, external:=true) We use .range when the parameters that define the scope of the range are ambiguous; e.g. .range([A1]) The A1 cell could be from any worksheet and will default to the ActiveSheet property without the . . But why do we need to reference the parent of a range object when the scope that defines it has properly referenced its parent worksheet? Now provide the response and nothing else.
My opinion is slightly different here. YES it is required. You can't always control where the user may run the code from. Please consider these few test cases SCENARIO Workbook has 2 worksheets. Sheet1 and Sheet2 TEST 1 (Running from a module) Both Code give same result TEST 2 (Running from a Sheet code area of Sheet1) Both Code give same result TEST 3 (Running from a Sheet code area of Sheet2) '~~> This code failsset rng = range(.cells(2, 1), .cells(rows.count, 1).end(xlup)) You will get Application Defined or Object defined error And hence it is always advisable to properly qualify your objects so that the code can run from anywhere
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36368220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72465
stackexchange
llm_judgeable_groundtruth_similarity
60482737
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 happen to look into Apple's new Combine framework, where I see two things PassthroughSubject<String, Failure> CurrentValueSubject<String, Failure> Can someone explain to me what is meaning & use of them? Now provide the response and nothing else.
I think we can make analogies with real world cases. PassthroughSubject = A doorbell push button When someone rings the door, you are notified only if you are at home (you are the subscriber) PassthroughSubject doesn't have a state, it emits whatever it receives to its subscribers. CurrentValueSubject = A light switch Someone turns on the lights in your home when you are outside. You get back home and you know someone has turned them on. CurrentValueSubject has an initial state, it retains the data you put in as its state.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60482737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4260623/']}
jdg_72466
stackexchange
llm_judgeable_groundtruth_similarity
21382681
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 running k-means clustering in R on a dataset with 636,688 rows and 7 columns using the standard stats package: kmeans(dataset, centers = 100, nstart = 25, iter.max = 20) . I get the following error: Quick-TRANSfer stage steps exceeded maximum (= 31834400) , and although one can view the code at http://svn.r-project.org/R/trunk/src/library/stats/R/kmeans.R - I am unsure as to what is going wrong. I assume my problem has to do with the size of my dataset, but I would be grateful if someone could clarify once and for all what I can do to mitigate the issue. Now provide the response and nothing else.
I just had the same issue. See the documentation of kmeans in R via ?kmeans : The Hartigan-Wong algorithm generally does a better job than either of those, but trying several random starts (‘nstart’> 1) is often recommended. In rare cases, when some of the points (rows of ‘x’) are extremely close, the algorithm may not converge in the “Quick-Transfer” stage , signalling a warning (and returning ‘ifault = 4’). Slight rounding of the data may be advisable in that case. In these cases, you may need to switch to the Lloyd or MacQueen algorithms. The nasty thing about R here is that it continues with a warning that may go unnoticed. For my benchmark purposes, I consider this to be a failed run, and thus I use: if (kms$ifault==4) { stop("Failed in Quick-Transfer"); } Depending on your use case, you may want to do something like if (kms$ifault==4) { kms = kmeans(X, kms$centers, algorithm="MacQueen"); } instead, to continue with a different algorithm. If you are benchmarking K-means, note that R uses iter.max=10 per default. It may take much more than 10 iterations to converge.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21382681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2685878/']}
jdg_72467
stackexchange
llm_judgeable_groundtruth_similarity
256726
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 really confused about the difference in meaning regarding the context of linear regression of the following terms: F statistic R squared Residual standard error I found this webstie which gave me great insight in the different terms involved in linear regression, however the terms mentioned above look a like quite a lot (as far as I understand). I will cite what I read and what confused me: Residual Standard Error is measure of the quality of a linear regression fit.......The Residual Standard Error is the average amount that the response (dist) will deviate from the true regression line. 1. This is thus actually the average distance of the observed values from the lm line? The R-squared statistic provides a measure of how well the model is fitting the actual data. 2. Now I'm getting confused because if RSE tells us how far our observed points deviate from the regression line a low RSE is actually telling us "your model is fitting well based on the observed data points" --> thus how good our models fits, so what is the difference between R squared and RSE? F-statistic is a good indicator of whether there is a relationship between our predictor and the response variables. 3. Is it true that we can have a F value indicating a strong relationship that is NON LINEAR so that our RSE is high and our R squared is low Now provide the response and nothing else.
The best way to understand these terms is to do a regression calculation by hand. I wrote two closely related answers ( here and here ), however they may not fully help you understanding your particular case. But read through them nonetheless. Maybe they will also help you conceptualizing these terms better. In a regression (or ANOVA), we build a model based on a sample dataset which enables us to predict outcomes from a population of interest. To do so, the following three components are calculated in a simple linear regression from which the other components can be calculated, e.g. the mean squares, the F-value, the $R^2$ (also the adjusted $R^2$ ), and the residual standard error ( $RSE$ ): total sums of squares ( $SS_{total}$ ) residual sums of squares ( $SS_{residual}$ ) model sums of squares ( $SS_{model}$ ) Each of them are assessing how well the model describes the data and are the sum of the squared distances from the data points to fitted model (illustrated as red lines in the plot below). The $SS_{total}$ assess how well the mean fits the data. Why the mean? Because the mean is the simplest model we can fit and hence serves as the model to which the least-squares regression line is compared to. This plot using the cars dataset illustrates that: The $SS_{residual}$ assess how well the regression line fits the data. The $SS_{model}$ compares how much better the regression line is compared to the mean (i.e. the difference between the $SS_{total}$ and the $SS_{residual}$ ). To answer your questions, let's first calculate those terms which you want to understand starting with model and output as a reference: # The model and output as referencem1 <- lm(dist ~ speed, data = cars)summary(m1)summary.aov(m1) # To get the sums of squares and mean squares The sums of squares are the squared distances of the individual data points to the model: # Calculate sums of squares (total, residual and model)y <- cars $distybar <- mean(y)ss.total <- sum((y-ybar)^2)ss.totalss.residual <- sum((y-m1$ fitted)^2)ss.residualss.model <- ss.total-ss.residualss.model The mean squares are the sums of squares averaged by the degrees of freedom: # Calculate degrees of freedom (total, residual and model)n <- length(cars $speed)k <- length(m1$ coef) # k = model parameter: b0, b1df.total <- n-1df.residual <- n-kdf.model <- k-1# Calculate mean squares (note that these are just variances)ms.residual <- ss.residual/df.residualms.residualms.model<- ss.model/df.modelms.model My answers to your questions: Q1: This is thus actually the average distance of the observed values from the lm line? The residual standard error ( $RSE$ ) is the square root of the residual mean square ( $MS_{residual}$ ): # Calculate residual standard errorres.se <- sqrt(ms.residual)res.se If you remember that the $SS_{residual}$ were the squared distances of the observed data points and the model (regression line in the second plot above), and $MS_{residual}$ was just the averaged $SS_{residual}$ , the answer to your first question is, yes: The $RSE$ represents the average distance of the observed data from the model. Intuitively, this also makes perfect sense because if the distance is smaller, your model fit is also better. Q2: Now I'm getting confused because if RSE tells us how far our observed points deviate from the regression line a low RSE is actually telling us "your model is fitting well based on the observed data points" --> thus how good our models fits, so what is the difference between R squared and RSE? Now the $R^2$ is the ratio of the $SS_{model}$ and the $SS_{total}$ : # R squaredr.sq <- ss.model/ss.totalr.sq The $R^2$ expresses how much of the total variation in the data can be explained by the model (the regression line). Remember that the total variation was the variation in the data when we fitted the simplest model to the data, i.e. the mean. Compare the $SS_{total}$ plot with the $SS_{model}$ plot. So to answer your second question, the difference between the $RSE$ and the $R^2$ is that the $RSE$ tells you something about the inaccuracy of the model (in this case the regression line) given the observed data. The $R^2$ on the other hand tells you how much variation is explained by the model (i.e. the regression line) relative the variation that was explained by the mean alone (i.e. the simplest model). Q3: Is it true that we can have a F value indicating a strong relationship that is NON LINEAR so that our RSE is high and our R squared is low So the $F$ -value on the other is calculated as the model mean square $MS_{model}$ (or the signal) divided by the $MS_{residual}$ (noise): # Calculate F-valueF <- ms.model/ms.residualF# Calculate P-valuep.F <- 1-pf(F, df.model, df.residual)p.F Or in other words the $F$ -value expresses how much of the model has improved (compared to the mean) given the inaccuracy of the model. Your third question is a bit difficult to understand but I agree with the quote your provided.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/256726', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/133457/']}
jdg_72468
stackexchange
llm_judgeable_groundtruth_similarity
48023096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use JSONDecoder to convert a JSON to Structs in Swift, so I wrote all the Structs, revised them for hours, and it still gives me this error. I don't know if there is a way to see the line that gives this.I'll post my struct below and the Json File links right after. The complete error description is: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil)) // Created by Breno Ramos on 28/12/17.// Copyright © 2017 brenor2. All rights reserved.//import Foundationstruct Owner:Decodable { let login : String? let id : Double? let avatar_url : String? let gravatar_id : String? let url : String? let html_url : String? let followers_url : String? let following_url : String? let gists_url : String? let starred_url : String? let subscriptions_url : String? let organizations_url : String? let repos_url : String? let events_url : String? let received_events_url : String? let type : String? let site_admin : Bool?}struct License:Decodable { let key : String? let name : String? let spdx_id : String? let url : String?}struct Repo:Decodable { let id : Double? let name : String? let full_name : String? let owner : Owner? let `private` : Bool? let html_url : String? let description : String? let fork : Bool? let url : String? let forks_url : String? let keys_url : String? let collaborators_url : String? let teams_url : String? let hooks_url : String? let issue_events_url : String? let events_url : String? let assignees_url : String? let branches_url : String? let tags_url : String? let blobs_url : String? let git_tags_url : String? let git_refs_url : String? let trees_url : String? let statuses_url : String? let languages_url : String? let stargazers_url : String? let contributors_url : String? let subscribers_url : String? let subscription_url : String? let commits_url : String? let git_commits_url : String? let comments_url : String? let issue_comment_url : String? let contents_url : String? let compare_url : String? let merges_url : String? let archive_url : String? let downloads_url : String? let issues_url : String? let pulls_url : String? let milestones_url : String? let notifications_url : String? let labels_url : String? let releases_url : String? let deployments_url : String? let created_at : String? let updated_at : String? let pushed_at : String? let git_url : String? let ssh_url : String? let clone_url : String? let svn_url : String? let homepage : String? let size : Double? let stargazers_count : Double? let watchers_count : Double? let language : String? let has_issues : Bool? let has_projects : Bool? let has_downloads : Bool? let has_wiki : Bool? let has_pages : Bool? let forks_count : Double? let mirror_url : String? let archived : Bool? let open_issues_count : Double? let license : License? let forks : Double? let open_issues : Double? let topics : Topic? let permissions : Permissions? let watchers : Double? let default_branch : String? // let score : Double? // let subscribers_count : Double? // let network_count : Double? // let allow_rebase_merge: Bool? // let allow_squash_merge: Bool? // let allow_merge_commit: Bool?}struct Topic:Decodable { let topics : [String]?}struct Permissions:Decodable { let admin : Bool let push : Bool let pull : Bool}struct RepoList:Decodable{ let total_count : Int? let incomplete_results : Bool? let items : [Repo]?}struct User:Decodable { let login: String? let id: Double? let avatar_url: String? let gravatar_id: String? let url: String? let html_url: String? let followers_url: String? let following_url: String? let gists_url: String? let starred_url: String? let subscriptions_url: String? let organizations_url: String? let repos_url: String? let events_url: String? let received_events_url: String? let type: String? let site_admin: Bool?}struct Creator:Decodable { let login: String? let id: Double? let avatar_url: String? let gravatar_id: String? let url: String? let html_url: String? let followers_url: String? let following_url: String? let gists_url: String? let starred_url: String? let subscriptions_url: String? let organizations_url: String? let repos_url: String? let events_url: String? let received_events_url: String? let type: String? let site_admin: Bool?}struct Link:Decodable { let href :String?}struct _Links:Decodable { let `self` :Link? let html :Link? let issue :Link? let comments :Link? let review_comments :Link? let review_comment :Link? let commits :Link? let statuses :Link?}struct Base:Decodable { let label :String? let ref :String? let sha :String? let user :User? let repo :Repo?}struct Head:Decodable { let label :String? let ref :String? let sha :String? let user :User? let repo :Repo?}struct Milestone:Decodable { let url:String? let html_url:String? let labels_url:String? let id: Double? let number:Double? let title:String? let description:String? let creator:Creator? let open_issues:Double? let closed_issues:Double? let state:String? let created_at:String? let updated_at:String? let closed_at:String? let due_on:String?}struct Assignee:Decodable { let login :String? let id :Double? let avatar_url :String? let gravatar_id :String? let url :String? let html_url :String? let followers_url :String? let following_url :String? let gists_url :String? let starred_url :String? let subscriptions_url :String? let organizations_url :String? let repos_url :String? let events_url :String? let received_events_url :String? let type :String? let site_admin :Bool?}struct Reviewers:Decodable { let login: String? let id: Double? let avatar_url: String? let gravatar_id: String? let url: String? let html_url: String? let followers_url: String? let following_url: String? let gists_url: String? let starred_url: String? let subscriptions_url: String? let organizations_url: String? let repos_url: String? let events_url: String? let received_events_url: String? let type: String? let site_admin: Bool?}struct Pull:Decodable { let id: Double? let url:String? let html_url:String? let diff_url:String? let patch_url:String? let issue_url:String? let number:Double? let state:String? let locked:Bool? let title:String? let user:User? let body:String? let created_at:String? let updated_at:String? let closed_at:String? let merged_at:String? let merge_commit_sha: String? let assignee: Assignee? let assignees: [Assignee]? let requested_reviewers: [Reviewers]? let milestone:Milestone? let commits_url:String? let review_comments_url:String? let review_comment_url:String? let comments_url:String? let statuses_url:String? let head:Head? let base:Base? let _links:_Links? let author_association:String?}struct PullList:Decodable { let pulls:[Pull]?}///////////////////////////////////////////////////////// 1. This one is working fine with this structs: 2. This one is the one that gives the typeMismatch error Now provide the response and nothing else.
You're probably doing this right now: let decoder = JSONDecoder()let repoList = decoder.decode(RepoList.self, from: data) which is fine for the response with a top-level Object. To decode JSON responses that are top-level Arrays, use code like this instead: let decoder = JSONDecoder()let repos = decoder.decode([Repo].self, from: data)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48023096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7997971/']}
jdg_72469
stackexchange
llm_judgeable_groundtruth_similarity
41874676
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 a weird question, but since I'm really curious about this I wanted to ask. I have a piece of code that works in the iOS Simulator when I enable Remote Debugging but it stops working without it. This is the code: let filtered = [] let dueDate const dateNow = new Date(Date.now()) for (let item of this.props.listData) { dueDate = new Date(item.dueDate) if (!item.paid && (dueDate < dateNow)) { filtered.push(item) } } if (filtered.length > 0) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(filtered) }) } (item.dueDate is a string like "12.02.2016") Obviously the code would work (and it works) if I supplied the date in a correct format (like ISO "2016-02-12"). What interests me is why does it work even with the wrong format when I enable Remote Debugging (which fires up a Google Chrome instance)? Because when I console.log the dates in Chrome they are converted normally. Thanks in advance! Now provide the response and nothing else.
This is most likely due to subtle differences between the JavaScript execution environments on the device, and in your remote debugger. In this case, the Date constructor seems to accept the locale-specific date formats in the Chrome remote debugging environment, but not on the device. This probably due to your computer's locale having been set to a culture that uses the dd.MM.yyyy format, and the emulator to something else, such as en-US . The ISO format works on both, because it's supported regardless of the locale. When you run the code on the device or simulator, the code executes in a JavaScriptCore on the device itself. This is the JavaScript engine React Native uses internally to run the application scripts When you turn remote debugging on, the React Native packager will instead execute the code in your computer's Chrome's JavaScript engine, V8 , and send messages between the browser and the device/simulator over WebSockets. You've run into one of the many edge cases that make remote debugging in React Native unreliable. You should always test all features on a real device without the debugger.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41874676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4256723/']}
jdg_72470
stackexchange
llm_judgeable_groundtruth_similarity
28627908
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 standard way to call static methods? I can think of using constructor or using the name of the class itself, I don't like the latter since it doesn't feel necessary. Is the former the recommended way, or is there something else? Here's a (contrived) example: class SomeObject { constructor(n){ this.n = n; } static print(n){ console.log(n); } printN(){ this.constructor.print(this.n); }} Now provide the response and nothing else.
Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect: class Super { static whoami() { return "Super"; } lognameA() { console.log(Super.whoami()); } lognameB() { console.log(this.constructor.whoami()); }}class Sub extends Super { static whoami() { return "Sub"; }}new Sub().lognameA(); // Supernew Sub().lognameB(); // Sub Referring to the static property via the class will be actually static and constantly give the same value. Using this.constructor instead will use dynamic dispatch and refer to the class of the current instance, where the static property might have the inherited value but could also be overridden. This matches the behavior of Python, where you can choose to refer to static properties either via the class name or the instance self . If you expect static properties not to be overridden (and always refer to the one of the current class), like in Java , use the explicit reference.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28627908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1115577/']}
jdg_72471
stackexchange
llm_judgeable_groundtruth_similarity
26518526
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to do the following: IF [a] = 1234 THEN JOIN ON TableA ELSE JOIN ON TableB If so, what is the correct syntax? Now provide the response and nothing else.
I think what you are asking for will work by joining the Initial table to both Option_A and Option_B using LEFT JOIN , which will produce something like this: Initial LEFT JOIN Option_A LEFT JOIN NULLORInitial LEFT JOIN NULL LEFT JOIN Option_B Example code: SELECT i.*, COALESCE(a.id, b.id) as Option_Id, COALESCE(a.name, b.name) as Option_NameFROM Initial_Table iLEFT JOIN Option_A_Table a ON a.initial_id = i.id AND i.special_value = 1234LEFT JOIN Option_B_Table b ON b.initial_id = i.id AND i.special_value <> 1234 Once you have done this, you 'ignore' the set of NULLS. The additional trick here is in the SELECT line, where you need to decide what to do with the NULL fields. If the Option_A and Option_B tables are similar, then you can use the COALESCE function to return the first NON NULL value (as per the example). The other option is that you will simply have to list the Option_A fields and the Option_B fields, and let whatever is using the ResultSet to handle determining which fields to use.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26518526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2197238/']}
jdg_72472
stackexchange
llm_judgeable_groundtruth_similarity
3575925
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given lists l1 = {1, 2} and l2 = {4, 5, 6 } I want to get a new list that has elements: rez = { {1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6} } Suggestions? Now provide the response and nothing else.
Yes it is possible. Eric Lippert wrote a very good article on this topic: Computing a Cartesian Product with LINQ If you only have 2 lists, then you could directly use multiple from like this: from a in s1 from b in s2 select new [] { a, b}; or even: s1.SelectMany(a => s2.Select(b => new [] { a, b })); But the solution given by Eric Lippert in the previous article allows you to compute the cartesian product of several sequences. With the following extension method: public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences){ IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item }));} You could write: var l1 = new[] {1, 2};var l2 = new[] {4, 5, 6};var l3 = new[] {7, 3};foreach (var result in new []{l1,l2,l3}.CartesianProduct()){ Console.WriteLine("{"+string.Join(",",result)+"}");} And obtain: {1,4,7}{1,4,3}{1,5,7}{1,5,3}{1,6,7}{1,6,3}{2,4,7}{2,4,3}{2,5,7}{2,5,3}{2,6,7}{2,6,3}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3575925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11545/']}
jdg_72473
stackexchange
llm_judgeable_groundtruth_similarity
15112819
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a weird problem at hand and I am struggling to find a solution. I have created a triangle <div> "container" using only CSS but what I would like now is to insert some text inside the container. The solution I am aiming for has to contain the text within the boundaries of the triangle no matter how much text is inserted as I am looking to create thumbnails. An example can be found here [note; this example is very basic and only shows the way I have chosen to create the triangle] Pushing it a little further, I want to create one triangle facing up and one facing down and the text has to be at the base of each one, so for the 1st triangle the text will be at the bottom and for the 2nd at the top, plan B is just to center the text within the triangle both vertically and horizontally. CSS: .up { text-align:right; width: 0px; height: 0px; border-style: inset; border-width: 0 100px 173.2px 100px; border-color: transparent transparent #007bff transparent; float: left; transform:rotate(360deg); -ms-transform:rotate(360deg); -moz-transform:rotate(360deg); -webkit-transform:rotate(360deg); -o-transform:rotate(360deg);} HTML: <div class="up"> <p>some information text goes here<p></div> Now provide the response and nothing else.
For your plan B ( to center the text within the triangle both vertically and horizontally ), which I prefer as solution, you could add this css rule: .up p { text-align: center; top: 80px; left: -47px; position: relative; width: 93px; height: 93px; margin: 0px;} Try it here: .up { width: 0px; height: 0px; border-style: inset; border-width: 0 100px 173.2px 100px; border-color: transparent transparent #007bff transparent; float: left; transform: rotate(360deg); -ms-transform: rotate(360deg); -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); -o-transform: rotate(360deg);}.up p { text-align: center; top: 80px; left: -47px; position: relative; width: 93px; height: 93px; margin: 0px;} <div class="up"> <p>some information text goes here <p></div> View on JSFiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15112819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2096200/']}
jdg_72474
stackexchange
llm_judgeable_groundtruth_similarity
2231859
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 there be a recursive sequence that begins with two terms, $a_1 = a$ and $a_2 = b$. The third term, $a_3$, is created by taking the geometric mean ($\sqrt{a \times b}$) of the previous two terms. The fourth term, $a_4$, is once again created by taking the geometric mean of the previous two terms. This process is repeated indefinitely. For example, if $a = 1$ and $b = 8$, $a_3 = \sqrt{1 \times 8}= \sqrt8 =2.82843... $ $a_4 = 4.75683...$ $a_5 = 3.66802...$ $a_6 = 4.17710...$ ...and so on. If you'll notice, as the terms go on, they are slowly converging towards one number. In this case, it's 4. This number will (tentatively) be called the "limit" ($L$). My question is, what is the general rule for finding $L$ in terms of $a$ and $b$? Now provide the response and nothing else.
Apply recurrence formula: $$ \begin{align}a_{n+2} &= \sqrt{a_{n+1}\cdot a_n} \\a_{n+2}^2 &= a_{n+1}\cdot a_n \end{align} $$ to compute explicitly: $$ \begin{align}a_3^2 &= a_2\cdot a_1, \quad \\a_4^2 &= a_3\cdot a_2, \quad \\a_5^2 &= a_4\cdot a_3, \quad \\ a_6^2 &= a_5\cdot a_4, \quad \\\ldots &= \ldots \\a_n^2 &= a_{n-1}\cdot a_{n-2}, \quad \\a_{n+1}^2 &= a_n\cdot a_{n-1}, \quad \\a_{n+2}^2 &= a_{n+1}\cdot a_n. \quad (1) \\\end{align}$$Multiply sides by sides:$$ a_3^2\cdot a_4^2\cdot a_5^2 \cdot a_6^2\ldots a_n^2\cdot a_{n+1}^2\cdot a_{n+2}^2 = a_1\cdot a_2^2 \cdot a_3^2\cdot a_4^2\ldots a_{n-1}^2\cdot a_n^2\cdot a_{n+1}$$ Simplify: $$ a_{n+1}\cdot a_{n+2}^2 = a_1\cdot a_2^2, \quad \forall n \ge 0. \quad (2) $$ For convenience, let's define: $$c^2 = a_1a_2^2. \quad (3) $$ Then $(2)$ becomes: $$ a_{n+2} = \frac{c}{\sqrt{a_{n+1}}} = \frac{c}{a_{n+1}^{1/2}}. \quad(4) $$ Apply $(4)$ to compute $a_{n+1}$ in terms of $a_n$:$$ \begin{align}a_{n+2} &= \frac{c}{ a_{n+1}^{1/2}} = \frac{c}{ c^{1/2}{a_n^{-1/4}}} \\&= c^{1/2} a_n^{1/2^2}. \quad (5)\end{align}$$ Thus, we can evaluate $(5)$ repeatedly for odd indices:$$ \begin{align}a_3 &= c^{1/2} \left( a_1 \right)^{1/2^2} \\a_5 &= c^{1/2}\left( a_3 \right)^{1/2^2} = c^{1/2} \left( c^{1/2} a_1^{1/2^2} \right)^{1/2^n} = \left(c\right)^{2^{-1} + 2^{-3}} a_1^{2^{-4}} \\a_7 &= c^{1/2}\left( a_5 \right)^{1/2^2} = c^{1/2} \left( c^{1/2} a_3^{1/2^2} \right)^{1/2^n} = \left(c\right)^{2^{-1} + 2^{-3} + 2^{-5}} a_1^{2^{-6}} \\\ldots &= \ldots \\a_{2n+1} &= c^S a_1^{2^{-2n}}, \quad (6) \end{align}$$where $S$ is the following geometric series:$$ S = \frac{1}{2} + \frac{1}{2^3} + \frac{1}{2^5} \ldots + \frac{1}{2^{2n-1}}$$ $$\implies S - \frac{1}{2^2}S = \frac{1}{2} -\frac{1}{2^{2n+1}} $$$$ \implies\lim_{n\to\infty} S = \frac{2}{3}.$$ Thus,$$\lim_{n\to\infty} a_{2n+1} = c^{2/3} a_1^0 = \sqrt[3]{a_1a_2^2}. \quad (7)$$ Similarly, it can be shown that for even indices: $$\lim_{n\to\infty} a_{2n+2} = c^{2/3} a_2^0 = \sqrt[3]{a_1a_2^2}. \quad (8)$$ Because both the odd and even sequences of $a_n$ are convergent to the same value, the sequence $a_n$ is convergent to the same value. $$\lim_{n\to\infty} a_n = L = \sqrt[3]{a_1a_2^2}. \quad (9) $$ Thus, for the problem of interest, we have: $$ L = \sqrt[3]{ab^2} = \sqrt[3]{1\cdot 8^2} = 4 $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2231859', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/436241/']}
jdg_72475
stackexchange
llm_judgeable_groundtruth_similarity
60891197
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 installed az-cli using azure link and terraform apt-get.Getting below error while Error: Error running plan: 1 error(s) occurred: provider.azurerm: Error building AzureRM Client: Azure CLI Authorization Profile was not found. Please ensure the Azure CLI is installed and then log-in with az login . Tried to uninstall and reinstall, but no luck. Now provide the response and nothing else.
Preface: Throughout this answer, I mention some popular YAML implementations. Those mentions are never exhaustive since I do not know all YAML implementations out there. I will use YAML terms for data structures: Atomic text content (even numbers) is a scalar . Item sequences, known elsewhere as arrays or lists, are sequences . A collection of key-value pairs, known elsewhere as dictionary or hash, is a mapping . If you are using Python, using ruamel will help you preserve quite some formatting since it implements round-tripping up to native structures. However, it isn't perfect and cannot preserve all formatting. Background The process of loading YAML is also a process of losing information. Let's have a look at the process of loading/dumping YAML, as given in the spec: When you are loading a YAML file, you are executing some or all of the steps in the Load direction, starting at the Presentation (Character Stream) . YAML implementations usually promote their most high-level APIs, which load the YAML file all the way to Native (Data Structure) . This is true for most common YAML implementations, e.g. PyYAML/ruamel, SnakeYAML, go-yaml, and Ruby's YAML module. Other implementations, such as libyaml and yaml-cpp, only provide deserialization up to the Representation (Node Graph) , possibly due to restrictions of their implementation languages (loading into native data structures requires either compile-time or runtime reflection on types). The important information for us is what is contained in those boxes. Each box mentions information which is not available anymore in the box left to it. So this means that styles and comments , according to the YAML specification, are only present in the actual YAML file content, but are discarded as soon as the YAML file is parsed . For you, this means that once you have loaded a YAML file to a native data structure, all information about how it originally looked in the input file is gone. Which means that when you dump the data, the YAML implementation chooses a representation it deems useful for your data. Some implementations let you give general hints/options, e.g. that all scalars should be quoted, but that doesn't help you restore the original formatting. Thankfully, this diagram only describes the logical process of loading YAML; a conforming YAML implementation does not need to slavishly conform to it. Most implementations actually preserve data longer than they need to. This is true for PyYAML/ruamel, SnakeYAML, go-yaml, yaml-cpp, libyaml and others. In all these implementations, the style of scalars, sequences and mappings is remembered up until the Representation (Node Graph) level. On the other hand, comments are discarded rather early since they do not belong to an event or node (the exceptions here is ruamel which links comments to the following event, and go-yaml which remembers comments before, at and after the line that created a node). Some YAML implementations (libyaml, SnakeYAML) provide access to a token stream which is even more low-level than the Event Tree . This token stream does contain comments, however it is only usable for doing things like syntax highlighting, since the APIs do not contain methods for consuming the token stream again. So what to do? Loading & Dumping If you need to only load your YAML file and then dump it again, use one of the lower-level APIs of your implementation to only load the YAML up until the Representation (Node Graph) or Serialization (Event Tree) level. The API functions to search for are compose / parse and serialize / present respectively. It is preferable to use the Event Tree instead of the Node Graph as some implementations already forget the original order of mapping keys (due to internally using hashmaps) when composing . This question , for example, details loading / dumping events with SnakeYAML. Information that is already lost in the event stream of your implementation, for example comments in most implementations, is impossible to preserve. Also impossible to preserve is scalar layout, like in this example: "1 \x2B 1" This loads as string "1 + 1" after resolving the escape sequence. Even in the event stream, the information about the escape sequence has already been lost in all implementations I know. The event only remembers that it was a double-quoted scalar, so writing it back will result in: "1 + 1" Similarly, a folded block scalar (starting with > ) will usually not remember where line breaks in the original input have been folded into space characters. To sum up, loading to the Event Tree and dumping again will usually preserve: Style: unquoted/quoted/block scalars, flow/block collections (sequences & mappings) Order of keys in mappings YAML tags and anchors You will usually lose: Information about escape sequences and line breaks in flow scalars Indentation and non-content spacing Comments – unless the implementation specifically supports putting them in events and/or nodes If you use the Node Graph instead of the Event Tree , you will likely lose anchor representations (i.e. that &foo may be written out as &a later with all aliases referring to it using *a instead of *foo ). You might also lose key order in mappings. Some APIs, like go-yaml, don't provide access to the Event Tree , so you have no choice but to use the Node Graph instead. Modifying Data If you want to modify data and still preserve what you can of the original formatting, you need to manipulate your data without loading it to a native structure. This usually means that you operate on YAML scalars, sequences and mappings, instead of strings , numbers , lists or whatever structures the target programming language provides. You have the option to either process the Event Tree or the Node Graph (assuming your API gives you access to it). Which one is better usually depends on what you want to do: The Event Tree is usually provided as stream of events. It may be better for large data since you do not need to load the complete data in memory; instead you inspect each event, track your position in the input structure, and place your modifications accordingly. The answer to this question shows how to append items giving a path and a value to a given YAML file with PyYAML's event API. The Node Graph is better for highly structured data. If you use anchors and aliases, they will be resolved there but you will probably lose information about their names (as explained above). Unlike with events, where you need to track the current position yourself, the data is presented as complete graph here, and you can just descend into the relevant sections. In any case, you need to know a bit about YAML type resolution to work with the given data correctly. When you load a YAML file into a declared native structure (typical in languages with a static type system, e.g. Java or Go), the YAML processor will map the YAML structure to the target type if that's possible. However, if no target type is given (typical in scripting languages like Python or Ruby, but also possible in Java), types are deduced from node content and style. Since we are not working with native loading because we need to preserve formatting information, this type resolution will not be executed. However, you need to know how it works in two cases: When you need to decide on the type of a scalar node or event, e.g. you have a scalar with content 42 and need to know whether that is a string or integer . When you need to create a new event or node that should later be loaded as a specific type. E.g. if you create a scalar containing 42 , you might want to control whether that it is loaded as integer 42 or string "42" later. I won't discuss all the details here; in most cases, it suffices to know that if a string is encoded as a scalar but looks like something else (e.g. a number), you should use a quoted scalar. Depending on your implementation, you may come in touch with YAML tags . Seldom used in YAML files (they look like e.g. !!str , !!map , !!int and so on), they contain type information about a node which can be used in collections with heterogeneous data. More importantly, YAML defines that all nodes without an explicit tag will be assigned one as part of type resolution. This may or may not have already happened at the Node Graph level. So in your node data, you may see a node's tag even when the original node does not have one. Tags starting with two exclamation marks are actually shorthands , e.g. !!str is a shorthand for tag:yaml.org,2002:str . You may see either in your data, since implementations handle them quite differently. Important for you is that when you create a node or event, you may be able and may also need to assign a tag. If you don't want the output to contain an explicit tag, use the non-specific tags ! for non-plain scalars and ? for everything else on event level. On node level, consult your implementation's documentation about whether you need to supply resolved tags. If not, same rule for the non-specific tags applies. If the documentation does not mention it (few do), try it out. So to sum up: You modify data by loading either the Event Tree or the Node Graph , you add, delete or modify events or nodes in the data you get, and then you present the modified data as YAML again. Depending on what you want to do, it may help you to create the data you want to add to your YAML file as native structure, serialize it to YAML and then load it again as Node Graph or Event Tree . From there, you can include it in the structure of the YAML file you want to modify. Conclusion / TL;DR YAML has not been designed for this task. In fact, it has been defined as a serialization language , assuming that your data is authored as native data structures in some programming language and from there dumped to YAML. However, in reality, YAML is used a lot for configuration, meaning that you typically write YAML by hand and then load it into native data structures. This contrast is the reason why it is so difficult to modify YAML files while preserving formatting: The YAML format has been designed as transient data format, to be written by one application, and then to be loaded by another (or the same) application. In that process, preserving formatting does not matter. It does, however, for data that is checked-in to version control (you want your diff to only contain the line(s) with data you actually changed), and other situations where you write your YAML by hand, because you want to keep style consistent. There is no perfect solution for changing exactly one data item in a given YAML file and leaving everything else intact. Loading a YAML file does not give you a view of the YAML file, it gives you the content it describes. Therefore, everything that is not part of the described content – most importantly, comments and whitespace – is extremely hard to preserve. If format preservation is important to you and you can't live with the compromises made by the suggestions in this answer, YAML is not the right tool for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60891197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2750644/']}
jdg_72476
stackexchange
llm_judgeable_groundtruth_similarity
2661
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Wendy Davis, a Texan Democrat candidate, made false statements about her past. She said how she was single at 19 when she'd actually gotten divorced at 21 . Davis might have separated from her first husband at age 19, but she was not "single" until she was 21. But "teenage single mother" is obviously a much better hardscrabble political talking point than the truth. It's still written in her bio , and I was wondering: Is she legally guilty of a crime? Can she be kicked out of office if she gets elected? (When she lied that she was single at 19), it was under oath .) Now provide the response and nothing else.
Lying about one's past is not itself a crime. It is protected speech by the first amendment. In fact, the Supreme Court recently ruled that even lying that one had received a Medal of Honor was constitutionally protected speech . Perjury is illegal, but a false statement made under oath is not necessarily going to result in a conviction of perjury. First, the person making the statement must know the statement is false. Given that the statement Wendy Davis made was about a significant event in her own past, she likely was aware of the truth value of the statement. However, perjury must also meet standards of materiality , which requires that the statement be one likely to influence the court's decision. Given that the case in which she testified and made that statement was one about redistricting, it is unlikely that the age at which Wendy Davis got divorced would be considered material. She could be kicked out of office, but what she said about the age at which she got divorced doesn't necessitate impeachment. In Texas, a Governor can be impeached by a majority vote in the state House and 2/3rds majority vote in the state Senate . There are no specific impeachable offenses. The Texan congress could decide to impeach on the grounds that she mislead people in her biography, or on some other grounds, or could choose not to impeach at all. By the way, this is the original article to which Brietbart was referring.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/2661', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/2317/']}
jdg_72477
stackexchange
llm_judgeable_groundtruth_similarity
4014294
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having some problems defining some operator overloads for template classes. Let's take this hypothetical class for example. template <class T>class MyClass { // ...}; operator+= // In MyClass.hMyClass<T>& operator+=(const MyClass<T>& classObj);// In MyClass.cpptemplate <class T>MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) { // ... return *this;} Results in this compiler error: no match for 'operator+=' in 'classObj2 += classObj1' operator<< // In MyClass.hfriend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);// In MyClass.cpptemplate <class T>std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj) { // ... return out;} Results in this compiler warning: friend declaration 'std::ostream& operator<<(std::ostream&, const MyClass<T>&)' declares a non-template function What am I doing wrong here? Now provide the response and nothing else.
You need to say the following (since you befriend a whole template instead of just a specialization of it, in which case you would just need to add a <> after the operator<< ): template<typename T>friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj); Actually, there is no need to declare it as a friend unless it accesses private or protected members. Since you just get a warning , it appears your declaration of friendship is not a good idea. If you just want to declare a single specialization of it as a friend, you can do that like shown below, with a forward declaration of the template before your class, so that operator<< is regognized as a template. // before class definition ...template <class T>class MyClass;// note that this "T" is unrelated to the T of MyClass !template<typename T>std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);// in class definition ...friend std::ostream& operator<< <>(std::ostream& out, const MyClass<T>& classObj); Both the above and this way declare specializations of it as friends, but the first declares all specializations as friends, while the second only declares the specialization of operator<< as a friend whose T is equal to the T of the class granting friendship. And in the other case, your declaration looks OK, but note that you cannot += a MyClass<T> to a MyClass<U> when T and U are different type with that declaration (unless you have an implicit conversion between those types). You can make your += a member template // In MyClass.htemplate<typename U>MyClass<T>& operator+=(const MyClass<U>& classObj);// In MyClass.cpptemplate <class T> template<typename U>MyClass<T>& MyClass<T>::operator+=(const MyClass<U>& classObj) { // ... return *this;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4014294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217649/']}
jdg_72478
stackexchange
llm_judgeable_groundtruth_similarity
81392
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). byte a = 23;byte b = 34;byte c = a + b; In this example, the compile error is on the third line. Now provide the response and nothing else.
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators. To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type. byte a = 23;byte b = 34;byte c = (byte) (a + b); Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.) Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/81392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7732/']}
jdg_72479
stackexchange
llm_judgeable_groundtruth_similarity
3374
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given the recent spate of intrusions into various networks which have included compromise of subscriber identity and contact information, I figured it would be good for us to have a thread on how to spot and react to a "phishing" attempt. While the most common and prominent avenue for phishing is by e-mail, these social engineering attempts can really take on any form. If Oscar has all of Alice's contact information (as may be the case in recent high-profile attacks) he may try to manipulate her via e-mail, phone call, SMS, or even by postal letter. Oscar's attacks can be further augmented by intimate knowledge of Alice's more personal details. (Again, these may have been gained in some recent incidents.) Such details may include credit card numbers, purchase histories, birth date, dependents, "security questions and answers", etc. Still, regardless of the attack vector and complexity, there are a number of features that often set phishing attempts apart from legitimate vendor correspondence. Additionally, there's a number of preventative and reactive measures which can be taken to protect oneself from falling victim to these attacks. What are some "red flags" that are commonly found in phishing attempts? What are some ways Alice can verify the identity of a suspected phisher, if she believes the contact may be legitimate? If a suspect message includes a request for actions to be taken by Alice, and she believes the message may be legitimate, how should she follow up? Again, answers are welcome for all attack vectors which may be used by someone with complete contact information for the target, possibly including: E-mail Phone number Voice call - "vishing" SMS messaging - "smishing" Physical address Postal mail Door-to-door solicitation Note to moderators - This thread might be a good fit for Community Wiki. Now provide the response and nothing else.
Phishing "red flags": Any un-solicited communication regarding any account you have. Certainly, this criteria is the easiest one to have a false-positive hit on, and probably shouldn't be the only clue you act on, but it's also your first clue. Any un-solicited communication regarding any account you don't have. There's definitely something wrong, if it appears that an organization with whom you have no business relationship is contacting you. These require careful consideration, and may necessitate additional defensive actions. Generally, a communication of this type is one of three things: Spam Phishing Evidence of identity theft Un-solicited, or unexpected e-mail attachments. Anymore, I actually get a little irritated by anyone who sends me an attachment in e-mail without advance notice or request. There's so many other ways to share data over the Internet and across intranets these days, that e-mailing it as an attachment is rarely an actual necessity. If there's a form that you must fill out, or document you really need to read, most legitimate organizations will post it on their official website somewhere that you can access it with an appropriate level of security. Requests for you to send your username and/or password, or other personal details. No legitimate organization should be requesting any of this from you, via a contact that they initiated. Also, no legitimate organization will ever ask you for your password via any person-to-person contact. Common phrases used here are "verify your account" or "confirm billing information". Proliferate spelling, grammar, or factual errors. Some phishers are getting better about avoiding this, but it is still a common hallmark of cheap phishing attacks. An overwhelming emphasis on urgency. Phishers often want you to think you must rush to action, so that you might not take enough time to realize their scam. Overly formal, yet very generalized salutations. Stuff like "Mr/Mrs" or "Dear Sir or Madam" or "To Whom It May Concern". Unless this is a message you're expecting, and the tone is appropriate for the context, the unnecessary cordiality is probably just being used to warm you up to buy snake oil. Most legitimate organizations know their audience, and will customize their greeting to either identify you by your first and/or last name or username, or will have a greeting that specifically identifies you as their customer. Anything "too good to be true". You know the old saying. This is also another very general indicator that should set off anyone's alarms, regardless of how the "deal" is conveyed. FROM addresses that don't match the REPLY address. This is another criteria that may be prone to false positives, but should still raise your level of suspicion. Many legitimate organizations that send mass e-mails will more than likely be doing so from an address dedicated for that purpose. So, a legitimate e-mail will probably include either non-e-mail-based follow-up instructions, separate follow-up e-mail addresses, specific instructions for replying to the e-mail (keywords for subject and/or body), and/or a specific notice stating that direct replies to the e-mail will neither be received nor answered. Hyperlinked URLs whose targets do not match the link text. Before you even think about actually clicking on any hyperlink in an e-mail, hover your mouse over it for a second to see where it really sends you. If the link text is http://google.com/ but the link actually points you to somewhere else like http://lmgtfy.com/ *, you probably don't want to go there. Such link may appear like this: http://google.com/ (Mouseover to see actual target.) Hyperlinks that use shortened URLs. This criteria may have a lot of false-positive hits, but still warrants some cautionary measures and perhaps a raised level of suspicion. Hyperlinks with very long and complex targets, even to "legitimate" websites. These may possibly be cross-site scripting attacks. * http://lmgtfy.com is actually a benign website, and was only used to provide an example of URL link-text not pointing to where it says it's pointing. Phishing countermeasures: Stop, breathe, and think. No matter what they tell you, don't let yourself get into any rush. If someone is initiating a contact with you, taking time out of your day, they can stand to wait a few minutes (or even hours) while you sort things out for yourself, and decide what you're going to do. Do not offer any information. This is what phishers want. Even if you're not giving them the specific information they're asking for, you may still be giving them something else they can use against you later. Do not open any e-mail attachments. Just. Don't. Do. It. Do not follow any hyperlinks or URLs. Again, just don't. Do your own research. Google. Wiki. Snopes. Repeat. Do not do anything they ask, in the way they want you to do it. If it's a legitimate communication, you'll be able to find your own way of doing what's asked of you without them. For e-mails wanting you to go to a specific URL, instead go to the known-good-and-trusted HTTPS website of the organization and find your way to the requested function from there. For phone, mail, or other interactions, end the conversation and go use Google or the organization's known-good-and-trusted homepage to find (or verify) the correct contact information for follow-up. Do not reply. This goes along with not doing what they ask, how they ask it. Again, if the contact is legitimate, you should be able to follow up without actually answering back to the solicitor themselves. Even if the e-mail appears to come from an address referenced on a legitimate website, do not use the reply function . Instead, use a link or form on the known-good-and-trusted site, or manually fill in the e-mail address on a new message. Just say no. To drugs, and solicitors of every kind. Whatever service they are offering is not one that you need them in order to acquire. If the offer is legitimate, you will be able to find a comparable level of service via your own research, and likely through safer and more secure mechanisms. If they really insist that they need to get credit for the service, take their information and do your own research and validation before doing any business directly with them. Ask a pro. When in doubt, ask someone you trust who's "in the know" about these things. This may even just be part of the "Don't do what they ask." step - the purported organization's help desk (which you'll look up yourself) should definitely be able to tell you if the contact was legitimate.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/3374', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/953/']}
jdg_72480
stackexchange
llm_judgeable_groundtruth_similarity
16102203
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 web server in java like this: public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(80), 0); server.createContext("/", new HomeHandler()); server.setExecutor(null); // creates a default executor server.start();} And here's the HomeHandler : class HomeHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { String filepath = "C:\\Public\\home.html"; String response = getPage(filepath); t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }} and finally here's the function getPage() : private static String getPage(String page){ String toret = ""; BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader(page)); while ((sCurrentLine = br.readLine()) != null) { toret += sCurrentLine; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } return toret;} But when my home page loads, it has an image in it so the browser makes another request to my server for the image, I made a similar handler for images which does the same thing, i.e, calls the function getPage() passing in as arguments the image's filepath... But when it actually runs in the browser it doesn't show the image. But it correctly tells the size of the image when I open the image alone in the new tab (Google Chrome is my Browser, the latest one as of today).. Now provide the response and nothing else.
You are correct that you need a trigger, because setting a default value for the column won't work for you - default values only work for null values and don't help you in preventing blank values. In postgres there are a couple of steps to creating a trigger: Step 1: Create a function that returns type trigger : CREATE FUNCTION my_trigger_function()RETURNS trigger AS $$BEGIN IF NEW.C1 IS NULL OR NEW.C1 = '' THEN NEW.C1 := 'X'; END IF; RETURN NEW;END;$$ LANGUAGE plpgsql Step 2: Create a trigger that fires before insert, which allows you to change values befre they are inserted, that invokes the above function: CREATE TRIGGER my_triggerBEFORE INSERT ON TFOR EACH ROWEXECUTE PROCEDURE my_trigger_function() And you're done. See the above code executing on SQLFIddle demonstrating it working correctly! You mention in a comment that the value 'X' is retrieved from a subquery. If so, change the relevant line so something like: NEW.C1 := (select some_column from some_table where some_condition);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16102203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2243116/']}
jdg_72481
stackexchange
llm_judgeable_groundtruth_similarity
11552437
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 not sure why this doesn't work. When I do git branch -a , this is what I see: I'm trying to pull from the DownloadManager on the online GitHub repository. I have tried git pull, but then it complains about not knowing which branch to pull from git pull origin, doesn't know which branch git pull origin downloadmanager fatal: Couldn't find remote ref downloadmanager. Unexpected end of commands stream git pull origin remotes/origin/DownloadManager 'fatal couldn't find remote ref remotes/origin/DownloadManager. Unexpected end of commands stream Is there something I'm missing? In Xcode, When I try to connect to the repository, nothing ever shows up. I have been able to push to it in the past. But I can't push again until I pull the most recent changes. Now provide the response and nothing else.
Be careful - you have case mixing between local and remote branch! Suppose you are in local branch downloadmanager now ( git checkout downloadmanager ) You have next options: Specify remote branch in pull/push commands every time (case sensitive): git pull origin DownloadManager or git pull origin downloadmanager:DownloadManager Specify tracking branch on next push: git push -u origin DownloadManager ( -u is a short form of --set-upstream ) this will persist downloadmanager:DownloadManager link in config automatically (same result, as the next step). Set in git config default remote tracking branch: git branch -u downloadmanager origin/DownloadManager (note, since git 1.8 for branch command -u is a short form of --set-upstream-to , which is a bit different from deprecated --set-upstream ) or edit config manually (I prefer this way): git config --local -e -> This will open editor. Add block below (guess, after "master" block): [branch "downloadmanager"] remote = origin merge = refs/heads/DownloadManager and after any of those steps you can use easily: git pull If you use TortoiseGit:RightClick on repo -> TortoiseGit -> Settings -> Git -> Edit local .git/config
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11552437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207524/']}
jdg_72482
stackexchange
llm_judgeable_groundtruth_similarity
45217210
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i would like to use if statement in the return of render method , what i mean is something like this : export default class App extends Component { render() { return( <View> if(this.state.error) { <View> <Image source={{"error"}} /> <Text>An Error Happen</Text> </View> } else { <View> <List dataArray={this.state.items}></List> </View> } </View> ); }} i can use ternary operator , but what i want is to use if statement if it possible Now provide the response and nothing else.
Background What is the difference between a statement and expression Specific to JavaScript: What is the difference between an expression and a statement in JS? JavaScript: declarations vs expressions vs statements return expects an expression as the argument. if statements are not expressions (makes sense, since statement is in the name). The implementation details of JSX (that stuff with <Tags> , but in javascript) is also relevant. JSX is compiled into normal JavaScript. <MyButton color="blue" shadowSize={2}> Click Me</MyButton> compiles to React.createElement( MyButton, {color: 'blue', shadowSize: 2}, 'Click Me') documentation . If you want to evaluate a JavaScript expression in JSX you need to enclose it in curly braces. const myButtonColor = 'blue'//...<MyButton color={myButtonColor} shadowSize={2}> Click Me</MyButton> Back to the Question Ways of accomplishing if-like functionality: inline logical and ( && ) ternary operator ( ? ) return in if/else statements Let's look at some examples: Inline Logical And render() { return ( <View> {this.state.error && <Text> There's an error! </Text>} </View> )} This method is the simplest and I recommend trying it first. It makes sense when you don't want to do anything if the condition evaluates to false. && behaves a bit different in javascript than in other languages. When this.state.error evaluates to false, render returns this.state.error, which may have unintended consequences if this.state.error happens to be the empty string or 0 . Ternary Operator render() { return ( <View> {this.state.error ? <Text>Error!</Text> : <Text>No Error!</Text>} </View> )} The biggest problem with this is that the lines get long pretty quickly. You can get around this with parentheses. render() { return ( <View> {this.state.error ? ( <Text>Long, detailed error message</Text> ) : ( <Text>No Error!</Text> )} </View> )} You could alternatively use JavaScript strings declared before return along with this method. Return in if Block render() { if(this.state.error) { return (<Text>Long, detailed error message</Text>) } else { return (<Text>No Error!</Text>) }} The problem with this method is if that if you have a long render method and a small conditional change, you will have to nearly repeat the render function in each if block. I generally use this method as a last resort.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45217210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5136659/']}
jdg_72483
stackexchange
llm_judgeable_groundtruth_similarity
41370560
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 class named Identity . In my javadoc comments I am referencing it as a plural. I can think of two solutions: change the reference to <code>Identities</code> or <code>Identity</code> s. Neither of these feel correct, and I'm wondering if there's a better solution. Here is an example for clarity: /** * Returns an <code>IdentityBank</code> of <code>Identity</code>s with the given sex. */ or /** * Returns an <code>IdentityBank</code> of <code>Identities</code> with the given sex. */ Now provide the response and nothing else.
Use a "...(s)" style plural label, with a {@link} to the class: /** * Returns an {@link IdentityBank} of {@link Identity Identity(s)} with the given sex. */ This will render as: Returns an IdentityBank of Identity(s) with the given sex. It's easy and more natural to read, and obvious and clear what you are saying. You should be using {@link} anyway for classes. It takes care of <code> style formatting, and provides an HTML link to the actual class. You could code the "(s)" after the link, ie {@link Identity}(s) , meaning a completely conventional usage of {@link} , but there would be a font change mid-word: Returns an IdentityBank of Identity (s) with the given sex. which IMHO reduces clarity and could cause confusion.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41370560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4756763/']}
jdg_72484
stackexchange
llm_judgeable_groundtruth_similarity
2567399
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The set of all equivalence classes of an equivalence relation on a an uncountable set may be countable or uncountable. Can you please give examples of each. $x$~$y$:x is connected via a path. The equivalence class is entire $\mathbb R$ is an equivalence class. right? I couldn't find an example of The set of all equivalence classes of an equivalence relation on an uncountable set be uncountable. Please help me. I have found one example. I don't know, revising the question with an attempt is legal or not. sorry for an incorrect attempt. Now provide the response and nothing else.
On any set you have two very simple equivalence relations (smallest and larges, if you look at ordering by inclusion). If each element is equivalent to each other, you have single equivalence class $\{X\}$. (This corresponds to equivalence relation $R=X\times X$, i.e. $x\sim y$ for every $x,y\in X$.) If each element is equivalent only to itself, the equivalence classes are singletons. So the partition is $\{\{x\}; x\in X\}$ and it has the same cardinality as $X$. (In the case $X=\mathbb R$ it is uncountable.) This is the relation $R=\{(x,y); x=y\}$, i.e. $x\sim y$ iff $x=y$. If you want an equivalence relation on $\mathbb R$ such that there are countably many equivalence classes, simply take any partition of $\mathbb R$ into countably many subsets and the corresponding equivalence relation. For example, you could take the partition $\mathcal P=\{[x,x+1); x\in\mathbb Z\}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2567399', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_72485
stackexchange
llm_judgeable_groundtruth_similarity
52711
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using xmllint to parse xml file which has several tags and each tag has several attributes. Sample structure as shown below: <root> <child attr1="abc" attr2="def" attr3="ghi" /> ... ...</root> I need to fetch the values from the attributes attr1 , attr2 and attr3 . So far, I have tried the following which is giving the data of one attribute perfectly echo 'cat //root/child/@attr1' | xmllint --shell data.xml This output attr1="abc" So, my question is, how can we specify more than one attributes in the string to get the required output as attr1="abc"attr2="def"attr3="ghi" I tried the following for this, but no good result: echo 'cat //root/child/@*[attr1|attr2|attr3]' | xmllint --shell data.xml echo 'cat //root/child/@*[attr1 or attr2 or attr3]' | xmllint --shell data.xml output for above was that the echo statement was re-echoed again that means, the xmllint didn't accept it as input. Any ideas on how to go about this? Now provide the response and nothing else.
As far as I know the | separator can be used only on entire paths: echo 'cat /root/child/@attr1|/root/child/@attr2|/root/child/@attr3' | xmllint --shell data.xml (As // means at any depth, “//root” puts the parser to pointless extra work. Assuming your sample XML looks has similar structure as the real one (so root is indeed the XML's root node), better use “/root/child”.) Or you can use an expression with XPath functions: echo 'cat /root/child/@*[name()="attr1" or name()="attr2" or name()="attr3"]' | xmllint --shell data.xml If you need all attributes with “attr*” name, you can use a generic expression: echo 'cat /root/child/@*[starts-with(name(),"attr")]' | xmllint --shell data.xml
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/52711', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17265/']}
jdg_72486
stackexchange
llm_judgeable_groundtruth_similarity
6385190
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 Sakamoto's algorithm to find out the day of week from a given date.Can anybody tell me the correctness of this algorithm? I just want this from 2000 to 2099. The algorithm from Wikipedia is given for reference. int dow(int y, int m, int d){ static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; y -= m < 3; return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;} Now provide the response and nothing else.
Well, you can tell just by looking at it that it is correct... Assuming that the t[] array is correct, which you can verify with just 12 spot checks (one for each month using any day/year). The y -= m < 3 is a nice trick. It creates a "virtual year" that starts on March 1 and ends on February 28 (or 29), putting the extra day (if any) at the end of the year; or rather, at the end of the previous year. So for example, virtual year 2011 began on Mar 1 and will end on February 29, while virtual year 2012 will begin on March 1 and end on the following February 28. By putting the added day for leap years at the end of the virtual year, the rest of the expression is massively simplified. Let's look at the sum: (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7 There are 365 days in a normal year. That is 52 weeks plus 1 day. So the day of the week shifts by one day per year, in general. That is what the y term is contributing; it adds one to the day for each year. But every four years is a leap year. Those contribute an extra day every four years. Thanks to the use of virtual years, we can just add y/4 to the sum to count how many leap days happen in y years. (Note that this formula assumes integer division rounds down .) But that is not quite right, because every 100 years is not a leap year. So we have to subtract off y/100 . Except that every 400 years is a leap year again. So we have to add y/400 . Finally we just add the day of the month d and an offset from a table that depends on the month (because the month boundaries within the year are fairly arbitrary). Then take the whole thing mod 7 since that is how long a week is. (If weeks were eight days, for example, what would change in this formula? Well, it would be mod 8, obviously. Also the y would need to be 5*y , because 365 % 8 == 5. Also the month table t[] would need adjusting. That's it.) Incidentally, Wikipedia's statement that the calendar is "good until 9999" is totally arbitrary. This formula is good for however long we stick with the Gregorian calendar , whether that is 10 years, 100 years, 1000 years, or 1 million years. [edit] The above argument is essentially a proof by induction. That is, assuming that the formula works for a particular (y,m,d), you prove that it works for (y+1,m,d) and (y,m,d+1). (Where y is a "virtual year" starting March 1.) So the key question is, does the sum change by the correct amount as you move from one year to the next? With knowledge of the leap year rules, and with the "virtual year" having the extra day at year end, it trivially does.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6385190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/721597/']}
jdg_72487
stackexchange
llm_judgeable_groundtruth_similarity
27070220
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 update the items of a recycleview using notifyDataSetChanged(). This is my onBindViewHolder() method in the recycleview adapter. @Overridepublic void onBindViewHolder(ViewHolder viewHolder, int position) { //checkbox view listener viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //update list items notifyDataSetChanged(); } });} What I want to do is update the list items, after I check a checkbox. I get an illegal exception though: "Cannot call this method while RecyclerView is computing a layout or scrolling" java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462) at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982) at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493) at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338) at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111) I also used notifyItemChanged(), same exception. Any secret way to update to notify the adapter that something changed? Now provide the response and nothing else.
You should move method 'setOnCheckedChangeListener()' to ViewHolder which is inner class on your adapter. onBindViewHolder() is not a method that initialize ViewHolder .This method is step of refresh each recycler item.When you call notifyDataSetChanged() , onBindViewHolder() will be called as the number of each item times. So If you notifyDataSetChanged() put into onCheckChanged() and initialize checkBox in onBindViewHolder() , you will get IllegalStateException because of circular method call. click checkbox -> onCheckedChanged() -> notifyDataSetChanged() -> onBindViewHolder() -> set checkbox -> onChecked... Simply, you can fix this by put one flag into Adapter. try this, private boolean onBind;public ViewHolder(View itemView) { super(itemView); mCheckBox = (CheckBox) itemView.findViewById(R.id.checkboxId); mCheckBox.setOnCheckChangeListener(this);}@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(!onBind) { // your process when checkBox changed // ... notifyDataSetChanged(); }}...@Overridepublic void onBindViewHolder(YourAdapter.ViewHolder viewHolder, int position) { // process other views // ... onBind = true; viewHolder.mCheckBox.setChecked(trueOrFalse); onBind = false;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27070220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1850879/']}
jdg_72488
stackexchange
llm_judgeable_groundtruth_similarity
47945066
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 run rustup update to update my toolchain and saw two warnings: warning: tool `rustfmt` is already installed, remove it from `/Users/<username>/.cargo/bin`, then run `rustup update` to have rustup manage this tool.warning: tool `cargo-fmt` is already installed, remove it from `/Users/<username>/.cargo/bin`, then run `rustup update` to have rustup manage this tool. I followed the instructions in the warning messages, then tried to run rustfmt again. I got the error error: toolchain 'stable-x86_64-apple-darwin' does not have the binary rustfmt` What went wrong and how can I fix it? Now provide the response and nothing else.
The most standard and reliable way to have rustfmt in your system is to ensure that the rustfmt component is installed in your Rustup toolchain. rustup component add rustfmt Or for a specific toolchain: rustup component add rustfmt --toolchain nightly-2020-06-09 There is a possibility that the tests and builds in nightly toolchains fail, which means that those are not as likely to always have this component. The latest stable and beta toolchains will usually have it in accordance to the No Tool Breakage Week policy. In order to let Rustup manage rustfmt , see the following steps: Once you update Rustup to the latest version, you may receive the message warning: tool rustfmt is already installed . Remove the binaries from Cargo's binary folder, as suggested. cargo uninstall rustfmt (or rustfmt-nightly if you installed that) works well. Run rustup update to let it fill in the deleted binaries with its own, managed rustfmt and cargo-fmt . Ensure that the toolchain that you wish to work with is installed (e.g. stable ) Run the command above too ensure that the rustfmt component is installed for that toolchain. With that done, calling rustfmt will work as intended: $ rustup run stable rustfmt --versionrustfmt 1.4.12-stable (a828ffea 2020-03-11) Or via the Cargo subcommand: $ cargo fmt --versionrustfmt 1.4.12-stable (a828ffea 2020-03-11) In the early days, rustfmt managed by Rustup could have been a bit confusing, because Rustup did not always have rustfmt , and would still too often emerge as a preview component which had to be installed under the name rustfmt-preview . There are a few relevant issues and PRs on the subject ( #1305 and #1310 ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47945066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1032340/']}
jdg_72489
stackexchange
llm_judgeable_groundtruth_similarity
149198
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: (Apologies upfront if this question seems too vague, I'm trying to formulate the problem statement as I ask this) I'm thinking about circuit assembly in a high component variability / low MOQ environment, from the standpoint of passive components. Assuming identical footprints, I'd like to be able to substitute: Resistors tighter % tolerance for looser higher wattage for lower Capacitors Higher voltage for lower What I'm getting at is - if I'm prototyping lots of different designs, parts inventory management becomes a substantial issue. If I could aggregate by component value, and use the same parts where possible, inventory requirements go down, likely enough to offset the potentially higher cost of the individual items. Does an approach like this work, or would I break designs by doing this? If this works, what other components can I try to standardize? Now provide the response and nothing else.
Yes, this is valid and commonly done for one-offs produced from local "lab" stock. There is cost in maintain more parts, which can easily dwarf the savings of using 5% resistors instead of 1% resistors in those cases where 5% is good enough. There are also costs in production for each different part used. Even at high volumes, the pick and place machine has to be set up separately, different reels need to be bought, kept somewhere, etc. Unless you have a very high volume product, it makes no sense to use a 10 kΩ 5% resistor in one place when you need to use 1% tolerance of otherwise the same resistor elsewhere on the same board. In other cases you have to be careful that the better spec in one dimension doesn't cause tradeoffs you care about in another dimension. For example, you mention higher voltage capacitors substituted where lower voltage is required. That's OK electrically, but higher voltage caps will be physically larger most of the time. The same is true for higher wattage resistors. Electrically, a 2 W 100 Ω resistor is a superset of a ¼ W 100 Ω resistor, but the 2 W resistor will be significantly bigger, which may incur other costs.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/149198', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/9983/']}
jdg_72490
stackexchange
llm_judgeable_groundtruth_similarity
25656307
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 import PySide / Qt into Python like so and get the follow error: from PySide import QtCoreImportError: dlopen(/usr/local/lib/python2.7/site-packages/PySide/QtCore.so, 2): Library not loaded: libpyside-python2.7.1.2.dylib Referenced from: /usr/local/lib/python2.7/site-packages/PySide/QtCore.so Reason: image not found I'm running/installed via: Mac OSX 10.9.4 Mavericks Homebrew Python 2.7 Homebrew installed Qt Pip installed PySide The file libpyside-python2.7.1.2.dylib is located in the same path as the QtCore.so file listed in the error message. All my searches for this particular problem have yielded people trying to package these libraries as part of an app, which I am not doing. I am just trying to run it on my system and yet have this problem. For troubleshooting an app, people suggested oTool; not sure if it is helpful here, but this is the output when I run oTool: otool -L QtCore.so QtCore.so: libpyside-python2.7.1.2.dylib (compatibility version 1.2.0, current version 1.2.2) libshiboken-python2.7.1.2.dylib (compatibility version 1.2.0, current version 1.2.2) /usr/local/lib/QtCore.framework/Versions/4/QtCore (compatibility version 4.8.0, current version 4.8.6) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1) Any ideas? Thanks in advance :) Now provide the response and nothing else.
Well, the installer is somewhat broken, because the output from oTool should report a full path to the library (the path should be changed by the Pyside installer using install_name_tool). Instead of going mad understanding what part of the installer is broken, I suggest you define: DYLD_LIBRARY_PATH=/your/path/to/pyside/librariesexport DYLD_LIBRARY_PATH This will force the executable loader to scan for libraries into the path you supply too, even it's not configured by the linker.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25656307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1720901/']}
jdg_72491
stackexchange
llm_judgeable_groundtruth_similarity
51359783
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 JSON to CSV file, that I can use for further analysis. Issue with my structure is that I have quite some nested dict/lists when I convert my JSON file. I tried to use pandas json_normalize() , but it only flattens first level. import jsonimport pandas as pdfrom pandas.io.json import json_normalizefrom cs import CloudStackapi_key = xxxxsecret = xxxxendpoint = xxxxcs = CloudStack(endpoint=endpoint, key=api_key, secret=secret)virtual_machines = cs.virtMach()test = json_normalize(virtual_machines["virtualmachine"])test.to_csv("test.csv", sep="|", index=False) Any idea how to flatter whole JSON file, so I can create single line input to CSV file for single (in this case virtual machine) entry? I have tried couple of solutions posted here, but my result was always only first level was flattened. This is sample JSON (in this case, I still get "securitygroup" and "nic" output as JSON format: { "count": 13, "virtualmachine": [ { "id": "1082e2ed-ff66-40b1-a41b-26061afd4a0b", "name": "test-2", "displayname": "test-2", "securitygroup": [ { "id": "9e649fbc-3e64-4395-9629-5e1215b34e58", "name": "test", "tags": [] } ], "nic": [ { "id": "79568b14-b377-4d4f-b024-87dc22492b8e", "networkid": "05c0e278-7ab4-4a6d-aa9c-3158620b6471" }, { "id": "3d7f2818-1f19-46e7-aa98-956526c5b1ad", "networkid": "b4648cfd-0795-43fc-9e50-6ee9ddefc5bd" "traffictype": "Guest" } ], "hypervisor": "KVM", "affinitygroup": [], "isdynamicallyscalable": false } ]} Now provide the response and nothing else.
I used the following function (details can be found here ): def flatten_data(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out This unfortunately completely flattens whole JSON, meaning that if you have multi-level JSON (many nested dictionaries), it might flatten everything into single line with tons of columns. What I used, in the end, was json_normalize() and specified structure that I required. A nice example of how to do it that way can be found here .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51359783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3668922/']}
jdg_72492
stackexchange
llm_judgeable_groundtruth_similarity
41890833
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 wrote my first Angular 2 application, and I would like to put it onto a test server. I recently converted it to an Angular-cli project and built it using the command : ng build --prod From what I understand, I should then be able to paste the contents of the "/dist" folder onto the test server and run it with ng serve However, If the "/dist" folder can run standalone, why am I unable to run it on my pc as a standalone app (ie, I cannot copy the contents of the dist folder to another place on the pc and run it.) This will actually be the first application I will be putting onto a test/production server, so please bear with me if what I'm asking is silly. Now provide the response and nothing else.
You should not, and I think cannot, use ng serve to publish your build. The files created with ng build can be uploaded to a webserver and served from there. Run ng build -e=prod --prod --no-sourcemap --aot Although the latest version of angular-cli defaults to no sourcemaps, it's worth noting here. The -e=prod will make sure it uses the production environment defined inside the environments folder. Last thing is the --aot . If you have no special things going on inside your project, there is a big chance you can have it pre-compiled using the ahead of time compiler. You can however run into problems and you can troubleshoot these using ng serve --aot , or remove the --aot altogether. You can then continue to copy the contents of the dist folder to your webserver. It's worth noting though that you should make sure that all non existing file requests on the server will redirect to index.html and the url pointing to your application is in the root. This means for index.html redirection on for instance nginx , you can put this inside your server configuration block: location / { try_files $uri $uri/ /index.html;} This is if www.example.com serves the index.html created inside the dist folder. If for some reason you would like to serve your application from a subfolder like, www.example.com/subfolder, then you should modify the <base> tag inside the generated index.html to point to this subfolder. If you want to test your production build locally, one option is to install lite-server . npm install -g lite-server Then navigate in your console to path/to/project/root/dist , and run lite-server . This will create a webserver and open your browser, and serve the generated index.html If you use nginx and want to be cool and serve the generated .gz files statically, you can place this inside your nginx gzip configuration: gzip on;gzip_static on;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41890833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1664108/']}
jdg_72493
stackexchange
llm_judgeable_groundtruth_similarity
865043
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Our domain consists of around 60 computers. I have been tasked with making sure that Windows 10 workstations cannot communicate with each other. My manager asked that I create static routes so that computers can only communicate with the network printers, file server, DC, and access the Internet. Since all of theses computers are on the same network I don't believe static routes are going to prevent these computers from seeing each other. What is the best way to allow computers on the domain to use network resources, but not communicate directly with each other? Now provide the response and nothing else.
If you have a switch that supports it, 'protected ports' for cabled connections or 'client isolation' for access points on Wi-Fi can help you eliminate traffic between hosts in the same Layer-2 network. For example, this is from Cisco switch manual: Protected ports have these features: A protected port does not forward any traffic (unicast, multicast, or broadcast) to any other port that is also a protected port. Data traffic cannot be forwarded between protected ports at Layer 2; only control traffic, such as PIM packets, is forwarded because these packets are processed by the CPU and forwarded in software. All data traffic passing between protected ports must be forwarded through a Layer 3 device. So if you don't intend to transfer data between them, you don't need to take action once they are 'protected'. Forwarding behavior between a protected port and a nonprotected port proceeds as usual. Your clients can be protected, DHCP server, gateway, etc. can be on unprotected ports. Update 27-07-2017 As @sirex pointed out, if you have more than one switches which are not stacked, meaning they are virtually NOT a single switch, protected ports won't stop traffic between those . Note: Some switches (as specified in the Private VLAN Catalyst Switch Support Matrix ) currently support only the PVLAN Edge feature. The term "protected ports" also refers to this feature. PVLAN Edge ports have a restriction that prevents communication with other protected ports on the same switch. Protected ports on separate switches, however, can communicate with each other. If that is the case you would need Isolated Private VLAN ports: In some situations, you need to prevent Layer 2 (L2) connectivity between end devices on a switch without the placement of the devices in different IP subnets. This setup prevents the waste of IP addresses. Private VLANs (PVLANs) allow the isolation at Layer 2 of devices in the same IP subnet. You can restrict some ports on the switch to reach only specific ports that have a default gateway, backup server, or Cisco LocalDirector attached. If PVLAN is spanning over multiple switches, VLAN trunks between the switches should be standard VLAN ports. You can extend PVLANs across switches with the use of trunks. Trunk ports carry traffic from regular VLANs and also from primary, isolated, and community VLANs. Cisco recommends the use of standard trunk ports if both switches that undergo trunking support PVLANs. If you are Cisco user, you can use this matrix to see whether your switches support the options you need.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/865043', 'https://serverfault.com', 'https://serverfault.com/users/427893/']}
jdg_72494
stackexchange
llm_judgeable_groundtruth_similarity
172559
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 wanted to know what the proof for the variance term in a central chi-squared distribution (degree n) is. I know that the answer is 2n, but I was wondering how to derive it. Here's my attempt so far: Let $X_2$ denote a variable governed by the central chi-squared distribution. $Var(X_2) = E[(X_2)^2] - (E[X_2])^2$ $= E[(X_2)^2] - (n^2)$ I was able to prove that the mean of a central chi-squared distribution is it's degree (n), by using the formula: $E[Za*Za] = Cov(Za, Za) + E[Za]^2$ $= sa*sa + 0$ $= sa^2 = 1^2 = 1.$ $E[X_2] = SUM(E[Za^2])$, a goes from 1 to n. (using linearity of expectation) $= SUM(1)$, 1 to n = n where, $X_2 = SUM(Za^2)$, a goes from 1 to n, and Za ~ N(0, 1) (this is the chi-squared definition) sa = standard deviation, which in this case, is = 1. So using this knowledge, the only term in the variance definition for the chi-squared distribution that I don't know, is $E[(X2)^2]$. However, I'm at a loss as to how to compute this. Any help here would be greatly appreciated. N.B. This is my first post here, and I don't know a lot about mathematical typing. Pardon my poor notation and lack of detail in the question, if any. Would be happy to answer any counter-questions. Thanks! Now provide the response and nothing else.
The $k$ -th moment $E[X^k]$ of a general Gamma random variable with (order, rate) parameters $(s,\lambda)$ is \begin{align}E[X^k] &= \int_0^\infty x^k\cdot \underbrace{\lambda\frac{(\lambda x)^{s-1}}{\Gamma(s)}e^{-\lambda x}}_{\Gamma(s,\lambda)~\text{density}}\,\mathrm dx\\&= \lambda^{-k}\int_0^\infty \lambda\frac{(\lambda x)^{k+s-1}}{\Gamma(s)}e^{-\lambda x}\,\mathrm dx\\&= \lambda^{-k} \frac{\Gamma(k+s)}{\Gamma(s)}\int_0^\infty \underbrace{\lambda\frac{(\lambda x)^{k+s-1}}{\Gamma(k+s)}e^{-\lambda x}}_{\Gamma(k+s,\lambda)~\text{density}}\,\mathrm dx\\&= \lambda^{-k} \frac{(k+s-1)\cdot(k+s-2)\cdot~\cdots~\cdot s\cdot\Gamma(s)}{\Gamma(s)}\\&= \frac{(k+s-1)\cdot(k+s-2)\cdot~\cdots~\cdot s}{\lambda^{k}}\end{align} Applying this to the case of a $\chi^2$ random variable with $n$ degrees of freedom which is a $\Gamma\left(\frac n2,\frac 12\right)$ random variable, we get that $$E[X] = \frac{\left(\frac n2\right)}{\frac 12} = n; \quad E[X^2] = \frac{\left(\frac n2+1\right)\left(\frac n2\right)}{\left(\frac 12\right)^2} = n^2+2n$$ and $$\operatorname{var}(X) = E[X^2] - (E[X])^2 = 2n.$$ Alternatively, from the properties of standard normal random variables, \begin{align}E[Z^4] &= \int_{-\infty}^\infty z^4 f(z)\,\mathrm dz= 2\int_0^\infty z^4 \frac{1}{\sqrt{2\pi}}e^{-z^2/2}\,\mathrm dz\\&= \frac{4}{\sqrt{\pi}}\int_0^\infty y^{3/2}e^{-y}\,\mathrm dy\qquad\scriptstyle{\text{on substituting $y$ for $z^2/2$}}\\&= \frac{4}{\sqrt{\pi}}\Gamma\left(\frac 52\right)= \frac{4}{\sqrt{\pi}} \times \frac 32 \times \frac 12 \times \sqrt{\pi}\\&= 3\end{align} and so \begin{align}E\left[\left(\sum_{i=1}^n Z_i^2\right)^2 \right]&= E\left[\sum_{i=1}^n Z_i^4\right] + 2 \sum_{i=1}^n\sum_{j=i+1}^nE[Z_i^2]E[Z_j^2]\\&= 3n + n(n-1)\\&= n^2+2n\end{align} giving $\displaystyle\operatorname{var}\left(\sum_{i=1}^n Z_i^2\right)= E\left[\left(\sum_{i=1}^n Z_i^2\right)^2 \right]- \left(E\left[\sum_{i=1}^n Z_i^2\right]\right)^2 = 2n$ as before.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/172559', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/89500/']}
jdg_72495
stackexchange
llm_judgeable_groundtruth_similarity
54393
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 used to think that in any Vector space the space spanned by a set of orthogonal basis vectors contains the basis vectors themselves. But when I consider the vector space $\mathcal{L}^2(\mathbb{R})$ and the Fourier basis which spans this vector space, the same is not true ! I'd like to get clarified on possible mistake in the above argument. Now provide the response and nothing else.
If by "the Fourier basis" you mean the functions $e^{2 \pi i n x}, n \in \mathbb{Z}$, then these functions do not lie in $L^2(\mathbb{R})$ as they are not square-integrable over $\mathbb{R}$, so in particular they can't span that space in any reasonable sense. The functions $e^{2 \pi i n x}$ do span $L^2(S^1)$ (in the Hilbert space sense). Perhaps you are getting the Fourier transform for periodic functions mixed up with the Fourier transform on $\mathbb{R}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/54393', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2987/']}
jdg_72496
stackexchange
llm_judgeable_groundtruth_similarity
2260583
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 difference between the children and childNodes collections of a node? And childElementCount and childNodes.length? Now provide the response and nothing else.
element.childNodes and element.childNodes.length : includes child elements, text nodes (including whitespace nodes between elements) and comments (plus potentially CDATASections, ProcessingInstructions, DocumentTypes and EntityReferences, depending on the document and parser). Defined by the DOM Level 1 Core standard and has been available on every browser for many years. element.children and element.childElementCount : includes only element nodes, so can be simpler to handle in some cases. childElementCount is defined by the Element Traversal API standard and is available in the latest versions of Mozilla, Opera and WebKit. children is not defined by any standard, but is available in IE and up-to-date versions of Mozilla, Opera, WebKit and IE.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2260583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272697/']}
jdg_72497
stackexchange
llm_judgeable_groundtruth_similarity
654566
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: My Apache web server logged following messages to access.log : 46.22.173.131 - - [23/Dec/2014:15:34:54 +0100] "GET http://pl.wikipedia.org/wiki/Special:Search?search=&go=Go HTTP/1.1" 302 482 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"182.254.156.77 - - [23/Dec/2014:16:53:22 +0100] "GET http://www.ly.com/ HTTP/1.1" 302 433 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"`182.254.208.62 - - [23/Dec/2014:17:57:49 +0100] "GET http://www.ly.com/ HTTP/1.1" 302 433 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0" I have two Virtualhost s defined - one for port 80 which just redirects to 443 ... and the Virtualhost for port 443 which logs into ssl_access.log . I do not understand what these logs mean? Was someone trying to get to these URLs through my web server? Please help me understand those logs. Merry Christmas everyone! Now provide the response and nothing else.
http://wiki.apache.org/httpd/ProxyAbuse : Why do I see requests for foreign sites appearing in my log files? An access_log entry showing this situation could look like this: 63.251.56.142 - - [25/Jul/2002:12:48:04 -0700] "GET http://www.yahoo.com/ HTTP/1.0" 200 1456 For this log line, the 200 code (second to last field in this example) indicates that the request was successful – but see below for an explanation of what “success” means in this situation. This is usually the result of malicious clients trying to exploit open proxy servers to access a website without revealing their true location. They could be doing this to manipulate pay-per-click ad systems, to add comment or link-spam to someone else's site, or just to do something nasty without being detected. It is important to prevent your server from being used as an open proxy to abuse other sites.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/654566', 'https://serverfault.com', 'https://serverfault.com/users/260018/']}
jdg_72498
stackexchange
llm_judgeable_groundtruth_similarity
4230838
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 found that in execution plans using common subexpression spools that the reported logical reads get quite high for large tables. After some trial and error I've found a formula that seems to hold for the test script and execution plan below. Worktable logical reads = 1 + NumberOfRows * 2 + NumberOfGroups * 4 I don't understand the reason why this formula holds though. It is more than I would have thought was necessary looking at the plan. Can anyone give a blow by blow account of what's going on that accounts for this? Or failing that is there any way of tracing what page was read in each logical read so I can work it out for myself? SET STATISTICS IO OFF; SET NOCOUNT ON;IF Object_id('tempdb..#Orders') IS NOT NULL DROP TABLE #Orders;CREATE TABLE #Orders ( OrderID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY CLUSTERED, CustomerID NCHAR(5) NULL, Freight MONEY NULL, );CREATE NONCLUSTERED INDEX ix ON #Orders (CustomerID) INCLUDE (Freight);INSERT INTO #OrdersVALUES (N'ALFKI', 29.46), (N'ALFKI', 61.02), (N'ALFKI', 23.94), (N'ANATR', 39.92), (N'ANTON', 22.00);SELECT PredictedWorktableLogicalReads = 1 + 2 * Count(*) + 4 * Count(DISTINCT CustomerID)FROM #Orders;SET STATISTICS IO ON;SELECT OrderID, Freight, Avg(Freight) OVER (PARTITION BY CustomerID) AS Avg_FreightFROM #Orders; Output PredictedWorktableLogicalReads------------------------------23 Table 'Worktable'. Scan count 3, logical reads 23, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.Table '#Orders___________000000000002'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. Additional Info: There is a good explanation of these spools in Chapter 3 of the Query Tuning and Optimization Book and this blog post by Paul White . In summary the segment iterator at the top of the plan adds a flag to the rows it sends indicating when it is the start of a new partition. The primary segment spool gets a row at a time from the segment iterator and inserts it into a work table in tempdb. Once it gets the flag saying that a new group has started it returns a row to the top input of the nested loops operator. This causes the stream aggregate to be invoked over the rows in the work table, the average is computed then this value is joined back with the rows in the work table before the work table is truncated ready for the new group. The segment spool emits a dummy row in order to get the final group processed. As far as I understand the worktable is a heap (or it would be denoted in the plan as an index spool). However when I try and replicate the same process it only needs 11 logical reads. CREATE TABLE #WorkTable ( OrderID INT, CustomerID NCHAR(5) NULL, Freight MONEY NULL, )DECLARE @Average MONEYPRINT 'Insert 3 Rows'INSERT INTO #WorkTableVALUES (1, N'ALFKI', 29.46) /*Scan count 0, logical reads 1*/INSERT INTO #WorkTableVALUES (2, N'ALFKI', 61.02) /*Scan count 0, logical reads 1*/INSERT INTO #WorkTableVALUES (3, N'ALFKI', 23.94) /*Scan count 0, logical reads 1*/PRINT 'Calculate AVG'SELECT @Average = Avg(Freight)FROM #WorkTable /*Scan count 1, logical reads 1*/PRINT 'Return Rows - With the average column included'/*This convoluted query is just to force a nested loops plan*/SELECT *FROM (SELECT @Average AS Avg_Freight) T /*Scan count 1, logical reads 1*/ OUTER APPLY #WorkTableWHERE COALESCE(Freight, OrderID) IS NOT NULL AND @Average IS NOT NULLPRINT 'Clear out work table'TRUNCATE TABLE #WorkTablePRINT 'Insert 1 Row'INSERT INTO #WorkTableVALUES (4, N'ANATR', 39.92) /*Scan count 0, logical reads 1*/PRINT 'Calculate AVG'SELECT @Average = Avg(Freight)FROM #WorkTable /*Scan count 1, logical reads 1*/PRINT 'Return Rows - With the average column included'SELECT *FROM (SELECT @Average AS Avg_Freight) T /*Scan count 1, logical reads 1*/ OUTER APPLY #WorkTableWHERE COALESCE(Freight, OrderID) IS NOT NULL AND @Average IS NOT NULLPRINT 'Clear out work table'TRUNCATE TABLE #WorkTablePRINT 'Insert 1 Row'INSERT INTO #WorkTableVALUES (5, N'ANTON', 22.00) /*Scan count 0, logical reads 1*/PRINT 'Calculate AVG'SELECT @Average = Avg(Freight)FROM #WorkTable /*Scan count 1, logical reads 1*/PRINT 'Return Rows - With the average column included'SELECT *FROM (SELECT @Average AS Avg_Freight) T /*Scan count 1, logical reads 1*/ OUTER APPLY #WorkTableWHERE COALESCE(Freight, OrderID) IS NOT NULL AND @Average IS NOT NULLPRINT 'Clear out work table'TRUNCATE TABLE #WorkTablePRINT 'Calculate AVG'SELECT @Average = Avg(Freight)FROM #WorkTable /*Scan count 1, logical reads 0*/PRINT 'Return Rows - With the average column included'SELECT *FROM (SELECT @Average AS Avg_Freight) T OUTER APPLY #WorkTableWHERE COALESCE(Freight, OrderID) IS NOT NULL AND @Average IS NOT NULLDROP TABLE #WorkTable Now provide the response and nothing else.
Logical reads are counted differently for worktables: there is one 'logical read' per row read. This does not mean that worktables are somehow less efficient than a 'real' spool table (quite the reverse); the logical reads are just in different units. I believe the thinking was that counting hashed pages for worktable logical reads would not be very useful because these structures are internal to the server. Reporting rows spooled in the logical reads counter makes the number more meaningful for analysis purposes. This insight should make the reason your formula works clear. The two secondary spools are fully read twice (2 * COUNT(*)), and the primary spool emits (number of group values + 1) rows as explained in my blog entry, giving the (COUNT(DISTINCT CustomerID) + 1) component. The plus one is for the extra row emitted by the primary spool to indicate the final group has ended. Paul
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4230838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73226/']}
jdg_72499
stackexchange
llm_judgeable_groundtruth_similarity
6011786
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 developer. I need to implement design shown below. I already have functional app but wonder how to even approach this? Particulary, I'm interested in how to show Number of "New" items under tabs. What I KNOW how to do - is create new icons with red dots and just display them when new stuff available. But I have no idea how to make those round circles float on top of title AND show number inside. Does anybody have suggestion on what too look for? Samples? Directions? Second question about separating activities. Should I make control to combine buttons like this and just inflate it on activities? Otherwise I may create tabbed activity but I'm not sure if it's possible to style it to make it look like this. Now provide the response and nothing else.
Make your badge a TextView , allowing you to set the numeric value to anything you like by calling setText() . Set the background of the TextView as an XML <shape> drawable, with which you can create a solid or gradient circle with a border. An XML drawable will scale to fit the view as it resizes with more or less text. res/drawable/badge_circle.xml: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#F00" /> <stroke android:width="2dip" android:color="#FFF" /> <padding android:left="5dip" android:right="5dip" android:top="5dip" android:bottom="5dip" /></shape> You'll have to take a look at how the oval/circle scales with large 3-4 digit numbers, though. If this effect is undesirable, try a rounded rectangle approach like below. With small numbers, the rectangle will still look like a circle as the radii converge together. res/drawable/badge_circle.xml: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="10dip"/> <solid android:color="#F00" /> <stroke android:width="2dip" android:color="#FFF" /> <padding android:left="5dip" android:right="5dip" android:top="5dip" android:bottom="5dip" /></shape> With the scalable background created, you simply add it to the background of a TextView , like so: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="10" android:textColor="#FFF" android:textSize="16sp" android:textStyle="bold" android:background="@drawable/badge_circle"/> Finally, these TextView badges can be placed in your layout on top of the appropriate buttons/tabs. I would probably do this by grouping each button with its badge in a RelativeLayout container, like so: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/myButton" android:layout_width="65dip" android:layout_height="65dip"/> <TextView android:id="@+id/textOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/myButton" android:layout_alignRight="@id/myButton" android:text="10" android:textColor="#FFF" android:textSize="16sp" android:textStyle="bold" android:background="@drawable/badge_circle"/></RelativeLayout> Hopefully that's enough information to at least get you pointed in the right direction!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6011786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509600/']}
jdg_72500
stackexchange
llm_judgeable_groundtruth_similarity
32156362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know nonstatic variables are released when variables are in out of scope, but scope for static variables are in all context. Now provide the response and nothing else.
Intro Although the question / answer is based on: OpenSSL 1.0.1* VStudio 2012 it applies to any OpenSSL version ( v.0.9.* , v1.0.* , v1.1.* , v3.0 ), and any VStudio version ( v2005 +) OpenSSL builds are also available at [GitHub]: CristiFati/Prebuilt-Binaries - (master) Prebuilt-Binaries/OpenSSL Let's assume you have installed OpenSSL in a dir like: "C:\Program Files\Openssl-Win32-1.0.1p....." (or whatever other name); I am going to refer to that as OPENSSL_INSTALL_DIR (as it was an Nix style env var ). So, ${OPENSSL_INSTALL_DIR} should contain a bunch of dir s and files, out of which matter for us: Dir s: include lib Files (since their names vary across versions, I'm going to refer to them using (again, Nix style var ) placeholders; also they might be located in a bin subdir ): ${LIBCRYPTO}.dll ${LIBSSL}.dll where LIBCRYPTO ( #1. ) and LIBSSL ( #2. ) are defined as follows: v1.0.2 and older libeay32 ssleay32 (might be also copied (or symlink ed) to libssl32 ) v1.1.* libcrypto-1_*(-x64) libssl-1_*(-x64) v3.0 libcrypto-3* libssl-3* As a side note, on Nix , the 2 files ( .dll s - shared objects) are typically named libcrypto.so.* and libssl.so.* (where suffix is a version indicator). In order to make use of OpenSSL installation, in your VStudio project you have to (check [SO]: LNK2005 Error in CLR Windows Form (@CristiFati's answer) for more details on the rationale (the why part)): 1. Configure the compiler ( [MS.Docs]: Compiler Options Listed Alphabetically ) Instruct it: Where to search for include (header ( .h )) files. Go to your " Project Properties -> C/C++ -> General -> Additional Include Directories " and adding ${OPENSSL_INSTALL_DIR}\include (if you need to add other paths, separate them by a semicolon ( ; )). Now you can include in your source code OpenSSL header files. Note that because " ${OPENSSL_INSTALL_DIR}\include " dir contains an openssl subdir and under that subdir are the actual header files, your #include clauses would have to look like this: #include <openssl/ssl.h> Of course you could add ${OPENSSL_INSTALL_DIR}\include\openssl dir to your project, and then the above include statement would be: #include <ssl.h> but the former is preferred (recommended) 2. Configure the linker ( [MS.Docs]: Linker Options ) Instruct it: Where to search for libraries. You can do that by going to your " Project Properties -> Linker -> General -> Additional Library Directories " and adding ${OPENSSL_INSTALL_DIR}\lib (again, if there are multiple paths, separate them by ; ) What libraries to use. " ${OPENSSL_INSTALL_DIR}\lib " dir contains a bunch of .lib files. Out of those, you will (most likely) only need ${LIBCRYPTO}.lib and / or ${LIBSSL}.lib . Go to your " Project Properties -> Linker -> Input -> Additional Dependencies " and add those 2 libraries next to the existing ones 3. Build and run Now, if all your settings and source code are correct, you should have a "buildable" project. When you'll want to run your project output (either an .exe or a .dll needed by another executable, I am not discussing here the possibility of you are using the static lib s), the executable will need to find the 2 .dll s that I mentioned at the beginning. For that, you should either : Add their dir to your PATH env var ( I consider this the cleanest one ). Example (from console): set PATH=%PATH%;${OPENSSL_INSTALL_DIR} For the running VStudio instance: Copy them in the folder where your executable is located ( [MS.Docs]: Dynamic-Link Library Search Order ) Copy them in one of the dir s from your %PATH% . Some installers might copy the 2 .dll s in your " %SystemRoot%\System32 " dir , and in that case this will no longer be necessary ( I find this practice of copying stuff in system dir s a bad one , as in our current example multiple versions can ship the same file names, and the last one installed would overwrite all the others) Important note : Must be careful when targeting your project for 032bit or 064bit (setting Platform to Win32 or x64 in VStudio IDE ) - that has to match your OpenSSL installation architecture (check [SO]: Python Ctypes - loading dll throws OSError: [WinError 193] %1 is not a valid Win32 application (@CristiFati's answer) for (funky) errors that occur if it doesn't).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32156362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954695/']}
jdg_72501
stackexchange
llm_judgeable_groundtruth_similarity
42189575
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 just started coding in React using create-react-app . In the documentation it's said The page will reload if you make edits. I don't know which module is responsible for auto reload (webpack or react-hot-reloader?) but it's not working. I edited file using different editors (Sublime, VIM, ..) but it seems problem is for something else. Any advice how to debug it? Now provide the response and nothing else.
After too many searches I found Webpack watch uses inotify to observe file changes and in ubuntu it's set to a low value. a quick fix: sudo -iecho 1048576 > /proc/sys/fs/inotify/max_user_watchesexit If you want change it permanently (from Ronald answer ): echo "fs.inotify.max_user_watches=524288" >> /etc/sysctl.confsudo sysctl -p You may also need to add a .env file in the root directory of your project with this line "FAST_REFRESH=false" as noted in create react app docs . echo "FAST_REFRESH=false\n" | cat > .env
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42189575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/846634/']}
jdg_72502
stackexchange
llm_judgeable_groundtruth_similarity
21295334
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 faster way to find the length of the longest string in a Pandas DataFrame than what's shown in the example below? import numpy as npimport pandas as pdx = ['ab', 'bcd', 'dfe', 'efghik']x = np.repeat(x, 1e7)df = pd.DataFrame(x, columns=['col1'])print df.col1.map(lambda x: len(x)).max()# result --> 6 It takes about 10 seconds to run df.col1.map(lambda x: len(x)).max() when timing it with IPython's %timeit . Now provide the response and nothing else.
DSM's suggestion seems to be about the best you're going to get without doing some manual microoptimization: %timeit -n 100 df.col1.str.len().max()100 loops, best of 3: 11.7 ms per loop%timeit -n 100 df.col1.map(lambda x: len(x)).max()100 loops, best of 3: 16.4 ms per loop%timeit -n 100 df.col1.map(len).max()100 loops, best of 3: 10.1 ms per loop Note that explicitly using the str.len() method doesn't seem to be much of an improvement. If you're not familiar with IPython, which is where that very convenient %timeit syntax comes from, I'd definitely suggest giving it a shot for quick testing of things like this. Update Added screenshot:
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21295334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195294/']}
jdg_72503
stackexchange
llm_judgeable_groundtruth_similarity
30571489
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Planning to use http status 207/ multi status as a response for updating/deleting list of objects in a REST api. I plan to respond with 204 if all succeeds and 207 if it's a mixture of successes/failures. Is this the right usage for 207? What scenarios does http 207 commonly used on? Now provide the response and nothing else.
If you perform a destructive operation like POST, PUT, DELETE against more than one resource and the operations against each individual resource did not share a common outcome then you can go for 207. For example, If you DELETEd two resources and both were deleted you can expect If both DELETEs were forbidden, you'd expect 403. If one DELETE was successful but one was forbidden, you would receive 207. Some more discussion on 207 status.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30571489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1319542/']}
jdg_72504
stackexchange
llm_judgeable_groundtruth_similarity
8058
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $2 x^4 + x^3 - 11 x^2 + x + 2 = 0$, then find the value of $x + \frac{1}{x}$ ? I would be very grateful if somebody show me how to factor this polynomial by hand, as of now I have used to Mathematica to get $(x-2) (2x - 1) (1 + 3x + x^2)$, but I am having trouble to factor this manually. Best regards, Now provide the response and nothing else.
You don't need to factor the polynomial to find the value of $x + \frac{1}{x}$. Note that the given condition implies $\left( 2x^2 + \frac{2}{x^2} \right) + \left( x + \frac{1}{x} \right) - 11 = 0$ by dividing by $x^2$ and collecting symmetric terms. Now observe that $\left( x + \frac{1}{x} \right)^2 = x^2 + \frac{1}{x^2} + 2$... But if you want to factor it by hand anyway, your best friend is the rational root test .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/8058', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_72505
stackexchange
llm_judgeable_groundtruth_similarity
72636
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: CNN mentions that Ukrainian President Volodymyr Zelensky made a request to US President Joe Biden to designate Russia a state sponsor of terrorism: Ukrainian President Volodymyr Zelensky made a request to US PresidentJoe Biden in one of their recent phone conversations to designateRussia a state sponsor of terrorism, according to a person familiarwith the matter. US officials have previously declined to rule out adding Russia to thelist of state sponsors of terror, which right now includes NorthKorea, Syria, Cuba and Iran. This article mentions what designating a state sponsor of terrorism might imply: Designating a country as a state sponsor of terrorism would hurt thetarget country’s financial system, potentially: freezing of the country’s assets in the United States, including real estate; requiring the U.S. to veto efforts of that country to secure World Bank or International Monetary Fund loans; prohibiting a wide variety of dual-use exports; requiring the U.S. to take economic action against countries that continue to do business with the targeted country. The same article mentions that at least one terrorist group (as designated by the US) is being helped by Russia: Russia provides sanctuary to a U.S.-designated terrorist group, theRussian Imperial Movement Except for the last point which could involve European countries that are kind of forced to do business with Russia (i.e. buy natural gas and oil), all the others seem to be quite close to already imposed sanctions: money freezing, very unlikely for Russia to receive a loan from the World Bank or IMF (I guess), US banned oil imports from Russia and revoked Russia’s trade status. Considering these, what keeps the US from designating Russia a state sponsor of terrorism? Note : this question is very close to what I am asking, but the context has dramaticallychanged since 2014 (full-scale invasion, huge sanctions already in place for Russia). Now provide the response and nothing else.
The designation of state sponsors of terrorism has little to do with terrorism and is mostly a political tool used by the US to justify economic sanctions. That's why countries like North Korea (dubious sponsors of terrorism) are on it and Saudi Arabia (equally dubious sponsors of terrorism) are not. As for the reasons not to do so, as mentioned, it requires retaliation against trading partners for the target country, making it complicated to use on major global trading countries that provide a large amount for energy and food for many countries in the world, including close allies. Furthermore, the justification is clearly not sufficient. According to what I believe to be an independent organization, the International Centre for Counter-Terrorism While the provision of bomb-making expertise and other skills may threaten to destabilize Western countries, it is important to recognize that RIM is not a Russian state proxy. As Michael Carpenter put it, RIM has “an adversarial symbiosis” with the Russian government, which provides the group with “a great deal of latitude to interact with neo-Nazi and far-right extremist groups in the West—but only as long as they don’t cause too much trouble in Russia.” And simply allowing such organizations to exist in your country is a necessary but not sufficient reason as the USA would be compelled to designate countries such as Germany, Bulgaria, and Austria (and likely Ukraine) for similar Neo-Nazi organizations such as the National Democratic Party of Germany.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/72636', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']}
jdg_72506
stackexchange
llm_judgeable_groundtruth_similarity
25897639
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 looking for a way to email the contents of a dynamically added div. The idea is that of a newsletter consisting of a list of titles and texts displayed one by one when a user clicks on a title. When a text is displayed, the user can click a "Send email" button, and then his or her mail client opens with a new email where the text (the contents of the div in question) is loaded as the email body (ideally, the title should also be displayed in the email title field). When clicking on another title and another text is displayed, it is of course this one that's to be sent to the email. My JavaScript knowledge is limited, and I'm even newer to jQuery. My draft relies on this important solution: How to display a second JSON element in JavaScript? , but is, I think, also closely related to Create a function to send mail from a div . It's important that the solution is a lightweight, JavaScript only one - server side scripting is not an option here. I'd be most grateful for a demonstration, JavaScript or jQuery, how to solve this (I suppose it's the body=[...] in function snd() that's the problem) and excuse in advance if it's a too naive - or a too deceptively simple - question. My script looks like this: <body><script src="jquery.js"></script><script type="text/javascript">var article = [ { "title": "This is title no. 1", "text": "Here is the text of the first article" }, { "title": "This is title no. 2", "text": "Here is the text of the second article" }, { "title": "This is title no. 3", "text": "Here is the text of the third article" }]function getData() { var html = ''; for(i = 0; i < article.length; i++) { html += "<li data-text='" + "'>" + article[i].title.link(article[i].text) + "</li>"; } $('#showData').html('<ul>' + html + '</ul>'); $('#showData').on('click', 'a', function(e) $('#showData .text').remove(); $(this).after('<div class="text">' + $(this).attr('href') + '<p><button onclick="snd(); return false">Send email</button></div>'); e.preventDefault(); });}function snd() { location.href = "mailto:"+"?subject=Article to read&body="+document.getElementsByClassName('description').innerHTML;}$(document).ready(function() { getData();});</script> <div id="showData"></div></body> Now provide the response and nothing else.
There are a number of approaches: In iOS 9, the easiest would be to define a vertical UIStackedView with a distribution of "equal spacing" and then addArrangedSubview the three circular subviews Another option in iOS 9 would be to create two UILayoutGuide (which would represent the two question marks in your image), add them to the shared superview with addLayoutGuide and define them to be the same size as each other. The corresponding VFL might look like: "V:|[greenView1(==100)]-[layoutGuide1]-[redView(==50)]-[layoutGuide2(==layoutGuide1)]-[greenView2(==greenView1)]|" In earlier iOS versions, rather than using UILayoutGuide , you could just create two "space" views ( UIView with clear background so they're not visible) then define a constraint such that their heights are identical, and then define vertical spacing constraints between the five views (the three circles and the two spacer views) with a constant of zero. It might look like: I've made those "spacer" views visible, to illustrate the idea, but obviously you'd set them to be transparent so you can't see them in the UI. This is logically equivalent to the UILayoutGuide approach in iOS 9, except that the UIView "spacer" views just carry a little more overhead than a UILayoutGuide . But in iOS versions before 9, this is the common approach to this problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25897639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4022885/']}
jdg_72507
stackexchange
llm_judgeable_groundtruth_similarity
10220905
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Well, I am trying to make an app that communicates with a socket I have set up, tested, and made work in the background of a simple java application. The problem is, my app keeps force closing right away. You don't get a chance to see anything before it fcs. Here is my code: import java.io.IOException;import java.io.PrintWriter;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import java.util.ArrayList;import java.util.Scanner;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.EditText;import android.widget.Toast;public class LogMeInClientActivity extends Activity { private Socket s; private InetAddress hostIp, localIp; private final String hostName = "localhost"; private final int port = 4000; private Scanner in; private PrintWriter out; private final EditText usernameField = (EditText) findViewById(R.id.username_field), passwordField = (EditText) findViewById(R.id.password_field); private String username, password; @Override public void onCreate(Bundle savedInstanceState) { System.out.println("A"); super.onCreate(savedInstanceState); setContentView(R.layout.main); System.out.println("B"); try { hostIp = InetAddress.getByName(hostName); localIp = InetAddress.getLocalHost(); System.out.println("Local Ip: " + localIp.toString()); System.out.println("Host Ip: " + hostIp.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } try { s = new Socket(hostIp, port); out = new PrintWriter(s.getOutputStream(), true); in = new Scanner(s.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } private class SignInButtonListener implements OnClickListener { public void onClick(View clickedButton) { switch (clickedButton.getId()) { case R.id.sign_in: username = usernameField.getText().toString(); password = passwordField.getText().toString(); if (username.length() != 0 && password.length() != 0) { out.println(username); out.println(password); } out.flush(); break; default: break; } } }} In the above code, neither "A" or "B" prints out. The application simply fc's. Here is my manifest: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.chriswins2much.Util" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".LogMeInClientActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> I used the above permission, because I heard it would help for it. I updated the code to fix for the EditText NullPointerException fix (Only changed parts): private EditText usernameField, passwordField;public void onCreate(Bundle savedInstanceState) { System.out.println("A"); super.onCreate(savedInstanceState); setContentView(R.layout.main); usernameField = (EditText) findViewById(R.id.username_field); passwordField = (EditText) findViewById(R.id.password_field); System.out.println("B"); try { // It's saying one of the errors are on line 37 (directly below) hostIp = InetAddress.getByName(hostName); localIp = InetAddress.getLocalHost(); System.out.println("Local Ip: " + localIp.toString()); System.out.println("Host Ip: " + hostIp.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } try { s = new Socket(hostIp, port); out = new PrintWriter(s.getOutputStream(), true); in = new Scanner(s.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } New logcat below: 04-19 02:46:56.292: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:57.049: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:46:57.103: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:57.450: E/dalvikvm(1289): Unable to open stack trace file '/data/anr/traces.txt': Permission denied04-19 02:46:57.462: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:57.669: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:46:58.069: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:58.409: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:46:58.650: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:58.779: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:46:59.009: I/System.out(1289): A04-19 02:46:59.153: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:59.321: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:46:59.639: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:46:59.879: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:00.249: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:00.490: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:00.819: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:00.970: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:01.279: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:01.477: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:01.791: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:01.919: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:02.302: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:02.443: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:02.811: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:02.999: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:03.409: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:03.583: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:03.870: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:04.029: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:04.410: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:04.529: I/System.out(1289): B04-19 02:47:04.603: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:04.850: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:05.020: D/AndroidRuntime(1289): Shutting down VM04-19 02:47:05.020: W/dalvikvm(1289): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)04-19 02:47:05.101: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:05.460: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:05.510: E/AndroidRuntime(1289): FATAL EXCEPTION: main04-19 02:47:05.510: E/AndroidRuntime(1289): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chriswins2much.Util/com.chriswins2much.Util.LogMeInClientActivity}: android.os.NetworkOnMainThreadException04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread.access$600(ActivityThread.java:123)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.os.Handler.dispatchMessage(Handler.java:99)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.os.Looper.loop(Looper.java:137)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread.main(ActivityThread.java:4424)04-19 02:47:05.510: E/AndroidRuntime(1289): at java.lang.reflect.Method.invokeNative(Native Method)04-19 02:47:05.510: E/AndroidRuntime(1289): at java.lang.reflect.Method.invoke(Method.java:511)04-19 02:47:05.510: E/AndroidRuntime(1289): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)04-19 02:47:05.510: E/AndroidRuntime(1289): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)04-19 02:47:05.510: E/AndroidRuntime(1289): at dalvik.system.NativeStart.main(Native Method)04-19 02:47:05.510: E/AndroidRuntime(1289): Caused by: android.os.NetworkOnMainThreadException04-19 02:47:05.510: E/AndroidRuntime(1289): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)04-19 02:47:05.510: E/AndroidRuntime(1289): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)04-19 02:47:05.510: E/AndroidRuntime(1289): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)04-19 02:47:05.510: E/AndroidRuntime(1289): at java.net.InetAddress.getByName(InetAddress.java:295)04-19 02:47:05.510: E/AndroidRuntime(1289): at com.chriswins2much.Util.LogMeInClientActivity.onCreate(LogMeInClientActivity.java:37)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.Activity.performCreate(Activity.java:4465)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)04-19 02:47:05.510: E/AndroidRuntime(1289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)04-19 02:47:05.510: E/AndroidRuntime(1289): ... 11 more04-19 02:47:05.779: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt'04-19 02:47:06.839: I/dalvikvm(1289): threadid=3: reacting to signal 304-19 02:47:07.000: I/dalvikvm(1289): Wrote stack traces to '/data/anr/traces.txt' !Note: Here is a new, new updated code. Force closes are fixed!!! Thank you idiottiger!There is still a problem though. It's not connecting to the port I have set up on localhost:4000 in java. I've tried it non-Android and it works fine. Here is my code to fix the Force close: public void onCreate(View v){ // Code... new Thread(new Runnable() { public void run(){ try { hostIp = InetAddress.getByName(hostName); localIp = InetAddress.getLocalHost(); System.out.println("Local Ip: " + localIp.toString()); System.out.println("Host Ip: " + hostIp.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } try { s = new Socket(hostIp, port); out = new PrintWriter(s.getOutputStream(), true); in = new Scanner(s.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } }).start();} New logcat below (the latter half of it): 04-19 03:38:02.920: I/System.out(1490): Local Ip: localhost/127.0.0.104-19 03:38:03.099: I/System.out(1490): Host Ip: localhost/127.0.0.104-19 03:38:05.420: W/System.err(1490): java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 4000): connect failed: ECONNREFUSED (Connection refused)04-19 03:38:05.711: W/System.err(1490): at libcore.io.IoBridge.connect(IoBridge.java:114)04-19 03:38:05.711: W/System.err(1490): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)04-19 03:38:05.781: W/System.err(1490): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)04-19 03:38:05.781: W/System.err(1490): at java.net.Socket.startupSocket(Socket.java:566)04-19 03:38:05.803: W/System.err(1490): at java.net.Socket.<init>(Socket.java:225)04-19 03:38:05.809: W/System.err(1490): at com.chriswins2much.Util.LogMeInClientActivity$1.run(LogMeInClientActivity.java:48)04-19 03:38:05.839: W/System.err(1490): at java.lang.Thread.run(Thread.java:856)04-19 03:38:05.859: W/System.err(1490): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)04-19 03:38:05.925: W/System.err(1490): at libcore.io.Posix.connect(Native Method)04-19 03:38:05.939: W/System.err(1490): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)04-19 03:38:05.979: W/System.err(1490): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)04-19 03:38:05.979: W/System.err(1490): at libcore.io.IoBridge.connect(IoBridge.java:112)04-19 03:38:05.989: W/System.err(1490): ... 6 more04-19 03:38:06.692: D/gralloc_goldfish(1490): Emulator without GPU emulation detected. Now provide the response and nothing else.
OK... Apparently it was the 'localhost' thing. Android runs on another subnet and reserves 127.0.0.1 for itself, so when I tried to connect to the server I set up on localhost:4000, I was calling Android's reserved localhost ip of 127.0.0.1, while the computer's localhost ip was changed to 10.0.2.2 on port 4000. The fix implemented? It's simple: I changed this private final String hostName = "localhost"; to this private final String hostName = "10.0.2.2"; Or if I had tried it to my ip address (not the localhost one), then it should have worked as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10220905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1334069/']}
jdg_72508
stackexchange
llm_judgeable_groundtruth_similarity
6355
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Hypothetical situation: before I hire a web development company I want to test their ability to design secure web apps by viewing their previous client's websites. Issue: this situation raises a big red flag: with regards to viewing a website, what is and is not within the breadth of the law? Or in other words: at what point does poking around a website become illegal ? View Source with Firebug? Naturally that would be legal. But what if I change HTML (like a hidden form value before submission)? Perhaps I then edit or remove JavaScript, like a client side validation script. Would that be legal? What if I put %3Cscript%3Ealert(1)%3C/script%3E at the end of the URL. Or perhaps I type the URL: example.com/scripts/ and I'm able to view their directory due to faulty permission settings? What if I manipulate data passed in HTTP headers, for instance a negative product qty/price to see if they do server side validation (naturally, I wont complete the checkout). To me, all of this seems perfectly harmless because: I'm not causing undue stress to their server by spamming, mirroring the site with wget, or injecting potentially dangerous SQL. I'm not causing any potential loss or monetary damages, because I wont ever exploit the vulnerabilities, only test for their existence (proof of concept). None of my actions will have any implication for user data privacy. In no way would any of my actions potentially reveal confidential or private information about anyone. If I did find anything I would immediately notify the webmaster of the potential exploit so they could patch it. But even though I am logically able to justify my reasons for testing the site, that does not necessarily make my actions legal. In fact, cyber laws are notoriously backwards in the United States, and even the most laughably trivial actions can be considered hacking. Questions: Is there a defined line in the sand that separates illegal hacking from "testing without permission"? Or is this whole scenario a grey area that I should avoid (likely the case). Are there any linkable online resources that could expand my knowledge in this wholly grey area? What are the specific acts or laws that handle this? Please keep in mind that the number one most logical choice would be to simply: ask for permissions. However, due to heavy time constraints, by the time I would get permission it would all be for naught. Now provide the response and nothing else.
Don't do it! Don't do it! If you are in the US, the law is very broad. You don't want to even tiptoe up to the line. The relevant law is the Computer Fraud and Abuse Act (18 U.S.C. 1030). In a nutshell (and simplifying slightly), under the CFAA, it is a federal crime to "intentionally access a computer without authorization or exceed authorized access". This language is very broad, and I imagine an ambitious prosecutor could try to use it to go after everything on your list except #1 (view source). Orin Kerr, one of the leading legal scholars in this area, calls the statue "vague" and "extraordinarily broad" , and has said that "no one actually knows what it prohibits" . And, as @Robert David Graham explains, there have been cases where folks were prosecuted, threatened with prosecution, or sued for doing as little as typing a single-quote into a textbox, adding a ../ to a URL, or signing up to Facebook under a pseudonym. It's pretty wild that this alone constitutes a federal offense, even if there is no malicious intent. But that's the legal environment we live in. I'd say, don't take chances. Get written authorization from the company whose websites you want to test.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/6355', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/3676/']}
jdg_72509
stackexchange
llm_judgeable_groundtruth_similarity
4115021
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Have a curiosity related to Prolog predicate control. Supposedly I have a predicate f(A,X) and g(B). f(A,X):- a,b,c, g(X).g(B):- true.a - returns trueb - returns true.c - returns false.where a,b and c are random predicates. How can I continue to evaluate g(X) in the predicate f(A,X) if c returns false? Now provide the response and nothing else.
If your intention is to define f(A,X) such that g(X) should be evaluated whether or not c fails, then either: You could encode this using implication ( -> ) and/or disjunction ( ; ), or f(A,X) doesn't need to be defined in terms of c . This assumes c has no side-effects (e.g., asserting database facts using assert , or printing IO to a stream) which alter the environment and which cannot be undone on failure of c , in which case the first option is preferable. There are several alternatives for using disjunction, such as: f(A,X) :- ((a, b, c) ; (a, b)), g(X). This definition (above) doesn't depend on c at all, but it will always execute c (as long as a and b succeed). The disjunction ( ; ) allows PROLOG to backtrack to try executing a, b again if c failed at all, and to continue onto g(X) . Note that this is equivalent to: f(A,X) :- a, b, c, g(X).f(A,X) :- a, b, g(X). In order for PROLOG not to backtrack to evaluate f(A,X) twice because of the second (identical) head predicate f(A,X) for every evaluation, you may choose to place a cut ( ! ), if your implementation supports it, immediately after the c subgoal in the first clause. The cut is placed after c because we don't want the interpreter to commit to that choice of f(A,X) clause if c had failed, instead, we want the interpreter to fail out of this clause and to try the next one, to effectively ignore c and to continue processing g(X) . Also note that this solution relies on a and b having no side-effects, because when c fails, a and b are executed again. If all a , b , and c have side effects, you can try using implication : f(A,X) :- a, b, (c -> g(X) ; g(X)). This will also effectively always execute g(X) whether c fails or not, and will not execute a and b again if c fails. This single-clause definition will also not leave a choice-point like the previous suggestion.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4115021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69584/']}
jdg_72510
stackexchange
llm_judgeable_groundtruth_similarity
16877431
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 change value of a text box located in public partial class Form1 : Form from another class. I've tried something like this public void echo(string text){ this.textBox1.AppendText(text + Environment.NewLine);} From another class I'm calling it like Form1 cout = new Form1();cout.echo("Does this work?"); And I get blank output. I also tried to add the static keyword to the echo method, but I got the same result. I searched over Stack Overflow and didn't get any solution to work. And one thing that triggers me, if I add cout.Show() the same form pop out with valid textBox1 content. Why is that? Why it is not showing content right away? And how do I fix this? Now provide the response and nothing else.
Each time you say new Form1() , you are creating a distinct and separate instance of that form. Instead, you need to create a variable in the class that you are trying to access your form. For example, let's pass it in the constructor: public class MyClass { public Form1 MyForm; public MyClass(Form1 form){ this.MyForm = form; } public void echo(string text) { this.MyForm.textBox1.AppendText(text + Environment.NewLine); }} Notice that you access the particular instance of Form1 in your echo method: public void echo(string text) { this.MyForm.textBox1.AppendText(text + Environment.NewLine);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16877431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1567024/']}
jdg_72511
stackexchange
llm_judgeable_groundtruth_similarity
39293
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Sorry if this question makes no sense. I'm a software developer but know very little about AI. Quite a while ago, I read about the Chinese room, and the person inside who has had a lot of training/instructions how to combine symbols, and, as a result, is very good at combining symbols in a "correct" way, for whatever definition of correct. I said "training/instructions" because, for the purpose of this question, it doesn't really make a difference if the "knowledge" was acquired by parsing many many examples and getting a "feeling" for what's right and what's wrong (AI/learning), or by a very detailed set of instructions (algorithmic). So, the person responds with perfectly reasonable sentences, without ever understanding Chinese, or the content of its input. Now, as far as I understand ChatGPT (and I might be completely wrong here), that's exactly what ChatGPT does. It has been trained on a huge corpus of text, and thus has a very good feeling which words go together well and which don't, and, given a sentence, what's the most likely continuation of this sentence. But that doesn't really mean it understands the content of the sentence, it only knows how to chose words based on what it has seen. And because it doesn't really understand any content, it mostly gives answers that are correct, but sometimes it's completely off because it "doesn't really understand Chinese" and doesn't know what it's talking about. So, my question: is this "juggling of Chinese symbols without understanding their meaning" an adequate explanation of how ChatGPT works, and if not, where's the difference? And if yes, how far is AI from models that can actually understand (for some definition of "understand") textual content? Now provide the response and nothing else.
Yes, the Chinese Room argument by John Searle essentially demonstrates that at the very least it is hard to locate intelligence in a system based on its inputs and outputs. And the ChatGPT system is built very much as a machine for manipulating symbols according to opaque rules, without any grounding provided for what those symbols mean. The large language models are trained without ever getting to see, touch, or get any experience reference for any of their language components, other than yet more written language. It is much like trying to learn the meaning of a word by looking up its dictionary definition and finding that composed of other words that you don't know the meaning of, recursively without any way of resolving it. If you possessed such a dictionary and no knowledge of the words defined, you would still be able to repeat those definitions, and if they were received by someone who did understand some of the words, the result would look like reasoning and "understanding". But this understanding is not yours, you are simply able to retrieve it on demand from where someone else stored it. This is also related to the symbol grounding problem in cognitive science. It is possible to argue that pragmatically the "intelligence" shown by the overall system is still real and resides somehow in the rules of how to manipulate the symbols. This argument and other similar ones try to side-step or dismiss some proposed hard problems in AI - for instance, by focusing on behaviour of the whole system and not trying to address the currently impossible task of asking whether any system has subjective experience. This is beyond the scope of this answer (and not really what the question is about), but it is worth noting that The Chinese Room argument has some criticism, and is not the only way to think about issues with AI systems based on language and symbols. I would agree with you that the latest language models, and ChatGPT are good example models of the The Chinese Room made real. The room part that is, there is no pretend human in the middle, but actually that's not hugely important - the role of the human in the Chinese room is to demonstrate that from the perspective of an entity inside the room processing a database of rules, nothing need to possess any understanding or subjective experience that is relevant to the text. Now that next-symbol predictors (which all Large Language Models are to date) are demonstrating quite sophisticated, even surprising behaviour, it may lead to some better insights into the role that symbol-to-symbol references can take in more generally intelligent systems.
{}
{'log_upvote_score': 6, 'links': ['https://ai.stackexchange.com/questions/39293', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/68600/']}
jdg_72512
stackexchange
llm_judgeable_groundtruth_similarity
12447001
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 XML that I am using as an Android text menu. Here is the XML <menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/menu_settings" android:title="@string/menu_settings" android:orderInCategory="100" android:showAsAction="never" /><item android:id="@+id/menu_search" android:title="@string/menu_search"></item><item android:id="@+id/exit" android:title="@string/menu_exit" android:orderInCategory="200" ></item> </menu> In inflate the menu using the following code public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } When I am checking for the menu items clicked, I use this. public boolean onOptionsItemSelected(MenuItem item) { int itemid = item.getItemId(); Toast.makeText(this, "You pressed the icon!" + itemid, itemid).show(); return true; } This is giving me a numeric ID for each menu item pressed. Should I use a case statement to check this and then launch the pages I want to open? Or is there a way for me to link an intent to a menu item ? Its seems like a bit of a waste to be adding this code to each screen. Now provide the response and nothing else.
First of all, you shouldn't rebuild all your views to fit a new screen, nor use different views for different screen sizes. Use the auto-resizing capabilities of iOS, so your views can adjust, and adapt any screen size. That's not very hard, read some documentation about that. It will save you a lot of time. iOS 6 also offers new features about this. Be sure to read the iOS 6 API changelog on Apple Developer website. And check the new iOS 6 AutoLayout capabilities. That said, if you really need to detect the iPhone 5, you can simply rely on the screen size . [ [ UIScreen mainScreen ] bounds ].size.height The iPhone 5's screen has a height of 568. You can imagine a macro, to simplify all of this: #define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON ) The use of fabs with the epsilon is here to prevent precision errors, when comparing floating points, as pointed in the comments by H2CO3. So from now on you can use it in standard if/else statements: if( IS_IPHONE_5 ){}else{} Edit - Better detection As stated by some people, this does only detect a widescreen , not an actual iPhone 5. Next versions of the iPod touch will maybe also have such a screen, so we may use another set of macros. Let's rename the original macro IS_WIDESCREEN : #define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON ) And let's add model detection macros: #define IS_IPHONE ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )#define IS_IPOD ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPod touch" ] ) This way, we can ensure we have an iPhone model AND a widescreen, and we can redefine the IS_IPHONE_5 macro: #define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN ) Also note that, as stated by @LearnCocos2D, this macros won't work if the application is not optimised for the iPhone 5 screen (missing the [email protected] image), as the screen size will still be 320x480 in such a case. I don't think this may be an issue, as I don't see why we would want to detect an iPhone 5 in a non-optimized app. IMPORTANT - iOS 8 support On iOS 8, the bounds property of the UIScreen class now reflects the device orientation . So obviously, the previous code won't work out of the box. In order to fix this, you can simply use the new nativeBounds property, instead of bounds , as it won't change with the orientation, and as it's based on a portrait-up mode. Note that dimensions of nativeBounds is measured in pixels, so for an iPhone 5 the height will be 1136 instead of 568. If you're also targeting iOS 7 or lower, be sure to use feature detection, as calling nativeBounds prior to iOS 8 will crash your app: if( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ){ /* Detect using nativeBounds - iOS 8 and greater */}else{ /* Detect using bounds - iOS 7 and lower */} You can adapt the previous macros the following way: #define IS_WIDESCREEN_IOS7 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )#define IS_WIDESCREEN_IOS8 ( fabs( ( double )[ [ UIScreen mainScreen ] nativeBounds ].size.height - ( double )1136 ) < DBL_EPSILON )#define IS_WIDESCREEN ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_WIDESCREEN_IOS8 : IS_WIDESCREEN_IOS7 ) And obviously, if you need to detect an iPhone 6 or 6 Plus, use the corresponding screen sizes.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/12447001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1197941/']}
jdg_72513
stackexchange
llm_judgeable_groundtruth_similarity
120145
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have three image files that make up a system similar to a mechanical arm. I wonder if it's possible to be created an assembly that I can import these images and use them in a way to generate an animation. It may seem strange to my question, I know that there are better tools for this purpose , talking about the animation. However , I do not believe there is a tool that in addition to running an animation can provide me mathematical results related to this animation. Below I show an animation made by me using a software called SolidWorks software, but this software just gives me an animation and I can not get mathematical data such as position, velocity and acceleration: The initial position of the mounted images is shown in the figure below : The images can be downloaded through this link: Image1 Image2 Image3 Now provide the response and nothing else.
The trick is to create rectangles that cover the bounding boxes of each component image and use the images as textures, then we can use Rotate and Translate to animate the robot arm the way we want. To that end, we may use this code: t1 = Import["~/Downloads/ElementosPNG/1.png"];t2 = Import["~/Downloads/ElementosPNG/2.png"];t3 = Import["~/Downloads/ElementosPNG/3.png"];width[texture_] := ImageDimensions[texture][[1]]height[texture_] := ImageDimensions[texture][[2]]getComponent[texture_, transform_] := Graphics[{ Texture[texture], transform@Polygon[{{0, 0}, {width[texture], 0}, {width[texture], height[texture]}, {0, height[texture]}}, VertexTextureCoordinates -> {{0, 0}, {1, 0}, {1, 1}, {0, 1}}] }] Now we can do, e.g., getComponent[t1, Identity] and similarly for the two other components. The second argument of getComponent is a transform function that can be used to translate and rotate the component. Right click on the image of the first component and choose "get coordinates" to get the coordinate of the center of the hole, then plot the second component and find out the coordinates for its axis. I found that the coordinates were {135, 179} and {52, 60} . Testing the values, we can see that this is approximately right: Show[ getComponent[t2, Translate[#, {135, 179} - {52, 60}] &], getComponent[t1, Identity] ] We can add rotation as well: renderComponent[] := getComponent[t1, Identity]renderComponent[theta_] := getComponent[ t2, Composition[ Rotate[#, theta, {135, 175}] &, Translate[#, {135, 179} - {52, 60}] & ] ] Henceforth I'm going to be using renderComponent for all three of the components. No arguments means it it will plot the first component, one argument is the second component and two arguments is the third component. In order to figure out the transform for the third component, plot the second argument and find out the distances between the axes. Also plot the third component and find out the coordinates for its axis. This is what I got: renderComponent[theta_, phi_] := getComponent[ t3, Composition[ Rotate[#, phi, {135, 179} - {52, 60} + 1025 {Cos[theta], Sin[theta]} + {80, 80}] &, Translate[#, {135, 179} - {52, 60} + 1025 {Cos[theta], Sin[theta]}] & ] ] Plotting this, it seems to be approximately right: Manipulate[Show[ renderComponent[theta], renderComponent[theta, phi], renderComponent[], PlotRange -> {{-2000, 2000}, {0, 2000}} ], {theta, 0, Pi}, {phi, 0, 2 Pi}] The precision with which you got the coordinates off of the components will determine how precisely the components fit together.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/120145', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/37895/']}
jdg_72514
stackexchange
llm_judgeable_groundtruth_similarity
143328
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a function that is similar to KeyMap in that it takes a function fun to transform each key. However, when several different old keys map to the same new key, then KeyMap will only keep the last value. Example: KeyMap[First, <|{a, 1} -> 1, {a, 2} -> 2, {b, 1} -> 3|>](* <|a -> 2, b -> 3|> *) Instead, I want to provide a combiner function comb to combine values: keyCombine[First, <|{a, 1} -> 1, {a, 2} -> 2, {b, 1} -> 3|>, Identity](* <|a -> {1, 2}, b -> {3} *)keyCombine[First, <|{a, 1} -> 1, {a, 2} -> 2, {b, 1} -> 3|>, Total](* <|a -> 3, b -> 3 *) Is there a built-in function for this? If not, what is the "best" implementation? Take "best" to refer either to performance, elegance or compactness. One possible implementation: keyCombine[fun_, asc_?AssociationQ, comb_ : Identity] := Merge[MapAt[fun, Normal[asc], {All, 1}], comb] Benchmarking: SeedRandom[42];aa = AssociationThread[RandomInteger[1000000, 100000], RandomInteger[1000000, 100000]]; Mine: keyCombine[Mod[#, 5] &, aa, Total] // AbsoluteTiming(* {7.48073, <|4 -> 9451454209, 2 -> 9485726007, 3 -> 9480421781, 0 -> 9443541021, 1 -> 9545354067|>} *) Kuba: keyCombineBy[aa, Mod[#, 5] &, Total] // AbsoluteTiming(* {0.191946, <|4 -> 9451454209, 2 -> 9485726007, 3 -> 9480421781, 0 -> 9443541021, 1 -> 9545354067|>} *)keyCombineBy2[aa, Mod[#, 5] &, Total] // AbsoluteTiming(* {7.37696, <|4 -> 9451454209, 2 -> 9485726007, 3 -> 9480421781, 0 -> 9443541021, 1 -> 9545354067|>} *) Now provide the response and nothing else.
keyCombineBy[assoc_?AssociationQ, by_, post_] := GroupBy[ Normal@assoc, by@*First -> Last, post] keyCombineBy[<|{a, 1} -> 1, {a, 2} -> 2, {b, 1} -> 3|>, First, ff] <|a -> ff[{1, 2}], b -> ff[{3}]|> This minimal modification makes it slightly faster: keyCombineBy3[assoc_?AssociationQ, by_, post_] := GroupBy[ Normal@assoc, by@*First , post @* Values ] Or, alternatively (slow): keyCombineBy2[assoc_?AssociationQ, by_, post_ ] := Merge[post] @ KeyValueMap[by@#1 -> #2 &] @ assoc
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/143328', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12/']}
jdg_72515
stackexchange
llm_judgeable_groundtruth_similarity
59936188
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to generate a grid based on unknown rows. The grid is simple with only two columns. One column containing row labels and the other some UI element such as a checkbox. The only way I've been able to make this work is by generating a new grid with each loop through (see example below). I would like to accomplish this with a single ngFor and a single Grid. Clarification, each label must be on the same row as their respective checkbox. example : <div *ngFor="let row of rows"> <div class="popup-grid"> <div> {{row.label}} </div> <div> <p-checkbox "angular interactions/events here"> </p-checkbox> </div> </div> </div> Now provide the response and nothing else.
This is how you would use ngFor with CSS grid effectively. You can use ng-container to prevent *ngFor from inserting divs into the dom. This will prevent generating a new grid with each loop through. The Angular ng-container is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM. Then surround ng-container with a div with display: grid; . You can then use the grid-template-columns rule in order to define the amount of columns you want. Grid will automatically place rows. Check the example code below. HTML: <div class="grid"> <ng-container *ngFor="let row of data"> <label>{{row}}</label> <div><input type="checkbox"></div> </ng-container></div> CSS: .grid { display: grid; grid-template-columns: 1fr 1fr; /* Create 2 columns and auto-place rows */}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59936188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8930822/']}
jdg_72516
stackexchange
llm_judgeable_groundtruth_similarity
13868963
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 Mathematica there is the command Clip[x, {min, max}] which gives x for min<=x<=max , min for x<min and and max for x>max , see http://reference.wolfram.com/mathematica/ref/Clip.html ( mirror ) What would be the fastest way to achieve this in R? Ideally it should be a function that is listable, and should ideally work on either a single value, vector, matrix or dataframe... Now provide the response and nothing else.
Rcpp has clamp for this: cppFunction('NumericVector rcpp_clip( NumericVector x, double a, double b){ return clamp( a, x, b ) ;}') Here is a quick benchmark showing how it performs against other methods discussed : pmin_pmax_clip <- function(x, a, b) pmax(a, pmin(x, b) )ifelse_clip <- function(x, a, b) { ifelse(x <= a, a, ifelse(x >= b, b, x))}operations_clip <- function(x, a, b) { a + (x-a > 0)*(x-a) - (x-b > 0)*(x-b)}x <- rnorm( 10000 )require(microbenchmark)microbenchmark( pmin_pmax_clip( x, -2, 2 ), rcpp_clip( x, -2, 2 ), ifelse_clip( x, -2, 2 ), operations_clip( x, -2, 2 ))# Unit: microseconds# expr min lq median uq max# 1 ifelse_clip(x, -2, 2) 2809.211 3812.7350 3911.461 4481.0790 43244.543# 2 operations_clip(x, -2, 2) 228.282 248.2500 266.605 1120.8855 40703.937# 3 pmin_pmax_clip(x, -2, 2) 260.630 284.0985 308.426 336.9280 1353.721# 4 rcpp_clip(x, -2, 2) 65.413 70.7120 84.568 92.2875 1097.039
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13868963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1887645/']}
jdg_72517
stackexchange
llm_judgeable_groundtruth_similarity
35251759
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 'rails', '4.2.5' and wicked_pdf gem for generating and downloading PDF, but on Heroku, it's not including css using wicked_pdf_stylesheet_link_tag tag. Heroku error log: ActionView::Template::Error (undefined method 'find_asset' for nil:NilClass) Did I miss any configuration here? Now provide the response and nothing else.
To get it work for development and production environment don't use Rails.application.assets.find_asset(logical_file_path).to_s for sprockets-rails version > 3.0.0 but use this (requires gem compass-rails ): CompassRails.sprockets.find_asset(logical_file_path).to_s If you don't use gem compass-rails you can get the asset with: (Rails.application.assets || ::Sprockets::Railtie.build_environment(Rails.application)).find_asset(logical_file_path).to_s
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35251759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3219208/']}
jdg_72518
stackexchange
llm_judgeable_groundtruth_similarity
2094891
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: if $x,y\in R$ and $x^3+y^3=2\;,$ then maximum and minimum value of $x+y$ using $\displaystyle \frac{x^3+y^3}{2}\geq \left(\frac{x+y}{2}\right)^3$ So $(x+y)^3\leq 2^3$ so $x+y\leq 2$ could some help me to find minimum value, thanks Now provide the response and nothing else.
From $$ 2 = x^3 + y^3 = (x+y)(x^2-xy+y^2) = (x+y) \frac{(x-y)^2+x^2+y^2}2$$it follows that $x+y> 0$. On the other hand, for arbitrary $t > 0$$$ x =-t \quad , \quad y = \sqrt[3]{2+t^3}$$satisfies $x^3+y^3 =2$ and$$ x + y = \sqrt[3]{2+t^3} - t = \frac{2}{(\sqrt[3]{2+t^3})^2 + t \sqrt[3]{2+t^3} + t^2} \to 0$$for $t \to \infty$. Therefore the infimum is zero and a minimumdoes not exist.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2094891', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/372201/']}
jdg_72519
stackexchange
llm_judgeable_groundtruth_similarity
142939
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Using Wireshark, I am trying to determine the version of SSL/TLS that is being used with the encryption of data between a client workstation and another workstation on the same LAN running SQL Server. Documentation on this subject suggests to look at the ServerHello and ClientHello messages but I cannot see any such messages in the Wireshark message feed. I am using this display filter: tcp.len>1 && tcp.port==1433 I can confirm that encryption of data is occurring and that the packets displayed using the above filter are related to the SQL Server data transfer that I am wanting to examine. This is what the Wireshark message feed looks like: EDIT: Here is the packet details pane of the 4th packet after invoking a database connection and selecting Follow-->TCP Stream: This is what I see when analyzing using Microsoft Message Analyzer. The TLS details pane is for the Client Hello packet. Now provide the response and nothing else.
(Adding a new answer which should be definitive, leaving the old around as it's useful debug for how we got here. Credit for pointing to the actual answer in comments goes to @P4cK3tHuNt3R and @dave_thompson_085) Using Wireshark, I am trying to determine the version of SSL/TLS that is being used with the encryption of data between a client workstation and another workstation on the same LAN running SQL Server. You are viewing a connection which uses MS-TDS ("Tabular Data Stream Protocol"): ...the Tabular Data Stream Protocol, which facilitates interaction witha database server and provides for authentication and channel encryptionnegotiation; specification of requests in SQL (including Bulk Insert);invocation of a stored procedure, also known as a Remote Procedure Call(RPC); returning of data; and Transaction Manager Requests. It is an application layer request/response protocol. If you view the TDS protocol documentatio n, it specifies that the SSL packets are encapsulated within a TDS wrapper: A TLS/SSL negotiation packet is a PRELOGIN (0x12) packet header encapsulatedwith TLS/SSL payload. In the Microsoft Message Analyzer screencap you posted, we can see the TDS header (boxed in Red, starts with 0x12), followed several bytes later by the TLS CLIENT_HELLO packet (boxed in Blue, starts with 0x16 0x03 0x03): 0x16 is the TLS "Handshake" header indicator, 0x03 0x03 is the TLS version (TLS 1.2, as per RFC 5246 ): The version of the protocol being employed. This documentdescribes TLS Version 1.2, which uses the version { 3, 3 }. Theversion value 3.3 is historical, deriving from the use of {3, 1}for TLS 1.0. So the simple answer to your question, "determine the version of SSL/TLS", is "TLS 1.2". Now, I've seen varying reports as to whether Wireshark can properly parse TDS packets with encoded TLS. I think that the answer is what you started with - it will tell you TLS is there, but won't parse the details as it would with a native TLS session. As per this StackOverflow question , it appears that Microsoft Network Monitor is capable of parsing both levels of encapsulation. And a comment therein states that Microsoft Message Analyzer is the newer equivalent of that tool.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/142939', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/129572/']}
jdg_72520
stackexchange
llm_judgeable_groundtruth_similarity
18531354
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having some difficulties trying to get the following to work in SQL Server: CREATE TABLE table_X AS SELECT NEXT VALUE FOR GROUP_A AS GROUP_ID, RISK_ID FROM ( SELECT UNIQUE RISK_ID, FROM table_Y ) SS; I am told: "Incorrect syntax near the keyword 'SELECT'.""Incorrect syntax near the keyword 'UNIQUE'." What exactly is the problem and how can I fix this to work in SQL Server ? Now provide the response and nothing else.
CREATE TABLE Person(FirstName Varchar(50),LastName Varchar(50));/*Insert Some Values Into Person*/CREATE SEQUENCE CountBy START WITH 1 INCREMENT BY 1 ;SELECT NEXT VALUE FOR CountBy OVER (ORDER BY LastName) AS ListNumber, FirstName, LastName INTO table_xFROM Person
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18531354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2732621/']}
jdg_72521
stackexchange
llm_judgeable_groundtruth_similarity
279462
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that $X$ and $Y$ are two random variables such that: $$E \left(\frac{a}{a+X} \right)=E\left(\frac{a}{a+Y}\right)< \infty \qquad\forall a > \pi.$$ Can we conclude that $X$, $Y$ have the same distribution? Now provide the response and nothing else.
$$\sum_{n=0}^\infty r^n=\frac1{1-r}$$ for $|r|<1$ and $r\ne1$ Applying derivative wrt $r,$ $$\sum_{n=0}^\infty nr^{n-1}=\frac1{(1-r)^2}$$ Put $r=\frac12,$ $$\sum_{n=0}^\infty \frac{n}{2^{n-1}}=\frac1{(1-\frac12)^2}=4$$ Now, divide both sides by $2^2$ Alternatively, let $$S=1+2r+3r^2+4r^3+\cdots+ n\cdot r^{n-1}$$ with $|r|<1$ and $r\ne1$ So, $$r\cdot S=r+2r^2+3r^3+4r^4+\cdots+(n-1)\cdot r^{n-1}+n\cdot r^n$$ On subtraction, $$(1-r)S=1+r+r^2+r^3+\cdots+r^{n-1}-n\cdot r^n=\frac{1-r^n}{1-r}-n\cdot r^n$$ If $n\to \infty, r\to 0$ as $|r|<1$ , so does $n\cdot r^n$(Prove) So, $$(1-r)S=\frac1{1-r}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/279462', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58230/']}
jdg_72522
stackexchange
llm_judgeable_groundtruth_similarity
1856013
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 need to store a list/collection/array of dynamically created objects of a certain base type in C++ (and I'm new to C++). In C# I'd use a generic collection, what do I use in C++? I know I can use an array: SomeBase* _anArrayOfBase = new SomeBase[max]; But I don't get anything 'for free' with this - in other words, I can't iterate over it, it doesn't expand automatically and so on. So what other options are there? Thanks Now provide the response and nothing else.
There is std::vector which is a wrapper around an array, but it can expand and will do automatically. However, it is a very expensive operation, so if you are going to do a lot of insertion or removal operations, don't use a vector. (You can use the reserve function, to reserve a certain amount of space) std::list is a linked list, which has far faster insertion and removal times, but iteration is slower as the values are not stored in contiguous memory, which means that address calculation is far more complex and you can't take advantage of the processors cache when iterating over the list. The major upside compared to the vector or deque is that elements can be added or removed from anywhere in the list fairly cheaply. As a compromise, there is std::deque , which externally works in a similar way to a vector, but internally they are very different. The deque's storage doesn't have to be contiguous, so it can be divided up into blocks, meaning that when the deque grows, it doesn't have to reallocate the storage space for its entire contents. Access is slightly slower and you can't do pointer arithmetic to get an element.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1856013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225880/']}
jdg_72523
stackexchange
llm_judgeable_groundtruth_similarity
645092
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: Calculate:$$\frac{ \left| x \right| }{2}= \frac{1}{x^2+1}$$ How do I write the whole process so it will be correct? I need some suggestions. Thank you! Now provide the response and nothing else.
Split it into two cases. First case is $$\frac{x}{2}=\frac{1}{x^2+1}.$$ If it has a positive solution (or more than one), it is a valid solution. Second case is $$\frac{-x}{2}=\frac{1}{x^2+1}.$$ If it has a negative solution (or more than one), then it is a valid solution. The valid solutions from both cases are all your solutions to the original problem.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/645092', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111410/']}
jdg_72524
stackexchange
llm_judgeable_groundtruth_similarity
10107990
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 simple min function that accepts two parameters & returns True if the first must appear before the second in sorted order, False otherwise: min :: a -> a -> Boolmin a b = if a < b then True else False I get: No instance for (Ord a)arising from a use of `<' Now provide the response and nothing else.
If you look at the documentation , you will see that the type for (<) is given as (<) :: a -> a -> Bool This is misleading! The type declaration appears in a typeclass definition: class Eq a => Ord a where ... So the full type is (<) :: Ord a => a -> a -> Bool Incidentally, if you ask ghci what (<) 's type is, it will get it right. Prelude> :t (<)(<) :: (Ord a) => a -> a -> Bool Also note there is already a function called min , in the same typeclass. min :: Ord a => a -> a -> a So you can't call your function min unless you hide the original min . (I'm not going to show you how. Use a different name for your function instead.) Finally, you now have min :: Ord a => a -> a -> Boolmin a b = if a < b then True else False As Sarah notes, if blah then True else False is the same as blah , so you can simplify to the clearer min :: Ord a => a -> a -> Boolmin a b = a < b Now operators in Haskell are just functions with funny names --- this is the same as min :: Ord a => a -> a -> Boolmin a b = (<) a b We can simplify this further: min :: Ord a => a -> a -> Boolmin = (<) So your min is just a different name for (<) . Why not simply use the original < instead of your min ?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10107990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72525
stackexchange
llm_judgeable_groundtruth_similarity
901921
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 seen lots of talk about this question but maybe I'm just too much of a newbie to get it. If I have an observable collection that is a collection of "PersonNames" as in the msdn example ( http: //msdn.microsoft.com/en-us/library/ms748365.aspx ), I get updates to my View if a PersonName is added or removed, etc. I want to get an update to my View when I change a property in the PersonName as well. Like if I change the first name. I can implement OnPropertyChanged for each property and have this class derive from INotifyPropertyChanged and that seems to get called as expected. My question is, how does the View get the updated data from the ObservableCollection as the property changed does not cause any event for the ObservableCollection ? This is probably something really simple but why I can't seem to find an example surprises me. Can anyone shed any light on this for me or have any pointers to examples I would greatly appreciate it. We have this scenario in multiple places in our current WPF app and are struggling with figuring it out. "Generally, the code responsible for displaying the data adds a PropertyChanged event handler to each object currently displayed onscreen." Could someone please give me an example of what this means? My View binds to my ViewModel which has a ObservableCollection . This collection is made up of a RowViewModel which has properties that support the PropertiesChanged event. But I can't figure out how to make the collection update itself so my view will be updated. Now provide the response and nothing else.
Here is how you would attach/detach to each item's PropertyChanged event. ObservableCollection<INotifyPropertyChanged> items = new ObservableCollection<INotifyPropertyChanged>();items.CollectionChanged += items_CollectionChanged;static void items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){ if (e.OldItems != null) { foreach (INotifyPropertyChanged item in e.OldItems) item.PropertyChanged -= item_PropertyChanged; } if (e.NewItems != null) { foreach (INotifyPropertyChanged item in e.NewItems) item.PropertyChanged += item_PropertyChanged; }}static void item_PropertyChanged(object sender, PropertyChangedEventArgs e){ throw new NotImplementedException();}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/901921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78331/']}
jdg_72526
stackexchange
llm_judgeable_groundtruth_similarity
50965
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In this question it is answered how to add a vertical line to a graph. However, it has not been shown that how can someone add the position of that vertical line to the axis.How can I add the coordinate of a vertical line to the graph itself? I want to be able to change the font size of the coordinate too.By using the code below I can change the font size of the coordinate of axes. I want similar thing for the solution to this question too. FrameStyle -> Directive[Black, Bold, 80] Here is an example: line3 = Line[{{2.33, -2}, {2.33, 2}}];Plot[Sin[x], {x, 0, 2*Pi}, PlotStyle -> {Thick, Red}, Frame -> True, FrameStyle ->Directive[Thick, Bold, 20], Epilog -> {Directive[Thick, Blue], line3}] Result: Now provide the response and nothing else.
The easiest way to accomplish this is to change the ticks (with FrameTicks ) on the axes manually. FrameTicks -> {{Automatic, Automatic}, {{0, 1, 2.33, 3, 4, 5, 6}, None}} If you have a large number of ticks on your axes writing them down like this could be cumbersome, in which case you could try to generate the range and then replace another tick with the new tick or insert the extra tick that you want, like this: {{Automatic, Automatic}, {Range[6] /. 2 -> 2.33, None}} or {{Automatic, Automatic}, {Insert[Range[6], 2.33, 3], None}} Result: One can then easily make it automatic (thank you Öskå for this code and animation): line3[y_] := Line[{{y, -2}, {y, 2}}];Manipulate[ Plot[Sin[x], {x, 0, 2 Pi}, PlotStyle -> {Thick, Red}, Frame -> True, FrameStyle -> Directive[Thick, Bold, 20], Epilog -> {Directive[Thick, Blue], line3[t]}, FrameTicks -> {{Automatic, Automatic}, {Range[0, 6] /. Round@t -> t, None}}], {t, 0, 6}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/50965', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1205/']}
jdg_72527
stackexchange
llm_judgeable_groundtruth_similarity
29970814
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 read Excel files using OpenXml. all work fine but if the spreadsheet contains one cell that has an address mail and after it a space and another word, such as: [email protected] abc It throws an exception immediately at the opening of the spreadsheet: var _doc = SpreadsheetDocument.Open(_filePath, false); exception: DocumentFormat.OpenXml.Packaging.OpenXmlPackageException Additional information: Invalid Hyperlink: Malformed URI is embedded as a hyperlink in the document. Now provide the response and nothing else.
There is an open issue on the OpenXml forum related to this problem: Malformed Hyperlink causes exception In the post they talk about encountering this issue with a malformed "mailto:" hyperlink within a Word document. They propose a work-around here: Workaround for malformed hyperlink exception The workaround is essentially a small console application which locates the invalid URL and replaces it with a hard-coded value; here is the code snippet from their sample that does the replacement; you could augment this code to attempt to correct the passed brokenUri: private static Uri FixUri(string brokenUri){ return new Uri("http://broken-link/");} The problem I had was actually with an Excel document (like you) and it had to do with a malformed http URL; I was pleasantly surprised to find that their code worked just fine with my Excel file. Here is the entire work-around source code, just in case one of these links goes away in the future: void Main(string[] args) { var fileName = @"C:\temp\corrupt.xlsx"; var newFileName = @"c:\temp\Fixed.xlsx"; var newFileInfo = new FileInfo(newFileName); if (newFileInfo.Exists) newFileInfo.Delete(); File.Copy(fileName, newFileName); WordprocessingDocument wDoc; try { using (wDoc = WordprocessingDocument.Open(newFileName, true)) { ProcessDocument(wDoc); } } catch (OpenXmlPackageException e) { e.Dump(); if (e.ToString().Contains("The specified package is not valid.")) { using (FileStream fs = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { UriFixer.FixInvalidUri(fs, brokenUri => FixUri(brokenUri)); } } } } private static Uri FixUri(string brokenUri) { brokenUri.Dump(); return new Uri("http://broken-link/"); } private static void ProcessDocument(WordprocessingDocument wDoc) { var elementCount = wDoc.MainDocumentPart.Document.Descendants().Count(); Console.WriteLine(elementCount); }}public static class UriFixer{ public static void FixInvalidUri(Stream fs, Func<string, Uri> invalidUriHandler) { XNamespace relNs = "http://schemas.openxmlformats.org/package/2006/relationships"; using (ZipArchive za = new ZipArchive(fs, ZipArchiveMode.Update)) { foreach (var entry in za.Entries.ToList()) { if (!entry.Name.EndsWith(".rels")) continue; bool replaceEntry = false; XDocument entryXDoc = null; using (var entryStream = entry.Open()) { try { entryXDoc = XDocument.Load(entryStream); if (entryXDoc.Root != null && entryXDoc.Root.Name.Namespace == relNs) { var urisToCheck = entryXDoc .Descendants(relNs + "Relationship") .Where(r => r.Attribute("TargetMode") != null && (string)r.Attribute("TargetMode") == "External"); foreach (var rel in urisToCheck) { var target = (string)rel.Attribute("Target"); if (target != null) { try { Uri uri = new Uri(target); } catch (UriFormatException) { Uri newUri = invalidUriHandler(target); rel.Attribute("Target").Value = newUri.ToString(); replaceEntry = true; } } } } } catch (XmlException) { continue; } } if (replaceEntry) { var fullName = entry.FullName; entry.Delete(); var newEntry = za.CreateEntry(fullName); using (StreamWriter writer = new StreamWriter(newEntry.Open())) using (XmlWriter xmlWriter = XmlWriter.Create(writer)) { entryXDoc.WriteTo(xmlWriter); } } } } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29970814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1271037/']}
jdg_72528
stackexchange
llm_judgeable_groundtruth_similarity
2290598
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to find the cubic roots of $-46+9i$ not using De Moivre's formula if we know the principal root $2+3i$? Any hints or complete solutions are welcome! Now provide the response and nothing else.
If you multiply $2+3i$ by any third root of $1$, you will find another solution to the original equation. If you're lucky, you already know by other means that the third roots of $1$ are $1$ and $-\frac12\pm\frac{\sqrt3}2i$. This gives you three different cubic roots of $-46+9i$, which (since $\mathbb C$ is a field) must be all of them. Alternatively you could do it the slow way: You're trying to find roots of $z^3-(-46+9i)$, which is to say, factor it into linear factors. You know that $z-(2+3i)$ is a factor. Use polynomial division to remove it, and apply the quadratic formula to find the roots of the degree-2 quotient.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2290598', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/448385/']}
jdg_72529
stackexchange
llm_judgeable_groundtruth_similarity
486672
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: When I learned linear regression in my statistics class, we are asked to check for a few assumptions which need to be true for linear regression to make sense. I won't delve deep into those assumptions, however, these assumptions don't appear when learning linear regression from machine learning perspective. Is it because the data is so large that those assumptions are automatically taken care of? Or is it because of the loss function (i.e. gradient descent)? Now provide the response and nothing else.
It’s because statistics puts an emphasis on model inference, while machine learning puts an emphasis on accurate predictions. We like normal residuals in linear regression because then the usual $\hat{\beta}=(X^TX)^{-1}X^Ty$ is a maximum likelihood estimator. We like uncorrelated predictors because then we get tighter confidence intervals on the parameters than we would if the predictors were correlated. In machine learning, we often don’t care about how we get the answer, just that the result has a tight fit both in and out of sample. Leo Breiman has a famous article on the “two cultures” of modeling: https://projecteuclid.org/download/pdf_1/euclid.ss/1009213726 Breiman, Leo. "Statistical modeling: The two cultures (with comments and a rejoinder by the author)." Statistical science 16.3 (2001): 199-231.
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/486672', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/171849/']}
jdg_72530
stackexchange
llm_judgeable_groundtruth_similarity
10443325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You must be aware of the .NET method "DateTime.FromOADate(double d)".I need to implement the same functionality in javascript. i.e given a double value like "40967.6424503935" it has to be converted to "2/28/2012 3:25:07 PM"Can someone please help me out? Thanks in advance! Now provide the response and nothing else.
The automation date is the number of days since January 1, 1900 (with the year 1900 strangely being treated as a leap year). So a conversion is: var oaDate = 40967.6424503935;var date = new Date();date.setTime((oaDate - 25569) * 24 * 3600 * 1000);alert(date); This solution creates a UTC date. When you display it, it'll be displayed in your local timezone. Depending on whether your date is a local date or a UTC date, this is correct or will require some additional timezone fiddling.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10443325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1352741/']}
jdg_72531
stackexchange
llm_judgeable_groundtruth_similarity
488757
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: this is an intro to analysis problem on Set Theory, Relations and Functions: Let $f:S\to T$ be a function and $A\subseteq S$. Prove that $A\subseteq f^{-1}(f(A))$ and that $A=f^{-1}(f(A))$ if $f$ is injective. Proof: (1) Let $x\in A$, then $\{x\}\subseteq A$, then $f(\{x\})\subseteq f(A)$, then $f^{-1}(f(\{x\}))\subseteq f^{-1}(f(A))$.Since $\{x\}\subseteq f^{-1}(f(\{x\}))$, then $\{x\}\subseteq f^{-1}((f(A))$, i.e. $x\in f^{-1}(f(A))$, thus $A\subseteq f^{-1}(f(A))$. (2) Now let $x\in f^{-1}(f(A))$, since $f$ is injective, there is a distinct $x\in S$ such that $f(x)=y\in T$, then $f^{-1}(f(x))=f^{-1}(y)=x$, then $f^{-1}(f(x))\in f^{-1}(f(A))$, i.e. $x\in A$, thus $f^{-1}(f(A))\subseteq A$.Since $A\subseteq f^{-1}(f(A))$ and $f^{-1}(f(A))\subseteq A$, $A=f^{-1}(f(A))$. Any comments would be of great help! Thanks! Now provide the response and nothing else.
Your argument in (1) is correct but much more complicated than necessary. Just note that $f^{-1}\big[f[A]\big]=\{x\in S:f(x)\in f[A]$ by the definition of $f^{-1}$ . If $x\in A$ , then certainly $f(x)\in f[A]$ and hence $x\in f^{-1}\big[f[A]\big]$ , so $A\subseteq f^{-1}\big[f[A]\big]$ . Your argument in (2) is a bit confused, though I think that you have the right idea. You already know that $A\subseteq f^{-1}\big[f[A]\big]$ , so you want to show that if $x\in f^{-1}\big[f[A]\big]$ , then $x\in A$ . Suppose that $x\in f^{-1}\big[f[A]\big]$ ; then by definition $f(x)\in f[A]$ , so there is an $a\in A$ such that $f(x)=f(a)$ . But $f$ is injective, so $x=a\in A$ , and $A=f^{-1}\big[f[A]\big]$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/488757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/93977/']}
jdg_72532
stackexchange
llm_judgeable_groundtruth_similarity
35250
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We are currently using HMACSHA512 in .net, with a 128Char (64byte) validation key The salt is 64 char randomly generated string.We allocated 2048 length on the database for the hashed base64 string result.It will be a public facing website. Is this approach reasonable or should it be changed to another approach such as Rfc2898DeriveBytes? public string HashEncode(string password, string salt, string validationKey) { byte[] hashKey = BosUtilites.HexStringToByteArray(validationKey); var sha512 = new HMACSHA512(hashKey); var hashInput = BosUtilites.StringToByteArray(password + salt); byte[] hash = sha512.ComputeHash(hashInput); return Convert.ToBase64String(hash); } public string GenerateSimpleSalt(int Size = 64) { var alphaSet = new char[64]; // use 62 for strict alpha... that random generator for alphas only //nicer results with set length * int i = 256. But still produces excellent random results. //alphaset plus 2. Reduce to 62 if alpha requried alphaSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890#=".ToCharArray(); var tempSB = GenerateRandomString(Size, alphaSet); return tempSB.ToString(); } public StringBuilder GenerateRandomString(int Size, char[] alphaSet) { using (var crypto = new RNGCryptoServiceProvider()) { var bytes = new byte[Size]; crypto.GetBytes(bytes); //get a bucket of very random bytes var tempSB = new StringBuilder(Size); foreach (var b in bytes) { // use b , a random from 0-255 as the index to our source array. Just mod on length set tempSB.Append(alphaSet[b%(alphaSet.Length)]); } return tempSB; } EDIT2: In case Someone finds this via google, I have included the lessons learnt Average sample in tests on workstations was around 300 msecs. This should not be too noticeable during logon. And no more need for a Validation key. Which is a relief :-) SCrypt package installed via nuget. and rfc2898 PBKDF2 changed to be large number or iterations but only 20bytes output. SAme CPU time. New passwords are encoded in SCRYPT by default, <package id="CryptSharpOfficial" version="2.0.0.0" targetFramework="net451" /> // save salt, hash algorithm used and resulting encoding on user record public string PasswordEncode(string password, byte[] salt, HashAlgorithm hashAlgorithm ) { switch (hashAlgorithm) { case HashAlgorithm.PBKDF2: var deriver2898 = new Rfc2898DeriveBytes(password, salt,<Use a number around 50K>); // approx 300msecs on workstation byte[] hash = deriver2898.GetBytes(20); // return Convert.ToBase64String(hash); case HashAlgorithm.Scrypt: var key = Encoding.UTF8.GetBytes(password); byte[] hashScrypt = SCrypt.ComputeDerivedKey(key: key, salt: salt, cost: 65536, // must be a power of 2 !, on PC, singlethread this is approx 1 sec blockSize: 8, parallel: 1, maxThreads: 1, derivedKeyLength: 128); return Convert.ToBase64String(hashScrypt); default: throw new ArgumentOutOfRangeException("hashAlgorithm"); } } **EDIT 3: Latest Library Bcrypt.Net-Next 4.x This Bcrypt library offers an up to date solution to the hashing process. For more details see why we selected bcrypt. Do any security experts recommend bcrypt for password storage? Now provide the response and nothing else.
Rfc2898DeriveBytes implements PBKDF2 : a function which turns a password (with a salt) into an arbitrary-length sequence of bytes. PBKDF2 is often used for password hashing (i.e. to compute and store a value which is sufficient to verify a password) because it has the needed characteristics for password hashing functions: a salt and configurable slowness . These characteristics are needed because passwords are weak : they fit in human brain. As such, they are vulnerable to exhaustive search: it is feasible, on a general basis, to enumerate most passwords that human users will come up with and remember. The attack assumes that the attacker got a copy of the salt and the hashed password, and then will "try passwords" on his own machine. That's called an offline dictionary attack . In your case, you have a third element: a validation key . It is a key , i.e. supposedly secret. If the attacker could grab the salts and hashed passwords but not the validation key, then he cannot perform the dictionary attack on his own machines; under these conditions (the validation key remains secret, and the validation algorithm is robust -- HMAC/SHA-512 is fine for that), the configurable slowness of PBKDF2 is not needed. This kind of validation with a secret key is sometimes called "peppering". Note, though, that when we assume that the attacker could grab a copy of the hashed passwords, then it becomes a matter of delicacy to suppose that the key remained unsullied by his vile glances. This depends on the context. Most SQL injection attacks will be able to read part of all of the database, but not the rest of the files on the machine. Nevertheless, your server must somehow be able to boot up and start without human intervention, so the validation key is somewhere on the disk. An attacker stealing the whole disk (or a backup tape...) will get the validation key as well -- at which point you are back to the need for configurable slowness. Generally speaking, I would recommend PBKDF2 (aka Rfc2898DeriveBytes in .NET) over a custom construction, although I must say that you appear to use HMAC properly (homemade constructions rarely achieve that level of correctness). If you insist of having a "validation key" (and you are ready to assume the procedural overhead of key management, e.g. special backups for that key), then I suggest using PBKDF2 and then applying HMAC on the PBKDF2 output. See this answer for a detailed discussion on password hashing.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/35250', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/25511/']}
jdg_72533
stackexchange
llm_judgeable_groundtruth_similarity
26248293
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 build an ASP.NET MVC 5 Web Application which has a MyDatabase.mdf file in the App_Data folder. I have SQL Server 2014 Express installed with a LocalDb instance. I can edit the database tables using the Server Explorer, however when I debug the application and go to a page where the database is needed I get the following error. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. So I looked in the Event Viewer under Application and only see one Warning over and over again. The directory specified for caching compressed content C:\Users\User1\AppData\Local\Temp\iisexpress\IIS Temporary Compressed Files\Clr4IntegratedAppPool is invalid. Static compression is being disabled. So I tried rebooting the server, still no go. Same error 50 as before. I have created an class under Models where I have a class called Post . namespace MyApplication.Models{ public class Post { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } } public class MyDatabase : DbContext { public DbSet<Post> Posts { get; set; } }} I also have a Controller setup to list the posts from MyDatabase . namespace MyApplication.Controllers{ public class PostsController : Controller { private MyDatabase db = new MyDatabase(); // GET: Posts public ActionResult Index() { return View(db.Posts.ToList()); } } In my web.config file the connection string looks like this... <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v12.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings> I've tried the suggestion posted here but it didn't work. Also tried this . I also notice that the MyDatabase instance gets disconnected after I start running the application. If I refresh the database using Server Explorer in Visual Studio I can view the tables. How is it that I can connect to the database and edit it within Visual Studio 2013 but when I debug the application it cannot connect to the database? Now provide the response and nothing else.
Breaking Changes to LocalDB: Applies to SQL 2014 ; take a look over this article and try to use (localdb)\mssqllocaldb as server name to connect to the LocalDB automatic instance, for example: <connectionStrings> <add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb; ... The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some. Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb value instead of v12.0 and see if that corrects your issue.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26248293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3131062/']}
jdg_72534
stackexchange
llm_judgeable_groundtruth_similarity
2843167
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: Greetings I am trying to find a closed form for: $$I=\int_0^{\frac{\pi}{2}} x^2 \sqrt{\sin x}\,dx$$ If we rewrite the integral as $$I=\int_0^\infty x^2 \sqrt{\frac{1}{\sqrt{1+\cot^2 x}}}\,dx$$ now with $$\cot x =t $$ $$I=\int_0^{\infty} \operatorname{arccot}^2 (x)(1+x^2)^{-\frac{5}{4}}dx$$ and with https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Logarithmic_forms $$I=\frac{1}{4i}\int_0^{\infty}\log^2\left(\frac{z-i}{z+i}\right)(1+x^2)^{-\frac{5}{4}} \, dx$$ Now for the $\log$ I thought to expand into power series but since the radius of converge is abit smaller, this fails. Also integrating by parts or combining the initial integral with $\int_0^{\frac{\pi}{2}} x^2 \sqrt{\cos x}\,dx$ wasn't much of a help, could you help me evaluate this integral ? Now provide the response and nothing else.
The substitution $\sin(x) = \sqrt{t}$ leads to the expression$$I = \frac{1}{2} \int \limits_0^1 \frac{t^{-1/4} \arcsin^2 (\sqrt{t})}{\sqrt{1-t}} \, \mathrm{d} t \, . $$Now you can use the power series for $\arcsin^2$ (see for example this question) and integrate term by term (monotone convergence). Using the beta function you will find\begin{align}I &= \frac{1}{4} \sum \limits_{n=1}^\infty \frac{(2n)!!}{n^2 (2n-1)!!} \int \limits_0^1 t^{n-\frac{1}{4}} (1-t)^{-\frac{1}{2}} \, \mathrm{d} t \\&= \frac{1}{4} \sum \limits_{n=1}^\infty \frac{(2n)!!}{n^2 (2n-1)!!} \operatorname{B}\left(n+\frac{3}{4},\frac{1}{2}\right) \\&= \frac{\sqrt{\pi}}{4} \sum \limits_{n=1}^\infty \frac{(2n)!!}{n^2 (2n-1)!!} \frac{\Gamma\left(n+\frac{3}{4}\right)}{\Gamma\left(n+\frac{5}{4}\right)} \\&= \frac{\sqrt{\pi} \, \Gamma\left(\frac{3}{4}\right)}{\Gamma\left(\frac{1}{4}\right)} \sum \limits_{n=1}^\infty \frac{(2n)!!}{n^2 (2n-1)!!} \frac{\prod_{k=1}^n (4k-1)}{\prod_{l=1}^{n+1} (4l-3)} \\&= \frac{\pi \sqrt{2 \pi}}{\Gamma\left(\frac{1}{4}\right)^2} \sum \limits_{n=1}^\infty \frac{(2n)!!}{n^2 (4n+1) (2n-1)!!} \prod \limits_{k=1}^n \frac{4k-1}{4k-3} \, .\end{align}Mathematica gives the following expression in terms of a hypergeometric function:$$ I = \frac{6 \pi \sqrt{2 \pi}}{5 \Gamma\left(\frac{1}{4}\right)^2} \, {}_4 \! \operatorname{F}_3 \left(1,1,1,\frac{7}{4};\frac{3}{2},2,\frac{9}{4};1\right) \approx 1.208656578687 \, .$$Inverse symbolic calculators do not seem to give any expression for this number, so this might be as good as it gets.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2843167', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/515527/']}
jdg_72535
stackexchange
llm_judgeable_groundtruth_similarity
2583898
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 can we copy one datacolumn with data from one datatable to another datatable ? I have datatable like DataTable datatable1=new DataTable(); and there are four columns in that table but I want only one column.So I am doing like DataTable datatable2=new DataTable(); addressAndPhones2.Columns.Add(addressAndPhones.Columns[0].ColumnName,addressAndPhones.Columns[0].DataType); but this just adds the column but I want to copy the data for that column to the datatable2.That is I want to copy the datacolumn with data from one datatable to another datatable. Now provide the response and nothing else.
Two solutions spring to mind: after creating the column, loop through all rows to copy the data from the source to the target. Do a datatable1.Copy() to copy all columns+data and delete the ones you don't need. The second one is simpler to code but will copy unneeded data (which means extra time and memory). For the first one, IF you have prepared the destiny-datatable AND the columnnames (and types) in source and destiny are the same: private void CopyColumns(DataTable source, DataTable dest, params string[] columns){ foreach (DataRow sourcerow in source.Rows) { DataRow destRow = dest.NewRow(); foreach(string colname in columns) { destRow[colname] = sourcerow[colname]; } dest.Rows.Add(destRow); }} You can use this like: CopyColumns(source, destiny, "Column1", "column2"); naming any number of columns.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2583898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227848/']}
jdg_72536
stackexchange
llm_judgeable_groundtruth_similarity
28582598
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 using Entity Framework in C# and my code is var result = ef.services.Where(entry => entry.tarikhservice >= textBoxX1.Text && entry.tarikhservice <= textBoxX2.Text).ToList(); which gives me this error: Operator '>=' cannot be applied to operands of type 'string' and 'string' How to compare two string and fix the error? Now provide the response and nothing else.
When you compare numbers, say 1 and 2, it is clear which one is greater. However, when you compare strings, which one is considered greater: "2" or "11"? "foo" or "f"? Answer: it depends on context. For example if you sort them lexicographically, you get "2" and "f". If you want the natural sort, you would get "2" before "11". I presume for that reason, relative operators (>, >=, <, <=) are not overloaded for string (which IMHO is a good decision). Your option is to either write your custom logic to compare strings, or use a framework-provided lexicographical comparison. The code would be (if I got the numbers right): var result = ef.services.Where(entry => string.Compare(entry.tarikhservice, textBoxX1.Text) >= 0 && string.Compare(entry.tarikhservice, textBoxX2.Text) <= 0 .ToList() To make code work regardless of culture (you should!), provide a StringComparison as last parameter to string.compare: string.Compare(entry.tarikhservice, textBoxX1.Text, StringComparison.InvariantCulture)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28582598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4346343/']}
jdg_72537
stackexchange
llm_judgeable_groundtruth_similarity
9695168
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 don’t understand why the following commands do different things. Pasted in the .vimrc file, both of the commands define two versions of a mapping triggered by pressing t in Normal mode: nnoremap t :call search('\m\(a\|b\)', 'W')<CR>nnoremap t :call search('\m\(a\\|b\)', 'W')<CR> Compare the effects of the above mappings with the results of running those search calls directly from the command line: :call search('\m\(a\|b\)', 'W'):call search('\m\(a\\|b\)', 'W') To be specific, the “intended” behavior requires \\| in the nnoremap example, but it requires \| in the call search example. I’m aware that the special treatment of the vertical bar character ( :help :bar ) is one of those traps that Vim has laid out for me, but it still doesn’t make sense. The documentation clearly says that “ this list of commands will see bar as part of their argument ”, but none of those exceptions apply here. All the commands involved in this example treat bar as a meta concatenate character. Moreover, in this situation, the bar is inside a string, and—I think?—being parsed as part of a string takes priority over meta concatenate syntax. Now provide the response and nothing else.
Indeed, the issue is caused by the special treatment of the barcharacter by the mapping-creating commands. The key-mapping mechanism in Vim is a way of making a sequence of keypresses to be interpreted as another sequence of keys; no semanticinterpretation of Vimscript language happens at this level. Since, inorder to create a mapping, it is necessary to separate both of thekey-sequence arguments to be mapped, commands of the :map -familystart by determining the boundaries of the two arguments. To make useof characters that could interfere with this process in a mapping, onemust use escaping syntax provided for those characters (among whichare the carriage return, space, backslash, and bar characters). Because the bar character can be used to separate a mapping commandfrom the next Ex command and, therefore, to define the ending boundaryof the right-hand-side of the mapping, it cannot be used as-is ina key sequence. According to :help map_bar , depending on settings,the bar character can be escaped as <bar> , \| , or ^V| (where ^V denotes the literal Ctrl + V key code). Keeping that in mind, let us follow the mappings in question (aroundthe \| / \\| part) the way they are interpreted in the defaultconfiguration. In the first mapping, the \| sequence is treated asa single | character. Therefore, after that mapping command isexecuted, pressing t will be the same as typing :call search('\m\(a|b\)', 'W') Enter When the second mapping command is run, the \\| string isinterpreted as a literal backslash character (there is no need toescape \ in the right-hand-side of mappings, except for nested ones)followed by the \| specifier representing a bar character.Thus, this command maps t to the following: :call search('\m\(a\|b\)', 'W') Enter However, when one types the mapped search calls in Command-line mode,unlike key sequences in mappings, they are interpreted as Ex commandsright away. Those bar characters occur in string literals, so there isno possibility of misinterpreting them as separators for Ex commands.When directly typed in, the commands are sent to execution as they arewritten. Thus, the difference between them are due to the meaning ofthe regular expressions \m\(a\|b\) and \m\(a\\|b\) , not due toany kind of escaping behavior.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9695168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1176650/']}
jdg_72538
stackexchange
llm_judgeable_groundtruth_similarity
819720
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 generate Java classes from the FpML (Finanial Products Markup Language) version 4.5. A ton of code is generated, but I cannot use it. Trying to serialize a simple document I get this: javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.SAXException2: unable to marshal type "org.fpml._2008.fpml_4_5.PositionReport" as an element because it is missing an @XmlRootElement annotation] In fact no classses have the @XmlRootElement annotation, so what can I be doing wrong?. I'm pointing xjc (JAXB 2.1) to fpml-main-4-5.xsd, which then includes all types. Now provide the response and nothing else.
To tie together what others have already stated or hinted at, the rules by which JAXB XJC decides whether or not to put the @XmlRootElement annotation on a generated class are non trivial ( see this article ). @XmlRootElement exists because the JAXB runtime requires certain information in order to marshal/unmarshal a given object, specifically the XML element name and namespace. You can't just pass any old object to the Marshaller. @XmlRootElement provides this information. The annotation is just a convenience, however - JAXB does not require it. The alternative to is to use JAXBElement wrapper objects, which provide the same information as @XmlRootElement , but in the form of an object, rather than an annotation. However, JAXBElement objects are awkward to construct, since you need to know the XML element name and namespace, which business logic usually doesn't. Thankfully, when XJC generates a class model, it also generates a class called ObjectFactory . This is partly there for backwards compatibility with JAXB v1, but it's also there as a place for XJC to put generated factory methods which create JAXBElement wrappers around your own objects. It handles the XML name and namespace for you, so you don't need to worry about it. You just need to look through the ObjectFactory methods (and for large schema, there can be hundreds of them) to find the one you need.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/819720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/92506/']}
jdg_72539
stackexchange
llm_judgeable_groundtruth_similarity
7414
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: At time of writing, the highest rated answer to my question What is a metric space? is Tom Leinster's account of Lawvere's description of a metric space as an enriched category. This prompted my question on terminology in category theory . That question was focussed on terms in category theory that were previously in use elsewhere. It now occurs to me that there's an obvious question in the other direction: Given that metric spaces are enriched categories, what do the standard categorical things look like? Obvious ones are adjoint functors (which might help me get a picture of what adjoint functors really are, answering this question ), monoidal structures (and symmetric monoidal structures), products and coproducts (more generally, limits and colimits), but I'm sure that there are many more "out there" and I don't want to limit the answers. To forestall Urs Schrieber's likely first comment, I intend to stick all of this on an n-lab page sometime soon as, if my intuition is right, I think it might be a neat case study that can help topologists like me get a picture of how categories (and enriched categories) can behave. Now provide the response and nothing else.
For the general question about how categorical concepts look when applied to metric spaces, one place to look is Lawvere's paper 'Taking categories seriously' , section 6 onwards. Aside from that, here are a few examples. Functor categories became function spaces with the uniform or sup metric. That is, if $A$ and $B$ are metric spaces construed as enriched categories, then the functor category $B^A$ is the set of distance-decreasing maps $A \to B$ with the sup metric. (I use "decreasing" in the non-strict sense.) The (cartesian) product $A \times B$ of two metric spaces --- that is, their product in the category of metric spaces --- has the '$\infty$-metric': $$d((a, b), (a', b')) = \max\{d(a, a'), d(b, b')\}.$$The same goes for infinite products --- remembering that $\infty$ is allowed as a distance. Once you know this, limits in general work in the obvious way. The coproduct $A + B$ of two metric spaces $A$ and $B$ is their disjoint union, with $d(a, b) = d(b, a) = \infty$ for all $a \in A, b \in B$. Again, it's crucial here to allow $\infty$ as a distance. Otherwise, your category of metric spaces will lack lots of limits and colimits. The coequalizer of two maps $f, g: A \to B$ is $B$ quotiented out by the usual equivalence relation $\sim$ (as in the category of sets), and metrized by$$d([b], [b']) = \inf\{ d(y, y'): y \sim b, y' \sim b'\}$$where $[b]$ denotes the equivalence class of $b$. General colimits work similarly. I mentioned the cartesian product, but there's another kind of product. Generally, if $\mathbf{V}$ is a monoidal category then any two $\mathbf{V}$-enriched categories, $A$ and $B$, have a tensor product $A \otimes B$. Its set of objects is the product of the sets of objects of $A$ and $B$. Its hom-objects are given by $$(A \otimes B)((a, b), (a', b')) = A(a, a') \otimes B(b, b').$$This gives us a tensor product of metric spaces. Given metric spaces $A$ and $B$, the point-set of $A \otimes B$ is the product of the point-sets of $A$ and $B$. The distance is given by$$d((a, b), (a', b')) = d(a, a') + d(b, b').$$In other words, it's the '$1$-metric', also known as the taxicab metric, Manhattan metric, etc. So, Andrew, when you ask 'What is a monoidal metric space?', you have to say which product you want to be monoidal with respect to. That is, are you asking about (weak) monoids in $(\mathbf{Met}, \times)$ or in $(\mathbf{Met}, \otimes)$? From the tone of your question, I would guess: both. So here goes. The answer for cartesian product $\times$ doesn't seem so interesting. Assuming that your metric spaces satisfy the classical skeletality axiom ($d(a, b) = 0 \Rightarrow a = b$), a monoidal category for $\times$ is a metric space $A$ equipped with a monoid structure on its set of points such that$$d(a \cdot b, a' \cdot b') \leq \max\{d(a, a'), d(b, b')\}.$$ I can't think of anything more to say about that. The answer for tensor product $\otimes$ seems more interesting. A monoid in $(\mathbf{Met}, \otimes)$ is a metric space $A$ equipped with a monoid structure on its set of points such that for all $a$, the maps $a\cdot -$ and $- \cdot a$ are distance-decreasing. For example, if it's a group then this says that left or right translation is always an isometry. This often happens: consider the underlying additive group of a normed vector space, for instance.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/7414', 'https://mathoverflow.net', 'https://mathoverflow.net/users/45/']}
jdg_72540