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
15537611
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 looks like mongodb offers two similar functions for geospatial queries - $near and $geoNear . According to the mongo docs The geoNear command provides an alternative to the $near operator. In addition to the functionality of $near, geoNear returns additional diagnostic information. It looks like geoNear provides a superset of the near functionality. For example, near seems to only return the closest 100 documents, whereas geoNear lets you specify a maximum. Is there a reason to use near instead of geoNear ? Is one more efficient than the other? Now provide the response and nothing else.
Efficiency should be identical for either. geoNear 's major limitation is that as a command it can return a result set up to the maximum document size as all of the matched documents are returned in a single result document. It also requires that a distance field be added to each result document which may or may not be an issue depending on your usage. $near is a query operator so the results can be larger than a single document (they are still returned in a single response but not a single document). You can also set the maximum number of documents via the query's limit(). I tend to recommend that users stick with the $near unless they need the diagnostics (e.g., distance, or location matched) from the geonear command.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15537611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121993/']}
jdg_70241
stackexchange
llm_judgeable_groundtruth_similarity
18583180
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My data file has this content # data file for use with gnuplot# Report 001# Data as of Tuesday 03-Sep-2013 total 1976case1 522 278 146 65 26 7case2 120 105 15 0 0 0case3 660 288 202 106 63 1 I am making a histogram from the case... lines using the script below - and that works. My question is: how can I load the grand total value 1976 (next to the word 'total') from the data file and either (a) store it into a variable or (b) use it directly in the title of the plot? This is my gnuplot script: resetset term png truecolorset terminal pngcairo size 1024,768 enhanced font 'Segoe UI,10'set output "output.png"set style fill solid 1.00set style histogram rowstackedset style data histogramsset xlabel "Case"set ylabel "Frequency"set boxwidth 0.8plot for [i=3:7] 'mydata.dat' every ::1 using i:xticlabels(1) with histogram \notitle, '' every ::1 using 0:2:2 \with labels \title "My Title" For the benefit of others trying to label histograms, in my data file, the column after the case label represents the total of the rest of the values on that row. Those total numbers are displayed at the top of each histogram bar. For example for case1, 522 is the total of (278 + 146 + 65 + 26 + 7). I want to display the grand total somewhere on my chart, say as the second line of the title or in a label. I can get a variable into sprintf into the title, but I have not figured out syntax to load a "cell" value ("cell" meaning row column intersection) into a variable. Alternatively, if someone can tell me how to use the sum function to total up 522+120+660 (read from the data file, not as constants!) and store that total in a variable, that would obviate the need to have the grand total in the data file, and that would also make me very happy. Many thanks. Now provide the response and nothing else.
Lets start with extracting a single cell at (row,col). If it is a single values, you can use the stats command to extract the values. The row and col are specified with every and using , like in a plot command. In your case, to extract the total value, use: # extract the 'total' cellstats 'mydata.dat' every ::::0 using 2 nooutputtotal = int(STATS_min) To sum up all values in the second column, use: stats 'mydata.dat' every ::1 using 2 nooutputtotal2 = int(STATS_sum) And finally, to sum up all values in columns 3:7 in all rows (i.e. the same like the previous command, but without using the saved totals) use: # sum all values from columns 3:7 from all rowsstats 'mydata.dat' every ::1 using (sum[i=3:7] column(i)) nooutputtotal3 = int(STATS_sum) These commands require gnuplot 4.6 to work. So, your plotting script could look like the following: resetset terminal pngcairo size 1024,768 enhancedset output "output.png"set style fill solid 1.00set style histogram rowstackedset style data histogramsset xlabel "Case"set ylabel "Frequency"set boxwidth 0.8# extract the 'total' cellstats 'mydata.dat' every ::::0 using 2 nooutputtotal = int(STATS_min)plot for [i=3:7] 'mydata.dat' every ::1 using i:xtic(1) notitle, \ '' every ::1 using 0:(s = sum [i=3:7] column(i), s):(sprintf('%d', s)) \ with labels offset 0,1 title sprintf('total %d', total) which gives the following output:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18583180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/424855/']}
jdg_70242
stackexchange
llm_judgeable_groundtruth_similarity
47946603
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 ng-bootstrap 4 (beta 8). At the moment i have this: <ng-template #rt let-r="result" let-t="term"> {{ r.label }}</ng-template><input id="typeahead-focus" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" [inputFormatter]="formatter" [resultTemplate]="rt" (focus)="focus$.next($event.target.value)" (click)="click$.next($event.target.value)" #instance="ngbTypeahead"/> Now, I want to open typeahead, if the user click in the input element. How can I do this? this.search = (text$) => text$ .map(term => (term === '' ? this.items : this.items.filter(v => v.label.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10));this.formatter = (x: {label: string}) => { console.log(x); return x.label; Now provide the response and nothing else.
The following solution works for me: Add onFocus event to your input search my.html file <input (focus)="onFocus($event)" type="text" (selectItem)="onItemSelected($event)" [(ngModel)]="myModel" [ngbTypeahead]="search" [resultTemplate]="rt" [inputFormatter]="formatter"/> my.ts file public onFocus(e: Event): void { e.stopPropagation(); setTimeout(() => { const inputEvent: Event = new Event('input'); e.target.dispatchEvent(inputEvent); }, 0); } search = (text$: Observable<string>) => text$ .debounceTime(200) .distinctUntilChanged() .map(term => this.myList .filter(v => this.myfilter(term)) .slice(0, 10)); Also take a look at Typeahed: allow search on focus #698
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47946603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9095860/']}
jdg_70243
stackexchange
llm_judgeable_groundtruth_similarity
19851005
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 a csv file without header, with a DateTime index. I want to rename the index and column name, but with df.rename() only the column name is renamed. Bug? I'm on version 0.12.0 In [2]: df = pd.read_csv(r'D:\Data\DataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] )In [3]: df.head()Out[3]: 10 2002-06-18 0.1120002002-06-22 0.1903332002-06-26 0.1340002002-06-30 0.0930002002-07-04 0.098667In [4]: df.rename(index={0:'Date'}, columns={1:'SM'}, inplace=True)In [5]: df.head()Out[5]: SM0 2002-06-18 0.1120002002-06-22 0.1903332002-06-26 0.1340002002-06-30 0.0930002002-07-04 0.098667 Now provide the response and nothing else.
The rename method takes a dictionary for the index which applies to index values . You want to rename to index level's name: df.index.names = ['Date'] A good way to think about this is that columns and index are the same type of object ( Index or MultiIndex ), and you can interchange the two via transpose. This is a little bit confusing since the index names have a similar meaning to columns, so here are some more examples: In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))In [2]: dfOut[2]: A B C0 1 2 31 4 5 6In [3]: df1 = df.set_index('A')In [4]: df1Out[4]: B CA 1 2 34 5 6 You can see the rename on the index, which can change the value 1: In [5]: df1.rename(index={1: 'a'})Out[5]: B CA a 2 34 5 6In [6]: df1.rename(columns={'B': 'BB'})Out[6]: BB CA 1 2 34 5 6 Whilst renaming the level names: In [7]: df1.index.names = ['index'] df1.columns.names = ['column'] Note: this attribute is just a list, and you could do the renaming as a list comprehension/map. In [8]: df1Out[8]: column B Cindex 1 2 34 5 6
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/19851005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2459096/']}
jdg_70244
stackexchange
llm_judgeable_groundtruth_similarity
32769505
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 Android SDK 23 onReceivedError(WebView view, int errorCode, String description, String failingUrl) has been deprecated and replaced with onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) . However if I put my phone in Airplane mode and load an url on my WebView, only the deprecated version of the method is called. onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse) is also not useful, as it only detects errors higher than 500, and I am getting a 109 status code. Is there a non-deprecated way of detecting that my WebView failed to load? Now provide the response and nothing else.
You could also do following: @SuppressWarnings("deprecation")@Overridepublic void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Handle the error}@TargetApi(android.os.Build.VERSION_CODES.M)@Overridepublic void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) { // Redirect to deprecated method, so you can use it in all SDK versions onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());} Make sure you import android.annotation.TargetApi
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32769505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/924054/']}
jdg_70245
stackexchange
llm_judgeable_groundtruth_similarity
2103094
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 get all HTML <p>...</p> in a document. Using Regex to find all such strings using: Regex regex = new Regex(@"\<p\>([^\>]*)\</p\>", RegexOptions.IgnoreCase); But I am not able to get any result. Is there anything wrong with my regular expression.? For now, I just want to get everything that comes in between <p>...</p> tags and want to use Regex for this as the source is not an HTML document. Now provide the response and nothing else.
DO NOT PARSE HTML USING Regular Expressions !!! Instead, use the HTML Agility Pack . For example: var doc = new HtmlDocument();doc.Load(...);var pTags = doc.DocumentNode.Descendants("p"); EDIT : You can do this even if the document isn't actually HTML.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2103094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186280/']}
jdg_70246
stackexchange
llm_judgeable_groundtruth_similarity
11629113
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 UIActionSheet with title string "DO: These tasks". In the title string, the substring "DO:" should be Bold(with a particular font size) and the substring "These tasks" should be Regular. Is it possible? How can I do this? Now provide the response and nothing else.
I assume you have a class which implements the UIActionSheetDelegate protocol and your class is a delegate class of the current UIActionSheet , so in that class you can change the whole title of the UIActionSheet like - (void)willPresentActionSheet:(UIActionSheet *)actionSheet { for (UIView *_currentView in actionSheet.subviews) { if ([_currentView isKindOfClass:[UILabel class]]) { [((UILabel *)_currentView) setFont:[UIFont boldSystemFontOfSize:15.f]]; } }} but as far as you see you have no chance to format the part of the UILabel object's text property. you could add a new UILabel for your actionsheet now with a different font, if you want to see a text with the bolded DO: string... but from here the limit is you imagination only, you can format the UIActionSheet 's elements in this method or inside the -didPresentActionSheet: method as well. so this would be the idea for this. UPDATE on 7 Oct 2013 in iOS7 we don't really have direct access to the subviews of an UIAlertView or an UIActionSheet object, so this solution might not be working properly on iOS7 environment. if you have any issue with it on iOS7, please comment it to me! thank you. UPDATE on 22 Jun 2014 I have not found any solution to do such thing directly with the new UIAlertController in iOS8, the title label looks to be not visible in the entire view-hierarchy of the UIAlertController , neither visible before it appears or even after. NOTE: I've also figured out that it is not forbidden to overlap/cover its content, after it appeared on the screen. currently it is impossible to predict that it will work over Beta or whether or not it is AppStore-safe. NOTE: please bear in your mind the view-lifecycle's schedule, and do not try to present any content in a view or view controler if that is not in the navigation stack already. anyway, here is a Swift solution how I could reach the layers and I could add my custom view to it. let alertController: UIAlertController = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.Alert)self.presentViewController(alertController, animated: true, completion: { let aboveBlurLayer: UIView = alertController.view.subviews[0] as UIView let belowBlurLayer: UIView = (aboveBlurLayer.subviews[0].subviews as Array<AnyObject>)[0] as UIView let customView: UIView = UIView(frame: aboveBlurLayer.bounds) customView.backgroundColor = UIColor.redColor() aboveBlurLayer.addSubview(customView) }) NOTE: it might be useful to add custom content to an alert/actionsheet, but if it does not work in the future, I will update my answer.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11629113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/988871/']}
jdg_70247
stackexchange
llm_judgeable_groundtruth_similarity
25702884
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i'm trying to get Jake Wharton's ViewPagerIndicator working with Android Studio but unfortunately it won't work. I downloaded the .aar file from here and included it in my libs folder. I referenced it like this: compile files('src/main/libs/viewpagerindicator_2.4.1.aar') Android Studio gives me the following error: Error:duplicate files during packaging of APK I'm not very familiar with gradle and don't know what to do when it gives me this error. Can you please help me with this one? Here's my complete build.gradle: apply plugin: 'com.android.application'android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { applicationId "de.xxx" minSdkVersion 15 targetSdkVersion 19 compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } }}dependencies { compile 'com.android.support:support-v4:20.0.0' compile 'com.github.amlcurran.showcaseview:library:5.0.0' compile files('src/main/libs/PdfViewer.jar') compile files('src/main/libs/viewpagerindicator_2.4.1.aar')} Now provide the response and nothing else.
UPDATE Based on the answer given by Jürgen 'Kashban' Wahlmann , it is now possible to add ViewPagerIndicator via gradle: Top Level Build.gradle: buildscript { repositories { maven { url "http://dl.bintray.com/populov/maven" } mavenCentral() }}allprojects { repositories { maven { url "http://dl.bintray.com/populov/maven" } mavenCentral() }} App's build.gradle: compile 'com.viewpagerindicator:library:2.4.1@aar' Also, based on the answer given by Enrico Susatyo now it seems possible to download the library from Jitpack maven repositories. Do it as follows: In root build.grade: allprojects { repositories { ... maven { url "https://jitpack.io" } } } In project build.grade: dependencies { compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1' } ------------ To use Android-ViewPagerIndicator in Android Studio, you can’t download it from gradle. Instead, you must import the library as an “Existing Project” to your current one. Follow these steps: #1 Download source code from GitHub. #2 In your Android Studio Project: File -> Project Structure -> add (+ symbol) -> Import Existing Project. Import just the folder called ”library”, not the entire project (leave the import options as Android Studio suggests). # 3 If the "compileSdkVersion" specified in your build.gradle doesn’t match with the one specified in the Android-ViewPagerIndicator project, change the second one. The same apply with any other property, such as "minSdkVersion" or even the current support library. # 4 Add Android-ViewPagerIndicator project as a dependency to your build.gradle module: dependencies { compile project(':library')} # 5 Sync project with gradle files.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25702884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3561817/']}
jdg_70248
stackexchange
llm_judgeable_groundtruth_similarity
155603
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: Let me try to sum up this question; I want to buy VPS from (vultr - I'm not promoting them), but before that I'm wondering how secure is to run VPN on this kind (or any kind) of VPS in sense that I can endanger myself by choosing wrong company, which can tap/monitor my traffic. I'm not trying to ask how secure is KVM virtualization, but which infrastructure is the safest for running a VPN, dedicated server, VPS (both are almost same, from my question perspective) or building own server or something else? Now provide the response and nothing else.
What is the risk of running VPN on VPS? The main risk is that all traffic inside the VPN can be passively sniffed by the entity hosting the server. Basically it is similar to giving someone physical access to a physical server. Actually the risk is a bit higher, because VPS could be passively replicated, so it's more like giving someone an unprotected, unlimited access to a real-time replica of a physical server. All the secrets required to set up a VPN connection are stored on the VPS itself and the traffic can be easily captured, so whoever has access to the underlying virtualisation platform can utilise them to monitor the communication in real time or afterwards. By extension, you also open your own (connecting) network to the party hosting the VPS. So if you were targeted, they could utilise this connection to get into your internal network, behind your perimeter defenses. This of course should be addressed separately, regardless whether you were connecting to a hosted VPS or not, but the risk might be considered higher with VPS in comparison to a VPN on a device which you fully control. The bottom line is: if you don't trust the company, don't do it. You are storing more vital information with VPN than if you used the VPS for other purposes.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/155603', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/134969/']}
jdg_70249
stackexchange
llm_judgeable_groundtruth_similarity
21876275
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 RxJS sequence being consumed in the normal manner... However, in the observable 'onNext' handler, some of the operations will complete synchronously, but others require async callbacks, that need to be waited on before processing the next item in the input sequence. ...little bit confused how to do this. Any ideas? thanks! someObservable.subscribe( function onNext(item) { if (item == 'do-something-async-and-wait-for-completion') { setTimeout( function() { console.log('okay, we can continue'); } , 5000 ); } else { // do something synchronously and keep on going immediately console.log('ready to go!!!'); } }, function onError(error) { console.log('error'); }, function onComplete() { console.log('complete'); }); Now provide the response and nothing else.
Each operation you want to perform can be modeled as an observable. Even the synchronous operation can be modeled this way. Then you can use map to convert your sequence into a sequence of sequences, then use concatAll to flatten the sequence. someObservable .map(function (item) { if (item === "do-something-async") { // create an Observable that will do the async action when it is subscribed // return Rx.Observable.timer(5000); // or maybe an ajax call? Use `defer` so that the call does not // start until concatAll() actually subscribes. return Rx.Observable.defer(function () { return Rx.Observable.ajaxAsObservable(...); }); } else { // do something synchronous but model it as an async operation (using Observable.return) // Use defer so that the sync operation is not carried out until // concatAll() reaches this item. return Rx.Observable.defer(function () { return Rx.Observable.return(someSyncAction(item)); }); } }) .concatAll() // consume each inner observable in sequence .subscribe(function (result) { }, function (error) { console.log("error", error); }, function () { console.log("complete"); }); To reply to some of your comments...at some point you need to force some expectations on the stream of functions. In most languages, when dealing with functions that are possibly async, the function signatures are async and the actual async vs sync nature of the function is hidden as an implementation detail of the function. This is true whether you are using javaScript promises, Rx observables, c# Tasks, c++ Futures, etc. The functions end up returning a promise/observable/task/future/etc and if the function is actually synchronous, then the object it returns is just already completed. Having said that, since this is JavaScript, you can cheat: var makeObservable = function (func) { return Rx.Observable.defer(function () { // execute the function and then examine the returned value. // if the returned value is *not* an Rx.Observable, then // wrap it using Observable.return var result = func(); return result instanceof Rx.Observable ? result: Rx.Observable.return(result); });}someObservable .map(makeObservable) .concatAll() .subscribe(function (result) { }, function (error) { console.log("error", error); }, function () { console.log("complete"); });
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21876275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3291110/']}
jdg_70250
stackexchange
llm_judgeable_groundtruth_similarity
6899088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to do this? I have tried padding the image and setting the width/height of the view, but neither seems to work. Here is an example: <ImageButton android:id="@+id/search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/search_small" android:paddingTop="4sp" android:paddingBottom="4sp" android:paddingLeft="6sp" android:paddingRight="6sp" android:layout_marginRight="10sp" android:layout_marginTop="6sp" android:layout_marginBottom="6sp" android:layout_alignParentRight="true"/> I want the button to be wider than it is tall, but it is coming out the other way round. Now provide the response and nothing else.
Just had a play to try and understand your problem. Seems ImageButton is a composite view which has a few pre-set values. Such as some sort of margin which you cannot override with the XML. If you cannot change your image to match what you want to happen then you are better to create your own composite view. Here is my example of a composite view you can make yourself: <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/saveSearchButton" android:layout_width="50dp" android:layout_height="50dp" /> <ImageView android:layout_width="45dp" android:layout_height="45dp" android:scaleType="fitXY" android:src="@drawable/ic_menu_save" android:layout_gravity="center"/></FrameLayout><FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/clearSearchButton" android:layout_width="50dp" android:layout_height="50dp" /> <ImageView android:layout_width="45dp" android:layout_height="45dp" android:scaleType="fitXY" android:src="@drawable/ic_menu_close_clear_cancel" android:layout_gravity="center"/></FrameLayout> And the original buttons: <ImageButton android:id="@+id/imageButton1" android:src="@drawable/ic_menu_save" android:layout_height="45dp" android:layout_width="45dp"/><ImageButton android:id="@+id/imageButton2" android:src="@drawable/ic_menu_close_clear_cancel" android:layout_height="45dp" android:layout_width="45dp"/> Here we can see custom image/button composite followed by the build in ImageButton as part of the SDK:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6899088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/619852/']}
jdg_70251
stackexchange
llm_judgeable_groundtruth_similarity
31703497
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 .NET, there's an easy way to combine two delegates (.NET's version of a lambda). Basically, you have: LambdaType f1 = (a, b) => doSomething(a, b);LambdaType f2 = (a, b) => doSomethingElse(a, b);LambdaType combined = System.Delegate.Combine(f1, f2); // combined is equiv to: (a, b) => { f1.invoke(a, b); f2.invoke(a, b);}; Is there something like this in Java to combine two lambdas? Nothing comes to mind. It'd be a nice little utility, although it's honestly not too hard to define a second lambda that just invokes two (or more). Now provide the response and nothing else.
Are you talking about Java 8 lambdas? Because such utilities exist, for example: Predicate<Foo> pred1 = f -> true; Predicate<Foo> pred2 = pred1.and(f -> false); or Function<Int,Int> func1 = x -> x + 1;Function<Int,Int> func2 = func1.andThen(x -> x*2); You should take a look at java.util.function package because you will likely find the feature already available. In your specific example you are not composing two functions, indeed, functionally speaking, you can't compose two functions that accept two arguments and return one argument (or void). This because you are lacking a requirement: the codomain of the first function must correspond to the domain of the second function, otherwise composition can't be done. What you are really doing here is sequentially calling two unrelated functions with same arguments. This problem can be solved by doing exactly the same thing: BiConsumer<Foo,Bar> combination = (f,b) -> { doSomething(f,b); doSomethingElse(f,b); };
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31703497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4220035/']}
jdg_70252
stackexchange
llm_judgeable_groundtruth_similarity
34122
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: If I wanted to apply a 100MHz frequency shift to a QAM signal with a 400MHz carrier frequency, I would Demodulate it at the carrier frequency Apply a frequency shift to the original signal Modulate it again at the new carrier frequency Is there a way to apply a frequency shift to the IQ values of a QAM signal without demodulating it? Now provide the response and nothing else.
I am not sure what the phrase to correct frequency offset in the title of this question means. Does it mean that the carrier frequency is supposed to be \$10\$ MHz but actually is \$10.001\$ MHz, that is, off by\$1\$ kHz, and what is wanted is a method to fix this problem? If so,the method described below will not work. Frequency translation by substantial amounts, e.g. changing a\$10\$ MHz to, say, \$455\$ kHz, is generally accomplished byheterodyning or mixing the signal with another carrier signal ata different frequencyand bandpass filtering the mixer output.Suppose that the QAM signal at carrier frequency \$f_c\$ Hzis $$x(t) = I(t)\cos(2\pi f_c t) - Q(t)\sin(2\pi f_c t)$$where \$I(t)\$ and \$Q(t)\$ are the in-phase and quadraturebaseband data signals. The spectrum of the QAM signal occupiesa relatively narrow band of frequencies, say, \$\left[f_c-\frac{B}{2}, f_c+ \frac{B}{2}\right]\$ centeredat \$f_c\$ Hz. Multiplying this signal by \$2\cos(2\pi\hat{f}_ct)\$and applying the trigonometric identities $$\begin{align*}2\cos(C)\cos(D) &= \cos(C+D) + \cos(C-D)\\2\sin(C)\cos(D) &= \sin(C+D) + \sin(C-D)\end{align*}$$ gives us $$\begin{align*}2x(t)\cos(2\pi \hat{f}_ct)&= \quad \left(I(t)\cos(2\pi (f_c +\hat{f}_c) t) - Q(t)\sin(2\pi (f_c+\hat{f}_c)t)\right)\\&\quad +\ \left(I(t)\cos(2\pi (f_c-\hat{f}_c)t) - Q(t)\sin(2\pi(f_c- \hat{f}_c)t)\right)\end{align*}$$ which is the sum of two QAM signals with identical data streamsbut different carrier frequencies shifted up and down by \$\hat{f}_c\$Hz from the input carrier frequency \$f_c\$. The frequencyspectra of these two QAM signals occupy bands of width \$B\$ Hzcentered at \$f_c+\hat{f}_c\$ and \$f_c-\hat{f}_c\$ respectively, and if $$f_c-\hat{f}_c + \frac{B}{2} < f_c+\hat{f}_c - \frac{B}{2}\Rightarrow \hat{f_c} > \frac{B}{2},$$then bandpass filtering can be used to eliminate one of thetwo QAM signals while retaining the other. Needless to say,if the frequency shift is muchlarger than the QAM signal bandwidth, that is, if \$\hat{f}_c \gg B/2\$, then the task of designingand implementing the bandpass filter is easier. Notealso that this method cannot be used to correctsmall frequency offsets because the two QAM signalsproduced at the mixer output will have overlapping spectra and cannot be separated by filtering.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/34122', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/9322/']}
jdg_70253
stackexchange
llm_judgeable_groundtruth_similarity
3530102
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the step by step answers, but I can't discover where the " $-1$ " comes from. A constant $= 0$ , so it can't be from the inside function. $$\begin{align*}P'(t) &= \frac{d}{dt}\left[20\left(1+e^{10-t}\right)^{-1}\right] \\ &= -20\left(1+e^{10-t}\right)^{-2}\cdot \frac{d}{dt}\left[1+e^{10-t}\right] \\ &= -20\left(1+e^{10-t}\right)^{-2}\cdot \color{red}{\boxed{\color{black}{e^{10-t}\cdot (-1)}}} \\ &= 20e^{10-t}\left(1+e^{10-t}\right)^{-2}\end{align*} \\$$ Thank you so much for the quick responses. Now provide the response and nothing else.
Because $e^{10-t}$ has also to be differentiated using the chain rule: $\frac d{dt}(e^{10-t}) = e^{10-t}\cdot \frac d{dt}(10-t) = e^{10-t}\cdot (-1)$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3530102', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/654940/']}
jdg_70254
stackexchange
llm_judgeable_groundtruth_similarity
12354515
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 the only difference between sets and lists in Python the fact that you can use the union, intersect, difference, symmetric difference functions to compare two sets? Why can't these functions simply be applied to lists? In what situations are sets more useful than lists? Now provide the response and nothing else.
There's a huge difference. Sets can't contain duplicates Sets are unordered In order to find an element in a set, a hash lookup is used (which is why sets are unordered). This makes __contains__ ( in operator) a lot more efficient for sets than lists. Sets can only contain hashable items (see #3). If you try: set(([1],[2])) you'll get a TypeError . In practical applications, lists are very nice to sort and have order while sets are nice to use when you don't want duplicates and don't care about order. Also note that if you don't care about order, etc, you can use new_set = myset.intersection(mylist) to get the intersection between a set and a list .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12354515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1588869/']}
jdg_70255
stackexchange
llm_judgeable_groundtruth_similarity
53604295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to log retry policy defined via Polly in APS.NET CORE 2.1+. My code is below showing Polly retry polly and using HttpClient. public IServiceProvider ConfigureServices(IServiceCollection services) { //... //https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory Random jitterer = new Random(); services.AddHttpClient<SimpleCastClient>() //TransientErrors: //Network failures(System.Net.Http.HttpRequestException) //HTTP 5XX status codes(server errors) //HTTP 408 status code(request timeout) .AddTransientHttpErrorPolicy(policyBuilder => //Exponential backoff with Randomisation policyBuilder.WaitAndRetryAsync(10, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)) + TimeSpan.FromMilliseconds(jitterer.Next(1, 100)) ));} [ApiVersion("1")] [Route("api/v{version:apiVersion}/[controller]")] [ApiController] public class MyController : ControllerBase { ILog _logger; private SimpleCastClient _simpleCastClient; public MyController(ILog logger, SimpleCastClient simpleCastClient) { _logger = logger; _simpleCastClient = simpleCastClient; } [HttpPost] public async Task Post() { await _simpleCastClient.PostAsync(); } } public class SimpleCastClient { private HttpClient _client; public SimpleCastClient(HttpClient client) { _client = client; } public async Task PostAsync() { string url = $"http://localhost:1111/api/v1/Mock/"; using (var content = new StringContent("data", Encoding.UTF8, "application/json")) { var response = await _client.PostAsync(url, content); } }} I wonder if there is a better way than what is on stevejgordon . Now provide the response and nothing else.
With HttpClientFactory you can apply a Polly policy to a pre-configured HttpClient , and use an ILogger configured on DI in that Polly policy, with code like this: services.AddHttpClient<MyServiceHttpClient>(/* etc */) .AddPolicyHandler((services, request) => HttpPolicyExtensions.HandleTransientHttpError() .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) }, onRetry: (outcome, timespan, retryAttempt, context) => { services.GetService<ILogger<MyServiceHttpClient>>() .LogWarning("Delaying for {delay}ms, then making retry {retry}.", timespan.TotalMilliseconds, retryAttempt); } )); Reference: https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory#configuring-policies-to-use-services-registered-with-di-such-as-iloggert
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53604295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665335/']}
jdg_70256
stackexchange
llm_judgeable_groundtruth_similarity
161
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: Econometricians often talk about a time series being integrated with order k, I(k) . k being the minimum number of differences required to obtain a stationary time series. What methods or statistical tests can be used to determine, given a level of confidence, the order of integration of a time series? Now provide the response and nothing else.
There are a number of statistical tests (known as "unit root tests") for dealing with this problem. The most popular is probably the "Augmented Dickey-Fuller" (ADF) test, although the Phillips-Perron (PP) test and the KPSS test are also widely used. Both the ADF and PP tests are based on a null hypothesis of a unit root (i.e., an I(1) series). The KPSS test is based on a null hypothesis of stationarity (i.e., an I(0) series). Consequently, the KPSS test can give quite different results from the ADF or PP tests.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/161', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/154/']}
jdg_70257
stackexchange
llm_judgeable_groundtruth_similarity
147795
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 now under a directory with very long path. For future visiting it quicker, I would like to create a link to it. I tried ln -s . ~/mylink ~/mylink actually links to ~ . So can I expand ~ into the obsolute pathname, and then give it to ln ? Now provide the response and nothing else.
A symlink actually stores the path you give literally, as a string¹. That means your link ~/mylink contains " . " (one character). When you access the link, that path is interpreted relative to where the link is, rather than where you were when you made the link. Instead, you can store the actual path you want in the link: ln -s "$(pwd)" ~/mylink using command substitution to put the output of pwd (the working directory name) into your command line. ln sees the full path and stores it into your symlink, which will then point to the right place. ¹ More or less.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/147795', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_70258
stackexchange
llm_judgeable_groundtruth_similarity
363577
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm studying recently Electric Circuits (9th edition) by Nilsson. In Chapter 2, an example bothers me. simulate this circuit – Schematic created using CircuitLab I don't understand why these above figures can't be permissible. (I know KVL and KCL , but I want to analyse these circuits with another physical meaning.) In addition, I want to know what situations will appear in these circuits. Now provide the response and nothing else.
Ask yourself: For the left circuit, what will be the voltage across V1 ? 10 V ? No because V2 puts 5 V directly across V1. 5 V ? No because V1 puts 10 V directly across V1. Do you spot the contradiction? For the right circuit, what will be the current flowing ? 5 A ? No because I2 forces 2 A to flow. 2 A ? No because I1 forces 5 A to flow. Do you spot the contradiction? In these circuits there is no solution as the sources are ideal so their voltage or current must be obeyed (for example: a 5 V voltage source must have 5 V across its terminals). For the left circuit the KVL states that V1 = V2 as the sources are in parallel, fill that in and you get: 10 = 5 We all know that 10 is not equal to 5. For the right circuit KCL states that I1 = I2 as the sources are in series, fill that in and you get: 5 = 2 We all know that 5 is not equal to 2.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/363577', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/182876/']}
jdg_70259
stackexchange
llm_judgeable_groundtruth_similarity
4219614
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In proving a change of basis theorem in linear algebra, our professor draw this diagram and simply stated that because all the outer squares in this diagram commute, the inner square (green) must also commute (I didn't write the exact mappings, because I think this question is more about diagram chasing and that it isn't really relevant). I can't, however, figure out why this is true. This class is also my first time experiencing commutative diagrams, so please explain it with as many details as possible. Edit: it turned out the questions wasn't fine, since "in general there is no implication either way", but "if the diagonal arrows are isomorphisms then the inner square commutes if and only if the (big) outer square commutes". In my case, the diagonal arrows actually are isomorphisms, which is why I am posting the extended diagram. To clear some notation: $A: U \to V$ is a linear map between vector spaces $U$ and $V$ . First bases for $U, V$ are $B, C$ . Another possible bases for $U, V$ are $B', C'$ . $\phi$ 's are isomorphisms $P_{XY}$ is a change-of-basis matrix from $Y$ to $X$ I would still appreciate if someone would help me understand why the inner square commutes, because I am lost. Now provide the response and nothing else.
because all the outer squares in this diagram commute, the inner square (green) must also commute That is not true in general. You can make a counterexample in the category of vector spaces by letting the green square be your favorite non-commuting square and then declare that the four outer objects in the black square are all the trivial space $\{0\}$ . Then the outer squares will commute automatically, because linear transformations always take $0$ to $0$ . So you need to know more about the maps before you can conclude the green square commutes. After question was updated: We now know that the blue arrows are isomorphisms -- then it's quite different. A useful principle is: if you have a commuting square (or other diagram) and replace an isomorphism with its inverse, the resulting diagram still commutes . In your case, you can flip just $\Phi_B$ in your diagram, and you should now be able to show step by step that the green square commutes. (In algebraic notation, what's going on is just that, for example, $A_{CB}\circ \Phi_B = \Phi_C\circ A$ implies $A_{CB} = \Phi_C \circ A \circ \Phi_B^{-1}$ when we compose with $\Phi_B^{-1}$ on the right.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4219614', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/726980/']}
jdg_70260
stackexchange
llm_judgeable_groundtruth_similarity
857072
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove if a non-decreasing function $f: \mathbb{R}\rightarrow (0,+\infty)$ satisfies $\lim \inf_{n\rightarrow \infty} (f(n+1)-f(n))>0$, then $\lim \sup_{x\rightarrow \infty} \frac{f(x)}{x}>0$ . Here is my trying: If $\lim \sup_{x\rightarrow \infty} \frac{f(x)}{x}\leq0$. Because $f\geq 0$, so $\lim \inf_{x\rightarrow \infty} \frac{f(x)}{x}\geq0$, so we get $\lim \sup_{x\rightarrow \infty} \frac{f(x)}{x}=\lim \inf_{x\rightarrow \infty} \frac{f(x)}{x}=0$, i.e $\lim_{x\rightarrow \infty} \frac{f(x)}{x}=0$. Then by Hospital's Rule, $\lim_{x\rightarrow \infty} \frac{f(x)}{x}=0=\lim_{x\rightarrow \infty} f'(x)=0$. In the following, I don't know how to prove when $n$ is large enough, $f(n+1)-f(n)$ can be very small and tends to 0, then contradictory to the known condition. So anyone can give me some idea? Now provide the response and nothing else.
You might want to forget L'Hospital and differentiability and proofs by contradiction, and go for a direct, hands-on, proof. Let $3\ell=\liminf\limits_{n\to\infty}f(n+1)-f(n)$ (yes, the factor $3$ is weird, but it simplifies things afterwards). Then $\ell\gt0$ hence $2\ell\lt3\ell$ and, by definition of liminf, $f(n+1)-f(n)\geqslant2\ell$ for every $n$ large enough, say every $n\geqslant N$. By concatenation, for every $n\geqslant N$, $f(n)\geqslant f(N)+2\ell\cdot(n-N)=2\ell\cdot n-C$, where $C=2\ell\cdot N-f(N)$ does not depend on $n$. Thus, $f(n)/n\geqslant2\ell-(C/n)$ and $2\ell-(C/n)\geqslant\ell$ for every $n$ large enough, say, every $n\geqslant\max\{N,C/\ell\}$. In particular, $\liminf\limits_{n\to\infty}f(n)/n\geqslant\ell$, which implies that $\limsup\limits_{n\to\infty}f(n)/n\geqslant\ell$, and finally that $\limsup\limits_{x\to\infty}f(x)/x\geqslant\limsup\limits_{n\to\infty}f(n)/n\geqslant\ell$ hence $\limsup\limits_{x\to\infty}f(x)/x\gt0$. The method above allows to prove that $\limsup\limits_{x\to\infty}f(x)/x\geqslant\liminf\limits_{n\to\infty}f(n+1)-f(n)$. The hypothesis that $f$ is nondecreasing is not useful here. If it holds, one can strengthen the result to $\liminf\limits_{x\to\infty}f(x)/x\geqslant\liminf\limits_{n\to\infty}f(n+1)-f(n)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/857072', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157361/']}
jdg_70261
stackexchange
llm_judgeable_groundtruth_similarity
45927140
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: List<String> listA = new Arraylist();List<String> listB = new Arraylist(); Given above 2 lists, I want to iterate and call the same method on each element. Option 1 for(String aStr: listA){ someCommonMethodToCall(aStr); someCommonMethodToCall(aStr); ...}for(String bStr: listB){ someCommonMethodToCall(bStr); someCommonMethodToCall(bStr); ...} or Option 2 List<String> mergedList = new ArrayList();mergedList.addAll(listA);mergedList.addAll(listB);for(String elem: mergedList){ someCommonMethodToCall(elem); someCommonMethodToCall(elem); ...} or Option 3 I feel the Option 1 should be the best. Is there some Java 8 lambda way to do this? Also, performance wise, would anything better than Option 1? Now provide the response and nothing else.
You can stream the lists and concat the streams into one: Stream.concat(listA.stream(), listB.stream()) .forEach(elem -> { someCommonMethodToCall(elem); someOtherMethodToCall(elem); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45927140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4017375/']}
jdg_70262
stackexchange
llm_judgeable_groundtruth_similarity
399277
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Covariance and Contravariance feature is well supported in C# and Java collections. However C++ doesn't support them in their STL containers. Why is it so? For example the below code will compile in C# and Java but not in C++. (The syntax will have to be translated to the specific language though) class Base{};class Child : public Base{};int main(){ std::vector<Base*> baseArray; std::vector<Child*> ChildArray; baseArray = ChildArray; return 0;} Now provide the response and nothing else.
The reason is the underlying object and memory models. To simplify the reasoning: In java and C#, objects of a class are managed by reference . Containers do not store directly the object value but a reference that says where to find the value. It is therefore technically easy to mix objects of different types in the same container (polymorphism) or to use the container for objects of covariant types. The only constraint is the language semantics. This facilitates significantly the implementation of covariant containers. In C++, objects are managed by value, following the rules of its memory model, which basically requires that objects of a given type a stored within a fixed size (which of course can contain pointers to elements having a dynamic size). A container therefore has to know the type of its objects at compile-time. Unfortunately (or not) C++ also allows for separate compilation. So when you compile a container for Animals in one translation unit, the compiler might not know the size of a Cat (which might not even yet be developed). All this makes it extremely difficult to implement covariance in the language. Interestingly, in C# you can have objects that are managed by value (in the case of a struct). But as this Microsoft documentation and this SO question explain, variance only applies to reference types. Of course, all this is simplified explanations and language-lawyers could argue on some details, but i hope it helps to grasp the idea.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/399277', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/309242/']}
jdg_70263
stackexchange
llm_judgeable_groundtruth_similarity
524272
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: What distributions have an undefined mean but are not symmetric? I'm looking for a probability distribution function (and CDF) for which the mean is undefined, but not symmetric like Cauchy, but a positive, continuous probability distribution with infinite mean and with a maximum density away from zero -- shaped like Poisson with a "hump". I think a fat tail to positive infinity should work for an undefined mean, but what distributions are like that? Now provide the response and nothing else.
I am guessing that you are looking for a positive , continuous probability distribution with infinite mean and with a maximum density away from zero. I thought that by analogy with a Gamma distribution ( $p(x) \propto x^a \exp(-x) \, dx$ ), we could try something with a rational (polynomial) rather than an exponential tail. After a little bit of lazy R and Python (sympy) experimentation, I came up with $$p(x) = \frac{1}{2\sqrt{3}\cdot \pi/9} \cdot \frac{x}{1+x^3} \, dx$$ (I initially tried $p(x) \propto x/(1+x^2)$ , but its integral diverges.) $\int_0^\infty p(x) \, dx$ is 1, as required, and $\int_0^\infty x p(x) \, dx$ diverges. I don't know if this distribution has a name/literature associated with it. The CDF is available in closed form but is pretty horrible ... (see Python code below ...) $$3 \sqrt{3} \left(- \frac{\log{\left(X + 1 \right)}}{6 \pi} + \frac{\log{\left(X^{2} - X + 1 \right)}}{12 \pi} + \frac{\sqrt{3} \operatorname{atan}{\left(\frac{2 \sqrt{3} X}{3} - \frac{\sqrt{3}}{3} \right)}}{6 \pi}\right) + \frac{1}{4}$$ Without actually trying anything, I would guess that distributions of the form $x^a/(1+x^{a+2})$ will generally have these properties (but the computations will get progressively nastier). Someone with more analysis skills could probably prove a bunch of things. An extremely knowledgeable colleague identified this as almost the same as a "Beta-Type 2 (m=2/3,n=1/3)" distribution (a Beta-Type 2 distribution has a term of the form $(1+x)^n$ in the denominator rather than the $1+x^n$ given above). You might want to use the Beta-Type 2 instead of my version; since you know what it's called you can search for useful code, or literature on its properties (e.g. here or here or McDonald et al 2013), or cite it in a paper: "Beta-Type 2" sounds so much better than "a distribution that some guy on CrossValidated made up". ... the Beta-Type 2 family with its density as $$f(x) = \frac{1}{\textrm{Beta}(m,n)} \frac{x^{m-1}}{(1+x)^{m+n}}$$ over the support $(0,\infty)$ It is evident that if $m$ is chosen to be > 1, the mode will be away from 0. Also, if $n$ is chosen to be $\leq 1$ , then the mean will be infinite. This family will produce [an] uncountable number of models with the property you are looking for.... If you set $Y=X^3$ in your model, then it becomes a Beta-Type 2 $(m=2/3,n=1/3)$ and you can see that this fits the description I have given above. They also identified the name of @ThomasLumley's contribution: ... it is called power gamma model or exponential-gamma model. McDonald, James B., Jeff Sorensen, and Patrick A. Turley. “Skewness and Kurtosis Properties of Income Distribution Models.” Review of Income and Wealth 59, no. 2 (2013): 360–74. https://doi.org/10.1111/j.1475-4991.2011.00478.x . R code: f <- function(x) 1/(2*sqrt(3)*pi/9)*x/(1+x^3)integrate(f, 0, Inf) ## 1 with absolute error < 4e-07curve(f, from=0, to=10) Python code (because I'm too lazy to integrate): from sympy import *x, n, N = symbols('x,n,N')n=integrate(x/(1+x**3), (x, 0, oo)) ## 2*sqrt(3)*pi/9integrate(x**2/(1+x**3), (x, 0, oo)) ## infinite meancdf = integrate(1/n*x/(1+x**3), (x, 0, X))print(latex(cdf))
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/524272', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/97642/']}
jdg_70264
stackexchange
llm_judgeable_groundtruth_similarity
257290
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: Here's the situation (I'm on a Mac, OS X El Capitan): # This works:$ cd /Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates/;# These do not work:$ INSTALL_DIR=/Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates;$ cd $INSTALL_DIR# Moves me here: /Applications/Adobe$ cd "$INSTALL_DIR"-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory$ cd "${INSTALL_DIR}"-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory My goal is to use $INSTALL_DIR in tar like so: $ tar -xz $SOURCE_ZIP --strip-components 1 -C $INSTALL_DIR "*.ait"; Unfortunately, the -C (changing to destination directory) doesn't like the spaces in $INSTALL_DIR ; if I use quotes, I can't get the * to work. Is there an elegant way to handle this scenario? Now provide the response and nothing else.
When the * is not quoted the shell expands the argument list before running the command. It passes the expand argument list to the program. When the * appears in a quoted string it is not expanded by the shell before being passed to the program. Try expanding the path, assigning it to another variable, and then quoting the second variable when passing it as an argument.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/257290', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/67282/']}
jdg_70265
stackexchange
llm_judgeable_groundtruth_similarity
54672
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 was looking to give out login information to a read-only mysql database (via phpmyadmin) to the public (the users of my program) to use for reference purposes on a production environment. Would I be risking anything on my side by doing so (assuming all privileges were locked down and the users could literally only read the database)? Data like: License Validation (Verifying if a user has a license key purchased and if they do remove Copyright Footer) and Data Like: Chargeback or Fradulent Paypal User Emails My only main concern is having the whole server compromised just because someone knows a username or password for the actual read-only database. Now provide the response and nothing else.
Yes, of course is a potential security threat. MySQL can always have a vulnerability in it, perhaps something like CVE-2003-0150 MySQL Root Privilege Escalation Vulnerability from many years ago. New flaws can be introduced with any update, and old flaws can be discovered at any time. Just because you ask MySQL not to let the user run or create anything doesn't mean MySQL is perfectly effective at doing so at all times and after each update. And, naturally, if then can execute SELECTs, they can execute SELECT with a cartesian product large enough to choke your server completely via IO and/or CPU load, or use up as much of network bandwidth as they can obtain. This is not even counting possible fun with transaction isolation level to try and cause locking and deadlocks. Watch out for temporary tables as well, of course.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/54672', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/41278/']}
jdg_70266
stackexchange
llm_judgeable_groundtruth_similarity
9773964
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 improve my understanding of the global namespace in javascript and I'm curious about a few things: is there a "GOD" (i.e. a parent) object that all objects (since all things except primitives are objects) to answer to and if so would that object be "window" ? why is it bad idea to have vars/functions on a global level? if it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this? example: function parent(){ var x = 'some value';//this var would be considered global to all children functions but not in the true global namespace function child1(){ x.someMethod() } function child2(){ x*something; } function child3(){ x+=something; child2() child1() } child3()}parent() Now provide the response and nothing else.
Is there a god (i.e. a parent) object? Yes. More technically, it's the global object that all these primitives are members of; it just happens that in the browser, the window object is the global object. > window.String === String;true Why is it bad idea to have vars/functions on a global level? Because if you're adding lots of 3rd party libraries/ scripts, they all share the same global object, there's the chance of name collisions. This is a real life problem with all the libraries which use $ as an alias (jQuery, Prototype and more). If it is really a bad idea to have vars/functions in global scope then would closures be the best way to avoid this? x shouldn't be considered global. It's part of the closure formed by declaring the child functions inside the parent() function. The problem part of your snippet is that parent() is global; what happens if some other code re-declared parent() ? This would be better: (function () {function parent(){ var x = 'some value'; function child1(){ x.someMethod() } function child2(){ x*something; } function child3(){ x+=something; child2() child1() } child3()}parent()}()); The fact x is accessible within the child functions isn't bad; you should have written those functions yourself, so you should be aware of the existence of x . Bear in mind that if you re-declare x within those child functions with var , you won't affect the x in parent() .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9773964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146022/']}
jdg_70267
stackexchange
llm_judgeable_groundtruth_similarity
15053
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it safe to use impact wrench when you try to loosen the crankshaft pulley retaining bolt?Many suggest just that without any concern for possibility of causing the damage to engine mounts, maybe crankshaft bearings, seals etc..I think Honda produced that 50 mm hex tool for reason. To hold crankshaft safely and protect it from surprises to say at least.Would it be better to use that tool and unscrew the bolt manually.Is there a chance that vibration from impact will cause damage or cause some components to fail sooner? Now provide the response and nothing else.
I wouldn't hesitate using an impact to loosen the crankshaft pulley retaining bolt. The reason for this is because even though there is an impact involved, it is a rotary impact. The crank itself would incur no damage, nor would the bearings. The bearings take a worse beating during normal operation than they would during crankshaft pulley retaining bolt removal (mind you with proper oil flow, bearings don't usually take a beating, anyway ... but that's a different subject.) With that said, if the engine was in the car this may be problematic. You may not be able to get to the crankshaft pulley retaining bolt with an impact wrench (most probably would not be able to get to it). Also, you'll noticed I emphasized the word loosen above. The reason for this is, while I would not hesitate to loosen most engine bolts using an impact, I would almost never utilize an impact gun to tighten one. Especially where the crankshaft pulley retaining bolt is concerned. The reason for this is you will most likely over torque it using an impact, which will cause issues for you. Also, you never want to use crankshaft bolt to draw in a balancer pulley, but utilize an installation tool instead. The installation tool will be completely engaged on the threads down to the bottom of the hole inside the crankshaft. This gives it enough purchase to run the pulley/balancer onto the crankshaft without the worry of stripping out the threads. By trying to use the bolt, you'd only be using a few (very few) of the threads, which can cause catastrophic results. Believe it or not, it's very easy to strip these threads out. Why is all of this important? Because you will most likely need the tool to hold things in place while you are installing the balancer onto the crankshaft.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/15053', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/9133/']}
jdg_70268
stackexchange
llm_judgeable_groundtruth_similarity
16134910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: UPDATE: I want to give an updated answer to this question. First, let me state if you're attempting to accomplish what I have below, I recommend that you manage events by adding event listeners instead. I highly recommend that you utilize jQuery for your project and use their syntax to manage event listeners over using DOM. QUESTION Okay, I am basically doing this: document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\'ex1\')' />"; I don't want double quotes (") where I put the \'. I only want a single quote, so I am trying to not make it put a double when it is used. I am trying to reach this in the final outcome. <img src="something" onmouseover="change('ex1')" /> Escaping isn't working for me. My marked answer works fine, however, the cleaner (and more professional-looking way, IMO) is loganfsmyth's answer . Now provide the response and nothing else.
You should always consider what the browser will see by the end. In this case, it will see this: <img src='something' onmouseover='change(' ex1')' /> In other words, the "onmouseover" attribute is just change( , and there's another "attribute" called ex1')' with no value. The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively. Armed with this knowledge, use this: document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />"; ... That being said, you could just use JavaScript quotes: document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16134910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1754890/']}
jdg_70269
stackexchange
llm_judgeable_groundtruth_similarity
43320272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Apppreciate any expert here could advise for below JVM and swap space related queries. Thanks in advance 1) Am I right that Operating System will use swap space when OutOfMemory occured in JVM Java Heap, Perm Generation or Native Heap ? Or swap space is used for OutOfMemory in Native Heap ? 2) Am I right that Native heap size is not configurable at JVM, because OS will assign available RAM to JVM during runtime ? 3) How can we enable swap space for JVM, or swap space is enabled for all processes at Unix and Window level by default ? 4) Understand that swap space can affect application performance, is that best practice to disable swap space for JVM ? If not, what is the reason ? 5) How can we disable swap space and change the swap space size for particular JVM in both Unix and Window OS, or it is only configurable at OS level which is applied to all processes in the OS ? Now provide the response and nothing else.
There are a lot of questions here... Operating systems indeed use swap space to create the so called virtual memory (which is obviously bigger then the RAM you might have). It is usually enabled by default, but you need to check. You can not instruct the JVM to use only the physical RAM AFAIK, but that would be a limitation of the OS itself and not JVM (this should answer 5). You can disable swap (again for the OS, not JVM ), but that is a bad idea. There are multiple processes that run inside the operating system and they each need space to run into (that at some point in time might exceed your actual RAM). It indeed affects performance, but what is worse - some performance penalties (I assume the OS has many things to make this better for you) or the death of the application? (this should answer 4). Regarding (2) there are two parameters that control how much heap you will have: Xmx - maximum heap that JVM process will use. And Xms - initial heap. Actually just recent there was a very good talk about this: here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43320272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5051750/']}
jdg_70270
stackexchange
llm_judgeable_groundtruth_similarity
10657315
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 tried to merge a file in the command line using Git, when an error message appeared telling me the merge was aborted. I thought that was the end of it, but then I realized there are gitmarks in my files. Like so: start = expressionvalidchar = [0-9a-zA-Z_?!+\-=@#$%^&*/.]integer = <<<<<<< HEAD digits:[0-9]+ { return digits.join(""); }======= sign:"-"* digits:[0-9]+ { return sign + digits.join(""); }>>>>>>> gh-pages The files have been edited not by me and show lines inserted with: HEAD after less than signs ( <<<<<<< HEAD ) lines of changed code a string of equals signs ( ======= ) the new version of the code another line starting with greater than signs and the name of the branch ( >>>>>>> gh-pages ) What's worse is that the file contents are no longer in order. Does anyone know how I get those files back to normal, and the changes I made in the gh-branch merged into the master branch? Now provide the response and nothing else.
Those are conflict markers . You're still in the process of merging, but there were some parts that Git couldn't merge automatically. You'll need to hand-edit those parts to what you want them to be and then commit the results. For instance, in your particular case, you'd probably want to resolve it like this (note - the arrows/text on the right are just my notes, not something you'd type into the file): integer = <<<<<<< HEAD <-+ remove the bits here digits:[0-9]+ | { return digits.join(""); } |======= <-+ sign:"-"* digits:[0-9]+ { return sign + digits.join(""); }>>>>>>> gh-pages <-- and this and thus you'd save the file as... integer = sign:"-"* digits:[0-9]+ { return sign + digits.join(""); }
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10657315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/387405/']}
jdg_70271
stackexchange
llm_judgeable_groundtruth_similarity
11539605
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 simple chain of events: Get Columns from a metaData table (async) load selected columns (async) render list I used to just the chain these functions, each calling the next when it had completed. However, its not very obvious what's going (calling getColumnsFromMeta results in the view being populated). So in the interest of clarity and code re-use I'd like to refactor these using JQuery Promises . I have used promises before. But how do I chain more than two? getColumnsFromMeta ().then(loadSourceFromDatabase /*some arguments*/) //.then(renderList)?; Here's an example of the getColumnsFromMeta : var getColumnsFromMeta = function(id){ var sql, dfd; dfd = $.Deferred(); var onSuccess = function(tx, result) { var columns = []; for (var i = 0; i < result.rows.length; i++) { columns.push(result.rows.item(i).Column); } dfd.resolve(columns); }; var onError = function(tx, error) { dfd.reject(error); }; sql = "SELECT Column FROM Meta WHERE id = ?"; database.query(sql, [id], onSuccess, onError); return dfd.promise();}; Now provide the response and nothing else.
It should be something like: function getColumnsFromMeta(){ var d = $.Deferred(); // retrieve data in async manner and perform // d.resolve(columns); return d.promise();}function loadSelectedColumns(columns){ var d = $.Deferred(); // retrieve data in async manner and perform // d.resolve(data); return d.promise();}function render(data){ // render your data}getColumnsFromMeta().pipe(loadSelectedColumns).pipe(render); http://jsfiddle.net/zerkms/xYDbm/1/ - here is a working sample http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ -- this is the article I really like about promises
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11539605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/874927/']}
jdg_70272
stackexchange
llm_judgeable_groundtruth_similarity
35668622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was watching a video called Becoming a C# Time Lord and at 0:35:36 this code popped up: async Task<TResult[]> PurelyWhenAll<TResult> (params Task<TResult>[] tasks) { var killJoy = new TaskCompletionSource<TResult[]>(); foreach ( var task in tasks ) task.ContinueWith(ant => { if ( ant.IsCanceled ) killJoy.TrySetCanceled(); else if ( ant.IsFaulted ) killJoy.TrySetException(ant.Exception.InnerException); }); return await await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks)); } Does this mean that a task returns a task and because of that we have double await ? If that is the case what happens concerning performance if we have more than two awaits? Is this good practice, should this be avoided? Now provide the response and nothing else.
Task.WhenAny is going to return a Task<Task<TResult>> : Awaiting the result of Task.WhenAny() will return the first task that completed Awaiting that task will return the results of the task, i.e. a TResult[] . You might find it easy to understand with explanatory variables: var firstCompletedTask = await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks));var firstResult = await firstCompletedTask;return firstResult; It's not clear why you're concerned around the performance of this - it's just two await expressions, not particularly different to any other method with two await expressions. It's pretty natural to do this when using Task.WhenAny<TResult>(Task<TResult>[]) , given that the return type is a Task<Task<TResult>> .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35668622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3248293/']}
jdg_70273
stackexchange
llm_judgeable_groundtruth_similarity
2631614
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 unable to override attributes when using <include> in my Android layout files. When I searched for bugs, I found Declined Issue 2863 : "include tag is broken (overriding layout params never works)" Since Romain indicates this works in the test suites and his examples, I must be doing something wrong. My project is organized like this: res/layout buttons.xmlres/layout-land receipt.xmlres/layout-port receipt.xml The buttons.xml contains something like this: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button .../> <Button .../></LinearLayout> And the portrait and landscape receipt.xml files look something like: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> ... <!-- Overridden attributes never work. Nor do attributes like the red background, which is specified here. --> <include android:id="@+id/buttons_override" android:background="#ff0000" android:layout_width="fill_parent" layout="@layout/buttons"/></LinearLayout> What am I missing? Now provide the response and nothing else.
I just found the issue. First, you can only override layout_* attributes, so the background won't work. That is documented behavior and simply an oversight on my part. The real problem is found in LayoutInflater.java: // We try to load the layout params set in the <include /> tag. If// they don't exist, we will rely on the layout params set in the// included XML file.// During a layoutparams generation, a runtime exception is thrown// if either layout_width or layout_height is missing. We catch// this exception and set localParams accordingly: true means we// successfully loaded layout params from the <include /> tag,// false means we need to rely on the included layout params.ViewGroup.LayoutParams params = null;try { params = group.generateLayoutParams(attrs);} catch (RuntimeException e) { params = group.generateLayoutParams(childAttrs);} finally { if (params != null) { view.setLayoutParams(params); }} If the <include> tag does not include both layout_width and layout_height, the RuntimeException occurs and is silently handled, without any log statement even. The solution is to always include both layout_width and layout_height when using the <include> tag, if you want to override any of the layout_* attributes. My example should change to: <include android:id="@+id/buttons_override" android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/buttons"/>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2631614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40257/']}
jdg_70274
stackexchange
llm_judgeable_groundtruth_similarity
906916
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday our Digital Ocean server encountered something that looked like an attack. The outbound traffic suddenly increased to 700Mbps, while the inbound traffic stayed at about 0.1Mbps, and didn't increase even once. The traffic lasted for several minutes until Digital Ocean cut our server off the network assuming we're performing a DoS (which is reasonable). I have two assumptions: either someone hacked into our server (after the attack I realised my colleague had enabled SSH login with password) or there's some kind of an attack that I don't know about. Can anyone clear this situation up for me? If there indeed is a kind of DoS which traffic looks like that, please educate me. Now provide the response and nothing else.
One likely possibility is an amplification attack. If you are running an open recursive DNS resolver (there are other protocols you can do this with though), for example, you can receive a very small UDP packet that has a spoofed IP address. Your server then generates a large response and sends it to the victim, thinking that it's a legitimate request. Another possibility is that someone was exfiltrating data off your network. If someone got into your server and was offloading every byte they could find, it would look like that as well. There's no way to know which one it was without doing an investigation, and hoping that whatever did happen left evidence. If it's the latter (exfiltration) then they probably cleared their tracks as best they could.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/906916', 'https://serverfault.com', 'https://serverfault.com/users/328994/']}
jdg_70275
stackexchange
llm_judgeable_groundtruth_similarity
29339
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Inbetween the Display port, and the Activity LED on my Raspbery Pi 2, There are 2 holes boxed off, labled with: "Run". What are those pins? What do they do? Is it a reset? Now provide the response and nothing else.
Short answer: It is a reset. Here is why: From the ARM information center - Cortex-A7 MPCore Technical Reference Manual Run mode This is the normal mode of operation where all of the processor functionality is available. The Cortex-A7 MPCore processor uses gated clocks and gates to disable inputs to unused functional blocks. Only the logic in use to perform an operation consumes any dynamic power. Basically, the BCM2835/BCM2836 runs normally when this RUN pin to the IC is held to a logical HIGH. From the Raspberry Pi Foundation's website - Released RPi Model B Schematics It might be a bit difficult to see, but off to the left of this schematic is the wiring for P6, which you see as RUN when you look at the physical board. During normal operation (leaving that connection open), PIN D15 (RUN) to the BCM IC (IC2) is held to a logical HIGH by R15 (pull-up resistor). When the P6 connection is closed, that same pin is pulled to a logical LOW (electricity likes to take the path of least resistance), effectively clearing that state to IC2 and resetting your system.
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/29339', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/11827/']}
jdg_70276
stackexchange
llm_judgeable_groundtruth_similarity
862146
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'm trying to implement an ingress helm template encoding the current application version into the url. This shall allow users to do soft migration by providing them different versions of the application. Example: mydomain.org/1.0/applicationpathmydomain.org/1.1/applicationpathmydomain.org/2.0/applicationpath To prevent configuring this manually in the ingress on each update, I would prefer a regex determining the major.minor version automatically.The application is revised according to Semver 2.0.0, so a pattern like \d+.\d+ should do the work. I tried something like this: apiVersion: extensions/v1beta1kind: Ingressspec: backend: serviceName: {{ .Release.Name }}-my-srv servicePort: 80 rules: - host: {{ .Values.app.ingress.host }} http: paths: - path: /{{ .Chart.AppVersion | regex \d+.\d+ }} Unfortunately I couldn't find a function for regular expressions.Is there an option to achieve this with a helm template? Now provide the response and nothing else.
Yes there is. However it is unfortunately undocumented. Helm uses the sprig library to provide additional functions for templating. What is undocumented is many of the sprig functions that have been added to the code (ref issue #84 ), and the regex functions are some of them. You can find these functions here: https://github.com/Masterminds/sprig/blob/master/regex.go Thus you can do {{ .Chart.AppVersion | regexFind "\d+\.\d+" }} (note that I also added a \ before the . to escape it as . means to match any character, which does not seem to be your intent) Not your use case, but one item of note for others which might be interested in using the regex* functions from sprig, is that unfortunately the sprig owner made the subject string the second argument of all the functions, and some of the functions have additional arguments after it (e.g. the regexReplaceAll function). The reason why this is a problem is that when a function is used in a pipeline, the result of the previous element in the pipeline becomes the last argument of the function. So this does not work: "foo subject string" | regexReplaceAll "foo" "bar" , as it'll treat bar as the string to operate on, and foo subject string as the string to replace any occurrences of foo with (which in this example there would not be any).
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/862146', 'https://serverfault.com', 'https://serverfault.com/users/148064/']}
jdg_70277
stackexchange
llm_judgeable_groundtruth_similarity
1251457
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am struggling with the concept of parameterizing curves. I am not even sure if I know what it means so I tried to look some things up. On Wikipedia it says: Parametrization is... the process of finding parametric equations of a curve, a surface, or, more generally, a manifold or a variety, defined by an implicit equation. The inverse process is called implicitization. Since I didn't know what a parametric equation was I also looked that up: In mathematics, parametric equations of a curve express the coordinates of the points of the curve as functions of a variable, called a parameter. For example, \begin{align} x&=\cos t\\ y&=\sin t \end{align} . So, basically I have some curve and I want to make up some equation that describes that curve? But doesn't this get very difficult if you don't have simple circles or spirals? Maybe someone can explain to me what's going on here. Thanks in advance. Now provide the response and nothing else.
The idea of parameterization is that you have some equation for a subset $X$ of a space (often $\mathbb{R}^n$), e.g., the usual equation$$x^2 + y^2 = 1$$for the unit circle $C$ in $\mathbb{R}^2$, and you want to describe a function $\gamma(t) = (x(t), y(t))$ that traces out that subset (or sometimes, just part of it) as $t$ varies. With a parameterization in hand, you can then specify a point on $X$ just by giving a single value of $t$, which corresponds to the point $\gamma(t)$ on $X$. One can still give points on $X$, say, $(x, y)$, directly, of course, but this has the disadvantage that often one needs to check that a given point $(x, y)$ is on $X$, that is, that it satisfies the equation defining $X$, whereas by construction a point $\gamma(t)$ is always on $X$. Provided that the function $\gamma(t)$ traces out all of $X$, we say that $X$ is the image of $\gamma$. In your example, we can parameterize the unit circle $C$ by the parametric function $$\gamma(t) = (x(t), y(t)) := (\cos t, \sin t).$$ We can check that the points specified by $\gamma(t)$ really do lie on $C$ just by substituting $\cos t$ for $x$ and $\sin t$ for $y$; indeed:$$(\cos t)^2 + (\sin t)^2 = 1.$$It's not too hard to show that $\gamma$ actually traces out the full circle $t$ (in fact, this is an immediate consequence of the usual geometric definitions of $\cos$ and $\sin$ ). Note too that this parameterization traces over the circle infinitely many times, and in particular, there is more than one $t$ value corresponding to any point on the circle. In fact, since the components $\cos t$ and $\sin t$ of $\gamma(t)$ have period $2 \pi$, we have $\gamma(t + 2\pi) = \gamma(t)$ for all $t$. There are many other parameterizations for all or part of the circle, too, and which is best depends on the context. Substituting the components in $x^2 + y^2 = 1$ (try this!) shows that for all $t$, $$\alpha(t) := \left(\frac{2t}{t^2 + 1}, \frac{t^2 - 1}{t^2 + 1}\right)$$ is on the unit circle, and with some more work we can show that (1) $\alpha$ traces out the full circle with the single exception of the point $(0, 1)$ (because we have $\frac{t^2 - 1}{t^2 + 1} < 1$ for all $t$), and (2) it is injective, that is, it only traces over the (punctured) circle once. This parameterization looks qualitatively different from the trigonometric parameterization $\gamma(t)$ above, but they are related by a clever and important change of variable related to Pythagorean triples and which proves to be extremely helpful in evaluating certain integrals . One can, by the way, also parameterize surfaces (and even higher-dimensional objects); the most important difference is that (at least sensible ) parameterizations of surfaces require two parameters, as a consequence of the fact that on surfaces one can move in two independent directions. A simple example is the parameterization ${\bf r}(\phi, \theta)$ of the unit sphere $$x^2 + y^2 + z^2 = 1$$ by latitude $\phi$ and longitude $\theta$:$${\bf r}(\phi, \theta) := (\cos \phi \cos \theta, \cos \phi \sin \theta, \sin \phi).$$When giving latitude an longitude of a point on Earth, we typically specify points with latitude $-90^{\circ} \leq \phi \leq 90^{\circ}$ and longitude $-180^{\circ} \leq \theta \leq 180^{\circ}$. (Here, points with $\phi = 0^{\circ}$ comprise the equator, and points with $\theta = 0^{\circ}$ the "prime meridian"). Many common shapes (lines, circles, other conic sections, planes, spheres, etc.) have well-known parameterizations, and graphs of functions $\mathbb{R}^m \to \mathbb{R}^n$ have canonical parameterizations that are easy to write down, but like you say, for sufficiently complicated shapes parameterization can be a very difficult problem.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1251457', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/197849/']}
jdg_70278
stackexchange
llm_judgeable_groundtruth_similarity
224824
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was attempting to investigate an SPI interface on a power line meter (typical model that measures Voltage, Frequency, Amps, Watts). I opened the module and found the SPI pins broken out. So I plugged in the meter and the oscilloscope, and connected the oscilliscope probe to the CLK pin, and the probe ground to the GND pin. A second or two after connecting the GND pin, the device IC caps blew off, and the RCD for the property blew and had to be reset. What did I do wrong? How did this blow the RCD? Now provide the response and nothing else.
The oscilloscope's probe ground is connected to the earth (0V). It's likely that the "ground" of the power meter is not really ground. It's likely that the board's "ground" is actually at the neutral or line voltage, so it would create a circuit between neutral and ground or line and ground, which the RCD detected. But, without a board schematic, it's difficult to debug. To debug the circuit, a differential voltage probe would be best. Otherwise, the probe ground could be connected to the earth prong in the power meter.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/224824', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3975/']}
jdg_70279
stackexchange
llm_judgeable_groundtruth_similarity
32955846
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically, I'm looking for something that offers a parallel map using python3 coroutines as the backend instead of threads or processes. I believe there should be less overhead when performing highly parallel IO work. Surely something similar already exists, be it in the standard library or some widely used package? Now provide the response and nothing else.
DISCLAIMER PEP 0492 defines only syntax and usage for coroutines. They require an event loop to run, which is most likely asyncio 's event loop . Asynchronous map I don't know any implementation of map based on coroutines. However it's trivial to implement basic map functionality using asyncio.gather() : def async_map(coroutine_func, iterable): loop = asyncio.get_event_loop() future = asyncio.gather(*(coroutine_func(param) for param in iterable)) return loop.run_until_complete(future) This implementation is really simple. It creates a coroutine for each item in the iterable , joins them into single coroutine and executes joined coroutine on event loop. Provided implementation covers part of the cases. However it has a problem. With long iterable you would probably want to limit amount of coroutines running in parallel. I can't come up with simple implementation, which is efficient and preserves order at the same time, so I will leave it as an exercise for a reader. Performance You claimed: I believe there should be less overhead when performing highly parallel IO work. It requires proof, so here is a comparison of multiprocessing implementation, gevent implementation by a p and my implementation based on coroutines. All tests were performed on Python 3.5. Implementation using multiprocessing : from multiprocessing import Poolimport timedef async_map(f, iterable): with Pool(len(iterable)) as p: # run one process per item to measure overhead only return p.map(f, iterable)def func(val): time.sleep(1) return val * val Implementation using gevent : import geventfrom gevent.pool import Groupdef async_map(f, iterable): group = Group() return group.map(f, iterable)def func(val): gevent.sleep(1) return val * val Implementation using asyncio : import asynciodef async_map(f, iterable): loop = asyncio.get_event_loop() future = asyncio.gather(*(f(param) for param in iterable)) return loop.run_until_complete(future)async def func(val): await asyncio.sleep(1) return val * val Testing program is usual timeit : $ python3 -m timeit -s 'from perf.map_mp import async_map, func' -n 1 'async_map(func, list(range(10)))' Results: Iterable of 10 items: multiprocessing - 1.05 sec gevent - 1 sec asyncio - 1 sec Iterable of 100 items: multiprocessing - 1.16 sec gevent - 1.01 sec asyncio - 1.01 sec Iterable of 500 items: multiprocessing - 2.31 sec gevent - 1.02 sec asyncio - 1.03 sec Iterable of 5000 items: multiprocessing - failed (spawning 5k processes is not so good idea!) gevent - 1.12 sec asyncio - 1.22 sec Iterable of 50000 items: gevent - 2.2 sec asyncio - 3.25 sec Conclusions Concurrency based on event loop works faster, when program do mostly I/O, not computations. Keep in mind, that difference will be smaller, when there are less I/O and more computations are involved. Overhead introduced by spawning processes is significantly bigger, than overhead introduced by event loop based concurrency. It means that your assumption is correct. Comparing asyncio and gevent we can say, that asyncio has 33-45% bigger overhead. It means that creation of greenlets is cheaper, than creation of coroutines. As a final conclusion: gevent has better performance, but asyncio is part of the standard library. Difference in performance (absolute numbers) isn't very significant. gevent is quite mature library, while asyncio is relatively new, but it advances quickly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32955846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164171/']}
jdg_70280
stackexchange
llm_judgeable_groundtruth_similarity
543142
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 may be a silly question, but it has been a long time since I have used set notation to any real extent. How would I write that $i$ is an integer ranging from $1$ to $N$? My (possibly faulty) recollection is that this is expressed as $i \in \{ \mathbb{Z}: [1,N]\}$. Is this correct? Now provide the response and nothing else.
Notationally, to write $i$ is an integer within a given interval, you could write several different things: $$i\in\Bbb Z:i\in[1,N]\tag 1$$ $$i\in\Bbb Z:1\le i\le N\tag 2$$ $$i\in\Bbb Z\cap[1,N]\tag 3$$ where each is read as follows: $(1)$ "$i$ is an integer such that $i$ is within the interval $1,N$" $(2)$ "$i$ is an integer such that $1$ is less than or equal to $i$ is less than or equal to $N$" $(3)$ "$i$ is an element of the set intersection of the integers with the interval $1,N$" Each would be considered a valid representation, and each may be considered more appropriate for given circumstances or writing styles than the others. As mentioned elsewhere, it is also common to write $i=1,2,\dots,N$ especially when $i$ is an indexing element.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/543142', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/98757/']}
jdg_70281
stackexchange
llm_judgeable_groundtruth_similarity
28535703
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my android app i want to get user current location every few minute interval and update in to my center server using web service.Currently i am using Fused Location Provide for get user current location, See link now i want to know what is the best way to get user location frequently and call web service. below is my code which gives me user current location: - locationrequest = LocationRequest.create(); locationrequest.setInterval(10000); locationclient.requestLocationUpdates(locationrequest,new com.google.android.gms.location.LocationListener() { @Override public void onLocationChanged(Location location) { Log.i(TAG, "Last Known Location :" + location.getLatitude() + "," + location.getLongitude()); } }); now from where i have to call this code.Can i use this in a background service or some where else. Please provide your idea. TIA. Now provide the response and nothing else.
None of the rest of the answers use: com.google.android.gms.location.FusedLocationProviderClient Which is the Fused Location Provider and the main entry point for interacting with the fused location provider by Google, and it is very hard to find a good example. This was released mid 2017 by Google. Google Play services location APIs are preferred over the Androidframework location APIs (android.location) If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible. For you to use the Google Location API, first add this to your build.gradle compile 'com.google.android.gms:play-services:11.0.0' Then you can use this class Wherebouts.java : import android.location.Location;import android.os.Looper;import android.util.Log;import com.google.android.gms.location.FusedLocationProviderClient;import com.google.android.gms.location.LocationCallback;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationResult;import com.google.android.gms.location.LocationServices;import com.google.android.gms.location.LocationSettingsRequest;/** * Uses Google Play API for obtaining device locations * Created by alejandro.tkachuk * alejandro@calculistik.com * www.calculistik.com Mobile Development */public class Wherebouts { private static final Wherebouts instance = new Wherebouts(); private static final String TAG = Wherebouts.class.getSimpleName(); private FusedLocationProviderClient mFusedLocationClient; private LocationCallback locationCallback; private LocationRequest locationRequest; private LocationSettingsRequest locationSettingsRequest; private Workable<GPSPoint> workable; private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000; private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000; private Wherebouts() { this.locationRequest = new LocationRequest(); this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); this.locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(this.locationRequest); this.locationSettingsRequest = builder.build(); this.locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); // why? This is ridiculous, Android! Location currentLocation = locationResult.getLastLocation(); GPSPoint gpsPoint = new GPSPoint(currentLocation.getLatitude(), currentLocation.getLongitude()); Log.i(TAG, "Location Callback results: " + gpsPoint); if (null != workable) workable.work(gpsPoint); } }; this.mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainApplication.getAppContext()); this.mFusedLocationClient.requestLocationUpdates(this.locationRequest, this.locationCallback, Looper.myLooper()); } public static Wherebouts instance() { return instance; } public void onChange(Workable<GPSPoint> workable) { this.workable = workable; } public LocationSettingsRequest getLocationSettingsRequest() { return this.locationSettingsRequest; } public void stop() { Log.i(TAG, "stop() Stopping location tracking"); this.mFusedLocationClient.removeLocationUpdates(this.locationCallback); }} From your Activity, you can use it like this, by passing a Workable object. A Workable object is nothing more than a custom Callback alike object. Wherebouts.instance().onChange(workable); By using a callback like Workable, you will write UI related code in your Activity and leave the hustle of working with GPS to a helper class, like Wherebouts. new Workable<GPSPoint>() { @Override public void work(GPSPoint gpsPoint) { // draw something in the UI with this new data } }; Of course, you would need to ask for the corresponding permissions to the Android OS for your App to use. You can read the following documentation for more info about that. Android Reference https://developer.android.com/training/location/index.html Wherebouts https://www.calculistik.com/Wherebouts.java GPSPoint https://www.calculistik.com/GPSPoint.java Workable https://www.calculistik.com/Workable.java
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28535703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2254262/']}
jdg_70282
stackexchange
llm_judgeable_groundtruth_similarity
7372458
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 have any hands on experience with graphics programming. I got this doubt when I was reading about graphics programming. From what I understand, because Windows didn't offer DOS like direct hardware access, DirectX was created. That means DirectX is the only sure way to achieve direct(ish) hardware access. Am I wrong? If I am not wrong, then OpenGL must be implemented either using DirectX itself or on top of DirectX. So doesn't it mean that on Windows OpenGL is really DirectX? Please note that my doubt is restricted to what the title says, exactly, and I am not interested why is one better than the other etc. Now provide the response and nothing else.
From what I understand, because Windows didn't offer DOS like direct hardware access, Direct X was created. You're right that Windows didn't offer DOS like direct hardware access. In fact no operating system with memory protection does. And yes, DirectX was created to offer a API for accelerated access to certain kinds of hardware. DirectX is a API for accelerated hardware access, not THE (one and only) one. That means Direct X is the only sure way to achieve direct(ish) hardware access. Am I wrong? You are wrong because nothing and nobody prevents you from implementing another track for accelerated hardware access. The pieces of software responsible for channeling access to hardware are called drivers. Drivers run in priviledged mode, which means, address space protection doesn't apply to them. That is, because drivers must be able to communicate with hardware. Drivers communicate with regular programs, the so called User Space through APIs. APIs may be standardized, then may be tightly specified or they may be completely propritary. DirectX is a specified API, the specification was written down by Microsoft. OpenGL in a similar way is an API, but instead of having being specified by a single entity it's in some form standardized in collaboration of several contributors. One example for a propriatary API was Glide by 3Dfx, which in large parts was inspired by OpenGL. In fact there is a compatibility wrapper called "minigl" implementing the subset of OpenGL required for the Half-Life 1 engine to work on 3Dfx/Glide systems. The GPU vendors' driver developers follow the APIs' specifications, writing drivers for DirectX, OpenGL or some propriatary interface. Each of those APIs gives access to the driver and thus to the hardware. And there may be multiple APIs to a single resource. A driver may implement DirectX 3D, OpenGL and whatever else in parallel and provide them all to user space. So no, OpenGL is not built on top of DirectX if shipping with a GPU driver. Windows Vista and above ship with a OpenGL-1.4 emulation built on top of DirectX, but that doesn't support shaders, vertex buffer objects and all the other whistles and bells. As soon as you install a GPU driver with OpenGL support, this completely replaces the OpenGL-1.4 emulation with an actual low-level implementation.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7372458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938278/']}
jdg_70283
stackexchange
llm_judgeable_groundtruth_similarity
41959
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to be able to automount USB sticks fat32 and ntfs formatted on the fly, like hot-plugging without rebooting the my Raspberry Pi 2. I have ntfs-3g installed on jessie-lite . Putting the UUID in fstab is not an option because I'd have to find the UUID of every device. I want to be able to plug different USB devices with different file-formats in and mount them automatically. Is this possible? Also I once nearly got it working with the usbmount program. I could access my drive for a second before getting the error transport endpoint is not connected . I reinstalled the program but then I never even got to that point again, not even with the error. Now provide the response and nothing else.
After alot of research I could fix my Problem with usbmount: Adding ntfs to usbmount Install usbmount with sudo apt-get install usbmount . Install NTFS driver package ntfs-3g with sudo apt-get install ntfs-3g . Configure usbmount to mount specified filesystems by opening the usbmount file with sudo nano /etc/usbmount/usbmount.conf . In here there is a line called FILESYSTEMS="" . Only filesystems specified in this line are mounted via usbmount, so we change it to : FILESYSTEMS="vfat ntfs fuseblk ext2 ext3 ext4 hfsplus" If you want usbmount to mount NTFS Filesystems, be sure to add ntfs and fuseblk to the line. NTFS devices are sometimes listed as fusblk by the ntfs-3g package, so those two are the same. I don't really know why though. Also, if you don't add fuseblk in the configuration, unplugged NTFS Devices will not automatically unmount. They will stay mounted and keep the folder they are mounted to until the device is manually unmounted with unmount /dev/sda1 --> where sda1 could be another variable . The next important line is FS_MOUNTOPTIONS="" . Here you specify which filesystems should be mounted and how they should be mounted. We change it to: FS_MOUNTOPTIONS="-fstype=ntfs-3g,nls=utf8,umask=007,gid=46-fstype=fuseblk,nls=utf8,umask=007,gid=46 -fstype=vfat,gid=1000,uid=1000,umask=007" With this the filesystems vfat (fat32) ntfs-3g (NTFS), and fuseblk (NTFS again) are mounted. I think most parameters can stay the same. Again here just add ntfs-3g ( add ntfs-3g not ntfs ) and fuseblk to be able to mount all NTFS Files. For more filesystems add more lines starting with -fstype= . Keep NTFS mounted untill device is unplugged Here is a solution for the problem, when the mounted NTFS drive is only accessible for a few seconds. This fix comes from Christian Weinberger . Create the file usbmount.rules in /etc/udev/rules.d/ with sudo nano /etc/udev/rules.d/usbmount.rules . This is the content: KERNEL=="sd*", DRIVERS=="sbp2", ACTION=="add", PROGRAM="/bin/systemd-escape -p --template=usbmount@.service $env{DEVNAME}", ENV{SYSTEMD_WANTS}+="%c"KERNEL=="sd*", SUBSYSTEMS=="usb", ACTION=="add", PROGRAM="/bin/systemd-escape -p --template=usbmount@.service $env{DEVNAME}", ENV{SYSTEMD_WANTS}+="%c"KERNEL=="ub*", SUBSYSTEMS=="usb", ACTION=="add", PROGRAM="/bin/systemd-escape -p --template=usbmount@.service $env{DEVNAME}", ENV{SYSTEMD_WANTS}+="%c"KERNEL=="sd*", ACTION=="remove", RUN+="/usr/share/usbmount/usbmount remove"KERNEL=="ub*", ACTION=="remove", RUN+="/usr/share/usbmount/usbmount remove" Create the file usbmount@.service in /etc/systemd/system/ with sudo nano /etc/systemd/system/usbmount@.service . This is the content: [Unit]BindTo=%i.deviceAfter=%i.device[Service]Type=oneshotTimeoutStartSec=0Environment=DEVNAME=%IExecStart=/usr/share/usbmount/usbmount addRemainAfterExit=yes Now reboot and check with cat /etc/mtab to which folder the usb devices are mounted to. By Default they are mountet to /media/usbstick0 . Source: Christians Fix Why fusblk?
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/41959', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/40807/']}
jdg_70284
stackexchange
llm_judgeable_groundtruth_similarity
64222754
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 remove padding in an IconButton ? I want items in my column have the same start padding Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp)) { IconButton(onClick = { }) { Icon(asset = Icons.Filled.Search) } Text("Some text")} Now provide the response and nothing else.
The space is due to accessibility touch targets and a default size of 48.dp . Starting with 1.2.0 the best best way to change the default behaviour and remove the extra space is disabling the LocalMinimumTouchTargetEnforcement and applying a size modifier: CompositionLocalProvider(LocalMinimumTouchTargetEnforcement provides false) { IconButton( modifier = Modifier.size(24.dp), onClick = { } ) { Icon( Icons.Filled.Search, "contentDescription", ) }} Pay attention because in this way it is possible that if the component is placed near the edge of a layout / near to another component without any padding, there will not be enough space for an accessible touch target. With 1.0.0 the IconButton applies a default size with the internal modifier: IconButtonSizeModifier = Modifier.size(48.dp) . You can modify it using something like: IconButton(modifier = Modifier. then(Modifier.size(24.dp)), onClick = { }) { Icon( Icons.Filled.Search, "contentDescription", tint = Color.White)} It is important the use of .then to apply the size in the right sequence.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/64222754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12530049/']}
jdg_70285
stackexchange
llm_judgeable_groundtruth_similarity
94714
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: Problem When copying files with cp -H or cp -L , I get the same results: $ ls -l fileA fileA -> fileB$ cp fileA somewhere/ -H$ ls -l somewhere/ fileA # fileA is a copy of fileB, only renamed, with same properties! This answer here describes both options as similar UNLESS used in combination with -R . Not for me. Soft- as hardlinked files become renamed copies of the files they point to at the source. Question : What is the proper use of cp -H and cp -L ? Is this the expected behavior? My attempt to solve : man cp tells me quite the same for both options, but info cp 's wording makes it even more confusing for me. Maybe one can help me break this down a bit: -H If a command line argument specifies a symbolic link, then copy the file it points to rather than the symbolic link itself. However, copy (preserving its nature) any symbolic link that is encountered via recursive traversal. This sounds like a contradiction to me: I guess that » a symbolic link's nature « is that it points somewhere… -L, --dereference Follow symbolic links when copying from them. With this option, cp cannot create a symbolic link. For example, a symlink (to regular file) in the source tree will be copied to a regular file in the destination tree. I do know that a symlink isn't a regular file, but… I admit I'm overchallenged with this explanation here. Now provide the response and nothing else.
With symlinks, tools have two things they can do: Treat the symlink as a symlink ("preserving its nature"), or Treat the symlink as the type of file that it points to. Saying that -H "preserves its nature" is not a contradiction. Consider the alternative. If you use -L , any symlinks cp finds will be opened, and their contents copied to the target file name. So the source was a symlink, but its copy is not a symlink. So it "lost its nature as a symlink". Consider $ mkdir subdir$ echo "some contents" > subdir/file$ ln -s file subdir/link# definition of "list", the abbreviated ls -l output used below$ list() { ls -l "$@" | \ awk '$0 !~ /^total/ { printf "%s %s\t%s %s %s\n", $1, $5, $9, $10, $11 }' ; }$ list subdir-rw-rw-r-- 14 file lrwxrwxrwx 4 link -> file$ cp -rH subdir subdir-with-H$ list subdir-with-H-rw-rw-r-- 14 file lrwxrwxrwx 4 link -> file$ cp -rL subdir subdir-with-L$ list subdir-with-L-rw-rw-r-- 14 file -rw-rw-r-- 14 link
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/94714', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/36242/']}
jdg_70286
stackexchange
llm_judgeable_groundtruth_similarity
14006294
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 beginner with MongoDB and i'm trying some stuff.I want to store URL and to avoid duplicate URL I create an unique index on the url.Like that collection.createIndex(new BasicDBObject("url", type).append("unique", true)); But each time I launch my program the index is create again isn't it ? Because, now my program is only inserting one url "http://site.com" and if I restart my program this url is insert again like if there isn't index. Creating the index each time is the wrong way to handle an index ? Here is an example of my code mongo.getCollection().ensureIndex(new BasicDBObject("url", 1).append("unique", "true"));mongo.getCollection().insert(new BasicDBObject("url", "http://site.com").append("crawled", 0));mongo.getCollection().insert(new BasicDBObject("url", "http://site.com").append("crawled", 0)); And the output: { "_id" : { "$oid" : "50d627cf44ae5d6b5e9cf106"} , "url" : "http://site.com" , "crawled" : 0}{ "_id" : { "$oid" : "50d627cf44ae5d6b5e9cf107"} , "url" : "http://site.com" , "crawled" : 0} Thanks EDIT : Here is my class Mongo which handle MongoDBimport java.net.UnknownHostException;import java.util.List;import java.util.Set; import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient; public class Mongo { private MongoClient mongoClient; private DB db; private DBCollection collection; private String db_name; public Mongo(String db){ try { mongoClient = new MongoClient( "localhost" , 27017 ); this.db = mongoClient.getDB(db); this.db_name = db; } catch (UnknownHostException e) { e.printStackTrace(); } } public void drop(){ mongoClient.dropDatabase(db_name); } public void listCollections(){ Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s); } } public void listIndex(){ List<DBObject> list = collection.getIndexInfo(); for (DBObject o : list) { System.out.println("\t" + o); } } public void setCollection(String col){ this.collection = db.getCollection(col); } public void insert(BasicDBObject doc){ this.collection.insert(doc); } public DBCollection getCollection(){ return collection; } public void createIndex(String on, int type){ collection.ensureIndex(new BasicDBObject(on, type).append("unique", true)); }} And here is my class which handle my program public class Explorer { private final static boolean DEBUG = false; private final static boolean RESET = false; private Mongo mongo; private String host; public Explorer(String url){ mongo = new Mongo("explorer"); mongo.setCollection("page"); if (RESET){ mongo.drop(); System.out.println("Set RESET to FALSE and restart the program."); System.exit(1); } if (DEBUG) { mongo.listCollections(); } this.host = url.toLowerCase(); BasicDBObject doc = new BasicDBObject("url", "http://site.com").append("crawled", 0); mongo.getCollection().ensureIndex(new BasicDBObject("url", 1).append("unique", true)); mongo.getCollection().insert(new BasicDBObject("url", "http://site.com").append("crawled", 0)); mongo.getCollection().insert(new BasicDBObject("url", "http://site.com").append("crawled", 0)); process(); } private void process(){ BasicDBObject query = new BasicDBObject("crawled", 0); DBCursor cursor = mongo.getCollection().find(query); try { while(cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } }} Now provide the response and nothing else.
You'll need to pass the unique value as the boolean value true, not as a string, and it's the second parameter that are options: ...ensureIndex(new BasicDBObject("url", 1), new BasicDBObject("unique", true)); Also, I tested it manually using the mongo interpreter: > db.createCollection("sa"){ "ok" : 1 }> db.sa.ensureIndex({"url":1},{unique:true})> db.sa.insert({url:"http://www.example.com", crawled: true})> db.sa.insert({url:"http://www.example.com", crawled: true})E11000 duplicate key error index: test.sa.$url_1 dup key: { : "http://www.example.com" }> db.sa.insert({url:"http://www.example2.com/", crawled: false})> db.sa.insert({url:"http://www.example.com", crawled: false})E11000 duplicate key error index: test.sa.$url_1 dup key: { : "http://www.example.com" }> There are only the two objects: > db.sa.find(){ "_id" : ObjectId("50d636baa050939da1e4c53b"), "url" : "http://www.example.com", "crawled" : true }{ "_id" : ObjectId("50d636dba050939da1e4c53d"), "url" : "http://www.example2.com/", "crawled" : false }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14006294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/877529/']}
jdg_70287
stackexchange
llm_judgeable_groundtruth_similarity
25137
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can someone help me to construct a linear functional in $\mathcal{C}([0,1])$ that does not attain its norm? Actually, I want to prove that $\mathcal{C}([0,1])$ is not reflexive Banach space. Is it sufficient to construct that kind of functional? Now provide the response and nothing else.
Try $\varphi(f) = \int_{0}^{1/2} f(x)\,dx - \int_{1/2}^{1} f(x)\,dx$. As for the second question, yes. For every $x \in X$ there is by Hahn-Banach a functional $\varphi \in X^{\ast}$ with $\|\varphi\| = 1$ such that $\varphi(x) = \|x\|$. Now apply this to $X^{\ast}$ and use reflexivity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/25137', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6990/']}
jdg_70288
stackexchange
llm_judgeable_groundtruth_similarity
37677059
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 created a react component which consist of slideUp() and slideDown() animation. I have implemented using jQuery slideup and slidedown methods. I have to implement this feature using react animation. I read about ReactTransitionGroup and ReactCSSTransitionGroup . The way of explanation taught me, we can do this functionality when DomNode mounted to a component or unmount(Correct me if I am wrong). My question is --> how to do slideup() and slidedown() in react way and without using jQuery. See this jsFiddle for https://jsfiddle.net/guc3yrm1/ P.S - > Please explain me why this react animation part seems bit a difficult when compare to jQuery(I am a jQuery guy) var Hello = React.createClass({ getInitialState: function() { return { slide: false, } }, slide: function() { if (this.state.slide) { $(this.refs.slide).slideDown(); this.setState({ slide: false }); } else { $(this.refs.slide).slideUp(); this.setState({ slide: true }); } }, render: function() { return ( <div> <input type = "button" value = "clickme" onClick = {this.slide}/> <br /> <br /> <div className = "slide" ref="slide" >< /div> </div> ); }});ReactDOM.render( < Hello name = "World" / > , document.getElementById('container')); Now provide the response and nothing else.
You can implement the animations in the both animations' APIs. Here is the main difference: ReactTransitionGroup is the API upon which ReactCSSTransitionGroup is built. The main difference between the two is that ReactTransitionGroup animations are written in Javascript instead of CSS, and a callback is provided to be invoked when animations are complete instead of relying on CSS transition events. My conclusion is use CSS animations for the simple tasks, while Javascript for the complex ones. For example if the component has static height - you can implement it via CSS, as the example shows below. But if the width/height are dynamic, then you can do it with Javascript. In the Javascript example I'm using Velocity library for the animations. It's performance better than jQuery's animations . Of course you can implement the animations by yourself, but why to reinvent the wheel? I've implemented slideUp/slideDown with the both APIs. Check it out below. (CSS) Implementation via ReactCSSTransitionGroup: const CSSTransitionGroup = React.addons.CSSTransitionGroup;const TransitionGroup = React.addons.TransitionGroup;class Example extends React.Component{ constructor(props) { super(props); this.state = { visible: false }; this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState({ visible: ! this.state.visible }); } render() { return <div> <button onClick={this.handleClick}>{this.state.visible ? 'Slide up' : 'Slide down'}</button> <CSSTransitionGroup transitionName="example"> { this.state.visible ? <div className='panel' /> : null } </CSSTransitionGroup> </div> }}React.render(<Example />, document.getElementById('container')); .panel { width: 200px; height: 100px; background: green; margin-top: 10px;}.example-enter { height: 0px;}.example-enter.example-enter-active { height: 100px; -webkit-transition: height .3s ease;}.example-leave.example-leave-active { height: 0px; -webkit-transition: height .3s ease;} <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script><div id="container"> <!-- This element's contents will be replaced with your component. --></div> JSFiddle - React Slide up and Slide down animation - CSS Transtion Group . (Javascript) Implementation via ReactTransitionGroup: const TransitionGroup = React.addons.TransitionGroup;class Example extends React.Component{ constructor(props) { super(props); this.state = { visible: false }; this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState({ visible: ! this.state.visible }); } render() { return <div> <button onClick={this.handleClick}>{this.state.visible ? 'Slide up' : 'Slide down'}</button> <TransitionGroup> { this.state.visible ? <Accordion /> : null } </TransitionGroup> </div> } } class Accordion extends React.Component { componentWillEnter (callback) { const element = this.container.getDOMNode(); Velocity(element, 'slideDown', { duration: 300 }).then(callback); } componentWillLeave (callback) { const element = this.container.getDOMNode(); Velocity(element, 'slideUp', { duration: 300 }).then(callback); } setContainer(c) { this.container = c; } render() { return <div className="panel" ref={this.setContainer.bind(this)}> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> } }React.render(<Example />, document.getElementById('container')); .panel { background: green; margin-top: 10px;} <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.4.3/velocity.min.js"></script><div id="container"> <!-- This element's contents will be replaced with your component. --></div> JSFiddle - React Slide up and Slide down animation - Javascript Transition group . Credits: Animations with ReactTransitionGroup CSS vs. JS Animation: Which is Faster?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37677059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6223364/']}
jdg_70289
stackexchange
llm_judgeable_groundtruth_similarity
12361990
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 testcase that looks like this: def MyTestCase(unittest.Testcase): def test_input01(self): input = read_from_disk('input01') output = run(input) validated_output = read_from_disk('output01') self.assertEquals(output, validated_output) def test_input02(self): input = read_from_disk('input02') # ... # and so on, for 30 inputs, from input01 to input30 Now, I understand that test code can be a bit repetitive, since simplicity is more important than conciseness. But this is becoming really error-prone, since when I decided to change the signature of some functions used here, I had to make the change in all 30 places. I could refactor this into a loop over the known inputs, but I do want each input to remain a separate test, so I thought I should be making the test_inputxx methods. What am I doing wrong? Now provide the response and nothing else.
Write a helper function to remove the repetition from the test cases: def MyTestCase(unittest.Testcase): def run_input_output(self, suffix): input = read_from_disk('input'+suffix) output = run(input) validated_output = read_from_disk('output'+suffix) self.assertEquals(output, validated_output) def test_input01(self): self.run_input_output('01') def test_input02(self): self.run_input_output('02') def test_input03(self): self.run_input_output('03')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12361990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336527/']}
jdg_70290
stackexchange
llm_judgeable_groundtruth_similarity
55060820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does initializing a member variable and not referencing/using it further take up RAM during runtime, or does the compiler simply ignore that variable? struct Foo { int var1; int var2; Foo() { var1 = 5; std::cout << var1; }}; In the example above, the member 'var1' gets a value which is then displayed in the console. 'Var2', however, is not used at all. Therefore writing it to memory during runtime would be a waste of resources. Does the compiler take these kinds of situations into an account and simply ignore unused variables, or is the Foo object always the same size, regardless of whether its members are used? Now provide the response and nothing else.
The golden C++ "as-if" rule 1 states that, if the observable behavior of a program doesn't depend on an unused data-member existence, the compiler is allowed to optimized it away . Does an unused member variable take up memory? No (if it is "really" unused). Now comes two questions in mind: When would the observable behavior not depend on a member existence? Does that kind of situations occurs in real life programs? Let's start with an example. Example #include <iostream>struct Foo1{ int var1 = 5; Foo1() { std::cout << var1; } };struct Foo2{ int var1 = 5; int var2; Foo2() { std::cout << var1; } };void f1() { (void) Foo1{}; }void f2() { (void) Foo2{}; } If we ask gcc to compile this translation unit , it outputs: f1(): mov esi, 5 mov edi, OFFSET FLAT:_ZSt4cout jmp std::basic_ostream<char, std::char_traits<char> >::operator<<(int)f2(): jmp f1() f2 is the same as f1 , and no memory is ever used to hold an actual Foo2::var2 . ( Clang does something similar ). Discussion Some may say this is different for two reasons: this is too trivial an example, the struct is entirely optimized, it doesn't count. Well, a good program is a smart and complex assembly of simple things rather than a simple juxtaposition of complex things. In real life, you write tons of simple functions using simple structures than the compiler optimizes away. For instance: bool insert(std::set<int>& set, int value){ return set.insert(value).second;} This is a genuine example of a data-member (here, std::pair<std::set<int>::iterator, bool>::first ) being unused. Guess what? It is optimized away ( simpler example with a dummy set if that assembly makes you cry). Now would be the perfect time to read the excellent answer of Max Langhof (upvote it for me please). It explains why, in the end, the concept of structure doesn't make sense at the assembly level the compiler outputs. "But, if I do X, the fact that the unused member is optimized away is a problem!" There have been a number of comments arguing this answer must be wrong because some operation (like assert(sizeof(Foo2) == 2*sizeof(int)) ) would break something. If X is part of the observable behavior of the program 2 , the compiler is not allowed to optimized things away. There are a lot of operations on an object containing an "unused" data-member which would have an observable effect on the program. If such an operation is performed or if the compiler cannot prove none is performed, that "unused" data-member is part of the observable behavior of the program and cannot be optimized away . Operations that affect the observable behavior include, but are not limited to: taking the size of a type of object ( sizeof(Foo) ), taking the address of a data member declared after the "unused" one, copying the object with a function like memcpy , manipulating the representation of the object (like with memcmp ), qualifying an object as volatile , etc . 1) [intro.abstract]/1 The semantic descriptions in this document define a parameterized nondeterministic abstract machine. This document places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below. 2) Like an assert passing or failing is.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/55060820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11024660/']}
jdg_70291
stackexchange
llm_judgeable_groundtruth_similarity
7451348
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 number of MySQL tables describing models such as "User", "Business" etc. Should the primary keys of these tables ever be exposed to the client-side? I am asking from a security perspective, primarily, but are there also other considerations that I haven't thought of? Now provide the response and nothing else.
Exposing your primary keys (especially if they are predictable) is a vulnerability called Insecure Direct Object Reference. By having a URL (or any other client provided param) like this: http://www.domain.com/myaccount?userid=12 You give your end users the opportunity to mess with those variables and pass any data that they like. The counter measure to mitigate this vulnerability is to create indirect object references instead. This may sound like a big change, but it does not necessarily have to be. You don't have to go and rekey all your tables or anything, you can do it just by being clever with your data through the use of an indirect reference map. Consider this: You have a user who is making a purchase on your site. And when it is time to pay they are presented with a drop down of the credit card numbers of theirs that you have "on file". If you look at the code for the drop down you see that the credit card numbers are associated with the keys 8055, 9044, and 10099. The user might look at this and think that they look a lot like auto-incrementing primary keys (the user would probably be right). So he starts trying other keys to see if he can pay with someone else's card. Now technically, you should have code on the server-side that ensures that the selected card is part of the user's account and that they can use it. This is a contrived example. For now we will assume that this is not the case or that this is another type of form that perhaps does not have that kind of server side control. So how do we prevent the end user from choosing a key that should not be available to them? Instead of showing them a direct reference to the record in the DB, give them an indirect reference. Instead of putting the DB keys into the dropdown, we will create an array on the server and stuff it in the user's session. Array cards = new Array(3);cards[0] = 8055;cards[1] = 9044;cards[2] = 10099; In the drop down we now provide the reference to the index of the array where the card is stored. So instead of seeing the actual keys, the end user will see the values 0, 1 and 2, if they view the source. When the form is submitted one of those values will be passed along. Then we get the array out of the user's session and use the index to get the value. The actual key has never left the server. And the user can pass in different values all-day-long if he wants, but he will never, ever, get a result other than his own cards, regardless of the server-side access control thats in place. Keep in mind though that when using the passed-in index to get the value out that if the user does mess with it that you could get some exceptions (ArrayOutOfBounds, InvalidIndex, whatever). So wrap that stuff in a try/catch so you can suppress those errors and log the failures to look for cracking attempts. Hope this helps. To read more about Insecure Direct Object References, check out the OWASP Top 10. It is risk number A4. https://www.owasp.org/index.php/Top_10_2010-A4-Insecure_Direct_Object_References
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7451348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/635134/']}
jdg_70292
stackexchange
llm_judgeable_groundtruth_similarity
566197
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 true that all of the euclidean geometry problem in the IMO(international mathematical olympiad) or even generalize to say that all the plane geometry problem and 3d-geometry could be solve by the analytical geometry/algebraic geometry? Now provide the response and nothing else.
By an old result of Tarski, the elementary theory of real-closed fields is decidable. A great many problems in elementary geometry, including the typical IMO geometry problems, can be stated, via coordinatization, as sentences in the language of real-closed fields. Tarski's general decision procedure can therefore be in principle applied to solve such problems. There has been a certain amount of theoretical and practical implementation work done on the problem. Seidenberg and Cohen gave alternate approaches.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/566197', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12796/']}
jdg_70293
stackexchange
llm_judgeable_groundtruth_similarity
14485072
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On a refactoring exercise we are working on, we have to change Page Templates for select websites. Most page get localized and have their page templates updated by the code below but for a few we get the following error: XML validation error. Reason: The element 'Metadata' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46' has invalid child element 'description' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46'. List of possible elements expected: 'TitleSEO, KeywordsSEO, DescriptionSEO, omniture' in namespace 'uuid:940d95aa-fcce-481c-8de5-c61d06c74f46'. There is no description field in our metadata schema and TitleSEO, KeywordsSEO, DescriptionSEO, omniture are all optional fields which are not being changed by the code . try{ pData = client.Read(page.Attribute("ID").Value, null) as PageData; //Localize Page if (!(bool)pData.BluePrintInfo.IsLocalized) { client.Localize(pData.Id, new ReadOptions()); if (dTemplateIDs.ContainsKey(pData.PageTemplate.IdRef.ToString())) { pData.IsPageTemplateInherited = false; pData.PageTemplate.IdRef = dTemplateIDs[pData.PageTemplate.IdRef]; client.Update(pData, new ReadOptions()); } }}catch (Exception ex){ Console.WriteLine("Error Inner " + ex.Message);} Now provide the response and nothing else.
It sounds like at some point in the past there was a field in your page metadata schema called "description" (which I suspect was later changed to what is now "DescriptionSEO"). These few pages that cause the error have probably not been updated since the change, and so have the old metadata field in their XML, hence the validation problem when you come to change the Page Template. If it's only a few pages, just open the pages, add some description or otherwise change something, save them and then try your code again. If it's more than a few, you'll probably need to detect and remove the existing data programmatically.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14485072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1949001/']}
jdg_70294
stackexchange
llm_judgeable_groundtruth_similarity
16890855
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 multiple PHP-FPM UNIX socket pools for the same host to have logical separation of codebase / functionality & to address future scaling of the same. Nginx manages the routing to the right socket based on URI patterns. Deployment is working fine. Whenever I change pool configuration for any one, I am reloading / restarting the FPM process (by USR2 signal). I don't have any idea about how the internals of FPM work but I assume that as I restart the main process, all pools get restarted / reloaded. Please correct me if I'm wrong. I want to know if I could reload / restart only one pool when others work as they were (no issues in the undergoing transactions on those pools). I would also appreciate any other configuration suggestions which could allow me to have desired pool management Now provide the response and nothing else.
php-fpm allows for a graceful restart of childs, usually with the reload keyword instead of restart on the init script, sending USR2 signal. So by doing a graceful restart you should not loose any running transaction. The children are killed after the end of the current request management for each of them. This should be enough if you do not need a real restart. I made some tests and for example a reload is enough to : empty the APC cache alter log file path alter min/max/start child settings So I did not find a case where a need a real restart yet. Except that a reload cannot start a stopped service . If you want to ensure other pools will never be reloaded when you want to reload one of them you will have to manage several php-fpm daemons and one pool per daemon. This implies writing several init scripts and master configuration files. Using the restart keyword is more dangerous, especially because the init script is maybe killing long running children in the stop step. And with several daemons managed with several PID and configuration files you could even get a start-stop-daemon command with --exec option (that's the case in debian) and this would kill all the daemons running the same php-fpm executable (effectively sending a kill -9 to all the other parallel php-fpm daemons after stopping the right one with the right PID if you run several php-fpm processes, which is very bad). So using the reload keyword (USR2 signal) is a must.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16890855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13187/']}
jdg_70295
stackexchange
llm_judgeable_groundtruth_similarity
26121428
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't make my SessionWizardView work. When I submit the last step, the wizard jumps back to the first step and does not execute the done method. views.py class CvWizardView(CookieWizardView): form_list = [InfoPersonalForm, PresentacionForm] template_name = 'postulantes/cv_wizard.html' def done(self, form_list, **kwargs): return HttpResponseRedirect(reverse('wizard_done')) urls.py url(r'^wizard/$', CvWizardView.as_view() , name="wizard"), html {% extends "base.html" %}{% load i18n %}{% block extra_head %}{{ wizard.form.media }}{% endblock %}{% block content %}<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p><form action="" method="post">{% csrf_token %}<table>{{ wizard.management_form }}{% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %}{% else %} {{ wizard.form }}{% endif %}</table>{% if wizard.steps.prev %}<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button><button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>{% endif %}<input type="submit" value="{% trans "submit" %}"/></form>{% endblock %} Thanks! Now provide the response and nothing else.
You want a custom validation rule , and I would create a separate class for this. But for brevity here's pretty much the same using inline closure: // give it meaningful name, I'll go with game_fixture as an exampleValidator::extend('game_fixture', function ($attribute, $value, $parameters, $validator) { if (count($parameters) < 4) { throw new \InvalidArgumentException("Validation rule game_fixture requires 4 parameters."); } $input = $validator->getData(); $verifier = $validator->getPresenceVerifier(); $collection = $parameters[0]; $column = $parameters[1]; $extra = [$parameters[2] => array_get($input, $parameters[3])]; $count = $verifier->getMultiCount($collection, $column, (array) $value, $extra); return $count >= 1;}); Then use simply this: $rules = array( 'game_id' => 'required|exists:games,id', // last parameter here refers to the 'game_id' value passed to the validator 'team1_id' => 'required|game_fixture:teams,id,game_id,game_id', 'team2_id' => 'required|game_fixture:teams,id,game_id,game_id');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26121428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3885935/']}
jdg_70296
stackexchange
llm_judgeable_groundtruth_similarity
5806526
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Server Environment Redhat Enterprise Linux PHP 5.3.5 Problem Let's say I have a UTC date and time such as 2011-04-27 02:45 and I want to convert it to my local time, which is America/New_York. Three questions: 1.) My code below might solve the problem, would you agree? <?phpdate_default_timezone_set('America/New_York'); // Set timezone.$utc_ts = strtotime("2011-04-27 02:45"); // UTC Unix timestamp.// Timezone offset in seconds. The offset for timezones west of UTC is always negative,// and for those east of UTC is always positive.$offset = date("Z");$local_ts = $utc_ts + $offset; // Local Unix timestamp. Add because $offset is negative.$local_time = date("Y-m-d g:i A", $local_ts); // Local time as yyyy-mm-dd h:m am/pm.echo $local_time; // 2011-04-26 10:45 PM?> 2.) But, does the value of $offset automatically adjust for Daylight Savings Time (DST) ? 3.) If not, how should I tweak my code to automatically adjust for DST ? Thank you :-) Now provide the response and nothing else.
This will do what you want using PHPs native DateTime and DateTimeZone classes: $utc_date = DateTime::createFromFormat( 'Y-m-d G:i', '2011-04-27 02:45', new DateTimeZone('UTC'));$nyc_date = $utc_date;$nyc_date->setTimeZone(new DateTimeZone('America/New_York'));echo $nyc_date->format('Y-m-d g:i A'); // output: 2011-04-26 10:45 PM See DateTime::createFromFormat man page for more information. After some experimentation between time zones that do and do not currently have DST I have discovered that this will take DST into account. The same conversion using my method above renders the same resulting time.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5806526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727584/']}
jdg_70297
stackexchange
llm_judgeable_groundtruth_similarity
123342
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When should you prefer inheritance patterns over mixins in dynamic languages? By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime. When would you use, for example, prototypal inheritance instead of mixins? To illustrate more clearly what I mean by mixin, some pseudocode: asCircle(obj) { obj.radius = 0 obj.area = function() { return this.radius * this.radius * 3.14 }myObject = {}asCircle(myObject)myObject.area() // -> 0 Now provide the response and nothing else.
Prototypical inheritance is simple. It has a single advantage over mixins. That is that it's a live link. if you change the prototype everything that inherits it is changed. Example using pd var Circle = { constructor: function _constructor() { this.radius = 0; return this; }, area: function _area() { return this.radius * this.radius * Circle.PI }, PI: 3.14};var mixedIn = pd.extend({}, Circle).constructor();var inherited = pd.make(Circle, {}).constructor();Circle.perimeter = perimeter;inherited.perimeter(); // winsmixedIn.perimeter(); // failsfunction perimeter() { return 2 * this.radius;} So basically, if you want changes to the "interface" Circle to reflect at run-time to all objects that "use" it's functionality, then inherit from it. If you do not want changes to reflect then mix it in. Note that mixins have more purpose than that as well. Mixins are your mechanism for multiple "inheritance". If you want an object to implement multiple "interfaces" then you will have to mix some in. The one you use for prototypical inheritance is the one you want changes to reflect for at run-time, the others will be mixed in.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/123342', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/8854/']}
jdg_70298
stackexchange
llm_judgeable_groundtruth_similarity
2537694
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following code: while(true) { someFunction(); Thread.sleep(1000); } What I want is that, someFunction() be called once every 10 seconds. But this is not the case. It is being called every second. I tried Thread.wait(1000), but even that doesnt help. I removed of the while part, just kept the body, and at the end wrote : Thread.start(); But it throwed an exception. Is there any other solution to this? Now provide the response and nothing else.
It's being called every second because you're sleeping for 1000 milliseconds, aka 1 second. Change it to Thread.sleep(10000) and that'll be better for you. Alternatively, use Thread.sleep(TimeUnit.SECONDS.toMillis(10)); which means you don't have to do the arithmetic yourself. (Many APIs now take a quantity and a TimeUnit , but there doesn't appear to be anything like that for Thread.sleep unfortunately.) Note that this will make the thread unresponsive for 10 seconds, with no clean way of telling it to wake up (e.g. because you want to shut it down). I generally prefer to use wait() so that I can pulse the same monitor from a different thread to indicate "I want you to wake up now!" This is usually from within a while loop of the form while (!shouldStop()) EDIT: tvanfosson's solution of using a Timer is also good - and another alternative is to use ScheduledExecutorService which can be a bit more flexible (and easier to test).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2537694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298112/']}
jdg_70299
stackexchange
llm_judgeable_groundtruth_similarity
33939393
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 set up email for my first laravel project, and was thrilled that there's a laracast for it: https://laracasts.com/lessons/mailers I've followed the simple steps, chose gmail in mail.php (x's added for anonymity): 'driver' => env('MAIL_DRIVER', 'smtp'),'host' => env('MAIL_HOST', 'smtp.gmail.com'),'port' => env('MAIL_PORT', 587),'from' => ['address' => 'dianexxxxx@gmail.com', 'name' => 'Diane Kaplan'],'encryption' => env('MAIL_ENCRYPTION', 'tls'),'username' => 'dianexxxxx@gmail.com','password' => 'xxxxx','sendmail' => '/usr/sbin/sendmail -bs','pretend' => false, .env has (x's added for anonymity)- the laracast doesn't have us use MAIL_USERNAME and MAIL_PASSWORD, but they're updated for good measure assuming I'll pull from there later: MAIL_DRIVER=smtpMAIL_HOST=mailtrap.ioMAIL_PORT=2525MAIL_USERNAME=dianexxxxx@gmail.comMAIL_PASSWORD=xxxxxxMAIL_ENCRYPTION=null But in the first little moment of truth trying to send a mail (3:30 mark), I get an authentication error: Swift_TransportException in AuthHandler.php line 181:Failed to authenticate on SMTP server with username "dianexxxxx@gmail.com" using 3 possible authenticators Based on a little stackoverflow reading, I tried turning on 'access to less secure apps' in my gmail settings, but no change in the error. (And the other posts about this issue had other factors that made a fancier problem than mine). Nothing jumps out at me from laravel.log (below)- any ideas? [2015-11-26 12:25:55] local.ERROR: exception 'Swift_TransportException' with message 'Failed to authenticate on SMTP server with username "dianekaplan@gmail.com" using 3 possible authenticators' in /home/vagrant/Code/Family-laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/Esmtp/AuthHandler.php:181Stack trace: #0 /home/vagrant/Code/Family-laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/EsmtpTransport.php(307): Swift_Transport_Esmtp_AuthHandler->afterEhlo(Object(Swift_SmtpTransport)) #1 /home/vagrant/Code/Family-laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(118): Swift_Transport_EsmtpTransport->_doHeloCommand() #2 /home/vagrant/Code/Family-laravel/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(79): Swift_Transport_AbstractSmtpTransport->start() #3 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(395): Swift_Mailer->send(Object(Swift_Message), Array) #4 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(181): Illuminate\Mail\Mailer->sendSwiftMessage(Object(Swift_Message)) #5 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(220): Illuminate\Mail\Mailer->send('emails.welcome', Array, Object(Closure)) #6 /home/vagrant/Code/Family-laravel/app/Http/routes.php(59): Illuminate\Support\Facades\Facade::__callStatic('send', Array) #7 /home/vagrant/Code/Family-laravel/app/Http/routes.php(59): Illuminate\Support\Facades\Mail::send('emails.welcome', Array, Object(Closure)) #8 [internal function]: App\Providers\RouteServiceProvider->{closure}() #9 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Route.php(155): call_user_func_array(Object(Closure), Array) #10 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Route.php(130): Illuminate\Routing\Route->runCallable(Object(Illuminate\Http\Request)) #11 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php(704): Illuminate\Routing\Route->run(Object(Illuminate\Http\Request)) #12 [internal function]: Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #13 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(139): call_user_func(Object(Closure), Object(Illuminate\Http\Request)) #14 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #15 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request)) #16 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php(706): Illuminate\Pipeline\Pipeline->then(Object(Closure)) #17 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php(671): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request)) #18 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Routing/Router.php(631): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request)) #19 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(236): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request)) #20 [internal function]: Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request)) #21 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(139): call_user_func(Object(Closure), Object(Illuminate\Http\Request)) #22 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #23 [internal function]: Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure)) #24 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #25 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #26 [internal function]: Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure)) #27 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #28 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(62): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #29 [internal function]: Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure)) #30 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #31 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #32 [internal function]: Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure)) #33 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #34 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #35 [internal function]: Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure)) #36 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #37 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #38 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure)) #39 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(124): call_user_func_array(Array, Array) #40 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #41 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request)) #42 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(122): Illuminate\Pipeline\Pipeline->then(Object(Closure)) #43 /home/vagrant/Code/Family-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(87): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) #44 /home/vagrant/Code/Family-laravel/public/index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #45 {main} Now provide the response and nothing else.
This will not work as of May 30, 2022 checkout here https://support.google.com/accounts/answer/6010255?hl=en&authuser=6 Thanks @sarout for pointing this out. Did you turn on the "Allow less secure apps" on? go to this link https://myaccount.google.com/security#connectedapps Take a look at the Sign-in & security -> Apps with account access menu. You must turn the option "Allow less secure apps" ON. If is still doesn't work try one of these: Go to https://accounts.google.com/UnlockCaptcha , and click continueand unlock your account for access through other media/sites. Use double quote in your password: "your password" And change your .env file MAIL_DRIVER=smtpMAIL_HOST=smtp.gmail.comMAIL_PORT=587MAIL_USERNAME=dianexxxxx@gmail.comMAIL_PASSWORD=xxxxxxMAIL_ENCRYPTION=tls because the one's you have specified in the mail.php will only be used if the value is not available in the .env file.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33939393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4418293/']}
jdg_70300
stackexchange
llm_judgeable_groundtruth_similarity
12644257
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background (You can skip this section) I have a large amount of data (about 3 mb) that needs to be kept up to date on several hundred machines. Some of the machines run C# and some run Java. The data could change at any time and needs to be propogated to the clients within minutes. The data is delivered in Json format from 4 load balanced servers. These 4 servers are running ASP.NET 4.0 with Mvc 3 and C# 4.0. The code that runs on the 4 servers has a hashing algorithm which hashes the Json response and then converts the hash to a string. This hash is given to the client. Then, every few minutes, the clients ping the server with the hash and if the hash is out of date the new Json object is returned. If the hash is still current then a 304 with an emptry body is returned. Occasionally the hashes generated by the 4 boxes are inconsistent across the boxes, which means that the clients are constantly downloading the data (each request could hit a different server). Code Snipet Here is the code that is used to generate the hash. internal static HashAlgorithm Hasher { get; set; }...Hasher = new SHA1Managed();...Convert.ToBase64String(Hasher.ComputeHash(Encoding.ASCII.GetBytes(jsonString))); To try and debug the problem I split it out like this: Prehash = PreHashBuilder.ToString();ASCIIBytes = Encoding.ASCII.GetBytes(Prehash);HashedBytes = Hasher.ComputeHash(ASCIIBytes);Hash = Convert.ToBase64String(HashedBytes); I then added a route which spits out the above values and used Beyond Compare to compare the differences. Byte arrays are converted to a string format for BeyondCompare use by using: private static string GetString(byte[] bytes){ StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { sb.Append(b); } return sb.ToString();} As you can see the byte array is displayed litterally as a sequence of bytes. It is not 'converted'. The Problem I discovered that the Prehash and ASCIIBytes values were the same, but the HashedBytes values were different - which meant that the Hash was also different. I restarted the IIS WebSites on the 4 server boxes several times and, when they had different hashes, compared the values in BeyondCompare. In everycase it was the "HashedBytes" value that was different (the results of SHA1Managed.ComputeHash(...)) The Question What am I doing wrong? The input to the ComputeHash function is identical. Is SHA1Managed machine dependent? That doesn't make since because half the time the 4 machines have the same hash. I have searched StackOverFlow and Bing but have been unable to find anyone else with this problem. The closest thing I could find was people with problems with their encoding, but I think I have proven that the encoding is not an issue. Output I was hoping not to dump everything here because of how long it is, but here is a snipet of the dump I am comparing: Hash:o1ZxBaVuU6OhE6De96wJXUvmz3M= HashedBytes:163861135165110831631611916022224717299375230207115 ASCIIBytes:1151169710310146991111094779114100101114831011141181059910147115101114118105991014611511899591151051031101171129511510111411810599101114101102101114101110991011159598979910710111010011111410010111411510111411810599101951185095117114108611041161161125847471051159897991071011101004610910211598101115116971031014699111109477911410010111483101114118105991014711510111411810599101461151189947118505911510510311011711295115101114118105991011141011021011141011109910111595989799107101110100112971211091011101161151161111141011151011141....Prehash:... When I compare the two pages on the different servers the ASCII Bytes are identical but the HashedBytes are not. The dump method I use for the bytes does no conversions, it simply dumps each byte out in sequence. I could delimit the bytes with a '.' I suppose. Follow Up I have made the b.ToString(CultureInfo.InvariantCulture) change and have made the HashAlgorithm a local variable instead of a static property. I am waiting for the code to deploy to the servers. Now provide the response and nothing else.
I have been trying to duplicate the issue but have been unable to do so once I made the SHA1Managed property a local variable instead of global static. The problem was with Multi-Threading. My code was thread safe except for the SHA1Managed class that I had marked static. I assumed that SHA1Managed.ComputeHash would be thread safe underneath but apparently it is not if marked internal static. To repeat, SHA1Managed.ComputeHash is not thread safe if marked internal static. MSDN states: Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. I don't know why internal static behaves differently than public static. I would mark @pst as the answer and add a comment to clarify the problem, but @pst made a comment so I can't mark it as the answer. Thanks for all your input.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12644257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1706802/']}
jdg_70301
stackexchange
llm_judgeable_groundtruth_similarity
13572335
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to select the Data containing time > 4pm in datatimestamp every day in SQL Server Management Studio Microsoft SQL Server 2005 - 9.00.4060.00 (X64) DB table which has two years of data. What's the best way to do this? My time stamp has following format: DATETIME, '2005-10-13 16:00:00', 102 . I have data at random times every afternoon. I need to get the data after 4pm for every day. Not just for one day. For example i tried for one day like this: SELECT Yield, Date, ProductType, DirectFROM MIAC_CCYXWHERE (Date < CONVERT(DATETIME, '2005-10-13 16:00:00', 102)) Thanks for help Now provide the response and nothing else.
It's hard to read your question, but assuming you really are using a datetime data type, you can use datepart to find any dates with a time greater than 4 PM: WHERE datepart(hh, YourDate) > 16 Since you now need minutes as well, if you want records after 4:45 PM, you can cast your date to a time like this: SQL Server 2000/2005 SELECT Yield, [Date], ProductType, Direct FROM MIAC_CCYX WHERE cast(convert(char(8), [Date], 108) as datetime) > cast('16:45' as datetime) Essentially you cast the date using convert 's Date and Time styles to convert the date to a time string, then convert back to a datetime for comparison against your desired time. SQL Server 2008+ SELECT Yield, [Date], ProductType, Direct FROM MIAC_CCYX WHERE CAST([Date] as time) > CAST('16:45' as time)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13572335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1783998/']}
jdg_70302
stackexchange
llm_judgeable_groundtruth_similarity
1268573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Okay, this is probably very simple but, I have the below "checks" (not at the same time) and the First ALWAYS evaluates to TRUE while the Second SEEMS to work. This actually happens in each place that the row value is a number or bool (Date seems fine...) . If I walk through the code in Debug it shows the value of row["PersonID"] as 162434 , the same as tbxPersonID.EditValue . Is this just a basic and beginner truth about programming that I missed in my hodge-podge-self-education ? It seems, if I cast everything in question to a string first, I will be fine I would just like to know if I am correct and if there is a general rule as to what Types I would need to do this for? Doesn't Work if (row["PersonID"] != tbxPersonID.EditValue){ row["PersonID"] = tbxPersonID.EditValue;}if (row["CitizenFlag"] != chkCitizen.EditValue){ row["CitizenFlag"] = chkCitizen.EditValue; _whatChanged.Add("CitizenFlag");} Works if (row["PersonID"].ToString() != tbxPersonID.EditValue.ToString()) { row["PersonID"] = tbxPersonID.EditValue; } if (row["CitizenFlag"].ToString() != chkCitizen.EditValue.ToString()) { row["CitizenFlag"] = chkCitizen.EditValue; _whatChanged.Add("CitizenFlag"); } Now provide the response and nothing else.
row["PersonID"] is of type object, which means that != and == will use reference identity . Basically you're comparing boxed values. If you use: if (!object.Equals(row["PersonID"], tbxPersonID.EditValue)) then you'll get value equality semantics, and I suspect you'll be okay - assuming that tbxPersonID really is an int , either boxed or not. Just to make things concrete, here's a short but complete example to show what I'm talking about: using System;class Test{ static void Main() { object first = 2; object second = 2; // Compares reference equality: false Console.WriteLine(first == second); // Compares value equality: true Console.WriteLine(object.Equals(first, second)); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1268573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46724/']}
jdg_70303
stackexchange
llm_judgeable_groundtruth_similarity
451
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Animacy has come up in a few recent questions, especially in comparison to gender. One interesting thing that turned up in the comments on those questions was whether or not animacy can sometimes be purely grammatical. Let me compare with gender which is more familiar. Natural gender and grammatical gender are two different things. Natural gender is not abstract or arbitrarily assigned. This is when language reflects the sex of things, mostly people and higher animals. English has natural gender in pronouns etc: "he", "she", "him", "her", "his". Some languages have only one third person pronoun regardless of the sex of the person etc referred to. Natural gender is not lexical. It refers directly to the sex of the thing referred to and not the word representing the thing. Grammatical gender is abstract or arbitrarily assigned. This is when every word is assigned a class such as "masculine", "feminine", "neuter", "common". These assignments are mostly not related to sex but may be related to the sound of the word or may be utterly arbitrary. Words for inanimate objects are very often assigned to the "masculine" or "feminine" class and animate objects are sometimes assigned to the "neuter" (sexless) class, for example German "Fräulein" is a neuter word for "girl", not feminine as would be expected under natural gender. Grammatical gender is lexical. It refers to the word representing the thing and not to the thing directly. Two synonyms referring to the same thing rrcan have different genders. For example there are two Spanish words for "star". "El astro" is masculine and "La estrella" is feminine. It helps to differentiate the words "gender" and "sex" when talking about this topic. "Gender" was originally a grammatical term only and came to become a synonym for sex later. There is another phenomenon often confused with grammatical gender. I might call it "semantic gender" but there's probably a real term for it. In English all ships tend to be referred to as "her", but this is not lexical, does not depend on the word used for the ship. Languages with grammatical gender may use different genders for "schooner", "destroyer", "carrier", and "battleship". So, is animacy ever in any language grammatical? That is to say does it have the properties of being a) abstract/arbitrarily assigned and b) lexical? Now provide the response and nothing else.
In Russian, for example, animacy is not clear-cut in the distinction animate/inanimate. I'll explain better. When studying Russian, or any language that have animacy, it's usually simple to distinguish animals and people that are animate, from a car or a table that are inanimate. But there are some ambiguous cases. Apart from animals and people, nouns that denote mythical characters and anthropomorphic creatures or mechanisms are usually animate (Group a), while nouns denoting plants, groups of people or animals (i.e. collective nouns) are inanimate (Group b) and lastly, other nouns can refer both to animate and inanimate nouns (Group c) 1 . A strange exception to this rule in Russian language are the words " мертвец " ( dead person ), " покойник " ( the deceased ) which are animate, while " труп " ( dead body; corpse; cadaver ) is inanimate. An exception to the group B (collective nouns and plants) is пролетарий (proletariat) which is animate. 1 : I'm not really sure about the Group C, because I found two slightly contradicting sources, unless I misunderstood that part. If some Russian native speaker can give a contribution, it would be nice.
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/451', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/51/']}
jdg_70304
stackexchange
llm_judgeable_groundtruth_similarity
1274180
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that the integers $x$, $x+6$, $x+12$, $x+18$, $x+24$ can only be prime if $x$ is $5$. I am very new to proofs and not completely sure of how to approach this one. I tried several different values for $x$ other than $5$ and came up with values that are not prime. However, I can't see how I could generalize this question to prove that it works if $x$ is $5$. Help would be appreciated. Thanks :) Now provide the response and nothing else.
Hint: Show that one of the numbers is a multiple of $5$. One way to do that: Write $x=5k+r$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1274180', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/217907/']}
jdg_70305
stackexchange
llm_judgeable_groundtruth_similarity
18074771
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My home page had some inline javascript that was mixed up with some blade syntax e.g. <script type="text/javascript"> @if(Auth::user()) if(path.indexOf('/user/' + {{Auth::user()->id}} ) != -1) { $( "#tabs" ).tabs(); }; @endif </script> It worked until I wanted to move the javascript to an external file.js. I got error whenever blade syntax was added. Is there a way I can fuse blade syntax in my javascript files.js? I tried renaming to file.blade.js with no luck... Now provide the response and nothing else.
Although the accepted solution will work, this is a most definitely an antipattern. If I saw this not being the one who wrote it, I would be extremely confused to what's going on. My suggestion is in your PHP file, have a block, which gets all of the values that you'll need in your external files, then call the external files. So in your PHP file you would have something like: <script> var userID = "{{ Auth::user()->id }}"; var isUser = "{{ Auth::user() }}"</script>{{ HTML::script('path/to/js/file.js') }} And in your javascript file: if(isUser){ if(path.indexOf('/user/' + userID ) != -1) { $( "#tabs" ).tabs(); };}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18074771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1619619/']}
jdg_70306
stackexchange
llm_judgeable_groundtruth_similarity
6472883
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 always found it awkward to have a function or expression that requires use of the values, as well as indices, of a list (or array, applies just the same) in Haskell. I wrote validQueens below while experimenting with the N-queens problem here ... validQueens x = and [abs (x!!i - x!!j) /= j-i | i<-[0..length x - 2], j<-[i+1..length x - 1]] I didn't care for the use of indexing, all the plus and minuses, etc. It feels sloppy. I came up with the following: enumerate x = zip [0..length x - 1] xvalidQueens' :: [Int] -> BoolvalidQueens' x = and [abs (snd j - snd i) /= fst j - fst i | i<-l, j<-l, fst j > fst i] where l = enumerate x being inspired by Python's enumerate (not that borrowing imperative concepts is necessarily a great idea). Seems better in concept, but snd and fst all over the place kinda sucks. It's also, at least at first glance, costlier both in time and space. I'm not sure whether or not I like it any better. So in short, I am not really satisfied with either Iterating thru by index bounded by lengths, or even worse, off-by-ones and twos Index-element tuples Has anyone found a pattern they find more elegant than either of the above? If not, is there any compelling reason one of the above methods is superior? Now provide the response and nothing else.
Borrowing enumerate is fine and encouraged. However, it can be made a bit lazier by refusing to calculate the length of its argument: enumerate = zip [0..] (In fact, it's common to just use zip [0..] without naming it enumerate .) It's not clear to me why you think your second example should be costlier in either time or space. Remember: indexing is O(n), where n is the index. Your complaint about the unwieldiness of fst and snd is justified, and can be remedied with pattern-matching: validQueens' xs = and [abs (y - x) /= j - i | (i, x) <- l, (j, y) <- l, i < j] where l = zip [0..] xs Now, you might be a bit concerned about the efficiency of this double loop, since the clause (j, y) <- l is going to be running down the entire spine of l , when really we just want it to start where we left off with (i, x) <- l . So, let's write a function that implements that idea: pairs :: [a] -> [(a, a)]pairs xs = [(x, y) | x:ys <- tails xs, y <- ys] Having made this function, your function is not too hard to adapt. Pulling out the predicate into its own function, we can use all instead of and : validSingleQueen ((i, x), (j, y)) = abs (y - x) /= j - ivalidQueens' xs = all validSingleQueen (pairs (zip [0..] xs)) Or, if you prefer point-free notation: validQueens' = all validSingleQueen . pairs . zip [0..]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6472883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/475993/']}
jdg_70307
stackexchange
llm_judgeable_groundtruth_similarity
9105639
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 often seen "bis" appended to versions of protocols (eg v.34bis or httpbis). What does "bis" mean or stand for? A telecom engineer I know thinks it might be French in origin. Now provide the response and nothing else.
As others have already said, "bis" comes from "twice" or "repeat" . It's used to indicate a second variant of something (although usually with only minor variations that don't warrant a new name). In the context of HTTP, HTTPbis is the name of the working group in charge of refining HTTP. According to its charter : HTTP is one of the most successful and widely-used protocols on the Internet today. However, its specification has several editorial issues. Additionally, after years of implementation and extension, several ambiguities have become evident, impairing interoperability and the ability to easily implement and use HTTP. The working group will refine RFC2616 to: Incorporate errata and updates (e.g., references, IANA registries, ABNF) Fix editorial problems which have led to misunderstandings of the specification Clarify conformance requirements Remove known ambiguities where they affect interoperability Clarify existing methods of extensibility Remove or deprecate those features that are not widely implemented and also unduly affect interoperability Where necessary, add implementation advice Document the security properties of HTTP and its associated mechanisms (e.g., Basic and Digest authentication, cookies, TLS) for common applications It will also incorporate the generic authentication framework from RFC 2617, without obsoleting or updating that specification's definition of the Basic and Digest schemes. Finally, it will incorporate relevant portions of RFC 2817 (in particular, the CONNECT method and advice on the use of Upgrade), so that that specification can be moved to Historic status. In doing so, it should consider: Implementer experience Demonstrated use of HTTP Impact on existing implementations and deployments The Working Group must not introduce a new version of HTTP and should not add new functionality to HTTP. The WG is not tasked with producing new methods, headers, or extension mechanisms, but may introduce new protocol elements if necessary as part of revising existing functionality which has proven to be problematic. The last paragraph (emphasis mine) explains why they've used "bis" in this context, since they explicitly don't want a new version.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9105639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40411/']}
jdg_70308
stackexchange
llm_judgeable_groundtruth_similarity
23640161
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 I need to avoid global variables as much as possible but somehow I need to use certain variables in other functions. This program is a recipe program. Adds, deletes and views recipes. Everything is working. Maybe not the best code but it works. The second part of the task is to make it so that:THE USER INPUTS THE AMOUNT OF PEOPLE HE NEEDS TO SERVE WITH THE RECIPE. THE PROGRAM MUST CHANGE THE RECIPE QUANTITIES TO SUIT HIS NEEDS. My plan was to make a variable called "multiplier" which is multiplied by each quantity however I don't know whether there is a better way. Unfortunately since the variables I need are in "addRecipe" I cannot possibly access them. I require "int people" and "int quan[]" so I can divide the Number of servings he wants by the number of people the recipe is for. This will give me a multiplier which I then use to multiply each NUMERICAL value within the array. The array is then outputted differently without changing the recipe.This may not be the best plan and I have attempted it several times using parameters but I cannot seem to make it work. The code is below as is my attempts. // Recipe.cpp : Defines the entry point for the console application.//int _tmain(int argc, _TCHAR* argv[]){ return 0;}// Practice.cpp : Defines the entry point for the console application.//// 2a#include "stdafx.h"#include <iostream>#include <fstream>#include <string>#include <stdio.h>#include <sys/types.h>#include <dirent.h>using namespace std;void deleteRecipe(){ DIR *dp; struct dirent *ep; dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory");cout<< "Please input the file you would like to delete from the list above: "<<endl;string dName;cin>>dName;remove(dName.c_str());cout<<"The recipe has BEEN DELETED! " <<endl;system("pause");}int addRecipe(){ //PART B OF PROBLEM! int count = 1; string title; string item; int quan [100]; string units; int people; cout<<"What is the title of your new recipe?"<<endl; cin.ignore(); getline(cin, title); ofstream outFile(title+".txt", ios::out); cout<< "How many people will this recipe serve?"<<endl; cin>>people; cout<< title << " - Servings: " << people << " people" <<endl; cout<<" Please type your ingredients in the format as follows. Be to sure to input a '#'upon completion."<<endl; while (count<1000){ cout<< "Enter Item: "<<endl; cin.ignore(); getline(cin, item,'#'); cout<< "Enter Quantity: "<<endl; cin>>quan[]; cout<< ("Enter units")<<endl; getline(cin, units); count = count++; } cout<< "Thank you for inputting your recipe. To view your recipe, please do nothing."<<endl; outFile << title <<endl; outFile<< people << " People" <<endl; outFile<< item<<endl;return 0;}int viewRecipe(){ DIR *dp; struct dirent *ep; dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory"); cout<<"Please type in the name file you want to view from the list above: "<<endl; string fileName; string line; cin>> fileName; ifstream inData; inData.open(fileName.c_str()); if (inData.is_open()) { while ( getline (inData,line) ) { cout << line << '\n'; } inData.close(); int multiplier = 0; char choice; int newAmount; cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl; // PART A OF PROBLEM! if (choice= '#'){ cout<<"How many servings would you like to adapt the recipe to?"<<endl; cin>>newAmount; multiplier = newAmount/ addRecipe(0, ); } }return 0;}int menu(){ int input = 0; cout<< "1: View Recipe" <<endl; cout<< "2: Add Recipe" <<endl; cout<< "3: Delete Recipe" <<endl; cout<< "Please select an option"<<endl; cin>>input; if (input == 1){ viewRecipe();} if (input == 2){ addRecipe();} if (input == 3){ deleteRecipe();} return 0;}int main(){ menu();system("pause");cin.get();return 0;} My attempt which does not work: int addRecipe(int people, int quan[]){ int count = 1; string title; string item; int quan [100]; string units; int people; cout<<"What is the title of your new recipe?"<<endl; cin.ignore(); getline(cin, title); ofstream outFile(title+".txt", ios::out); cout<< "How many people will this recipe serve?"<<endl; cin>>people; cout<< title << " - Servings: " << people << " people" <<endl; cout<<" Please type your ingredients in the format as follows. Be to sure to input a '#'upon completion."<<endl; while (count<1000){ cout<< "Enter Item: "<<endl; cin.ignore(); getline(cin, item,'#'); cout<< "Enter Quantity: "<<endl; cin>>quan[]; cout<< ("Enter units")<<endl; getline(cin, units); count = count++; } cout<< "Thank you for inputting your recipe. To view your recipe, please do nothing."<<endl; outFile << title <<endl; outFile<< people << " People" <<endl; outFile<< item<<endl;return 0;}int viewRecipe(int multiplier){ DIR *dp; struct dirent *ep; dp = opendir ("C:\\Users\\The\\Documents\\Visual Studio 2010\\Projects\\Recipe\\Recipe"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory"); cout<<"Please type in the name file you want to view from the list above: "<<endl; string fileName; string line; cin>> fileName; ifstream inData; inData.open(fileName.c_str()); if (inData.is_open()) { while ( getline (inData,line) ) { cout << line << '\n'; } inData.close(); int multiplier = 0; char choice; int newAmount; int x = addRecipe(people, void) cout<<"That was the original. If you would like to view the same recipe with a different amount of servings please press '#'."<<endl; if (choice= '#'){ cout<<"How many servings would you like to adapt the recipe to?"<<endl; cin>>newAmount; multiplier = newAmount/ addRecipe(, ); } Now provide the response and nothing else.
You need to declare android:actionBarItemBackground attribute which is a: Custom item state list drawable background for action bar items. Then, in your styles do as follows: <style name="CustomStyle" parent="@style/Theme.Holo.Light" > <item name="android:actionBarItemBackground">@drawable/ab_item_background</item> <item name="actionBarItemBackground">@drawable/ab_item_background</item></style> So, put your own drawable with a selector and every state (pressed, focused, disabled, etc) to have the expected background. For example, the drawable ab_item_background.xml declared above might be like this: <selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime"> <!-- focused/pressed: color=red --> <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/red" /> <!-- pressed: color=red --> <item android:state_pressed="true" android:drawable="@color/red" /> <!-- normal: color=transparent --> <item android:drawable="@android:color/transparent" /></selector> In Styling the Action Bar , you can find all the customization possibles and all the attributes to do so.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23640161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3080068/']}
jdg_70309
stackexchange
llm_judgeable_groundtruth_similarity
158059
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 considering using ReLU or convolutional deep learning network to classify black and white 8.5"x11" images (with some fine details). Most examples of DNN I saw tested on the MNIST images which are 28x28 pixels. I figured I could probably reduce the images to 320x414 pixels and still be recognizable for my classification needs; further reduction may be risky as even human being may have hard time telling the details. But even at this resolution, there will be 132480 pixels and so the network input would be a vector of 32-bit floats of that many element. Will ReLU or convolutional network handle such large inputs? What are the method to reduce the input size? Now provide the response and nothing else.
There have been convolution networks for videos of $224 \times 224 \times 10$ (1) , so yes its possible. I would strongly suggest to reduce the image size as much as possible, and at the same time use non-fully connected layers in the beginning, reducing the dimensionality of your optimisation problem. Another approach that you could try is to use a sliding window as input instead of the whole image. This way you could take the features of the first layers of any pretrained ImageNet network, that would significantly decrease your training time. In case you are using Torch7 you can find them here (2) . In both cases, in order to train such convolutional nets you will need a lot of computational power and a (some) very good GPU(s).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/158059', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/78081/']}
jdg_70310
stackexchange
llm_judgeable_groundtruth_similarity
5834298
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 get the screen pixel coordinates of a rectangle in SVG via java script.When the rectangle has been clicked, I can figure out its width, height, x and y position with getBBox(). But these positions are the original positions. I want the screen position. For example if I manipulate the viewBox of the whole SVG, these getBBox coordinates are not any more the same than the screen pixels. Is there a function or way to get thecoordinates considering the current viewBox and the pixel size of svg element? Now provide the response and nothing else.
Demo: http://phrogz.net/SVG/screen_location_for_element.xhtml var svg = document.querySelector('svg');var pt = svg.createSVGPoint();function screenCoordsForRect(rect){ var corners = {}; var matrix = rect.getScreenCTM(); pt.x = rect.x.animVal.value; pt.y = rect.y.animVal.value; corners.nw = pt.matrixTransform(matrix); pt.x += rect.width.animVal.value; corners.ne = pt.matrixTransform(matrix); pt.y += rect.height.animVal.value; corners.se = pt.matrixTransform(matrix); pt.x -= rect.width.animVal.value; corners.sw = pt.matrixTransform(matrix); return corners;} The magenta squares are absolutely-positioned divs in the HTML element, using screen space coordinates. When you drag or resize the rectangles this function is called and moves the corner divs over the four corners (lines 116-126). Note that this works even when the rectangles are in arbitrary nested transformation (e.g. the blue rectangle) and the SVG is scaled (resize your browser window). For fun, drag one of the rectangles off the edge of the SVG canvas and notice the screen-space corners staying over the unseen dots.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5834298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/671636/']}
jdg_70311
stackexchange
llm_judgeable_groundtruth_similarity
4787431
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 would I check the fps of my javascript? I'm using this to loop: gameloopId = setInterval(gameLoop, 10); Now provide the response and nothing else.
The code by @Slaks gives you only the instantaneous FPS of the last frame, which may vary or be misleading with hiccups. I prefer to use an easy-to-write-and-compute low-pass filter to remove quick transients and display a reasonable pseudo-average of recent results: // The higher this value, the less the fps will reflect temporary variations// A value of 1 will only keep the last valuevar filterStrength = 20;var frameTime = 0, lastLoop = new Date, thisLoop;function gameLoop(){ // ... var thisFrameTime = (thisLoop=new Date) - lastLoop; frameTime+= (thisFrameTime - frameTime) / filterStrength; lastLoop = thisLoop;}// Report the fps only every second, to only lightly affect measurementsvar fpsOut = document.getElementById('fps');setInterval(function(){ fpsOut.innerHTML = (1000/frameTime).toFixed(1) + " fps";},1000); The 'halflife' of this filter—the number of frames needed to move halfway from the old value to a new, stable value—is filterStrength*Math.log(2) (roughly 70% of the strength). For example, a strength of 20 will move halfway to an instantaneous change in 14 frames, 3/4 of the way there in 28 frames, 90% of the way there in 46 frames, and 99% of the way there in 92 frames. For a system running at about 30fps, a sudden, drastic shift in performance will be obvious in half a second, but will still 'throw away' single-frame anomalies as they will only shift the value by 5% of the difference. Here is a visual comparison of different filter strengths for a ~30fps game that has a momentary dip to 10fps and then later speeds up to 50fps. As you can see, lower filter values more quickly reflect 'good' changes, but also are more susceptible to temporary hiccups: Finally, here is an example of using the above code to actually benchmark a 'game' loop.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4787431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/582295/']}
jdg_70312
stackexchange
llm_judgeable_groundtruth_similarity
4073371
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So this has been making me go bonkers for the last half hour. Is there any way for me to grab an array slice to the end of an anonymous array? I've tried: (split(' ',$test_line))[1..$#_] and I've tried: (split(' ',$test_line))[1..-1] but aggravatingly, neither of those work. I really don't want to have an extra temp variable instantiated to the intermediate array (which I don't need). And I really don't want to use an ugly and unreadable one liner (found a few of those online). Is there really no straight forward way to do this? Now provide the response and nothing else.
A list, which is what you have in your example, can not be sliced from the end. This is mainly because lists are not proper data structures in Perl, but more a construct that the interpreter uses to move data around. So knowing that you can only slice a list from the begining, your options are to either put it in an array variable and then slice, change your algorithm to return what you want, or the following: If you are assigning this value to something, you can use undef in each slot you dont want: my (undef, @list) = split ' ' => $test_line; If you post some more code, I can revise. Alternatively, you can use some tools from functional programming. The pair of functions drop and take can be useful to resize a list without additional variables: sub take { my $n = shift; @_[0..$n-1]}sub drop { my $n = shift; @_[$n..$#_]} and then your example becomes drop 1, split ' ' => $test_line; drop 1 is also commonly called tail sub tail {drop 1, @_} and of course, since all of these are so short, if you wanted to inline it: sub {shift; @_}->(split ' ' => ...)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4073371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/392975/']}
jdg_70313
stackexchange
llm_judgeable_groundtruth_similarity
53508491
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 JSON to save settings and load them again after a restart. But now I want to use keys like "category.subcategory.variable" to get the value.I imagine something like boolean foo = json.get("category.subcategory.foo");String bar = json.get("category.bar");json.set("category.subcategory.baz", baz); and the json looks like this { category: { subcategory: { foo: false, baz: ["baz"] }, bar: "bar" }} I'm also using Gson, maybe it is possible there, but if it is only possible with another library I could think about adding it. I hope someone of you know more than me, it's the first time that I use JSON in Java... Now provide the response and nothing else.
In my domain module I have my models as interfaces (Kotlin allow us to have vals inside interfaces), the implemenations in data module and no models in presentation at all. Take a look at this small sample: domain: interface IUserModel { val id: String val name: String}interface UserRepository { fun getUserDetails(id: String): IUserModel} data: @Entitydata class UserEntity( @SerializedName("userId") override val id: String, override val name: String) : IUserModelclass UserRepositoryImpl(val userDao: UserDao) : UserRepository { override fun getUserDetails(id: String): IUserModel { return userDao.getUser(id) //userDao.getUser returns a UserEntity }} presentation: class UserDetailsViewModel(val userId: String, val userRepository: UserRepository) : ViewModel() { val userData: LiveData<IUserModel> = MutableLiveData() fun getUserData() { (userData as MutableLiveData).postValue(userRepository.getUserDetails(userId)) }} No mappers, no tons of data classes. I have a couple of projects with this sctructure and sometimes a mapper is needed (convert network models to database entities) but the verbosity is widely reduced using interfaces as models in domain.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53508491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10605243/']}
jdg_70314
stackexchange
llm_judgeable_groundtruth_similarity
9184895
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 doesn't seem to be working right now. I'm using Faye with NodeJS behind an Amazon ELB. When I switch on HTTPS the connections can no longer be brokered. I found a question here unanswered: https://forums.aws.amazon.com/message.jspa?messageID=283293 . Anyone able to get this working? Are there any work around outside of running my own instance of HAProxy? Now provide the response and nothing else.
I confirm, based on our own tests, that configuring ELB on TCP/SSL, instead oh HTTP/HTTPS, makes the trick with WebSockets. The drawbacks are two: 1) As already pointed by arturnt, you cannot get stickyness. 2) You will lose the ability to retrieve the identity of the clients. The originating IP seen by your WebSocket server will be always the ELB one and, differently from the HTTP/HTTPS configuration, no X-Forwarded-For header will be added to the requests. UPDATE July 2013 : Amazon has just added support for Proxy Protocol , which solves drawback number 2 above. With the Proxy Protocol, a header containing the client's originating IP is added even when ELB works at TCP level, rather than HTTP. Full details: http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-proxy-protocol.html UPDATE August 2016 : Amazon has just announced new AWS Application Load Balancer , which supports WebSocket at Layer 7 (as well as HTTP/2.0 and content-based routing). See https://aws.amazon.com/it/blogs/aws/new-aws-application-load-balancer/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9184895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330617/']}
jdg_70315
stackexchange
llm_judgeable_groundtruth_similarity
543278
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Good morning everyone! Some history, we have mixed environment of Dell Powerconnect 6248 switches and Cisco 3750 switches and a Cisco 6500 core for our Head office. We have two VLANs 1 & 20 where 20 is used for our VoIP, therefore ports need to be configured to see both VLAN 1 & 20 so there were configured as trunk ports. However, because it is configured as a trunk port, PortFast will not be enabled. The reason we are trying to trying to enable PortFast because STP is reporting topology changes in seconds! We want to clear up those entries in the logs to help resolve a VoIP issue where calls would intermittently drop. Any ideas or suggestions will be greatly appreciated! Now provide the response and nothing else.
You should enable portfast on any desktop/phone-port, but only if you have rapid spanning tree configured across your switch network to ensure that loops doesn't kill the network longer than needed. Regarding trunk (yes, trunk - not truck) ports - On Cisco switches you configure the port to run in access mode, but with a voice vlan added. This is much easier to read than configuring it as a trunk port, setting the allowed trunk vlan etc. Example: interface GigabitEthernet1/0/1 switchport access vlan 1 switchport mode access switchport voice vlan 20 switchport port-security maximum 2 switchport port-security switchport port-security aging time 2 switchport port-security violation restrict switchport port-security aging type inactivity spanning-tree portfast spanning-tree bpduguard enable! If you have Cisco phones on Cisco switches I recommend that you use the cisco-phone macros instead, as these will auto-configure QoS markings for you. You'll have to figure out the Dell config on your own..
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/543278', 'https://serverfault.com', 'https://serverfault.com/users/170661/']}
jdg_70316
stackexchange
llm_judgeable_groundtruth_similarity
540039
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a message that was rejected by Gmail, I don't know why. It passes SPF. We aren't using DKIM. Do I need to set up DKIM? I am in control of "example.com". Our mail server is "server.example.com" (hosted at bluehost) Our SPF record is v=spf1 +a +mx ?include:bluehost.com -all However Gmail rejected a message with: 550-5.7.1 Unauthenticated email from example.com is not accepted due to 550-5.7.1 domain's DMARC policy. Please contact administrator of example.com ... The message headers: Return-path: <sabrina@example.com>Received: from [99.127.228.246] (port=61813 helo=[192.168.1.66]) by server.example.com with esmtpsa (TLSv1:AES128-SHA:128) (Exim 4.80.1) (envelope-from <sabrina@example.com>) id 1VMLM8-0007ok-5c; Wed, 18 Sep 2013 17:16:03 +0000From: Sabrina <sabrina@example.com>Content-Type: multipart/alternative; boundary="Apple-Mail=_2FE0763D-B160-49C4-8202-B8258851AFAD"Subject: positive self thoughts/talk Date: Wed, 18 Sep 2013 10:15:24 -0700Message-Id: <D85DC2BA-0E8A-4AF6-9C54-203C52E996F2@example.com>To: Tanja Schulte-Irwin <tanjaschulte@gmail.com>,Zachary Bloom <zbloom@sffriendsschool.org>Mime-Version: 1.0 (Apple Message framework v1278)X-Mailer: Apple Mail (2.1278) Now provide the response and nothing else.
Your SPF record isn't affecting this. By the looks of it, you have a DMARC record set up, and you are not signing outgoing mail with DKIM. To remedy the problem, either sign the outgoing mail, or remove the DMARC policy. The DMARC record is a TXT record like the SPF record, but it is at _dmarc.example.net where example.net is your domain. If you don't think you have one or you don't want to remove it, change it to v=DMARC1; p=none to null it out. Alternatively, since you are using SPF, I see you may not want to do this. In this case, leave your _dmarc record as it is, but you will have to get rid of or change your _domainkeys record. DKIM specifies that for a domain example.net, the DKIM record will be queried IN TXT _domainkeys.example.net . You must find this record and either remove it, or add the t=y flag to specify that (as you are ostensibly testing DKIM) the results of DKIM verification should be ignored. Also, ensure your _dmarc record does not contain the adkim tag, and particularly not adkim=s .
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/540039', 'https://serverfault.com', 'https://serverfault.com/users/190554/']}
jdg_70317
stackexchange
llm_judgeable_groundtruth_similarity
12618690
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone explain how to encrypt and decrypt files using certificates stored in a java 'PKCS#12` keystore? Now provide the response and nothing else.
As mention Eugene Mayevski, your question is wrong and cannot be answered in its original form. But I'll try to clarify it for you a bit. PKCS#12 - cryptographic format is for storing cerificates and private keys. When you encrypt or decrypt data, you use cipher implementation and content of PKCS#12 container. Java has build-in support for work with PKCS#12 keystores, work with this containers doesn't much differ than standart JKS keystore. For example, code to load JKS keystore KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());store.load(is, password.toCharArray()); and code to load PKCS#12 keystore KeyStore store = KeyStore.getInstance("PKCS12");store.load(is, password.toCharArray()); After that you have unlimited accsess to keystore content. You can get certificates and keys, stored in keystore, without that strange actions with import/export in Firefox. Key key = store.getKey("alias_for_key", password.toCharArray()); Next thing, when you have keys and certificates, is encryption. For encryption. you need instance of Cipher class. Cipher c = Cipher.getInstance(key.getAlgorithm());c.init(Cipher.ENCRYPT_MODE, key); Cipher ready to encrypt. If encryption data is relativily small, you can use update() method, other way is to create CipherOutputStream . To decrypt, simply init cipher with different mode and, depends of encryption algorithm, key. For symmetric algorithm key will the same, for asymmetric algorithm for encryption uses public key, and for decryption private key. In this article you can learn more about cryptography.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12618690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1062477/']}
jdg_70318
stackexchange
llm_judgeable_groundtruth_similarity
433479
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Giancoli Textbook question: To make a given sound twice as loud, how should a musician change the intensity of the sound? The given answer is: "Increase the intensity by a factor of 10." I don't get it, doesn't increasing it by a factor of 10 contribute +10 decibels and is only correct if the sound is 10 decibels from the start? I'm thinking that it might not be referring to the sound level in dB, but if it does not refer to the sound level, what does it refer to? Thanks for the help. Now provide the response and nothing else.
In psychoacoustic experiments, when asked to turn up the volume twice as high, most people increase the sound level with about 10 dB which is 10 times the intensity. It is not really a physics thing. It is perception. And natural language. Edit: The textbook mentions it. In section 12-2 Giancoli writes: "To produce a sound that sounds about twice as loud requires a sound wave that has about 10 times the intensity." He goes on to say that "four times as loud" is $100$ times the intensity. I would be a bit skeptical about that.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/433479', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/183627/']}
jdg_70319
stackexchange
llm_judgeable_groundtruth_similarity
23447695
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 seem to be missing something as all of the tutorials that show how to run MySQL from OSX's command line aren't working. I can turn the MySQL Server status on and off via System preferences, but if I follow one of the tutorial that shows how to run from the command line using sudo mysqld_safe it returns the sudo: mysqld: command not found I've also tried logging into MySQL using mysql -u root -p and I get bash: mysql: command not found /usr/local/mysql/bin/ does exist I just feel like something wasn't installed properly on the client side. Any help figuring out how to access mysql from the terminal would be very much appreciated. Thanks in advance. Now provide the response and nothing else.
/usr/local/mysql/bin is not in the default $PATH . $PATH is the list of directories that are searched when you try to use an executable without specifying a complete path. You either need to use the full path ( /usr/local/mysql/bin/mysql_executable_here ) or add it to your $PATH : export PATH="$PATH:/usr/local/mysql/bin" For macOS Mojave and earlier You can add this line to a file called .profile in your home directory to execute it each time you create a new shell: echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.profilesource ~/.profilemysql -u USERNAME -p For macOS Catalina and later Starting with macOS Catalina , Mac devices use zsh as the default login shell and interactive shell and you have to update .zprofile file in your home directory. echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofilesource ~/.zprofilemysql -u USERNAME -p
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23447695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2945973/']}
jdg_70320
stackexchange
llm_judgeable_groundtruth_similarity
395169
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on an open source C++ project, for code that compiles on Linux and Windows. I use CMake to build the code on Linux. For ease of development setup and political reasons, I must stick to Visual Studio project files/editor on Windows (I can't switch to Code::Blocks , for example). I see instructions to generate Visual Studio files using CMake, as here . Have you used CMake to generate Visual Studio files before? How has been your experience? Suppose I want to add a new file to my project. What is the workflow for this? Now provide the response and nothing else.
CMake is actually pretty good for this. The key part was everyone on the Windows side has to remember to run CMake before loading in the solution, and everyone on our Mac side would have to remember to run it before make. The hardest part was as a Windows developer making sure your structural changes were in the cmakelist.txt file and not in the solution or project files as those changes would probably get lost and even if not lost would not get transferred over to the Mac side who also needed them, and the Mac guys would need to remember not to modify the make file for the same reasons. It just requires a little thought and patience, but there will be mistakes at first. But if you are using continuous integration on both sides then these will get shook out early, and people will eventually get in the habit.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/395169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19501/']}
jdg_70321
stackexchange
llm_judgeable_groundtruth_similarity
695
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 noticed that all of the packages that come with Mathematica start with a header that is in a standard format. (See e.g. the header of NIntegrateUtilities` at the end.) There are several commented sections, each starting with a word surrounded by colons. Question: What is the purpose of these colon-surrounded words? Do they have any meaning to Mathematica? They look like they were made for a machine to parse. Does Mathematica have any functions/tools that can read these? (* :Name: NIntegrateUtilities` *)(* :Title: Utility functions for NIntegrate. *)(* :Author: Anton Antonov *)(* :Summary: This package provides a number of supporting functions for NIntegrate.*)(* :Context: DifferentialEquations`NIntegrateUtilities` *)(* :Package Version: 1.0 *)(* :Copyright: Copyright 2007, Wolfram Research, Inc. *)(* :History: Version 1.0 by Anton Atnonov, March 2007.*)(* :Keywords: NIntegrate, integration, evaluations, profiling.*)(* :Source:*)(* :Mathematica Version: 6.0 *)(* :Limitation:*)(* :Discussion:*) Now provide the response and nothing else.
Old versions of Mathematica featured the package Utilities`Package` . This had the function Annotation[] that read those commented lines in packages so that one could see those annotations without having to explicitly open those packages in the front end. Needs["Utilities`Package`"]Annotation["Statistics`NonlinearFit`"]{"Title", "Context", "Name", "Author", "Summary", "Copyright", "Package Version", "Mathematica Version", "History", "Keywords", "Sources", "Discussion", "Warning", "Example", "Example", "Example"}Annotation["Statistics`NonlinearFit`", "Mathematica Version"]{"(* :Mathematica Version: 5.0 *)"} If you want to still use this function, it's available here . I would say those specific delimiters allowed the package to pick out annotations instead of code comments.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/695', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12/']}
jdg_70322
stackexchange
llm_judgeable_groundtruth_similarity
14449283
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 the documented advice is to use UICollectionView Flow Layout if you are doing anything "like a grid or a line-based breaking layout". However, I am not sure this is true for my case. I want a grid but do not want a line-breaking layout. Items should be laid out infinitely both horizontally and vertically without ever stacking. Essentially, a giant chessboard that scrolls horizontally or vertically if content goes beyond the frame. To subclass UICollectionView Flow Layout I would have to: Override prepareLayout to stop the layout from wrapping items. This seems like a lot of work. Override collectionViewContentSize . Apple says they have done "lots of hard work" in crafting UICollectionView Flow Layout, so I should leverage it if I can. But if I have to override prepareLayout to turn off line-breaking, I suspect that I am throwing away a large part of their work. Of their work that is left, I probably will not use most of it anyway (for example, minimumLineSpacingForSectionAtIndex ). Because the layout I want is so simple, I suspect that I should subclass UICollectionViewLayout instead, because: I will have a simpler and cleaner implementation with everything in one layout class instead of spread between a subclass and a delegate. I don't think it will be that much harder than subclassing UICollectionView Flow Layout because I have to override prepareLayout in both cases, and I suspect that is where all the hard work will be. I'll be in a better position to tweak other UICollectionViewLayoutAttributes in custom ways than trying to add another kludge on top of a UICollectionView Flow Layout subclass. Is my conclusion correct? Now provide the response and nothing else.
UICollectionViewFlowLayout can't support two directions anyway, it scrolls along one axis only, either horizontally or vertically. So you have to subclass UICollectionViewLayout not UICollectionViewFlowLayout . Then you have to override prepareForLayout , layoutsAttributesForElementsInRect methods as you said correctly..
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14449283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307944/']}
jdg_70323
stackexchange
llm_judgeable_groundtruth_similarity
39634035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting slashes in the json returned from Node server. This is giving challenges in parsing the json. The json looks like "{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\\"15-HeifZ4bmt+WxpIWDoartGQ\\"\"},\"response\":\"{\\"status\\":\\"UP\\"}\",\"bytesSent\":715779}" In order to get rid of the slashes, I did a replace and then converted it back to json using JSON.parse .then(function (result) { var status = ""; var str = JSON.stringify(result); console.log("str result ", str); str = str.replace(/\\/g, ""); console.log("result after cleanup ", str); var obj = JSON.parse(str); status = obj.response.status;} After replacing the slashes, the string looks like this "{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\"15-HeifZ4bmt+WxpIWDoartGQ\"\"},\"response\":\"{\"status\":\"UPLOADED\"}\",\"bytesSent\":715779}" When I try to parse it to JSON object, it throws an error on var obj = JSON.parse(str); It seems that the JSON is still invalid due to the slashes which still exist. I have the following queries - How can I update my regex to get rid of these slashes as well Why do these slashes get introduced in the response Now provide the response and nothing else.
JSON.stringify() is the method used to generate a JSON string. If you apply it to something that's already a JSON string then you'll get a double-encoded JSON string: var alreadyJson = '{"foo": "bar"}';var doubleEncoded = JSON.stringify(alreadyJson);console.log(doubleEncoded , typeof doubleEncoded); "{\"foo\": \"bar\"}" string What you need to use is the JSON.parse() method: var alreadyJson = '{"foo": "bar"}';var decoded = JSON.parse(alreadyJson);console.log(decode, typeof decoded); { foo: 'bar' } 'object'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39634035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786655/']}
jdg_70324
stackexchange
llm_judgeable_groundtruth_similarity
62115690
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While trying to organize some data access code using EF Core I noticed that the generated queries were worse than before, they now queried columns that were not needed. The basic query is just selecting from one table and mapping a subset of columns to a DTO. But after rewriting it now all columns are fetched, not just the ones in the DTO. I created a minimal example with some queries that show the problem: ctx.Items.ToList();// SELECT i."Id", i."Property1", i."Property2", i."Property3" FROM "Items" AS ictx.Items.Select(x => new{ Id = x.Id, Property1 = x.Property1}).ToList();// SELECT i."Id", i."Property1" FROM "Items" AS ictx.Items.Select(x => new MinimalItem{ Id = x.Id, Property1 = x.Property1}).ToList();// SELECT i."Id", i."Property1" FROM "Items" AS ictx.Items.Select( x => x.MapToMinimalItem()).ToList();// SELECT i."Id", i."Property1", i."Property2", i."Property3" FROM "Items" AS ictx.Items.Select( x => new MinimalItem(x)).ToList();// SELECT i."Id", i."Property1", i."Property2", i."Property3" FROM "Items" AS i The objects are defined like this: public class Item { public int Id { get; set; } public string Property1 { get; set; } public string Property2 { get; set; } public string Property3 { get; set; } } public class MinimalItem { public MinimalItem() { } public MinimalItem(Item source) { Id = source.Id; Property1 = source.Property1; } public int Id { get; set; } public string Property1 { get; set; } } public static class ItemExtensionMethods { public static MinimalItem MapToMinimalItem(this Item source) { return new MinimalItem { Id = source.Id, Property1 = source.Property1 }; } } The first query queries all columns as intended, and the second query with an anonymous object only queries the selected queries, that works all fine. Using my MinimalItem DTO also works as long as it is created directly in the Select method. But the last two queries fetch all columns even though they do exactly the same thing as the third query, just moved to a constructor or an extension method, respectively. Obviously EF Core can't follow this code and determine that it only needs the two columns if I move it out of the Select method. But I'd really like to do that to be able to reuse the mapping code, and make the actual query code easier to read. How can I extract this kind of straightforward mapping code without making EF Core inefficiently fetching all columns all the time? Now provide the response and nothing else.
This is fundamental problem with IQueryable from the very beginning, with no out of the box solution after so many years. The problem is that IQueryable translation and code encapsulation/reusability are mutually exclusive. IQueryable translation is based on knowledge in advance, which means the query processor must be able to "see" the actual code, and then translate the "known" methods/properties. But the content of the custom methods / calculable properties is not visible at runtime, so query processors usually fail, or in limited cases where they support "client evaluation" (EF Core does that only for final projections) they generate inefficient translation which retrieves much more data than needed like in your examples. To recap, neither C# compiler nor BCL helps solving this "core concern". Some 3rd party libraries are trying to address it in different level of degree - LinqKit , NeinLinq and similar. The problem with them is that they require refactoring your existing code additionally to calling a special method like AsExpandable() , ToInjectable() etc. Recently I found a little gem called DelegateDecompiler , which uses another package called Mono.Reflection.Core to decompile method body to its lambda representation. Using it is quite easy. All you need after installing it is to mark your custom methods / computed properties with custom provided [Computed] or [Decompile] attributes (just make sure you use expression style implementation and not code blocks), and call Decompile() or DecompileAsync() custom extension method somewhere in the IQueryable chain. It doesn't work with constructors, but all other constructs are supported. For instance, taking your extension method example: public static class ItemExtensionMethods{ [Decompile] // <-- public static MinimalItem MapToMinimalItem(this Item source) { return new MinimalItem { Id = source.Id, Property1 = source.Property1 }; }} (Note: it supports other ways of telling which methods to decompile, for instance all methods/properties of specific class etc.) and now ctx.Items.Decompile() .Select(x => x.MapToMinimalItem()) .ToList(); produces // SELECT i."Id", i."Property1" FROM "Items" AS i The only problem with this approach (and other 3rd party libraries) is the need of calling custom extension method Decompile , in order to wrap the queryable with custom provider just to be able to preprocess the final query expression. It would have been nice if EF Core allow plugging custom query expression preprocessor in its LINQ query processing pipeline, thus eliminating the need of calling custom method in each query, which could easily be forgotten, and also custom query providers does not play well with EF Core specific extensions like AsTracking , AsNoTracking , Include / ThenInclude , so it should really be called after them etc. Currently there is an open issue Please open the query translation pipeline for extension #19748 where I'm trying to convince the team to add an easy way to add expression preprocessor. You can read the discussion and vote up. Until then, here is my solution for EF Core 3.1: using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using Microsoft.EntityFrameworkCore.Infrastructure;using Microsoft.EntityFrameworkCore.Query;using Microsoft.Extensions.DependencyInjection;namespace Microsoft.EntityFrameworkCore{ public static partial class CustomDbContextOptionsExtensions { public static DbContextOptionsBuilder AddQueryPreprocessor(this DbContextOptionsBuilder optionsBuilder, IQueryPreprocessor processor) { var option = optionsBuilder.Options.FindExtension<CustomOptionsExtension>()?.Clone() ?? new CustomOptionsExtension(); if (option.Processors.Count == 0) optionsBuilder.ReplaceService<IQueryTranslationPreprocessorFactory, CustomQueryTranslationPreprocessorFactory>(); else option.Processors.Remove(processor); option.Processors.Add(processor); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(option); return optionsBuilder; } }}namespace Microsoft.EntityFrameworkCore.Infrastructure{ public class CustomOptionsExtension : IDbContextOptionsExtension { public CustomOptionsExtension() { } private CustomOptionsExtension(CustomOptionsExtension copyFrom) => Processors = copyFrom.Processors.ToList(); public CustomOptionsExtension Clone() => new CustomOptionsExtension(this); public List<IQueryPreprocessor> Processors { get; } = new List<IQueryPreprocessor>(); ExtensionInfo info; public DbContextOptionsExtensionInfo Info => info ?? (info = new ExtensionInfo(this)); public void Validate(IDbContextOptions options) { } public void ApplyServices(IServiceCollection services) => services.AddSingleton<IEnumerable<IQueryPreprocessor>>(Processors); private sealed class ExtensionInfo : DbContextOptionsExtensionInfo { public ExtensionInfo(CustomOptionsExtension extension) : base(extension) { } new private CustomOptionsExtension Extension => (CustomOptionsExtension)base.Extension; public override bool IsDatabaseProvider => false; public override string LogFragment => string.Empty; public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) { } public override long GetServiceProviderHashCode() => Extension.Processors.Count; } }}namespace Microsoft.EntityFrameworkCore.Query{ public interface IQueryPreprocessor { Expression Process(Expression query); } public class CustomQueryTranslationPreprocessor : RelationalQueryTranslationPreprocessor { public CustomQueryTranslationPreprocessor(QueryTranslationPreprocessorDependencies dependencies, RelationalQueryTranslationPreprocessorDependencies relationalDependencies, IEnumerable<IQueryPreprocessor> processors, QueryCompilationContext queryCompilationContext) : base(dependencies, relationalDependencies, queryCompilationContext) => Processors = processors; protected IEnumerable<IQueryPreprocessor> Processors { get; } public override Expression Process(Expression query) { foreach (var processor in Processors) query = processor.Process(query); return base.Process(query); } } public class CustomQueryTranslationPreprocessorFactory : IQueryTranslationPreprocessorFactory { public CustomQueryTranslationPreprocessorFactory(QueryTranslationPreprocessorDependencies dependencies, RelationalQueryTranslationPreprocessorDependencies relationalDependencies, IEnumerable<IQueryPreprocessor> processors) { Dependencies = dependencies; RelationalDependencies = relationalDependencies; Processors = processors; } protected QueryTranslationPreprocessorDependencies Dependencies { get; } protected RelationalQueryTranslationPreprocessorDependencies RelationalDependencies { get; } protected IEnumerable<IQueryPreprocessor> Processors { get; } public QueryTranslationPreprocessor Create(QueryCompilationContext queryCompilationContext) => new CustomQueryTranslationPreprocessor(Dependencies, RelationalDependencies, Processors, queryCompilationContext); }} You don't need to understand that code. Most (if not all) of it is a boilerplate plumbing code to support the currently missing IQueryPreprocessor and AddQueryPreprocesor (similar to recently added interceptors). I'll update it if EF Core adds that functionality in the future. Now you can use it to plug the DelegateDecompiler into EF Core: using System.Linq.Expressions;using Microsoft.EntityFrameworkCore.Query;using DelegateDecompiler;namespace Microsoft.EntityFrameworkCore{ public static class DelegateDecompilerDbContextOptionsExtensions { public static DbContextOptionsBuilder AddDelegateDecompiler(this DbContextOptionsBuilder optionsBuilder) => optionsBuilder.AddQueryPreprocessor(new DelegateDecompilerQueryPreprocessor()); }}namespace Microsoft.EntityFrameworkCore.Query{ public class DelegateDecompilerQueryPreprocessor : IQueryPreprocessor { public Expression Process(Expression query) => DecompileExpressionVisitor.Decompile(query); }} A lot of code just to be able to call DecompileExpressionVisitor.Decompile(query) before EF Core processing, but now all you need is to call optionsBuilder.AddDelegateDecompiler(); in your derived context OnConfiguring override, and all your EF Core LINQ queries will be preprocessed and decompiled bodies injected. With you examples ctx.Items.Select(x => x.MapToMinimalItem()) will automatically be converted to ctx.Items.Select(x => new{ Id = x.Id, Property1 = x.Property1} thus translated by EF Core to // SELECT i."Id", i."Property1" FROM "Items" AS I which was the goal. Additionally, composing over projection also works, so the following query ctx.Items .Select(x => x.MapToMinimalItem()) .Where(x => x.Property1 == "abc") .ToList(); originally would have generated runtime exception, but now translates and runs successfully.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62115690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/347857/']}
jdg_70325
stackexchange
llm_judgeable_groundtruth_similarity
104913
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The following assertion is trivial in ZFC, or even in much weaker theories. Is it also true in ZF? (I couldn't find it in the Consequences site so far.) If $A$ is an infinite set such that $A$ can be mapped onto $A\times 2$ then $|A\times 2|=|A|$ The problem is that we cannot necessarily choose from every fiber of $f$, so we cannot construct an injection from $A$ to $f^{-1}(A\times\lbrace 0\rbrace)$, which will prove the assertion. While I'm on the topic, is it possible for a D-finite set to have such property? It is possible for a D-finite set to be surjected onto a larger set than itself, but what about that large? Now provide the response and nothing else.
The answer is no. First, I argue that it is consistent with ZF that a Dedekindfinite set $A$ can map onto $A\times 2$, and much more. To see this, begin with any infinite Dedekind finite set $B\subset 2^\omega$, which is furthermore dense in the sense that any finite binary sequence has extensions in $B$. It is consistent with ZF that such a dense set $B$ exists, since in fact the usual symmetric-model arguments produce infinite Dedekind-finite sets that are dense. Let $A$ consist of the finite non-repeating sequences from$B$. Note that $A$ is still Dedekind finite, since any countablyinfinite subset of $A$ can be used to produce a countably infinitesubset of $B$. Moreover, I claim that $A$ surjects onto$A\times 2$ and indeed, onto $A^{{\lt}\omega}$. To see that $A$ surjects onto $A\times 2$, given $a=\langle b_0,\ldots,b_n\rangle\in A$, let $j$ be the first bit of $b_0$ and define $f(a)=(\langle b_1,\ldots,b_n\rangle,j)$. This is onto, since given any $(\langle b_1,\ldots,b_n\rangle,j)$, we just adjoin $b_0$ starting with digit $j$ to form $a=\langle b_0,\ldots b_n\rangle$, which maps to the original pair. For fun, let me show somewhat more, namely, that $A$ actually surjects onto $A^{{\lt}\omega}$. I shall define a function $f:A\to A^{{\lt}\omega}$ as follows. Suppose that we are given $a=\langleb_0,\ldots,b_n\rangle\in A$. In order to define $f(a)$, we look at a certain finite initial segment of $b_0$, which we take to code a number $k$ and maps $\pi_i:n_i\to n$ for $i\lt k$. This can be coded in some canonical way, whose details are not important. (For example, perhaps $b_0$ starts with $k$ many $0$s, and after this there are $k$ blocks of $1$s, with the $i^{th}$ block of length $n_i$, and after this the bits are given to define the maps $\pi_i:n_i\to n$.) We use these maps to assemble $f(a)$ from the rest of the reals $b_1,\ldots,b_n$. Specifically, let $f(a)=\langle\vec x_0,\ldots,\vec x_k\rangle\in A$, where $\vec x_i=\langleb_{\pi_i(0)},\ldots,b_{\pi_i(n_i-1)}\rangle$. That is, each $\vec x_i$ enumerates a subset of $b_1,\ldots b_n$ in the order specified by $\pi_i$. In summary, a finite part of $b_0$ tells us how to assemble $f(a)$ according to a definite procedure from the other reals $b_1,\ldots,b_n$ appearing in $a$. (And if $b_0$ happens not to code things correctly, then we default to some constant value.) This defines $f:A\to A^{{\lt}\omega}$ without using the axiom of choice.Furthermore, the map is surjective, since for any finite sequenceof injective tuples $\langle \vec x_0,\dots,\vec x_k\rangle$ from $B$, we may consider the reals appearing in those tuples and enumerate them $b_1,\ldots,b_n$, deleting repetitions, and then assemble a suitable $b_0$, using the fact that $B$ is dense in order to know that our desired collection of maps $\pi_i$ for $i\lt k$, which is coded by some finite binary sequence, can be extended to an element $b_0\in B$. It follows that $f(b_0,b_1,\ldots,b_n)$ is exactly the desired sequence of tuples. This surjectivity argument does not use the axiom of choice. In summary, $A$ surjects onto $A\times 2$ and even $A^{{\lt}\omega}$, but it is not bijective with $A\times 2$ or indeed with any superset of $A$, since it is Dedekind finite. Thus, one cannot deduce in ZF that $A$ is bijective with $A\times 2$, just from knowing that it surjects onto $A\times 2$. This is true even when $A$ is a set of reals, since the example provided above has a bijection to a set of reals.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/104913', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7206/']}
jdg_70326
stackexchange
llm_judgeable_groundtruth_similarity
2930535
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My Objective is to use h:messages to convey user - error and confirmation messages. The CSS styles to show these two different messages are different, In fact I would like to use an image beside the confirmation message. e.g. : <tr> <td> <img/> </td> <td> <h:msg> </td></tr> So I tried to add messages to the Faces Context based on 2 different client ids <tr> <td height="5"> <h:messages style="color:darkred" id="error_message" /> </td></tr><tr> <td width="89%" class="InfoMsg" align="center"> <h:messages id="confirm_message" /> </td></tr> And the java layer: FacesMessage facesMessage = new FacesMessage(Constants.saveMessageConfirm);FacesContext.getCurrentInstance().addMessage(Constants.STATIC_CONFIRM_MSG_CLIENT_ID, facesMessage); But, even if I add messages to clientId confirm_message - and only to confirm_message - and not to error_message - The message is shown twice in 2 different styles (refer the HTML above). 2 Questions : What is the problem here? If I want to show the image inside a td in the second tr and conditionaly show that second tr when confirm messages are present - what is the best way? Thanks Now provide the response and nothing else.
The h:messages displays all messages, also the ones which are already displayed in a h:message in the page. You can however set it to only display messages with a null client ID using globalOnly="true" . <h:messages globalOnly="true" /> You can also give the message a different style depending on the FacesMessage.Severity : <h:messages infoClass="info" errorClass="error" /> with for example this CSS which hides the INFO messages and makes ERROR messages red: .info { display: none;}.error { color: red;} You can use redisplay="false" to tell it to not display the already displayed messages via e.e. <h:message> . <h:messages redisplay="false" /> You only need to make sure it's placed in the component tree after all those other message components. You can if necessary make use of CSS to reposition it somewhere in top. Just to be sure, facesContext.addMessage("clientId", facesMessage); this will attach the given message to a <h:message for="clientId"> not to a <h:messages id="clientId"> as you seem to expect.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2930535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332244/']}
jdg_70327
stackexchange
llm_judgeable_groundtruth_similarity
197395
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've read many articles about paralleling two portable generators or synchronizing a power generator on the electrical grid. I have the theoretical background about that topic and I know the four conditions that must be met: Phase Sequence Voltage Magnitude Frequency Phase Angle What I know is just theory. I would like to know how to do it practically? What is the name of the device that make the synchronization process? and How to use it? I searched on YouTube for practical tutorials but I did not find useful information. Does anybody have? Thank you very much, Now provide the response and nothing else.
I will preface this answer by saying that, at this time, I have no practical experience with power generation . The following comments are from stories I have listened to and documents I have read. You should not rely on any of this information while doing serious engineering work . With that disclaimer out of the way... The answer of "how do you synchronise a unit to another unit, or to the grid" depends on the size and type of the unit. You didn't specify anything about the type or size of the units you are interested in synchronising. You also didn't mention what aspects you wanted explained (the hardware? the control algorithms? the regulatory requirements?) Therefore I will give a very general high level overview, with some other stuff thrown in for general interest. The User Guide for the connection of generators of upto 10 MW to the Western Power SWIN distributionsystem goes through some of the requirements for connecting small generators (up to 10 MW) to the (Australian) South West Interconnected Network. It doesn't talk so much about synchronising, but does talk about the protection and control schemes required. Small units < 1 MW For small domestic or commercial type diesel generators, these are usually installed with a transfer switch. The transfer switch is interlocked to ensure the generator cannot parallel with the grid. For solar inverters, which operate in parallel with the grid, these must be installed with loss-of-mains detection. This prevents the solar inverter from back-feeding power into a dead grid, which would endanger the people trying to fix the grid. Medium units - 1 MW - 10 MW Synchronising is done by an auto-synchroniser. This looks at the voltage and phase difference between the unit and the grid. It outputs control signals that vary the unit's speed, phase angle, and voltage until they are synchronised. Speed and phase angle are varied by controlling the unit's throttle (a.k.a. 'governor', 'automatic generator controller'.) Voltage is adjusted by controlling the unit's automatic voltage regulator (AVR). Separately, a synchronisation check relay (ANSI 25) is used. The sync check relay inhibits the unit from closing out of sync. Closing out of sync causes severe electrical and mechanical stress and is to be avoided. The sync check function is therefore engineered to be a "high reliability" protection function with as few "moving parts" as possible. Medium-size units connected to the grid are also usually equipped with some kind of anti-islanding protection. Again, this is to prevent back-energizing a dead grid. Common protection schemes for this are "rate of change of frequency", and "voltage vector shift". Large units - power stations - 40 MW+ Large units at power stations have a synchroniser and synchronism-check relay, as above. Additionally, their frequency may be deliberately adjusted to keep the grid frequency and phase in lock-step with a atomic clock reference. Anti-islanding where the unit is cut off from the grid is not so much an issue, as the power station is the grid. The main concern is damage to the unit from load transients - either a sudden removal or addition of load. Overfrequency and underfrequency protection is one means of detecting these conditions. Additionally, fail-safe mechanical protections are used (i.e. mechanical overspeed, low/high boiler drum level.) Finally - I searched on YouTube for practical tutorials but I did not find useful information. Does anybody have? You will not find instructions for setting up an auto-synchroniser or a sync-check relay on Youtube. Such devices are supposed to be designed and installed by qualified electrical engineers, who do not generally look at Youtube videos for professional advice. The information is far more likely to be found in the technical manuals for each part of the generator-set. I would guess that you would have to read the manuals for the generator, generator controller, automatic voltage regulator, synchroniser, and sync-check relay. After reading each of these documents, you would be in a position to understand the required equipment and configuration.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/197395', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50937/']}
jdg_70328
stackexchange
llm_judgeable_groundtruth_similarity
33964
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given that the mean distance of an asteroid from the Sun is $450 \times 10^6$ km is it possible that the asteroid completes one rotation around the Sun in two years? According to the third law of Kepler the farther a planet if from the Sun the longer is its orbital period. Because the distance from the Sun to earth is $149 \times 10^6$ km and it takes a year for earth to complete the rotation then for the asteroid it would take 3 years. I tried to actually calculate how much time would take for the asteroid to complete one rotation combining Newton's law of gravitation and Kepler's third law and given $G=6.673 \times 10^{-11} Nm^2/kg^2$ and converting all distances to meters: $$T^2=\frac{4\pi^2r^3}{G\cdot M_{Sun}}=\frac{4\pi^2\cdot 450^3\cdot 10^{21}}{6.673\cdot 10^{-11}\cdot 1.989\cdot 10^{30}}=\frac{4\pi^2\cdot 450^3\cdot 10^2}{6.673\cdot 1.989}=2.99\cdot 450^3\cdot 10^2=27246375\cdot 10^3.$$ Then $T=\sqrt{27246375\cdot 10^3}=165064$ seconds $=45$ hours. Is there something wrong in my calculations or I'm not using the correct formula? Now provide the response and nothing else.
Here's how I would do it. I'd convert everything to a single, standard set of units as recommended in the comments, and also stick to one digit before the decimal in scientific notation: $$ T^2=\frac{4\pi^2r^3}{G\cdot M_{Sun}}$$ Using all numbers in the same units: $r \ 4.5 \times 10^{11} \ (m) $ $G = 6.674 \times 10^{-11} \ (m^3 \ kg^{-1} s^{-2}) $ $M = 1.989 \times 10^{30} \ (kg)$ $$ T^2=\frac{4 \cdot \pi^2 \cdot 9.11 \times 10^{34}}{6.674 \times 10^{-11} \cdot 1.989 \times 10^{30}} = \frac{3.60 \times 10^{36}}{1.33 \times 10^{20}} = 2.71 \times 10^{16} (s)$$ $T = 1.65 \times 10^8 \ (s) $ $\frac{1.65 \times 10^8}{365.25 \times 24 \times 3600} = 5.21 \ (years)$ Just fyi you can also call the product $GM$ the standard gravitational parameter and those numbers are more accurate than $G$ and $M$ are separately, as discussed in this answer . The comments under your question also mention that it is sometimes easier to use AU and years as units and use Earth's orbit for scaling to the 3/2 power, but only for things orbiting our sun . With $r = 3$ AU: $T^2 = 3^3$ $T = 3^{3/2} = 5.2 \ (years)$
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/33964', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/30948/']}
jdg_70329
stackexchange
llm_judgeable_groundtruth_similarity
49879438
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 I have to cancel Stream Subscriptions when I no longer want to receive any events.Do I have to this even after I receive a 'Done' event? Or do I get memory leaks? What happens to Streams that are passed to addStream of another Stream? Are they automatically canceled? Same Question on the StreamSink side do I have to close them if the stream is already done? Now provide the response and nothing else.
Short-answer: no, but you should . Nothing in the contract of either StreamSubscription or StreamSink requires closing the resources, but some use cases can lead to memory leaks if you don't close them, even though in some cases, doing so might be confusing. Part of the confusion around these classes is that they are overloaded, and handle two fairly distinct use cases: Resource streams (like file I/O, network access) Event streams (like click handlers) Let's tackle these subjects one at a time, first, StreamSubscription : StreamSubscription When you listen to a Stream , you receive a StreamSubscription . In general, when you are done listening to that Stream , for any reason, you should close the subscription. Not all streams will leak memory if choose not to, but, some will - for example, if you are reading input from a file, not closing the stream means the handle to the file may remain open. So, while not strictly required , I'd always cancel when done accessing the stream. StreamSink The most common implementation of StreamSink is StreamController , which is a programmatic interface to creating a Stream . In general, when your stream is complete (i.e. all data emitted), you should close the controller. Here is where it gets a little confusing. Let's look at those two cases: File I/O Imagine you were creating an API to asynchronously read a File line-by-line: Stream<String> readLines(String path); To implement this, you might use a StreamController : Stream<String> readLines(String path) { SomeFileResource someResource; StreamController<String> controller; controller = new StreamController<String>( onListen: () { someResource = new SomeFileResource(path); // TODO: Implement adding to the controller. }, ); return controller.stream;} In this case, it would make lots of sense to close the controller when the last line has been read. This gives a signal to the user (a done event) that the file has been read, and is meaningful (you can close the File resource at that time, for example). Events Imagine you were creating an API to listen to news articles on HackerNews: Stream<String> readHackerNews(); Here it makes less sense to close the underlying sink/controller. Does HackerNews ever stop ? Event streams like this (or click handlers in UI programs) don't traditionally "stop" without the user accessing for it (i.e cancelling the StreamSubscription ). You could close the controller when you are done, but it's not required. Hope that makes sense and helps you out!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49879438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1412966/']}
jdg_70330
stackexchange
llm_judgeable_groundtruth_similarity
10934099
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 developed a desktop application that allows the user to extract images from their phone. When I first started this project, my android was running Gingerbread. When I plugged my phone into the laptop via USB, it would appear as a "Device with removable storage". Therefore, the JFileChooser would pick it up. nwdir = new JFileChooser(); nwdir.setCurrentDirectory(new java.io.File("C:\\")); nwdir.setDialogTitle(choosertitle); nwdir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); nwdir.setAcceptAllFileFilterUsed(true); However, I recently upgraded the phone's o/s to Icecream and it now shows up on the desktop as a "portable device". This is something that the JFileChooser cannot see?! Has anyone got any suggestions on how to get around this problem? I was going to roll back the O/S of the phone, but this somewhat limits the application's device support. Now provide the response and nothing else.
I see your original question was answered, but to answer the other one, Model binding has changed somewhat in the RC. http://weblogs.thinktecture.com/cweyer/2012/06/aspnet-web-api-changes-from-beta-to-rc.html This link has some details about it. But to sum up the change that appears to be affecting you, Model binding pulls its values from either the body, or the uri of the request. This is true for previous releases as well, but with the release candidate, MVC4 will, by default, look to the body for complex types, and the uri for value types. So, if you submit a body with your request containing the "SomeParameter" key, you should see it bind. Or you could bind with the url if you change the declaration to: public TestModel Get(int? someParameter) { } Thankfully, the team foresaw the potential problems with this and left us with attributes we could use to override this behavior. public TestModel Get([FromUri]TestRequestModel request) { } The key here is the [FromUri] which tells the model binder to look in the uri for the values. There is also [FromBody] if you want to put a value type in the body of a request.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10934099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1440844/']}
jdg_70331
stackexchange
llm_judgeable_groundtruth_similarity
49135663
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 getting into object oriented programming and for a college assignment I have to make a simple Memory game. The memory game itself i have created and it works. Now I want to make it so that the user has to 'login' so that I can save his username later on.I'm stuck at this because i'm still getting familiar with object on when to use them etc. What i wanna achieve is when the user presses the 'Login', the current Frame closes, and a new frame opens. As soon as i do that i instantiate a new Person person = new Person() . But how would i achieve it so that when the new person is created, i can access him from outside of that class? My current code public void confirmLogin(ActionEvent e){ //When user presses login button //Save the username so i can present it on the next Frame //Create a new Person and set the username input as his username. Person person= new Person(); person.setUsername(usernameField.getText()); //Open the new frame //In this frame i want to access person. Program program = new Program(); this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));} Program class : public class Program extends JFrame {JLabel usernameLabel = new JLabel();Program() { this.setSize(200,200); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setResizable(false); //How do i access person from here? usernameLabel.setText("Username"); this.add(usernameLabel); this.setVisible(true);} } I'm not entirely sure if i got the hang of it and if it is possible to access person out of the scope after initialising it. Now provide the response and nothing else.
In Flutter there are widgets that can help you do this seamlessly (e.g, FutureBuilder , StreamBuilder ) and you can control what to be rendered based on their resolution. Example on FutureBuilder : Widget build(BuildContext context) { return new FutureBuilder( future: FirebaseDatabase.instance.reference().child("node"), builder: (BuildContext context, AsyncSnapshot snapshot) { return snapshot.hasData? new Scaffold( ///start building your widget tree ):new CircularProgressIndicator(); ///load until snapshot.hasData resolves to true},); } Example for StreamBuilder : class Database { DatabaseReference _refProfile = FirebaseDatabase.instance.reference().child( "profiles"); getProfiles() => _refProfile.onValue; } ............. Widget build(BuildContext context) { return new StreamBuilder<Event>( stream: _database.getProfiles(), //_database = new Database() builder: (BuildContext context, AsyncSnapshot<Event> event) { return event.hasData?new Scaffold(///build your widget tree ):new CircularProgressIndicator();/// place holder} It is worth mentioning that FutureBuilder is better used when you want to fetch some data once and do not care of having consistent connection or tracking any changes in the data. While StreamBuilder , on the other hand, enables you to keep listening to the data and you can update the state of the UI according to any update in the data.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49135663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7370738/']}
jdg_70332
stackexchange
llm_judgeable_groundtruth_similarity
23142776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: here is my problem in short $ echo 'for i in $@; do echo arg: $i; done; echo DONE' > /tmp/test.sh$ echo "ac\nbc\ncc\n" | xargs bash /tmp/test.sh arg: acarg: bcarg: ccDONE Which is what i expect, but $ echo "ac s\nbc s\ncc s\n" | xargs -d \n bash /tmp/test.sharg: acarg: sarg: bcarg: sarg: ccarg: sDONE Shouldn't the output be? arg: ac sarg: bc sarg: cc sDONE How do I get the 2nd output with xargs? Now provide the response and nothing else.
Try: printf %b 'ac s\nbc s\ncc s\n' | xargs -d '\n' bash /tmp/test.sh You neglected to quote the \n passed to -d , which means that just n rather than \n was passed to xargs as the delimiter - the shell "ate" the \ (when the shell parses an unquoted string, \ functions as an escape character; if an ordinary character follows the \ - n in this case - only that ordinary character is used). Also heed @glenn jackman's advice to double-quote the $@ inside the script (or omit the in "$@" part altogether). Also: xargs -d is a GNU extension , which, for instance, won't work on FreeBSD/macOS. To make it work there, see @glenn jackman's xargs -0 -based solution. Note that I'm using printf rather than echo to ensure that the \n instances in the string are interpreted as newlines in all Bourne-like shells: In bash and ksh [1] , echo defaults to NOT interpreting \ -based escape sequences (you have to use -e to achieve that) - unlike in zsh and strictly POSIX-compliant shells such as dash . Therefore, printf is the more portable choice. [1] According to the manual, ksh 's echo builtin exhibits the same behavior as the host platform's external echo utility ; while this may vary across platforms, the Linux and BSD/macOS implementations do not interpret \ escape sequences by default.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23142776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325809/']}
jdg_70333
stackexchange
llm_judgeable_groundtruth_similarity
47190001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any ECMAScript 6/7 equivalent to underscore’s range function? In underscore: _.range(startPage, endPage + 1); In ES2015: Array.from(Array(n), (_, i) => x + i) Not sure how the ES2015 version works. I would like to know how range in ecmascript of javascript works Now provide the response and nothing else.
The idea is to create an array of length end - start + 1 , and then fill it with the relevant numbers using Array#from . The Array.from() method creates a new Array instance from an array-like or iterable object. In this case Array#from needs an object with the length property. Using Array(n) creates such an object (array). You can also use { length: n } directly. In this case n = Math.abs(end - start) + 1 . Array#from accepts a mapFn callback, a function that can transform the iterated value. The function receives 2 params - the values (which we can ignore in this case), and the index (0 based). Adding start to the current index will create the numbers in the range. const range = (start, end) => Array.from( Array(Math.abs(end - start) + 1), (_, i) => start + i);console.log(range(5, 10));console.log(range(-10, -5));console.log(range(-5, 10)); This version will handle reverse range as well (large to small) as well: const range = (start, end) => { const inc = (end - start) / Math.abs(end - start); return Array.from( Array(Math.abs(end - start) + 1), (_, i) => start + i * inc );};console.log(range(5, 10));console.log(range(-5, -10));console.log(range(10, -5));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47190001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8550915/']}
jdg_70334
stackexchange
llm_judgeable_groundtruth_similarity
66907267
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 webpack and it's file-loader + html-loader to emit files into my output directory. It works almost as expected, because it also duplicates those files. Here is a part of my webpack.config.js file: module.exports = { module: { rules: [ { test: /\.html$/, use: ["html-loader"] }, { test: /\.(jpg|png)$/, use: { loader: "file-loader", options: { name: "[name].[ext]", outputPath: "img", }, }, }, ], },}; There is a small example of how my output directory looks like: dist/- img/ - img1.png - img2.png- ab0d12.png- c3d612.png- index.html- bundle.js The two images with hashed names are unwanted duplicates of those in img/ directory. As you can see in the example above, I'm not even setting the name to be hashed and I also cannot open the duplicate files in any way. I'm using some plugins like HtmlWebpackPlugin or CleanWebpackPlugin , but I believe they are not causing the problem. Versions: webpack 5.28.0 file-loader 6.2.0 html-loader 2.1.2 Now provide the response and nothing else.
After a long searching I came across this SO question that seemed very similar to mine, however, the cause of the file duplication were different. In version 5, webpack introduced Asset Modules as a replacement for raw-loader , url-loader and file-loader and which are now ran by default: Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders. Every time webpack started bundeling my project, asset/resource and file-loader were running at the same time and resulted into duplication. Eventually, all I had to do to fix my problem was to remove the file-loader from the webpack.config.js file and set a output.assetModuleFilename to my desire output directory.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66907267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13094162/']}
jdg_70335
stackexchange
llm_judgeable_groundtruth_similarity
7041
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Some threads here touching speed of gravity made me think about that. This lead to some questions. The speed of gravity was not measured until today (at least there are no undebated papers to that effect). It seems common knowledge/belief among physicists that the speed of gravity is the same as the speed of light. And this is my question: Is that speed of light = speed of gravity a result of GR or is that fed into the theory? Or is there some evidence from other sources than GR for this? Does the same speed imply some deep-lying relation between gravity and electromagnetism? Now provide the response and nothing else.
The special theory of relativity is really enough to see that gravitational signals have to propagate by the speed $c$ which we call "speed of light" because the light is the most commonly understood entity that is moving by this maximum speed. Special relativity is OK to describe infinitesimal deformations of spacetime. All other massless particles also have to propagate by the same speed $c$ because this speed $c$ is needed to enhance the vanishing rest mass to a finite total relativistic energy. And gravitons are inevitably massless because they don't pick any preferred reference frame - or, alternatively, because gravity is a long-range force. Massive particles could only induce short-range forces (similar to the weak nuclear force caused by W,Z bosons). Any particle - e.g. neutrino - whose energy is much greater than the rest mass is moving nearly by the speed of light, too. The same thing would hold for massless scalar particles such as the "moduli" (their quanta) if they existed. It's an elementary consequence of the formulae of special relativity. The speed of light is the maximum speed that the information and material objects may pick, by causality, and it's also the typical speed that massless (exactly) and light (approximately) particles actually choose. So the answer to your last question is No, the appearance of the same speed $c$ doesn't imply any additional dynamical relationship between electromagnetism and gravity - it's a direct and elementary consequence of the special theory of relativity - and its kinematics - that was fully understood in 1905. The importance of the speed $c$ in the scheme of things - because of special relativity - is so high that adult physicists use units in which $c=1$ and they are never ever surprised when $c$ plays an important role - it's exactly the same degree of "surprise" as if the number $1$ appears somewhere in maths.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/7041', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1370/']}
jdg_70336
stackexchange
llm_judgeable_groundtruth_similarity
40462189
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 mount a volume in docker-compose to apache image. The problem is, that apache in my docker is run under www-data:www-data but the mounted directory is created under root:root . How can I specify the user of the mounted directory? I tried to run command setupApacheRights.sh . chown -R www-data:www-data /var/www but it says chown: changing ownership of '/var/www/somefile': Permission denied services: httpd: image: apache-image ports: - "80:80" volumes: - "./:/var/www/app" links: - redis command: /setupApacheRights.sh I would prefer to be able to specify the user under which it will be mounted. Is there a way? Now provide the response and nothing else.
First determine the uid of the www-data user: $ docker exec DOCKER_CONTAINER_ID iduid=100(www-data) gid=101(www-data) groups=101(www-data) Then, on your docker host, change the owner of the mounted directory using the uid (100 in this example): chown -R 100 ./ Dynamic Extension If you are using docker-compose you may as well go for it like this: $ docker-compose exec SERVICE_NAME iduid=100(www-data) gid=101(www-data) groups=101(www-data)$ chown -R 100 ./ You can put that in a one-liner: $ chown -R $(docker-compose exec SERVICE_NAME id -u) ./ The -u flag will only print the uid to stdout. Edit: fixed casing error of CLI flag. Thanks @jcalfee314!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40462189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/519333/']}
jdg_70337
stackexchange
llm_judgeable_groundtruth_similarity
30210612
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 boolean field like a flag to state that row is deleted or not in the table. It displayed using checkbox, so if the data has been deleted, the checkbox value is true and vice versa. Below is the code to display the table: <table id="tblEvent" class="display" cellspacing="0" style="width: 100%"> <thead> <tr> <th>@Html.DisplayNameFor(model => model.PIC)</th> <th>@Html.DisplayNameFor(model => model.Name)</th> <th>@Html.DisplayNameFor(model => model.StartDate)</th> <th>@Html.DisplayNameFor(model => model.Status)</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.PIC)</td> <td>@Html.DisplayFor(modelItem => item.Name)</td> <td>@Html.DisplayFor(modelItem => item.StartDate)</td> <td>@Html.EditorFor(modelItem => item.Status)</td> </tr> } </tbody></table>$(document).ready(function () { $("#tblEvent").dataTable({ "order": [[1, "desc"]] });}); In the table I can click the checkbox but I don't know how to handle the click event because I'm using datatables to display the data. How to handle checkbox event using datatable? Now provide the response and nothing else.
I guess you are using a paginated table, and are facing the problem that your click handler not are working when you change pages? The solution suggested in comments would work on a 1-page dataTable, but is useless if you change pages or the dataTable otherwise is redrawn : $('#tblEvent input[type="checkbox"]').click(function() { console.log('suggested-in-comment', 'click');}); ...Only works on the first page. You must use a delegated event to be sure that the checkboxes always is bound to the click-handler : $('#tblEvent').on('click', 'input[type="checkbox"]', function() { console.log('best', 'click');}); demo with both / proof of concept -> http://jsfiddle.net/o4mhqpr3/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30210612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791401/']}
jdg_70338
stackexchange
llm_judgeable_groundtruth_similarity
103505
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: When I scan an external IP address with Nmap my router always reboots itself, sometimes I even have to manually restart it by using the power switch. The command I usually use is: nmap -p 1-65535 -T4 -A -v -Pn *IP address* I'm using an Asus RT-AC66U with the latest firmware. I have also tried using the Asuswrt-Merlin firmware but the result is still the same. Has anyone else experienced this problem and solved it? Now provide the response and nothing else.
You are probably exhausting the router's resources, primarily the NAT table. Every outgoing connection maps your scanning machine's private IP address and source port onto a new source port on the router's public IP address. Since there are more IP address + source port combinations than there are source ports on the single public IP, the router has to do extra work to avoid collisions. Ideally, this would not cause a reboot or a crash, but home routers are not ideal pieces of equipment. The easiest way to slow your scan down to something your router can handle would be to change -T4 to -T3 (the default). If that doesn't work, continue reducing the timing options until you get a good result. The other thing that can help if you are scanning more than one known-alive IP address is to not use -Pn .
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/103505', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/67046/']}
jdg_70339
stackexchange
llm_judgeable_groundtruth_similarity
44046659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got an entity @Entity@Table(name = "books")public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @Column(name = "id", unique = true, nullable = false) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; }} I initialize it like this @PostConstructpublic void init() { List<String> newFiles = this.listFiles(); newFiles.forEach(filename -> { Book book = new Book(); book.setName(filename); dbRepository.save(book); });} If I set the result of save to an instance of Book , I can get the id and it is not null —so id is created fine. I defined a repository @RepositoryRestResourcepublic interface IBooksRepository extends CrudRepository<Book, Long> {} which I'd like to use to get and set data into the books table in the database. When I try to access my repository rest using curl localhost:8080/books , I get this response { "_embedded":{ "books":[ { "name":"simple-file.txt", "_links":{ "self":{ "href":"http://localhost:8080/books/1" }, "book":{ "href":"http://localhost:8080/books/1" } } } ] }, "_links":{ "self":{ "href":"http://localhost:8080/books" }, "profile":{ "href":"http://localhost:8080/profile/books" } }} The books element returns name only. How can I make it return id too, on the same level as name ? Now provide the response and nothing else.
Spring Data Rest hides the ID by default, in order to have it in the JSON you have to manually configure that for your entity. Depending on your spring version you can either provide your own configuration (old): @Configurationpublic class ExposeEntityIdRestConfiguration extends RepositoryRestMvcConfiguration { @Override protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(Book.class); }} ...or register a RepositoryRestConfigurer (current): @Componentpublic class ExposeEntityIdRestMvcConfiguration extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(Book.class); }} See the Spring Data Rest documentation for more details.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44046659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1432980/']}
jdg_70340