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
|
45613330
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
.zd-slider { position:relative; overflow:hidden; margin-top: 0px; }.zd-slider img[id*="img"] {width:100%; position:absolute; left:0; top:0; opacity:0; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";}/* set the width/height of the slideshow */.zd-slider img#blank {display:block; width:100%; visibility:hidden;}/* the slideshow */.zd-slider #img_01 {-webkit-animation:autoplay 9s linear infinite 0s; animation:autoplay 9s linear infinite 0s;}.zd-slider #img_02 {-webkit-animation:autoplay 9s linear infinite 3s; animation:autoplay 9s linear infinite 3s;}.zd-slider #img_03 {-webkit-animation:autoplay 9s linear infinite 6s; animation:autoplay 9s linear infinite 6s; }@-webkit-keyframes autoplay { 4%,33% {opacity:1;-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";} 0%,37%,100% {opacity:0;-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";}}@keyframes autoplay { 4%,33% {opacity:1;-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";} 0%,37%,100% {opacity:0;-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";}}/* the slide timing indicator */.zd-slider #slide {width:98px; height:5px; position:absolute; left:0; bottom:0; background:rgba(255,255,255,0.5); -webkit-animation:slide 3s linear infinite; animation:slide linear 3s infinite;}@keyframes slide { 0% {left:-100px;} 100% {left:100%;}}@-webkit-keyframes slide { 0% {left:-100px;} 100% {left:100%;}} <div class="zd-container" id="zd-collection2"> <div class="zd-slider"> <img id="blank" src="http://via.placeholder.com/1440x133" alt="" /> <img id="img_01" src="http://via.placeholder.com/1440x133" alt="" /> <a href="http://www.google.com"> <img id="img_02" src="http://via.placeholder.com/1440x133" alt="" /></a> <img id="img_03" src="http://via.placeholder.com/1440x133" alt="" /> <div id="slide"></div> </div> </div> I'm using this slideshow format to display banners on an eBay store listing. I want to have the slides link to various pages in the store however I've tried to add a hyperlink in the traditional way (see "img_02") and had absolutely no luck making the slide clickable. I've seen similar questions on here and tried a few different "working" solutions but had no luck with any. If anyone could advise on how to solve this problem it would greatly appreciated.
Now provide the response and nothing else.
|
Those two functions perform quite different tasks on quite different arguments. texture expects normalized floating point texture coordinates in [0,1] (i.e. 0 being left/bottom and 1 being right/top) and performs proper wrapping (so the coordinates don't necessarily have to be in [0,1]) and filtering (so you don't necessarily get the exact texel color) according to whatever sampling modes you set. texelFetch on the other hand expects integer texel indices in [0,width-1] (and respectively height/depth for y and z) and doesn't perform any kind of filtering or wrapping, accessing the exact texel value at the specified index in a specified mipmap level. So texelFetch(texture_3D, ivec3(coord * vec3(256.0), 0) should be equivalent to texture(texture_3D, coord) with filter modes GL_NEAREST and wrapping modes GL_CLAMP_TO_EDGE . However, also keep in mind possible rounding problems in case coord is exactly 1.0 or on texel boundaries, maybe texelFetch(texture_3D, ivec3(coord * vec3(255.0) + vec3(0.5), 0) might be advisable to be more secure in that regard. However, just changing it this way seems a rather useless aproach compared to simply keeping your current texture access with a GL_NEAREST filter. It is more useful if you already have integer texel coordinates and already know the texture size. Just emulating nearest filtering this way won't really buy you anything. It's basically two conceptually different approaches, one filters a texture with size-independent floating point coordinates and the other one accesses a 3D-array with integer indices. It depends on your surrounding code which approach is more appropriate for your use case.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45613330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8444857/']}
|
jdg_374741
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16859980
|
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 the mail gem to send E-Mail with UTF-8 content using this code Mail.defaults do ...endMail.deliver do from "user@example.com" to "otheruser@example.com" subject "Mäbülö..." body "Märchenbücher lösen Leseschwächen."end This works, but gives the warning Non US-ASCII detected and no charset defined.Defaulting to UTF-8, set your own if this is incorrect. Now after much trying around, consulting mail gem's generated documentation as well as source code, I'm still unable to set the charset. There is a method charset= in Message.rb, but when I add a call to charset, like so: Mail.deliver do from "user@example.com" to "otheruser@example.com" charset "UTF-8" subject "Mäbülö..." body "Märchenbücher lösen Leseschwächen."end I get this ArgumentError: /usr/local/lib/ruby/gems/1.9.1/gems/mail-2.4.4/lib/mail/message.rb:1423:in `charset': wrong number of arguments (1 for 0) (ArgumentError) How can I set the charset within the deliver block?
Now provide the response and nothing else.
|
mail.charset() returns the current charset, it does not allow to set one and does not take any argument. To do so you need to use mail.charset = ... It's actually possible inside the block with: Mail.deliver do from "user@example.com" to "otheruser@example.com" subject "Mäbülö..." body "Märchenbücher lösen Leseschwächen." charset = "UTF-8"end It's also possible without a block: mail = Mail.newmail.charset = 'UTF-8'mail.content_transfer_encoding = '8bit'mail.from = ...mail.to = ...mail.subject = ...mail.text_part do body ...endmail.html_part do content_type 'text/html; charset=UTF-8' body ...endmail.deliver!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16859980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911635/']}
|
jdg_374742
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10042857
|
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 filters available in ios to convert a image to cartoonistic image like exactly in the above picture?
Now provide the response and nothing else.
|
For a much faster solution than ImageMagick, you could use the GPUImageToonFilter from my GPUImage framework: It combines Sobel edge detection with posterization of the image to give a good cartoon-like feel. As implemented in this framework, it's fast enough to run on realtime video from the iPhone's camera, and is probably at least an order of magnitude faster than something similar in ImageMagick. My framework's also a little easier to integrate with an iOS project than ImageMagick. If you want more of an abstract look to the image, the GPUImageKuwaharaFilter converts images into an oil painting style, as I show in this answer .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10042857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1310087/']}
|
jdg_374743
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46662580
|
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 nested class called cell in my main class something.I c class Something{ class Cell { public: int get_row_Number(); void set_row_Number(int set); char get_position_Letter(); static void set_position_Letter(char set); void set_whohasit(char set); char get_whohasit(); Cell(int row,char letter,char whohasit); private: char position_Letter; int row_Number; char whohasit; };}; I wanna implement nested class constructor in .cpp file Something::Cell Cell(int row,char letter,char whohasit){ Something::Cell::set_position_Letter(letter); Something::Cell::set_row_Number(row); Something::Cell::set_whohasit(whohasit);} But it is wrong. I assumed correct would be Something::Cell::Something::Cell at first but i don't think thats true either.
Now provide the response and nothing else.
|
You are almost there. It's as simple as: Something::Cell::Cell(int row,char letter,char whohasit){ Something::Cell::set_position_Letter(letter); Something::Cell::set_row_Number(row); Something::Cell::set_whohasit(whohasit);} But actually, I would strongly recommend you use initializers, rather than constructing the members uninitialized, and then assigning to them: Something::Cell::Cell(int row, char letter, char whohasit) :position_Letter(letter) ,row_Number(row) ,whohasit(whohasit){}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46662580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5451495/']}
|
jdg_374744
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49540752
|
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 I use JSON.NET in Visual Studio 2008 with .NET 3.5 Compact Framework? And how can I install/Configure it in the IDE? I've searched the internet but could not find it. I found this NuGet Support for Visual Studio 2008 to try install JSON.NET through NuGet but could not get it working. The result of this tutorial was an error Unable to find package 'your.package.name' :
Now provide the response and nothing else.
|
I don't think NuGet will help you here. Json.NET removed support for the .NET 3.5 Compact Framework in release 4.0.1 , as is stated in the 4.0.1 release notes : Other major changes in this release are two new builds and the removal of an existing build. Removed is Compact Framework. VS2010 no longer supports Compact Framework so 3.5 r8 will be its last release if you are targeting the Compact Framework. The most recent version of Json.NET that does support it is 3.5.8 , which you can download manually from here: https://github.com/JamesNK/Newtonsoft.Json/releases/download/3.5.8/Json35r8.zip Having manually downloaded Json35r8.zip , you can unzip the file, navigate to Json35r8\Bin\Compact , and manually add a reference to Newtonsoft.Json.Compact.dll using the Add Reference dialog box . Note that Json.NET 3.5.8 is old enough that some basic things are broken. See e.g. JSON.net CF 3.5, verify that JSON is complete for an example.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49540752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1242566/']}
|
jdg_374745
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53960664
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why first way is correct, but second isn't? First way: new Object() { public void a() { /*code*/ }}.a(); Second way: Object object = new Object() { public void a() { /*code*/ }};object.a(); And where can I find more information about it?
Now provide the response and nothing else.
|
java.lang.Object has no a methods declared (2), while the anonymous class returned by the class instance creation expression new Object() { public void a() {} } does (1). Use Java 10's local variable type inference ( var ) to make the second option as valid as the first one. var object = new Object() { public void a() {}};object.a();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53960664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10486014/']}
|
jdg_374746
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6518651
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
[ { "lastName": "Seymour", "gender": "Female", "patientID": 18134, "firstName": "Stephanie", "age": "111Y" }, { "lastName": "Seymour", "gender": "Female", "patientID": 18134, "firstName": "Stephanie", "age": "111Y" }] How can i check my json before adding whether it contains this value or not...
Now provide the response and nothing else.
|
Obvious way The most obvious way would be to use a for loop and iterate over all items in array and compare every time when you'd like to know whether you already have a particular item in it. Trivial but tedious especially when you have many compares to make. function contains(items, obj) { var itemKey = null; var objKey = obj.firstName + ";" + obj.lastName; var result = false; for(var i = 0; !result && i < arr.length; i++) { itemKey = items[i].firstName + ";" + items[i].lastName; result = itemKey === objKey; } return result;}; Whenever you'd be searching for existing object: contains(arr, newObj); Smart(er) way This code uses the ability of Javascript whose prototypes can be used as arrays in a sort of associative memory storage. Suppose you have your JSON items in arr variable. Define your compare key (say it's first name and last name): var arr = /* your JSON object */;var hash = (function() { var keys = {}; return { contains: function(key) { return keys[key] === true; }, add: function(key) { if (keys[key] !== true) { keys[key] = true; } } };})();var key = null;for (var i = 0; i < arr.length; i++){ key = arr[i].firstName + ";" + arr[i].lastName; if (!hash.contains(key)) { hash.add(key); }} Finding out whether you already have an item in your array is then pretty simple: hash.contains(key); And that's it. Much faster than iterating over the whole array. Especially when it has many items.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6518651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/733644/']}
|
jdg_374747
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4560372
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
when reading "Beyond the C++ Standard Library: An Introduction to Boost " ,I got a very interesting example: class A { public: virtual void sing()=0; protected: virtual ~A() {}; };class B : public A{ public: virtual void sing( ) { std::cout << "Do re mi fa so la"<<std::endl;; } }; and I do some testing: int main(){ //1 std::auto_ptr<A> a(new B); //will not compile ,error: ‘virtual A::~A()’ is protected//2A *pa = new B;delete pa; //will not compile ,error: ‘virtual A::~A()’ is protecteddelete (dynamic_cast<B*>(pa)); //ok//3 boost::shared_ptr<A> a(new B);//ok} what I am very curious here is how ~shared_ptr works?how it deduce the derived class B ? Thanks advance for your help! thanks all,I write a simple sample about how ~shared_ptr works class sp_counted_base{public: virtual ~sp_counted_base(){}};template<typename T>class sp_counted_base_impl : public sp_counted_base{public: sp_counted_base_impl(T *t):t_(t){} ~sp_counted_base_impl(){delete t_;}private: T *t_;};class shared_count{public: static int count_; template<typename T> shared_count(T *t): t_(new sp_counted_base_impl<T>(t)) { count_ ++; } void release() { --count_; if(0 == count_) delete t_; } ~shared_count() { release(); }private: sp_counted_base *t_;};int shared_count::count_(0);template<typename T>class myautoptr{public: template<typename Y> myautoptr(Y* y):sc_(y),t_(y){} ~myautoptr(){ sc_.release();}private: shared_count sc_; T *t_;};int main(){ myautoptr<A> a(new B);} the key is: template construct function the resource not deleted in ~shared_ptr ,it is deleted by shared_count
Now provide the response and nothing else.
|
Surprisingly, the key here is not boost::shared_ptr destructor but its constructor(s). If you look into boost/shared_ptr.hpp , you will see that shared_ptr<T> does not 'simply' have a constructor expecting a T * but : template<class Y>explicit shared_ptr( Y * p ); In //3 when you construct a boost::shared_ptr from a B * , no conversion to A * takes place, and the shared_ptr internals are built with the actual B type. Upon destruction of the object, deletion occurs on a B pointer (not through a base class pointer).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4560372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/440403/']}
|
jdg_374748
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8400530
|
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 java application that got SIG TERM . I want to know the pid of the process that sent this signal. Is that possible?
Now provide the response and nothing else.
|
Two Linux-specific methods are SA_SIGINFO and signalfd() , which allows programs to receive very detailed information about signals sent, including the sender's PID. Call sigaction() and pass to it a struct sigaction which has the desired signal handler in sa_sigaction and the SA_SIGINFO flag in sa_flags set. With this flag, your signal handler will receive three arguments, one of which is a siginfo_t structure containing the sender's PID and UID. Call signalfd() and read signalfd_siginfo structures from it (usually in some kind of a select/poll loop). The contents will be similar to siginfo_t . Which one to use depends on how your application is written; they probably won't work well outside plain C, and I wouldn't have any hope of getting them work in Java. They are also unportable outside Linux. They also likely are the Very Wrong Way of doing what you are trying to achieve.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8400530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411965/']}
|
jdg_374749
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2352672
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have seen this post, but my question is a bit different. Suppose $b_1,b_2\in G$ and $b_1\neq b_2^{-1}$. And suppose you have a subgroup $H\leq G$ and neither $b_1$ nor $b_2$ belong to $H$. Can $b_1b_2\in H$? So far I have just gone round in s circle and been rearranging without getting anywhere. I have tried proof by contradiction but again I get nowhere. It seems like either the above is true or I am missing some obvious step.
Now provide the response and nothing else.
|
This certainly can be true. If $H$ is a subgroup of index $2$, then it is necessarily true for any $b_1,b_2\not\in H$. (Example: in $\mathbb{Z}$, odd + odd = even ) Even if $H$ has index greater than $2$, it can be true. You only need that $b_1$ and $b_2$ belong to cosets of $H$ that are inverses in the quotient group.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2352672', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169507/']}
|
jdg_374750
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43014341
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The event passed to my Google cloud function only really tells me the name of the bucket and file, and whether the file was deleted. Yes, there's more there, but it doesn't seem all that useful: { timestamp: '2017-03-25T07:13:40.293Z', eventType: 'providers/cloud.storage/eventTypes/object.change', resource: 'projects/_/buckets/my-echo-bucket/objects/base.json#1490426020293545', data: { kind: 'storage#object', resourceState: 'exists', id: 'my-echo-bucket/base.json/1490426020293545', selfLink: 'https://www.googleapis.com/storage/v1/b/my-echo-bucket/o/base.json', name: 'base.json', bucket: 'my-echo-bucket', generation: '1490426020293545', metageneration: '1', contentType: 'application/json', timeCreated: '2017-03-25T07:13:40.185Z', updated: '2017-03-25T07:13:40.185Z', storageClass: 'STANDARD', size: '548', md5Hash: 'YzE3ZjUyZjlkNDU5YWZiNDg2NWI0YTEyZWZhYzQyZjY=', mediaLink: 'https://www.googleapis.com/storage/v1/b/my-echo-bucket/o/base.json?generation=1490426020293545&alt=media', contentLanguage: 'en', crc32c: 'BQDL9w==' } } How do I get the contents and not merely the meta-data of a new .json file uploaded to a gs bucket? I tried using npm:request() on event.data.selfLink , which is a URL for the file in the storage bucket, and got back an authorization error: "code": 401, "message": "Anonymous users does not have storage.objects.get access to object my-echo-bucket/base.json." There was a similar question on SO about reading storage buckets, but probably on a different platform. Anyway it was unanswered : How do I read the contents of a file on Google Cloud Storage using javascript `
Now provide the response and nothing else.
|
You need to use a client library for google storage instead of accessing via the URL. Using request() against the URL would only work if the file was exposed to public access. Import the google cloud storage library in the npm-managed directory containing your project. npm i @google-cloud/storage -S The npm page for google-cloud/storage has decent examples but I had to read through the API a bit to see an easy way to download to memory. Within the Google Cloud Functions environment, you do not need to supply any api key, etc. to storage as initialization. const storage = require('@google-cloud/storage')(); The metadata passed about the file can be used to determine if you really want the file or not. When you want the file, you can download it with the file.download function, which can take either a callback or, lacking a callback, will return a promise. The data however, is returned as a Buffer so you will need to call data.toString('utf-8') to convert it to a utf-8 encoded string. const storage = require('@google-cloud/storage')();exports.logNewJSONFiles = function logNewJSONFiles(event){ return new Promise(function(resolve, reject){ const file = event.data; if (!file){ console.log("not a file event"); return resolve(); } if (file.resourceState === 'not_exists'){ console.log("file deletion event"); return resolve(); } if (file.contentType !== 'application/json'){ console.log("not a json file"); return resolve(); } if (!file.bucket){ console.log("bucket not provided"); return resolve(); } if (!file.name){ console.log("file name not provided"); return resolve(); } (storage .bucket(file.bucket) .file(file.name) .download() .then(function(data){ if (data) return data.toString('utf-8'); }) .then(function(data){ if (data) { console.log("new file "+file.name); console.log(data); resolve(data); } }) .catch(function(e){ reject(e); }) ); });}; Deployment is as expected: gcloud beta functions deploy logNewJSONFiles --stage-bucket gs://my-stage-bucket --trigger-bucket gs://my-echo-bucket Remember to look in the Stackdriver:Logging page on Google Cloud Platform for the console.log entries. UPDATE: (2019) When cloud-functions first released, they had some issues with ECONNRESET . I think that's fixed now. If not, use something like npm:promise-retry
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43014341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103081/']}
|
jdg_374751
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3222125
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say we have the following string string data= "/temp string"; If we want to remove the first character / we can do by a lot of ways such as : data.Remove(0,1);data.TrimStart('/');data.Substring(1); But, really I don't know which one has the best algorithm and doing that faster.. Is there a one that is the best or all are the same ?
Now provide the response and nothing else.
|
The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo". The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable. (Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.) I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3222125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84216/']}
|
jdg_374752
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2656448
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have the sentence something about something WORD still something... what is the most efficient metod to delete the word " WORD " from sentence in php?thanks
Now provide the response and nothing else.
|
You could replace it with nothing: $sentence = str_replace('word', '', $sentence); Although that would also ruin words like swordfish , turning them into sfish . So you could put spaces around the edges: $sentence = str_replace(' word ', ' ', $sentence); But then it won't match words at the end and beginning of sentences. So you might have to use a regex: $sentence = preg_replace('/\bword\b/', '', $sentence); The \b is a word boundary, which could be a space or a beginning of a string or anything like that.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2656448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291772/']}
|
jdg_374753
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
366718
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I am running several fileservers using this controller, filesystem and disk setup. All of them are suffering from poor write performance, once the 256MB BBU Write Cache is full i get really high iowait (>40) and the write speed goes down to a few MB/s It get's even worse if the servers are encountering medium to heavy reads while writing. I am looking for suggestions on how to tweak the controller or the filesystem to improve write performance. Some data about the Raid Array and Controller: RAID Level: Primary-5, Secondary-0, RAID Level Qualifier-3Size:5.456 TBState: OptimalStripe Size: 64 KBNumber Of Drives:4Span Depth:1Default Cache Policy: WriteBack, ReadAdaptive, Cached, No Write Cache if Bad BBUCurrent Cache Policy: WriteBack, ReadAdaptive, Cached, No Write Cache if Bad BBUAccess Policy: Read/WriteDisk Cache Policy: EnabledEncryption Type: NoneProduct Name : PERC 6/i IntegratedFW Version : 1.22.12-0952BIOS Version : 2.04.00 Data about the filesystem: Filesystem features: has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize Default mount options are used and the filesystem was created using the default options of the mkfs.ext4 command. edit: Just to illustrate my use-case i will describe what these servers are doing They are serving files via lighttpd at 40-80 MB/s, new files are periodically being downloaded to the servers via ftp. The files are between 800MB and 6GB. Serving the files works great, without any noticable IOWait, but everytime the ftp transfers kick in to get new files you can see it really struggeling. as requested, here is the bonnie++ output: Version 1.96 ------Sequential Output------ --Sequential Input- --Random-Concurrency 1 -Per Chr- --Block-- -Rewrite- -Per Chr- --Block-- --Seeks--Machine Size K/sec %CP K/sec %CP K/sec %CP K/sec %CP K/sec %CP /sec %CPXXXXXXX 8G 580 99 94284 14 61903 9 2853 83 189033 11 420.5 8Latency 14004us 825ms 1548ms 105ms 202ms 98036usVersion 1.96 ------Sequential Create------ --------Random Create--------XXXXXXX -Create-- --Read--- -Delete-- -Create-- --Read--- -Delete-- files /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP /sec %CP 5 +++++ +++ +++++ +++ +++++ +++ +++++ +++ +++++ +++ +++++ +++Latency 406us 535us 598us 374us 21us 60us The disks in use are D-WMAY03176700WDC WD2002FAEX-007BA0 on all servers
Now provide the response and nothing else.
|
few random points: go raid 10 [ you will lose the data in the process ] mount all 'busy' filesystems with noatime option in fstab experiment with different io schedulers - check what works best for you your drives seem large-ish - most probably they have physical sector of 4KB rather than 512B - make sure your partitions are aligned to the disk & raid-stripe boundaries [ 1 , 2 ; you will lose data in the process ] i assume you have a lot of ram that is used for io buffers, if so - reconfigure your PERC/6i cache to be only for writes, no read ahead. benchmark write speed again - let's say it's X; throttle uploads to eg. 60% of X to leave 'spare' IO for reads.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/366718', 'https://serverfault.com', 'https://serverfault.com/users/107668/']}
|
jdg_374754
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1940846
|
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 written a C++ library that saves my data (a collection of custom structs etc) into a binary file. I currently use (i.e. create and consume ) the files locally, on my Windows (XP) machine. For simplicity, lets think of the library in two parts: a writer (Creates the files) and a reader or consumer (simply reads data from the files). Recently though, I would like to also consume (i.e. read) the data files I have created on my XP machine, on my Linux machine. I must point out at this stage that both machines are PCs (so have the same endianess etc). I can build a reader (and compile for Linux [Ubuntu 9.10 to be precise]), since I am the library creator. My question, before I embark down this road (of building the reader etc) is: Assuming I have succesfully built the reader for Linux, Can I simply copy accross, files that were created on the windows (XP) machine to the Linux (Ubuntu 9.10) machine and use the Linux reader to successfully read the copied over file?
Now provide the response and nothing else.
|
For the files to be binary compatible: endianness must match (as it does for you) bitfield packing order must be the same sizes and signedness of types must be the same the compiler must make the same decisions about padding and alignment It's certainly possible for all of these conditions to be fulfilled, or for you to not happen to be hitting any cases for which they are not. At the very least, though, I'd add some sanity checks and/or sentinel members to detect problems.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1940846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205040/']}
|
jdg_374755
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
88202
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be an $n \times n$ matrix. Are there formulas that convert linear combinations of traces of powers of $A$ to determinant of $A$ and vice versa from linear combinations of determinants of powers of $A$ to trace of $A$? (I am mainly looking for the latter - conversion of determinants to trace of $A$).
Now provide the response and nothing else.
|
You can find the determinant of a matrix $A$ of size $n$ in terms of the traces of $A^m$, for $m = 1, \ldots, n$. The trace of $A^m$ is the sum of the $m$th powers of the eigenvalues of $A$, and you can express the elementary symmetric polynomials (so in particular the product of the eigenvalues, which is the determinant) in terms of the power sums, see for example here . The converse is not possible. For example, the determinants of all powers of $\begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix}$ and of $\begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}$ are 1, but the traces are different.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/88202', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10035/']}
|
jdg_374756
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7599771
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently our company is using Team Foundation Server 2010, and we have quite a bit of source code in our repositories. Although I am not a big fan of TFS, we are still continuing to use it. I do have hope for TFS 11, but I wanted to know: what needs to be done to make the move from our current setup to the new TFS 11. Does it require us to reestablish our source code repository, or can we simply point the new TFS at our legacy repository. What are, if any, the best practices on migrating source code repositories.
Now provide the response and nothing else.
|
There will be an in-place upgrade wizard going from TFS 2010 to TFS 2012 & TFS 2013. It is also an upgrade going from 2012 RTM to Update 1 and Update 2, and beyond. More below** Here's how it will work: Go into Add/Remove programs Uninstall TFS 2010 - not required in 2012 RTM and beyond Run the install for TFS 2012 When the wizard launcher comes up, choose upgrade. Select your database (Tfs_Configuration) in the db picker, accept all the defaults, next, next. You're done. //Build conference CTP is out there so you can play with it. Since you're looking at 2012 TFS product, make sure you checkout the new TFS in the cloud. You can try it out @ http://tfs.visualstudio.com/ for free without deploying your own. EDIT: The team is working on a blog with step by step walkthrough here: http://elhajj.wordpress.com/ It's also included here: https://www.smashwords.com/books/view/181289 Note that when you go from 2012 RC to RTM (and beyond), the uninstall step will not be required. You just run the setup of the new version. EDIT: give it a shot. http://www.microsoft.com/visualstudio/11/en-us/downloads#tfs-group Also note the addition of the TFS Express sku which is a free version of TFS which uses SQL Express. 2013 preview is available. Same story. Here: http://www.microsoft.com/visualstudio/eng/2013-downloads ** TFS has gone to a cloud cadence where the service (tfs.visualstudio.com) is updated every 3 weeks. Those rollup into CTPs for shipping quarterly updates. So going to a quarterly update on-premise is an upgrade. Remember that it contains rolled up features from months of product development so you are doing a forward only upgrade of the DBs (backup and restore is going back). So, it's not a trivial patch - it's an event but you get the value and are closer to the cloud feature set.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7599771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180253/']}
|
jdg_374757
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1328
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Richard Carrier summarizes an argument made by Steve Mason in his book Josephus and the New Testament that Luke knew of Josephus' Jewish War (79 CE) and Jewish Antiquities (94 CE). At it's core, the argument stems from a similar purpose behind the writings of Josephus and the Luke–Acts history buttressed by general and specific parallels between the authors. Looking at the list of parallels, there don't seem to be any smoking guns. Any of them could arise because both men are telling the history of the same times and place. The strongest evidence seems to be the mentions of Judas the Galilean ( Acts 5:37 ; JW 2 , JA 18 ), Theudas ( Acts 5:36 ; JA 20 ), and "The Egyptian" ( Acts 21:38 ; JW 2 , JA 20 ). Mason makes a case for Luke misunderstanding the relevant history, which Josephus provides in greater detail. But the heart of the argument is that both Josephus and Luke made parallels between Greek schools of philosophy and Jewish sects in order to make either Judaism or Christianity palatable to Romans. Was this a tactic both authors could reasonably be expected to innovate separately?
Now provide the response and nothing else.
|
Carrier's thesis 1 is highly improbable. He overstates the similarities between Luke and Josephus, and ignores the possibility that the similarities that do exist could be the result of two historians writing as contemporaries. Carrier makes several claims in his conclusion. I'll discuss a few of them: Luke-Acts was written in the late 1st or early 2nd century Luke "almost certainly" knew the works of Josephus Luke found his basic historical framework in Josephus and "cut-and-pasted" it into Luke-Acts If Luke hadn't read Josephus, "an amazing series of coincidences remains in want of an explanation" Was Luke-Acts written in the late first or early second century? This claim is almost certainly true. A) The dating of the synoptic gospels is too complex to discuss here, but Luke was likely the third gospel to be published. In his preface Luke says he knows of other gospels, and the word-for-word agreement (with occasional editing) between his and the other synoptics indicates that he likely had copies of them available when composing his own gospel. B) The very earliest Christian writers after the New Testament era—Clement of Rome, Ignatius of Antioch, Polycarp—quote the gospels frequently. But when they do, they always quote/paraphrase Matthew or Mark, or material found in multiple synoptic gospels. Papias, a bishop in Hierapolis in the early second century, is the earliest to name Mark and Matthew as the authors of these two gospels. Irenaeus of Lyons, writing around 180, names all four gospel writers. So by the late 2nd century Luke's gospel had been circulated as far as France. By examining more evidence, it's possible to narrow the date further, but for the purposes of this question this is enough. Did Luke know the works of Josephus? It's hard to say. If Luke was written in the early 2nd century, it's possible he was familiar with Josephus. If Luke was written in the late 1st century, say between 80 and 100 AD, he would have been a contemporary of Josephus. He probably would not have had a copy of The Jewish War and certainly would not have had a copy of Antiquities of the Jews . Did Luke cut and paste material from Josephus into Acts? The ancient world had no copyright laws, so copying from another's work would not have had the negative connotations it has today. In fact, we can see examples of this by comparing Luke's gospel with Mark's. I've bolded word-for-word agreement within these passages, and italicized paraphrased material: Mark 9:2-8 NRSV Six days later, Jesus took with him Peter and James and John , and led them up a high mountain apart, by themselves. And he was transfigured before them , and his clothes became dazzling white , such as no one on earth could bleach them. And there appeared to them Elijah with Moses, who were talking with Jesus . Then Peter said to Jesus , " Rabbi , it is good for us to be here; let us make three dwellings, one for you, one for Moses, and one for Elijah ." He did not know what to say , for they were terrified. Then a cloud overshadowed them , and from the cloud there came a voice , " This is my Son, the Beloved ; listen to him! " Suddenly when they looked around, they saw no one with them any more, but only Jesus . Luke 9:28-36 NRSV Now about eight days after these sayings Jesus took with him Peter and John and James , and went up on the mountain to pray. And while he was praying, the appearance of his face changed , and his clothes became dazzling white . Suddenly they saw two men, Moses and Elijah, talking to him . They appeared in glory and were speaking of his departure, which he was about to accomplish at Jerusalem. Now Peter and his companions were weighed down with sleep; but since they had stayed awake, they saw his glory and the two men who stood with him. Just as they were leaving him, Peter said to Jesus , " Master , it is good for us to be here; let us make three dwellings, one for you, one for Moses, and one for Elijah "— not knowing what he said . While he was saying this, a cloud came and overshadowed them ; and they were terrified as they entered the cloud. Then from the cloud came a voice that said , " This is my Son , my Chosen ; listen to him! " When the voice had spoken, Jesus was found alone . And they kept silent and in those days told no one any of the things they had seen. It seems clear—and virtually all scholars today agree—that Luke knew the gospel of Mark, and used it as one of the sources he mentions in his prologue. However, if we compare Acts with Josephus regarding other messianic claimants, the correlation just isn't the same. Again I've bolded word-for-word agreement and italicized paraphrases. Jewish War 2 AND now Archelaus's part of Judea was reduced into a province, and Coponius, one of the equestrian order among the Romans, was sent as a procurator, having the power of [life and] death put into his hands by Caesar. Under his administration it was that a certain Galilean, whose name was Judas , prevailed with his countrymen to revolt , and said they were cowards if they would endure to pay a tax to the Romans and would after God submit to mortal men as their lords. This man was a teacher of a peculiar sect of his own, and was not at all like the rest of those their leaders. Acts 5:34-37 NRSV But a Pharisee in the council named Gamaliel, a teacher of the law, respected by all the people, stood up and ordered the men to be put outside for a short time. Then he said to them, "Fellow Israelites, consider carefully what you propose to do to these men. For some time ago Theudas rose up, claiming to be somebody, and a number of men, about four hundred, joined him; but he was killed, and all who followed him were dispersed and disappeared. After him Judas the Galilean rose up at the time of the census and got people to follow him ; he also perished, and all who followed him were scattered. Antiquities of the Jews 20 NOW it came to pass, while Fadus was procurator of Judea, that a certain magician, whose name was Theudas , persuaded a great part of the people to take their effects with them, and follow him to the river Jordan; for he told them he was a prophet, and that he would, by his own command, divide the river, and afford them an easy passage over it; and many were deluded by his words. However, Fadus did not permit them to make any advantage of his wild attempt, but sent a troop of horsemen out against them; who, falling upon them unexpectedly, slew many of them, and took many of them alive. They also took Theudas alive, and cut off his head , and carried it to Jerusalem. This was what befell the Jews in the time of Cuspius Fadus's government. Acts 5:34-36 NRSV But a Pharisee in the council named Gamaliel, a teacher of the law, respected by all the people, stood up and ordered the men to be put outside for a short time. Then he said to them, "Fellow Israelites, consider carefully what you propose to do to these men. For some time ago Theudas rose up, claiming to be somebody, and a number of men, about four hundred, joined him ; but he was killed , and all who followed him were dispersed and disappeared. Jewish War 2 But there was an Egyptian false prophet that did the Jews more mischief than the former; for he was a cheat, and pretended to be a prophet also, and got together thirty thousand men that were deluded by him; these he led round about from the wilderness to the mount which was called the Mount of Olives, and was ready to break into Jerusalem by force from that place; and if he could but once conquer the Roman garrison and the people, he intended to domineer over them by the assistance of those guards of his that were to break into the city with him. Acts 21:37-38 NRSV Just as Paul was about to be brought into the barracks, he said to the tribune, "May I say something to you?" The tribune replied, "Do you know Greek? Then you are not the Egyptian who recently stirred up a revolt and led the four thousand assassins out into the wilderness?" Antiquities of the Jews 20 Moreover, there came out of Egypt about this time to Jerusalem one that said he was a prophet, and advised the multitude of the common people to go along with him to the Mount of Olives, as it was called, which lay over against the city, and at the distance of five furlongs . He said further, that he would show them from hence how, at his command, the walls of Jerusalem would fall down; and he promised them that he would procure them an entrance into the city through those walls, when they were fallen down. Now when Felix was informed of these things, he ordered his soldiers to take their weapons, and came against them with a great number of horsemen and footmen from Jerusalem, and attacked the Egyptian and the people that were with him. He also slew four hundred of them, and took two hundred alive. But the Egyptian himself escaped out of the fight, but did not appear any more. And again the robbers stirred up the people to make war with the Romans, and said they ought not to obey them at all; and when any persons would not comply with them, they set fire to their villages, and plundered them. Acts 21:37-38 NRSV Just as Paul was about to be brought into the barracks, he said to the tribune, "May I say something to you?" The tribune replied, "Do you know Greek? Then you are not the Egyptian who recently stirred up a revolt and led the four thousand assassins out into the wilderness ?" It's hard to make the case that Luke had read Josephus, after we've seen how Luke works with material that he is familiar with. While Carrier's claim can't be dismissed entirely, a connection between Luke and Josephus does not appear to be likely, and is definitely not "almost certain". Are similarities between Luke-Acts and Josephus coincidence? Despite the lack of word-for-word agreement between Luke and Josephus, some similarities do exist, including some not mentioned by Carrier. The Acts passage we looked at above portrays Rabbi Gamaliel, a Pharisee, in a good light. Josephus, in his autobiography speaks highly of a Pharisee, in fact none other than Simon son of Gamaliel. This is not the only positive treatment of Pharisees in Luke's work. A number of times in Luke's gospel, Jesus is reported to have eaten at the homes of Pharisees (See 7:36 and 11:37 ). Both Matthew and Mark, in the parallel passages, go to great lengths to omit this information. Luke 13:31 some Pharisees come to Jesus to warn him that Herod wants to kill him. 2 According to The image of the Judaeo-Christians in ancient Jewish and Christian literature by Doris Lambers-Petry: Steve Mason has established that as distinct from the Jewish War, Josephus' later works display a clear sympathy for the Pharisees. A somewhat similar sympathy is found in Luke's works, in roughly the same period. Rather than give in to speculative theories of dependence, we must think of a common setting, which in view of the prominent patrons both authors mention in their dedications apparently had to do with influential circles in Rome. In this setting they both took care to portray the Pharisees and especially their influential representatives in a positive daylight. If Luke and Josephus were contemporaries, they would have had access to the same sources, thus the appearance of the same characters should not be a surprise. Therefore Carrier is probably right that any similarities are not a coincidence. But the very different way the two authors treat these characters suggests that they were probably not familiar with each other's work. 1 Steve Mason begins his chapter on Josephus and Luke-Acts by acknowledging, regarding the notions that Luke borrowed from Josephus or that Josephus borrowed from Luke, "Neither position has much of a following today, because of the significant differences between the two works in their accounts of the same events." ( Josephus and the New Testament , p. 251) But after reviewing the breadth of events mentioned in both Josephus and Luke, and noting that no other writings from the first century even come close to covering all these events, Mason concludes, "I find it easier to believe that Luke knew something of Josephus' work than that he independently arrived at these points of agreement. Nevertheless, further study may provide alternatives." (p. 293) Mason also concedes that the dating is a bit tricky, since most scholars consider Luke-Acts to have been written before Josephus' Antiquities of the Jews . In response Mason suggests, "Luke may have heard an earlier version or only a part of the work recited, perhaps in 90 or so." (p. 293) But even this pushes Luke to the very late end of the range considered by mainstream scholars today. Ultimately, Mason's conclusion exhibits a much greater uncertainty than Carrier's summary admits. 2 John's gospel, almost universally agreed to be the last written, also contains a positive story about a Pharisee , Nicodemus, who came to Jesus at night for instruction. A fragment of John's gospel has been found which dates to about 125 AD, which virtually forces us to date the original in the first century. This adds support to the positive-mention-of-Pharisees-in-the-late-first-century hypothesis.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/1328', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/68/']}
|
jdg_374758
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41215365
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Thanks to David Beazley's tweet , I've recently found out that the new Python 3.6 f-strings can also be nested: >>> price = 478.23>>> f"{f'${price:0.2f}':*>20s}"'*************$478.23' Or: >>> x = 42>>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-''''-*+.42.+*-' While I am surprised that this is possible, I am missing on how practical is that, when would nesting f-strings be useful? What use cases can this cover? Note: The PEP itself does not mention nesting f-strings, but there is a specific test case .
Now provide the response and nothing else.
|
I don't think formatted string literals allowing nesting (by nesting, I take it to mean f'{f".."}' ) is a result of careful consideration of possible use cases, I'm more convinced it's just allowed in order for them to conform with their specification. The specification states that they support full Python expressions * inside brackets. It's also stated that a formatted string literal is really just an expression that is evaluated at run-time (See here , and here ). As a result, it only makes sense to allow a formatted string literal as the expression inside another formatted string literal, forbidding it would negate the full support for Python expressions. The fact that you can't find use cases mentioned in the docs (and only find test cases in the test suite) is because this is probably a nice (side) effect of the implementation and not it's motivating use-case. Actually, with two exceptions: An empty expression is not allowed, and a lambda expression must be surrounded by explicit parentheses.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41215365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/771848/']}
|
jdg_374759
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9012529
|
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 vbscript that is used to rename files. What I need to implement into the script is something that deletes the "new file" if it already exists. For example: I have a batch of files that are named like this 11111111.dddddddd.pdf where the files get renamed to 11111111.pdf. The problem is that when I rename to the 11111111.pdf format I end of with files that are duplicated and then makes the script fail because you obviously cant have 2 files with the same name. I need it to rename the first one but then delete the others that are renamed the same. Here is what I have so far for my IF statement but it doesnt work and I get and error that says "Type mismatch: 'FileExists". I am not sure how to get this part of the code to execute the way I would like. Any help or suggestions would be greatly appreciated. dim infolder: set infolder = fso.GetFolder(IN_PATH)dim filefor each file in infolder.filesdim name: name = file.namedim parts: parts = split(name, ".")dim acct_, date_acct_ = parts(0)date_ = parts(1)' file format of a.c.pdfif UBound(parts) = 2 then ' rebuild the name with the 0th and 2nd elements dim newname: newname = acct_ & "." & parts(2) ' use the move() method to effect the rename file.move fso.buildpath(OUT_PATH, newname) if newname = FileExists(file.name) Then newname.DeleteFile() end if end ifnext 'file
Now provide the response and nothing else.
|
You're close, you just need to delete the file before trying to over-write it. dim infolder: set infolder = fso.GetFolder(IN_PATH)dim file: for each file in infolder.Files dim name: name = file.name dim parts: parts = split(name, ".") if UBound(parts) = 2 then ' file name like a.c.pdf dim newname: newname = parts(0) & "." & parts(2) dim newpath: newpath = fso.BuildPath(OUT_PATH, newname) ' warning: ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ... ' only one of them will be saved as D:\OUT_PATH\ABC.PDF if fso.FileExists(newpath) then fso.DeleteFile newpath end if file.Move newpath end ifnext
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9012529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/890457/']}
|
jdg_374760
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7227510
|
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 populating a DropDownList from a SQL Server database as shown below. It works fine, but I'm not sure it's a good way. Can someone shed some light on this method, and give some improvements? private void LoadSubjects(){ ddlSubjects.Items.Clear(); string selectSQL = "SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(selectSQL, con); SqlDataReader reader; try { ListItem newItem = new ListItem(); newItem.Text = "<Select Subject>"; newItem.Value = "0"; ddlSubjects.Items.Add(newItem); con.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { newItem = new ListItem(); newItem.Text = reader["SubjectName"].ToString(); newItem.Value = reader["SubjectID"].ToString(); ddlSubjects.Items.Add(newItem); } reader.Close(); } catch (Exception err) { //TODO } finally { con.Close(); }}
Now provide the response and nothing else.
|
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc). For example, if you wanted to use a DataTable: ddlSubject.DataSource = subjectsTable;ddlSubject.DataTextField = "SubjectNamne";ddlSubject.DataValueField = "SubjectID";ddlSubject.DataBind(); EDIT - More complete example private void LoadSubjects(){ DataTable subjects = new DataTable(); using (SqlConnection con = new SqlConnection(connectionString)) { try { SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con); adapter.Fill(subjects); ddlSubject.DataSource = subjects; ddlSubject.DataTextField = "SubjectNamne"; ddlSubject.DataValueField = "SubjectID"; ddlSubject.DataBind(); } catch (Exception ex) { // Handle the error } } // Add the initial item - you can add this even if the options from the // db were not successfully loaded ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));} To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true: <asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true"> <asp:ListItem Text="<Select Subject>" Value="0" /></asp:DropDownList> You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove: ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0")); from the code-behind, or you'll have two "" items.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7227510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94169/']}
|
jdg_374761
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46013418
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a system call and in case it fails, I need to do different things for different errnos. I need to write code that looks something like this: int res;res = systemCall();if (res == -1){ if (errno == ENOMSG) { doSomething(); } else { doSomethingElse(); }} perror doesn't help, because it only prints the value. As for strerro - if it is what I need, I am not suer how to use it, because here it says that the actual string is not the same as the error. Quote from the man page: "(For example, if errnum is EINVAL, the returned description will be "Invalid argument")". I am using Linux.System calls: msgsend and msgrcv ( https://linux.die.net/man/2/msgrcv ). I am not sure what C libraries you are asking about. I see I didn't explain myself well. Is the statement if (errno == ENOMSG) valid? Is there such a variable errno? Basically my question is: What should go in the if statement in order to test the errno?
Now provide the response and nothing else.
|
I assume you are using Linux, and I suppose that you don't directly use the system call, but some of the (simple) wrappers (from your C library) listed in syscalls(2) . Notice that some weird system calls are not wrapped by the C library (a well known example of unwrapped system call would be sigreturn(2) which you probably should never use). Quite often the C library is GNU glibc , but it might be musl-libc etc. Notice also that kernel raw system calls have different calling conventions than ordinary C function (so in practice a libc wrapper is required, and is in charge of dealing with errno ). Notice also that errno(3) is generally a macro (almost behaving as some variable). The msgrcv(2) man page documents that errno could be one of E2BIG , EACCES , EFAULT ... ENOMSG , ENOSYS ... (refer to that man page to get the list of all possible errors). So you would code something like ssize_t siz = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg);if (siz<0) { // msgrcv failed and has set errno if (errno == ENOMSG) dosomething(); else if (errno == EAGAIN) dosomethingelse(); /// etc else { syslog(LOG_DAEMON|LOG_ERR, "msgrcv failure with %s\n", strerror(errno)); exit(EXIT_FAILURE); };}; Is the statement if (errno == ENOMSG) .... valid? Yes it is; you want to test errno only after some system call failure (e.g. when siz<0 ). Is there such a variable errno ? Not any more. Please read carefully errno(3) documentation. You should not declare extern int errno; (this was possible in the 1980s, not in 21 st century) but you should always #include <errno.h> and use errno as if it was a variable, but it is almost always some macro (whose definition appears in /usr/include/bits/errno.h which is included by /usr/include/errno.h ). BTW, SysV-style facilities tend to become obsolete and are not always available. I recommend using POSIX message queues facilities, read mq_overview(7) . You might want to read the freely downloadable Advanced Linux Programming (an old book; you can buy something better & newer) and/or all the man pages reachable from intro(2) & syscalls(2) & intro(3) .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46013418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7449638/']}
|
jdg_374762
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24645113
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I increment a variable in a PowerShell function? I'm using the below example without any data to be input to the function. I want to increment a variable every time a function is called. The variable $incre has 1 added to it and then displays the total of $incre when the script completes. The total when running the below is 0, whereas the result I want is 4 as the function comparethis has been run 4 times and each time $incre has been incremented by 1. $incre = 0 function comparethis() { # Do this comparison $incre++ Write-Host $incre } comparethis #compare 2 variables comparethis #compare 2 variables comparethis #compare 2 variables comparethis #compare 2 variables Write-Host "This is the total $incre"
Now provide the response and nothing else.
|
You are running into a dynamic scoping issue. See about_scopes . Inside the function $incre is not defined so it is copied from the global scope. The global $incre is not modified. If you wish to modify it you can do the following. $incre = 0function comparethis() { #Do this comparison $global:incre++ Write-Host $global:incre}comparethis #compare 2 variablescomparethis #compare 2 variablescomparethis #compare 2 variablescomparethis #compare 2 variablesWrite-Host "This is the total $incre"
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24645113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3175140/']}
|
jdg_374763
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20834838
|
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 use tuple consisting of int , char , char in my unordered_map . I am doing like this: #include <string>#include <unordered_map>#include <cstring>#include <iostream>#include <tuple>using namespace std;tuple <int,char,char> kk;unordered_map<kk,int> map;int main(){ map[1,"c","b"]=23; return 0;} but this gives me following errors: map.cpp:9:21: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map’map.cpp:9:21: error: expected a type, got ‘kk’map.cpp:9:21: error: template argument 3 is invalidmap.cpp:9:21: error: template argument 4 is invalidmap.cpp:9:21: error: template argument 5 is invalidmap.cpp:9:26: error: invalid type in declaration before ‘;’ tokenmap.cpp: In function ‘int main()’:map.cpp:14:16: error: assignment of read-only location ‘"b"[map]’ What I am doing wrong in this?
Now provide the response and nothing else.
|
The template arguments for an unordered_map looks like this: template< class Key, class T, class Hash = std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator< std::pair<const Key, T> >> class unordered_map; std::hash is not specialized for tuples (scroll down to Standard specializations for library types). Therefore you need to provide your own, something like this: typedef std::tuple<int, char, char> key_t;struct key_hash : public std::unary_function<key_t, std::size_t>{ std::size_t operator()(const key_t& k) const { return std::get<0>(k) ^ std::get<1>(k) ^ std::get<2>(k); }};// ..snip..typedef std::unordered_map<const key_t,data,key_hash,key_equal> map_t;// ^ this is our custom hash And finally, as Benjamin Lindley answer already addresses, you need to use std::make_tuple : // d is datam[std::make_tuple(1, 'a', 'b')] = d;auto itr = m.find(std::make_tuple(1, 'a', 'b')); The code was grabbed from Using a std::tuple as key for std::unordered_map and here is the Live Example .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20834838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1170920/']}
|
jdg_374764
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2740939
|
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 transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example: class Node{ ...}...Node *node1 = malloc(sizeof(Node)); //mallocNode *node2 = new Node; //new Which one should I use?
Now provide the response and nothing else.
|
Use new . You shouldn't need to use malloc in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way. Your example of node = malloc(sizeof(Node)) is a bad idea, because the constructor of Node (if any exists) would not be called, and a subsequent delete node; would have undefined results. If you need a buffer of bytes, rather than an object, you'll generally want to do something like this: char *buffer = new char[1024]; or, preferably, something like this: std::vector<char> buffer(1024); Note that for the second example (using std::vector<> ), there is no need to delete the object; its memory will automatically be freed when it goes out of scope. You should strive to avoid both new and malloc in C++ programs, instead using objects that automatically manage their own memory.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2740939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200477/']}
|
jdg_374765
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3542449
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example, my $str = '中國c'; # Chinese language of china I want to print out the numeric values 20013,22283,99
Now provide the response and nothing else.
|
unpack will be more efficient than split and ord , because it doesn't have to make a bunch of temporary 1-character strings: use utf8;my $str = '中國c'; # Chinese language of chinamy @codepoints = unpack 'U*', $str;print join(',', @codepoints) . "\n"; # prints 20013,22283,99 A quick benchmark shows it's about 3 times faster than split+ord : use utf8;use Benchmark 'cmpthese';my $str = '中國中國中國中國中國中國中國中國中國中國中國中國中國中國c';cmpthese(0, { 'unpack' => sub { my @codepoints = unpack 'U*', $str; }, 'split-map' => sub { my @codepoints = map { ord } split //, $str }, 'split-for' => sub { my @cp; for my $c (split(//, $str)) { push @cp, ord($c) } }, 'split-for2' => sub { my $cp; for my $c (split(//, $str)) { $cp = ord($c) } },}); Results: Rate split-map split-for split-for2 unpacksplit-map 85423/s -- -7% -32% -67%split-for 91950/s 8% -- -27% -64%split-for2 125550/s 47% 37% -- -51%unpack 256941/s 201% 179% 105% -- The difference is less pronounced with a shorter string, but unpack is still more than twice as fast. ( split-for2 is a bit faster than the other splits because it doesn't build a list of codepoints.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3542449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365256/']}
|
jdg_374766
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42173350
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are loops synchronous or asynchronous in JavaScript? (for, while, etc) Supposing I have: for(let i=0; i<10; i++){ // A (nested stuff...)}// B ... Using for the execution of B will start before A sometimes... (so asynchronous) Is there a way to use statements in a synchronous way?
Now provide the response and nothing else.
|
The for loop runs immediately to completion while all your asynchronous operations are started. Well, here we have some nested loops. Notice, "BBB" always fires after. for(let i=0; i<10; i++){ for(let i=0; i<10; i++){ for(let i=0; i<10; i++){ console.log("AA") } }}console.log('BBB') now, look at this for(let i=0; i<10; i++){ setTimeout(function() {console.log("AA")}, 2000)}console.log('BBB') This is because of something called the "event loop". And the fact that with that setTimeout we are simulating an async operation. It could be an ajax call or some other async process. Check this out: http://latentflip.com/loupe This will really help you understand these sorts of async/sync loop topics. updated to show how promises might work here (given comments below): var stringValues = ['yeah', 'noooo', 'rush', 'RP'];var P = function(val, idx){ return new Promise(resolve => setTimeout(() => resolve(val), 1000 * idx));};// We now have an array of promises waiting to be resolved.// The Promise.all basically will resolve once ALL promises are // resolved. Keep in mind, that if at any time something rejects// it stops// we iterator over our stringValues array mapping over the P function, // passing in the value of our array.var results = Promise.all(stringValues.map(P));// once all are resolved, the ".then" now fires. It is here we would do results.then(data => console.log(data) //["yeah", "noooo", "rush", "RP"]); let me know if I am not clear enough.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42173350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5638869/']}
|
jdg_374767
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
236772
|
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 statement cannot be proven in $\mathsf{ZFC}$: (S) : If $A, B$ are sets with $|A| < |B|$, then $2^{|A|} = |{\cal P}(A)| < |{\cal P}(B)| = 2^{|B|}$. Obviously, $\mathsf{GCH}$ implies (S). Does (S) imply $\mathsf{GCH}$ too?
Now provide the response and nothing else.
|
No, take Merimovich's model in which $2^\kappa=\kappa^{+3}$ for all cardinals $\kappa.$ Merimovich, Carmi A power function with a fixed finite gap everywhere . J. Symbolic Logic 72 (2007), no. 2, 361–417. Let me add that the statement "the power function is injective" is known as weak GCH, which has important applications. See Why the weak GCH is true! .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/236772', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
|
jdg_374768
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43167317
|
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 name of the user after su in a bash script. I used the following code: user=`who am i`#user <- "user4035 pts/0 2017-04-02 05:13 (my-hostname)"userarray=($user)#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]user=${userarray[0]}#outputs "user4035"echo $user It works correctly, but is it possible to achieve the same result with less number of commands?
Now provide the response and nothing else.
|
Use bash parameter-expansion without needing to use arrays, myUser=$(who am i)printf "%s\n" "${myUser%% *}"user4035 (or) just use a simple awk , command, who am i | awk '{print $1}'user4035 i.e. in a variable do, myUser=$(who am i | awk '{print $1}')printf "%s\n" "$myUser" (or) if your script is run with sudo privileges, you can use this bash environment-variable, printf "%s\n" "${SUDO_USER}"
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43167317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/789186/']}
|
jdg_374769
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
383402
|
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 another question , a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new . I didn't believe that was true, mostly because I've used Prototype , Script.aculo.us and other excellent JavaScript libraries, and everyone of them used the new keyword. In spite of that, yesterday I was watching Douglas Crockford's talk at YUI theater and he said the exactly same thing, that he didn't use the new keyword anymore in his code ( Crockford on JavaScript - Act III: Function the Ultimate - 50:23 minutes ). Is it 'bad' to use the new keyword? What are the advantages and disadvantages of using it?
Now provide the response and nothing else.
|
Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times. Use of the functionality provided by the new keyword has several advantages over building each object from scratch: Prototype inheritance . While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory. And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself: function foo(){ // if user accidentally omits the new keyword, this will // silently correct the problem... if ( !(this instanceof foo) ) return new foo(); // constructor logic follows...} Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja , which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick). A general-purpose sanity check You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception: if ( !(this instanceof arguments.callee) ) throw new Error("Constructor called as a function"); Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification. ES5 taketh away As Sean McMillan , stephenbez and jrh noted, the use of arguments.callee is invalid in ES5's strict mode . So the above pattern will throw an error if you use it in that context. ES6 and an entirely harmless new ES6 introduces Classes to JavaScript - no, not in the weird Java-aping way that old-school Crockford did, but in spirit much more like the light-weight way he (and others) later adopted, taking the best parts of prototypal inheritance and baking common patterns into the language itself. ...and part of that includes a safe new : class foo{ constructor() { // constructor logic that will ONLY be hit // if properly constructed via new } }// bad invocationfoo(); // throws, // Uncaught TypeError: class constructors must be invoked with 'new' But what if you don't want to use the new sugar? What if you just want to update your perfectly fine old-style prototypal code with the sort of safety checks shown above such that they keep working in strict mode? Well, as Nick Parsons notes , ES6 provides a handy check for that as well, in the form of new.target : function foo(){ if ( !(new.target) ) throw new Error("Constructor called as a function"); // constructor logic follows...} So whichever approach you choose, you can - with a bit of thought and good hygiene - use new without harm.
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/383402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7595/']}
|
jdg_374770
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20042952
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I execute my code below, this error message occurs: "An exception of type 'System.Data.SqlClient.SqlException' occurred inSystem.Data.dll but was not handled in user code Additional information: Incorrect syntax near '='. " And this is the code: string position;SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; ");con.Open();SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=" + id.Text, con);SqlDataReader Read = cmd.ExecuteReader();if (Read.Read()==true){ position = Read[0].ToString(); Response.Write("User Registration successful");}else{ Console.WriteLine("No Employee found.");}Read.Close(); What is causing this, and how can I resolve it?
Now provide the response and nothing else.
|
There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework: var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);cmd.Parameters.AddWithValue("@id", id.Text); Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar : var name = cmd.ExecuteScalar();if (name != null){ position = name.ToString(); Response.Write("User Registration successful");}else{ Console.WriteLine("No Employee found.");} The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of: string position;using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; ")){ con.Open(); using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con)) { cmd.Parameters.AddWithValue("@id", id.Text); var name = cmd.ExecuteScalar(); if (name != null) { position = name.ToString(); Response.Write("User Registration successful"); } else { Console.WriteLine("No Employee found."); } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20042952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2621133/']}
|
jdg_374771
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3106862
|
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 USB Joystick, and I want to write my own HID driver for it. Notably I want to inject delay between when the joystick input is received by Windows and when my application is notified of that input event. I would also like to change the identity of the joystick percieved by my application. I have never written a driver, let alone an HID driver, for Windows. Can anyone provide me with advice or pointers on how to go about doing this?
Now provide the response and nothing else.
|
When you press knobs on the Joystick the electric signals reach the operating system (and onto the game) in the form of IRP's through the drivers chain. Intercepting these IRP's at some point and delaying the forwarding to the next driver can delay the joystick input. This can be achieved with driver filters . To write windows drivers you need to use WinDDK . The entrypoint of a windows driver is the DriverEntry function . In this function you will be hooking what IRP's you want to intercept and the callback functions that deal with them, in our case, the callback functions that delay the forwarding. For example, say our IRP to be delayed is IRP_MJ_READ and our callback function is called CallbackDelayForwarding : // the function that delays the IRPNTSTATUS CallbackDelayForwarding( IN PDEVICE_OBJECT pDeviceObject, IN PIRP pIrp){ // delay the forwarding}// this is the driver entrypoint, similar to "main" in user-mode executablesNTSTATUS DriverEntry( IN PDRIVER_OBJECT pDriverObject, IN PUNICODE_STRING RegistryPath ){ pDriverObject->MajorFunction[IRP_MJ_READ] = CallbackDelayForwarding; ...} To delay the forwarding inside CallbackDelayForwarding , you must use functions from the KeInitializeTimer family to simulate some sort of sleep (maybe in conjunction with locks), KeDelayExecutionThread etc. To install your filter driver in the joystick driver chain, you can use .inf files . Check the toaster filter driver sample in the WinDDK, you can find it at INSTALL_DIR/src/general/toaster/ see also here . Related links: http://www.rootkit.com/newsread.php?newsid=187 http://www.techtalkz.com/microsoft-device-drivers/269654-toaster-filter-driver.html
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3106862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212215/']}
|
jdg_374772
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2468410
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
data GroceryItem = CartItem ItemName Price Quantity | StockItem ItemName Price QuantitymakeGroceryItem :: String -> Float -> Int -> GroceryItemmakeGroceryItem name price quantity = CartItem name price quantityI want to create a `GroceryItem` when using a `String` or `[String]`createGroceryItem :: [String] -> GroceryItemcreateGroceryItem (a:b:c) = makeGroceryItem a b c The input will be in the format ["Apple","15.00","5"] which I broke up using Haskell's words function. I get the following error which I think is because makeGroceryItem accepts a Float and an Int . *Type error in application*** Expression : makeGroceryItem a read b read c*** Term : makeGroceryItem*** Type : String -> Float -> Int -> GroceryItem*** Does not match : a -> b -> c -> d -> e -> f* But how do I make b and c of type Float and Int , respectively?
Now provide the response and nothing else.
|
read can parse a string into float and int: Prelude> :set +tPrelude> read "123.456" :: Float123.456it :: FloatPrelude> read "123456" :: Int123456it :: Int But the problem (1) is in your pattern: createGroceryItem (a:b:c) = ... Here : is a (right-associative) binary operator which prepends an element to a list. The RHS of an element must be a list. Therefore, given the expression a:b:c , Haskell will infer the following types: a :: Stringb :: Stringc :: [String] i.e. c will be thought as a list of strings. Obviously it can't be read or passed into any functions expecting a String. Instead you should use createGroceryItem [a, b, c] = ... if the list must have exactly 3 items, or createGroceryItem (a:b:c:xs) = ... if ≥3 items is acceptable. Also (2), the expression makeGroceryItem a read b read c will be interpreted as makeGroceryItem taking 5 arguments, 2 of which are the read function. You need to use parenthesis: makeGroceryItem a (read b) (read c)
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2468410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286204/']}
|
jdg_374773
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9989731
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a function in that uses binary search, like lower_bound but that returns the last item less-than-or-equal-to according to a given predicate? lower_bound is defined to: Finds the position of the first element in an ordered range that has a value greater than or equivalent to a specified value, where the ordering criterion may be specified by a binary predicate. and upper_bound : Finds the position of the first element in an ordered range that has a value that is greater than a specified value, where the ordering criterion may be specified by a binary predicate. Specifically, I have a container of time ordered events and for a given time I want to find the last item that came before or at that point. Can I achieve this with some combination of upper/lower bound, reverse iterators and using std::greater or std::greater_equal ? EDIT: A tweak was needed to user763305's suggestion to cope with if you ask for a point before the start of the array: iterator it=upper_bound(begin(), end(), val, LessThanFunction());if (it!=begin()) { it--; // not at end of array so rewind to previous item} else { it=end(); // no items before this point, so return end()}return it;
Now provide the response and nothing else.
|
In a sorted container, the last element that is less than or equivalent to x , is the element before the first element that is greater than x . Thus you can call std::upper_bound , and decrement the returned iterator once.(Before decrementing, you must of course check that it is not the begin iterator; if it is, then there are no elements that are less than or equivalent to x .)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9989731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188414/']}
|
jdg_374774
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2136603
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicates: Using the using statment in c# What is the C# Using block and why should I use it? Just wondering what this means? I've seen lots of tutorials online that have the syntax: using (SqlCeCommand cmd2 = new SqlCeCommand("SELECT city FROM cities JOIN states ON states.id=cities.state WHERE states.state='" + read.GetString(0) + "'", con)){ SqlCeDataReader readCities = cmd2.ExecuteReader(); while (readCities.Read()) { parent.Nodes.Add(readCities.GetString(0)); }} Why is it used? I tried searching Google, but it comes up with the 'using' keyword which is used for including dll's and other files.
Now provide the response and nothing else.
|
The using statement using(var disposableObject = new object_that_implements_IDisposable()) { ... } is syntactic sugar for code similar to following: var disposableObject = new object_that_implements_IDisposable()try{ ...}finally{ if(disposableObject != null) { ((IDisposable)your_object).Dispose(); }} This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system. In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)! As to why you'd use using over try / finally , it is purely a coder's preference. I prefer using because you can cascade them: using(var a = new class())using(var b = new class())using(var c = new class())using(var d = new class()){ ...} You'd need quite a few more lines of code to do that with try / finally . using has additional advantages as well. For example, whereas calling x.Dispose directly might throw a NullReferenceException if x is null, using(x) will not. See also: Link Using the using statement in C# What is the C# Using block and why should I use it? http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2136603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256409/']}
|
jdg_374775
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30650343
|
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 I'm making a game in which I am dropping objects which have to be destroyed by a spike(triangle) at the bottom of the screen by a user. I cannot work out how to make a UIView that is a triangle. However I have been able to make it work as a rectangle like this: let barrier = UIView(frame: CGRect(x:125, y: 650, width: 130, height:20)) barrier.backgroundColor = UIColor.orangeColor() view.addSubview(barrier) And this has worked. But I cannot work out how to make a triangle. The reason I want it as a UIView is because im using collisions on it and for the user to move it. I have tried a PNG triangle but it detects the collision as the border of the image not the start of the triangle. I have tried this but it doesn't work... let square = UIView(frame: CGPathMoveToPoint(path, nil, 50, 0), CGPathAddLineToPoint(path, nil, 100, 50), CGPathAddLineToPoint(path, nil, 0, 100)) square.backgroundColor = UIColor.purpleColor() view.addSubview(square) Any and all help will be appreciated, Thanks, Alex
Now provide the response and nothing else.
|
Updated for Swift 3 : class TriangleView : UIView { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.beginPath() context.move(to: CGPoint(x: rect.minX, y: rect.maxY)) context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY)) context.closePath() context.setFillColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 0.60) context.fillPath() }} Swift 2 : import UIKitclass TriangleView : UIView { override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawRect(rect: CGRect) { var ctx : CGContextRef = UIGraphicsGetCurrentContext() CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)) CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect)) CGContextAddLineToPoint(ctx, (CGRectGetMaxX(rect)/2.0), CGRectGetMinY(rect)) CGContextClosePath(ctx) CGContextSetRGBFillColor(ctx, 1.0, 0.5, 0.0, 0.60); CGContextFillPath(ctx); } } This will start from MinX, MaxY; Draw a line from the start to MaxX, MaxY; Draw a line from MaxX,MaxY to MaxX/2, MinY; Then close the path to the start location. The next part sets the color you want to use. In this example 255,127,0, Alpha 0.6Then will fill the path you just drew above with the set color. Then in your View Controller Swift 3 : class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let triangle = TriangleView(frame: CGRect(x: 10, y: 20, width: 25 , height: 30)) triangle.backgroundColor = .white view.addSubview(triangle) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }} Swift 2 : class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let triangle = TriangleView(frame: CGRectMake(10, 20, 25, 30)) triangle.backgroundColor = .whiteColor() view.addSubview(triangle) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }} However, this is going to cause the same problem as the frame of this view is still going to be a rectangle. UIKit works with rectangles, you would have to use another framework, like Sprite Kit.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30650343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4138917/']}
|
jdg_374776
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18248287
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For now, I just know how to copy file using: IStorageFolder dir = Windows.Storage.ApplicationData.Current.LocalFolder;IStorageFile file = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///file.txt"));await file.CopyAsync(dir, "file.txt"); When I try to copy folder and all the content inside, I cannot find the API like CopyAsync above. Is it possible to copy folder and all the content in WinRT?
Now provide the response and nothing else.
|
Code above didn't satisfy me (too specific), i made my own generic one so figured i could share it : public static async Task CopyFolderAsync(StorageFolder source, StorageFolder destinationContainer, string desiredName = null) { StorageFolder destinationFolder = null; destinationFolder = await destinationContainer.CreateFolderAsync( desiredName ?? source.Name, CreationCollisionOption.ReplaceExisting); foreach (var file in await source.GetFilesAsync()) { await file.CopyAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting); } foreach (var folder in await source.GetFoldersAsync()) { await CopyFolderAsync(folder, destinationFolder); } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18248287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1159948/']}
|
jdg_374777
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13602965
|
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 finding it bit confusing working around this problem. I have parent DIV and 3/more Child DIV. Parent DIV is center aligned and child DIV should be floating left but should be aligned center. CSS contains, .center { float:left; height:250px; width:15%; margin: 0 auto; border: 1px solid black;} I have a sample of the code link here...
Now provide the response and nothing else.
|
If you want to horizontally align your elements centrally, then don't float them. Change the way they are displayed to inline-block and align them in the center by changing the text-align style of their parent: #parent { text-align:center; height:450px; width:75%; border:1px solid blue;}.center { display:inline-block; height:250px; width:15%; margin: 0 auto; border: 1px solid black;} <div id="parent"> <div id="child1" class="center"></div><!-- --><div id="child2" class="center"></div><!-- --><div id="child3" class="center"></div></div> Be sure to have no white-space or newlines between your children <div> s (in your HTML, that is) or comment it out. Now that these are inline elements, this white-space will be interpreted as a space.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13602965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2437138/']}
|
jdg_374778
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37072872
|
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 developing my first Larvel-based package. I want to include the Socialite package, so I put it like this in my composer.json file "require": { "laravel/socialite": "^2.0"}, Now, how do I include the provider and the alias as you'd normally do in /config/app.php ? I think by now I've read every stackoverflow there is about this matter, but nothing seems to work. This is my package's serviceprovider: public function boot() { include __DIR__.'/routes.php'; $this->app->register('Laravel\Socialite\SocialiteServiceProvider'); $this->app->alias('Laravel\Socialite\Facades\Socialite', 'Socialite'); $this->loadViewsFrom(__DIR__.'/../views', 'package-name'); $this->loadTranslationsFrom(__DIR__.'/../lang', 'package-name'); $this->publishes([ __DIR__.'/../views' => resource_path('views/vendor/package-name'), ]); $this->publishes([ __DIR__.'/../database/migrations/' => database_path('migrations') ], 'migrations'); } Result: Class 'Laravel\Socialite\SocialiteServiceProvider' not found UPDATE "psr-4": { "App\\": "app/", "Rubenwouters\\CrmLauncher\\": "packages/rubenwouters/crm-launcher/src/" }
Now provide the response and nothing else.
|
Your train_test_split() output is not correct. Change this line: train_x, train_y, test_x, test_y = train_test_split(x, y_enc, test_size=0.33) To this: train_x, test_x, train_y, test_y = train_test_split(x, y_enc, test_size=0.33) Also, to use probabilities instead of class predictions, you'll need to change SVC() to SVC(probability = True) and change clf.predict_proba to clf.predict . Putting it all together: from sklearn import metricsfrom sklearn.preprocessing import MultiLabelBinarizerfrom sklearn.multiclass import OneVsRestClassifierfrom sklearn.cross_validation import train_test_splitfrom sklearn.svm import SVCx = [[1,2,3],[3,3,2],[8,8,7],[3,7,1],[4,5,6]]y = [['bar','foo'],['bar'],['foo'],['foo','jump'],['bar','fox','jump']]mlb = MultiLabelBinarizer()y_enc = mlb.fit_transform(y)train_x, test_x, train_y, test_y = train_test_split(x, y_enc, test_size=0.33)clf = OneVsRestClassifier(SVC(probability=True))clf.fit(train_x, train_y)predictions = clf.predict(test_x)my_metrics = metrics.classification_report( test_y, predictions)print my_metrics This gives me no errors when I run it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37072872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4243855/']}
|
jdg_374779
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3860692
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Piano Frequencies formula maps the position of a piano key on the standard piano n to a specific note and frequency e.g. key n=49 maps to A4 with a frequency of 440 hz . $ f(n) = 440(\sqrt[12]2)^{n-49}$ Article about the formula here: https://en.wikipedia.org/wiki/Piano_key_frequencies . My question is pretty simple: how do you re-arrange the equation so that you can find the specific piano note n given a frequency? For example, how do we solve for n in the equation below? $ 27.5 = 440(\sqrt[12]2)^{n-49} $ I know from trial and error that the note f(n)=27.5 is A1 so n=1 . But I had a lot of difficulty in approaching how to rearrange the equation and would appreciate some insight and help. Thanks in advance!
Now provide the response and nothing else.
|
The following is inspired by Bound on a complex polynomial on AoPS. For $|z| = 1$ we have $\overline z = 1/z$ , so that expanding $|P(z)|^2 = P(z)\overline{P(z)}$ gives $$ |P(z)|^2 = 4 + 2 \operatorname{Re} \left( a \overline b z + a \overline c z^2 + a \overline d z^3 + b \overline c z + b \overline d z^2 + c \overline d z \right) \, .$$ Now let $\omega = e^{2 \pi i /3}$ be a third root of unity, and note that $1 + \omega + \omega^2 = 0$ . It follows that $$|P(z)|^2 + |P(\omega z)|^2 + |P(\omega^2 z)|^2 =12 + 6 \operatorname{Re}(a \overline d z^3)$$ because all the terms with $z$ and $z^2$ cancel in the sum. We can choose $z_0$ on the unit circle such that $a \overline d z_0^3 = 1$ . Then $$|P(z_0)|^2 + |P(\omega z_0)|^2 + |P(\omega^2 z_0)|^2 = 18$$ so that one term on the left must be at least $6$ , and that implies the desired conclusion.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3860692', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/656510/']}
|
jdg_374780
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3373948
|
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 planning to develop a cross-platform script. On Linux and other operating systems, it will store configuration in XDG_CONFIG_HOME and data files (specifically, downloaded plugins) in XDG_DATA_HOME . On Windows, it will use APPDATA for both (unless someone has a better idea). However, what would be the proper thing to do on Mac OS X? On my first glance through a handy Macbook's ~/Library directory, I saw Preferences and Application Support folders. I was originally planning to use those, but Preferences seems to just contain plists with reverse domain names like com.apple.foo.bar.baz.plist , and every folder in Application Support corresponds to a bundle in /Applications , so I'm not sure how well the system would react to files that don't match its standards. Storing them directly in ~/Library might be an option, but I don't want to pollute it with a stray myscript.conf file if there's a better place for it. Where should I store these files? (And please don't say just ~/.myscript . I know it's the Unix tradition, but it annoys me to see random dotfiles in the home directory.)
Now provide the response and nothing else.
|
Comparing Apple's documentation for the various paths to the XDG Base Directory specifications approximates to the following locations: XDG_CONFIG_HOME ▶︎ ~/Library/Preferences/ XDG_DATA_HOME ▶︎ ~/Library/ XDG_CACHE_HOME ▶︎ ~/Library/Caches/ Mapping XDG Base Directory Specification locations for "My App" on Mac OS X could look like this: XDG_CONFIG_HOME ▶︎ ~/Library/Preferences/name.often.with.domain.myapp.plist XDG_DATA_HOME ▶︎ ~/Library/My App/ XDG_CACHE_HOME ▶︎ ~/Library/Caches/My App/ These mappings seem pretty reasonable but they aren't exact. Some kinds of cache or data may be appropriate for ~/Library/Application Support/My App , and other may be best in the temp locations or the App bundle. All of it is by convention and the same reasons for using the best XDG_ locations apply to using the best locations on the Mac OS X system. Your annoyance at ~/.myscript is in line with Apple's guidelines: "Don't pollute user space". References: Mac OS X Reference Library: Where to Put Application Files Mac OS X Reference Library: Important Java Directories on Mac OS X
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3373948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244407/']}
|
jdg_374781
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12657202
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As a simple example, suppose I have a list of numbers L and I want to find the first element that is greater than some specific number X . I could do this with list comprehensions like this: (mynode@127.0.0.1)24> L = [1, 2, 3, 4, 5, 6]. [1,2,3,4,5,6](mynode@127.0.0.1)25> X = 2.5.2.5(mynode@127.0.0.1)26> [First | _] = [E || E <- L, E > X]. [3,4,5,6](mynode@127.0.0.1)27> First.3 But this seems potentially very inefficient, since the list could be very long and the first match could be early on. So I'm wondering whether either a) Is there an efficient way to do this that won't evaluate the rest of the elements in the list after the first match is found? or b) When this gets compiled, does Erlang optimize the rest of the comparisons away anyways? This is how I would achieve what I'm looking for in C: int first_match(int* list, int length_of_list, float x){ unsigned int i; for(i = 0; i < length_of_list, i++){ if(x > list[i]){ return list[i]; } /* immediate return */ } return 0.0; /* default value */}
Now provide the response and nothing else.
|
well, something like firstmatch(YourList, Number) -> case lists:dropwhile(fun(X) -> X =< Number end, YourList) of [] -> no_solution; [X | _] -> X end.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12657202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630588/']}
|
jdg_374782
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3599256
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently I use this function, based on JCL code, which works fine: function IsDirectoryWriteable(const AName: string): Boolean;var FileName: PWideChar; H: THandle;begin FileName := PWideChar(IncludeTrailingPathDelimiter(AName) + 'chk.tmp'); H := CreateFile(FileName, GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); Result := H <> INVALID_HANDLE_VALUE; DeleteFile(FileName);end; Is there anything I could improve with the flags? Can the test be done without actually creating a file?Or is this functionality even already available in one of the RTL or Jedi libraries?
Now provide the response and nothing else.
|
Actually writing to the directory is the simpliest way to determine if the directory is writable. There are too many security options available to check individually, and even then you might miss something. You also need to close the opened handle before calling DeleteFile() . Which you do not need to call anyway since you are using the FILE_FLAG_DELETE_ON_CLOSE flag. BTW, there is a small bug in your code. You are creating a temporary String and assigning it to a PWideChar , but the String goes out of scope, freeing the memory, before the PWideChar is actually used. Your FileName variable should be a String instead of a PWideChar . Do the type-cast when calling CreateFile() , not before. Try this: function IsDirectoryWriteable(const AName: string): Boolean; var FileName: String; H: THandle; begin FileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp'; H := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); Result := H <> INVALID_HANDLE_VALUE; if Result then CloseHandle(H);end;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3599256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80901/']}
|
jdg_374783
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12645270
|
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 do something like: case someenumvalue || someotherenumvalue: // do some stuff break; Is this legal in C? The variable that I am doing a switch on is an enumerated list data struct.
Now provide the response and nothing else.
|
You can rely on the fact that case statements will fall-through without a break : case SOME_ENUM_VALUE: // fall-throughcase SOME_OTHER_ENUM_VALUE: doSomeStuff(); break; You can also use this in a more complicated case, where both values require shared work, but one (or more) of them additionally requires specific work: case SOME_ENUM_VALUE: doSpecificStuff(); // fall-through to shared codecase SOME_OTHER_ENUM_VALUE: doStuffForBothValues(); break;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12645270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2607746/']}
|
jdg_374784
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16761596
|
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 use regex, to check if a string starts with a double quotes character ( " ) and ends with a double quotes character too. The problem is I can't use a double quotes character, cause it gets confused. Is there any other way to represent a double quotes character " in regex, or in string in general? String s = """; // ?
Now provide the response and nothing else.
|
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex . However, because Java uses double quotes to delimit String constants, if you want to create a string in Java with a double quote in it, you must escape them. This code will test if your String matches: if (str.matches("\".*\"")) { // this string starts and end with a double quote} Note that you don't need to add start and end of input markers ( ^ and $ ) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16761596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2410538/']}
|
jdg_374785
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58323212
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TL,DR; ContextCompat.getColor() does not use the night colors ( values-night/colors.xml ) though it should when night mode is enabled. Here is the problem: Hi everyone, So I'm implementing a dark theme for my Android app, I call this to enable it : AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); I have set colors in values/colors.xml and there dark version in values-night/colors.xml . The colors changes well depending on the nightMode, BUT : when I use ContextCompat.getColor(getApplicationContext(), R.id.myColor) , it uses the normal colors ( values/colors.xml ) and not the night colors ( values-night/colors.xml ). In my build.gradle , I have set these : implementation 'androidx.appcompat:appcompat:1.1.0'implementation 'androidx.core:core-ktx:1.2.0-beta01' Could someone please tell me what am I doing wrong ? PS : I already looked at the following question and it does not answer this problem https://stackoverflow.com/questions/57779661/contextcompat-getcolor-method-ignores-night-mode
Now provide the response and nothing else.
|
I faced similar issues with night mode. Some screens were fine but others were keeping the regular theme. In the end, I found out that I was instantiating some views using the Application's context instead of the current's activity context. For some reason, Application's context does not track this kind of information. So, update your code to use current's activity context instead of the application context. For reference for other users. Avoid: ContextCompat.getColor(getApplicationContext(), R.id.myColor) And use: // In a ActivityContextCompat.getColor(this, R.id.myColor)// In a ViewContextCompat.getColor(getContext(), R.id.myColor)// In a Fragment (check against null because getContext can trigger a NPEContext context = getContext()if (context != null) { ContextCompat.getColor(context, R.id.myColor)}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58323212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1027466/']}
|
jdg_374786
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20742595
|
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 look for a substitute in std::vector in my project, and I found out that std::queue is what I'm looking for. I have lots of function that uses range-based loop for iteration and I'm trying to maintain it as far as I can. I try to compile a range-based loop in std::queue but all I get are compile errors error: no matching function for call to 'begin(std::queue&)' Doesn't std::queue support range base loop? I did try Google search but didn't find any topic regarding to this. Update: My compiler is GCC v4.7.1 -std=c++11 is enabled And here's the faulty test code: std::queue<int> Q;for (int i = 0;i < 10; ++i) Q.push(i);std::cout << "\nqueue contains: ";for (auto i : Q) std::cout << i << ", ";
Now provide the response and nothing else.
|
Well, the answer is actually pretty simple: there is no function begin() in std::queue and there isn't any overload of std::begin taking a std::queue either. You can have a look at the documentation . The core problem is that std::queue is not meant to be iterated over. It exists to satisfy other needs. If you really need to iterate over it, you should just use the underlying container (by default std::deque ) which supports iteration and for which your code would be valid.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20742595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2304737/']}
|
jdg_374787
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1789433
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do find the sum of the series till infinity? $$ \frac{2}{1!}+\frac{2+4}{2!}+\frac{2+4+6}{3!}+\frac{2+4+6+8}{4!}+\cdots$$ I know that it gets reduced to $$\sum\limits_{n=1}^∞ \frac{n(n+1)}{n!}$$But I don't know how to proceed further.
Now provide the response and nothing else.
|
Define $f$ by $$f(x) = \sum_{n=0}^\infty \frac{x^{n+1}}{n!}$$ for $x\in\mathbb{R}$. (It is easy to check that the radius of convergence of this function is infinite.) In particular: For all $x\in\mathbb{R}$, $f''(x) = \sum_{n=1}^\infty \frac{(n+1)n}{n!}x^{n-1}$, so you are looking for $f''(1)$; For all $x\in\mathbb{R}$, $f(x) = x e^x$ using the known power series for $\exp$, so that $f''(x) = (x+2)e^x$. Therefore, $f''(1) = 3e$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1789433', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/319642/']}
|
jdg_374788
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6319514
|
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 add an iframe to the page. This iframe should refer to a URL. I added the below code to page HTML, but it doesn't work: document.createElement('<iframe src='http://example.com'></iframe>');
Now provide the response and nothing else.
|
Here you go: var iframe;iframe = document.createElement('iframe');iframe.src = 'http://example.com/file.zip';iframe.style.display = 'none';document.body.appendChild(iframe); Live demo: http://jsfiddle.net/USSXF/2/ Your code doesn't work because you're passing an entire HTML string into the createElement function ("jQuery style" :) ), which is invalid. The valid parameter for this function is a string representing the tag-name (like 'div' , 'iframe' , 'p' , etc.). Read about document.createElement here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6319514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313421/']}
|
jdg_374789
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3362474
|
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 doing a cross domain request using $.ajax . It works on Firefox and Chrome, but does not issue a call on IE 7 or 8. Can anyone tell me what's wrong with the following? I have used JSON and JSONP (which I stopped using, due to some custom restrictions). I am already using Allow-access-control-origin header on my site. (Without those, Chrome and Firefox were not making successful requests.) I have already tried https://developer.mozilla.org/en/http_access_control Code: $.ajax({ type: 'GET', url: "http://anotherdomain.com/Service/GetControl?id=" + zoneID, cache: false, contentType: "application/x-www-form-urlencoded", async: false, beforeSend: function (request) { //alert('before send'); //request.setRequestHeader("X-Requested-With", "XMLHttpRequest"); //request.setRequestHeader("X-PINGOTHER", "pingpong"); } , success: function (data, status) { //alert("Data returned :" + data); //alert("Status :" + status); if (status == "success" && data != "") $("#" + div.id).append(data); else $("#" + div.id).attr("style", "display:none;"); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }}); I have tried various tips present on multiple sites, but no luck yet.
Now provide the response and nothing else.
|
Could you check if the problem with IE relies on not defining security zones to allow cross domain requests? See this microsoft page for an explanation. OTOH, this page mentions that IE7 and eariler cannot do cross domain calls, but IE8 can, using a different object than XMLHttpRequest, the one JQuery uses. Could you check if XDomainRequest works? EDIT (2013-08-22) The second link is dead, so I'm writing here some of its information, taken from the wayback machine : XDomainRequestSupported: IE8 Rather than implement the CORS version of XMLHttpRequest, the IE team have gone with there own propriety object, named XDomainRequest. The usage of XDomainRequest has been simplified from XMLHttpRequest, by having more events thrown (with onload perhaps being the most important). This implementation has a few limitations attached to it. For example, cookies are not sent when using this object, which can be a headache for cookie based sessions on the server side. Also, ContentType can not be set, which poses a problem in ASP.NET and possibly other server side languages (see http://www.actionmonitor.co.uk/NewsItem.aspx?id=5 ). var xdr = new XDomainRequest();xdr.onload = function() { alert("READY"); };xdr.open("GET", "script.html");xdr.send();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3362474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405673/']}
|
jdg_374790
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3585631
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to create a function that automatically generates uni and multivariate regression analyses, but I'm not able to figure out how I can specify **variables in vectors...**This seems very easy, but skimming the documentation I havent figured it out so far... Easy example a<-rnorm(100)b<-rnorm(100)k<-c("a","b")d<-c(a,b)summary(k[1]) But k[1]="a" and is a character vector...d is just b appended to a, not the variable names. In effect I'd like k[1] to represent the vector a. Appreciate any answers... //M
Now provide the response and nothing else.
|
You can use the "get" function to get an object based on a character string of its name, but in the long run it is better to store the variables in a list and just access them that way, things become much simpler, you can grab subsets, you can use lapply or sapply to run the same code on every element. When saving or deleting you can just work on the entire list rather than trying to remember every element. e.g.: mylist <- list(a=rnorm(100), b=rnorm(100) )names(mylist)summary(mylist[[1]])# orsummary(mylist[['a']])# orsummary(mylist$a)# or d <- 'a'summary(mylist[[d]])# orlapply( mylist, summary ) If you are programatically creating models for analysis with lm (or other modeling functions), then one approach is to just subset your data and use the ".", e.g.: yvar <- 'Sepal.Width'xvars <- c('Petal.Width','Sepal.Length')fit <- lm( Sepal.Width ~ ., data=iris[, c(yvar,xvars)] ) Or you can build the formula using "paste" or "sprintf" then use "as.formula" to convert it to a formula, e.g.: yvar <- 'Sepal.Width'xvars <- c('Petal.Width','Sepal.Length')my.formula <- paste( yvar, '~', paste( xvars, collapse=' + ' ) )my.formula <- as.formula(my.formula)fit <- lm( my.formula, data=iris ) Note also the problem of multiple comparisons if you are looking at many different models fit automatically.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3585631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338745/']}
|
jdg_374791
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6441013
|
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 sometimes it's a good feature, but if i need to store large amount of data, it's unnecessary other "meta-data" around the data itself. Is there any way how to disable versioning in CouchDB, or do i need to use different DB engine, like Mongo?
Now provide the response and nothing else.
|
Versioning isn't a feature of CouchDB it is a core function of the way it works writing the data to the disk and preforms replication conflict resolution with other nodes. It is not a history mechanism. It is very unfortunate that there isn't a better term than version for referring to the previous copies of the documents. Because version to most developers means something historical that is warehoused. That isn't what it is intended to be used as at all in CouchDB. It is plastered all over the CouchDB documentation to not rely on previous versions as backups or a versioning system, that they can potentially disappear at anytime, because they are used for replication conflict detection mainly. But the simple fact is this isn't a feature it is just how CouchDB works. The only way to remove the past versions is to compact the database periodically. In the current version of CouchDB this can be enabled with a script that hooks into document updates and fires off semi-automatic compaction based on a high water mark threshold. Usually this is done manually after a large set of documents are updated in a batch a you know that this might be beneficial from an application specific standpoint. That said, if you aren't updating documents no history is generated and this is not needed.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6441013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335717/']}
|
jdg_374792
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
94726
|
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:
When preparing non-standard graphs, it is common that one needs an "extra" axis, parallel but displaced from a traditional axis. This might happen in many cases: When you want to plot two curves with different y-values , (or here ) When plotting parallel coordinates Many other situations A generic solution is to create a plot with the relevant axis, keep only the axis (by making the data transparent or something), and use Overlay . However, this produces an object which is not a Graphics , and thus is not amenable to further manipulations. Thus, it would be very useful to have a function that generates a second axis with ticks and labels. Alternatively, it would be nice to have a clever way to position an axis in a plot in an exact way (i.e. a way that respects the data) without using Overlay .
Now provide the response and nothing else.
|
Here I am adapting LLlAMnYP's answer , and I hope that it can meet the requirements. If someone can tell me how to better handle the options statement than by the kludgy Which statement I would be most appreciative. Options[extraAxisPlot] = {"AxisType" -> "xAxis", "AxisOptions" -> {}, "ExtraEpilog" -> {}};extraAxisPlot[plot_, {axisStart_, axisFinish_}, {xpos_, ypos_}, OptionsPattern[]] := Module[ {printerPointsPlotRange, realImageDimensions, realPlotRange, plotRangeRatio, axisplotrange, axisxrange, axisaxes, insetpos, axis}, printerPointsPlotRange = (#[[2]] - #[[1]] &)@(Rasterize[ Show[#, Epilog -> {Annotation[ Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]], "Two", "Region"]}], "Regions"][[-1, 2]]) &; realImageDimensions = (#[[2]] - #[[1]] &)@(Rasterize[ Show[#, Epilog -> {Annotation[ Rectangle[ImageScaled[{0, 0}], ImageScaled[{1, 1}]], "Two", "Region"]}], "Regions"][[-1, 2]]) &; realPlotRange = Module[{padding = Total /@ (Options[#, PlotRangePadding][[-1, 2]] /. None -> 0), baserange = (#[[2]] - #[[1]] &) /@ PlotRange[#], range}, range = (baserange + padding) /. {a_ Scaled[b_] -> Scaled[a b], Scaled[a_] + Scaled[b_] -> Scaled[a + b]} /. {a_ + Scaled[b_] -> a/(1 - b)}; range] &; plotRangeRatio = realPlotRange[#1]/realPlotRange[#2] &; {axisplotrange, axisxrange, axisaxes, insetpos} = Which[OptionValue["AxisType"] == "xAxis", {{{axisStart, axisFinish}, Automatic}, {axisStart, axisFinish}, {True, False}, {axisStart, 0}}, OptionValue["AxisType"] == "yAxis", {{Automatic, {axisStart, axisFinish}}, {0, 1}, {False, True}, {0, axisStart}}, OptionValue["AxisType"] == "Both", {Transpose@{axisStart, axisFinish}, {axisStart[[1]], axisFinish[[1]]}, {True, True}, axisStart}, True, Print["Invalid axis type"]; Abort[] (*If the option isn't one of the three axis types, then quit the code*)]; axis = Plot[Null, {x, axisxrange[[1]], axisxrange[[2]]}, PlotRange -> axisplotrange, Axes -> axisaxes, Evaluate@OptionValue["AxisOptions"]]; Show[plot, Epilog -> { Evaluate@OptionValue["ExtraEpilog"], Inset[Show[axis, ImageSize -> plotRangeRatio[axis, plot] printerPointsPlotRange[ plot] + (realImageDimensions[axis] - printerPointsPlotRange[axis]), AspectRatio -> (Last[#]/First[#] &)@(plotRangeRatio[axis, plot] printerPointsPlotRange[plot])], {xpos, ypos}, insetpos, Automatic]}] ] The function extraAxisPlot takes the following arguments, A one-dimensional plot, upon which you wish to overlay an axis A list of the initial and final values of the axis. In the case where both x and y axes are requested, these should be lists with 2 elements. A list of the coordinates where the axis should start, in the absolute reference frame of the underlying plot. Options, one option specifying which type of axis, and another which passes options on for the axis. The output is a Graphics object. Here are three examples, plot1 = Plot[5 Sin[x], {x, 32, 40}, GridLines -> Automatic,ImageSize -> 400]{extraAxisPlot[plot1, {-2, 4}, {34, -2}], extraAxisPlot[plot1, {107, 113}, {36, -2}, "AxisOptions" -> {AxesStyle -> Red}, "AxisType" -> "yAxis"], extraAxisPlot[plot1, {{7, -3}, {11, 4}}, {36, -2}, "AxisOptions" -> {AxesStyle -> Red, BaseStyle -> 20}, "AxisType" -> "Both"]} In the underlying plot I added gridlines to show that the scales for the two axes overlap exactly - that is, one unit in the underlying plot is one unit in the extra axis. To have a different scale, I think it is necessary to change the Ticks for the axis, extraAxisPlot[plot1, {-2, 4}, {34, -2}, "AxisOptions" -> {Ticks -> {{{-1.5, "Hello"}, {1.5, "world"}}, None}}] I'm a fan of using the CustomTicks package , Needs["CustomTicks`"];extraAxisPlot[plot1, {-2, 4}, {34, -2}, "AxisOptions" -> {Ticks -> {LogTicks, None}}] One caveat is that it is necessary to set the size of the underlying image when defining it. If you try to resize the image with the mouse, it totally messes up the Inset . This seems to work fine when exporting to vector or bitmap formats (I tested PNG and PDF). Any suggestions to improve the function are greatly appreciated, as well as examples that break the code.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/94726', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/367/']}
|
jdg_374793
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11433848
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
body { background: rgba(0, 0, 0, 0.8); font-family: sans-serif; font-size: 11px; color: #e0e0e0;}#wrapper {}#login { margin-left: auto; margin-right: auto; margin-top: 50px; background: rgba(0, 0, 0, 0.9); width: 360px; padding: 20px; position: relative; -webkit-border-radius: 15px; border-radius: 15px;}#registercontainer { position: relative; margin-left: auto; margin-right: auto; width: 1050px;}#register { position: absolute; left: 740px; top: 50px;} // <div id="wrapper"> <div id="login"> <h2>Login to The Something Project</h2> <form action="game" method="post"> <input type="text" name="username" maxlength="20" placeholder="username"><br> <input type="text" name="usericon" placeholder="http://imgur.com/icon.png"><br> <br> <input type="submit" value="login"> </form> </div> <div id="registercontainer"> <div id="register"> <h2>Register for The Something Project</h2> </div> </div> </div> I want to have a div next to the centered div (see the image above) but what i get instead is this. http://i.imgur.com/X0e4s.png How do i solve this? Greetings
Now provide the response and nothing else.
|
I imagine there are quite a few approaches you can take. Here is one. Using the same HTML structure as in your example, the goal can be achieved thus: Make all elements except the main wrapper inline-block . Center the "centered" element by giving text-align: center to the main wrapper. Put the sidebar out of the document flow by giving it position: absolute . This requires that you give its container position: relative as well. Give the sidebar's container zero width and height so that it doesn't affect the centering calculations. Give it vertical-align: top so that its top edge (which is also the sidebar's top edge) aligns with the top edge of the centered element. Optionally specify text-align for the centered element and the sidebar if you don't want their contents to be centered within themselves. As a bonus, with this approach you can directly specify the widths for both the centered div and the sidebar in just one place. See it in action .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11433848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528370/']}
|
jdg_374794
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17100
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can my wifi board detect wireless networks that are in range? What protocol is used to communicate with the devices in the area to announce a wifi AP? Does every router transmit on its own frequency and my wifi board scans "every" frequency to detect one?
Now provide the response and nothing else.
|
How can my wifi board detect wireless networks that are in range? Your client has a radio which listens to the wifi 802.11 frequencies for the country configured in the radio. What protocol is used to communicate with the devices in the area to announce a wifi AP? Wifi APs are configured with an SSID; those SSIDs are known via beacon frames ; by default beacon frames are sent every 102.4 milliseconds. The beacon frame format includes an SSID field, and the beacon interval. The radio in your AP is configured for a specific channel . Those beacon frames are transmitted on the AP's channel. Does every router transmit on its own frequency and my wifi board scans "every" frequency to detect one? Every wireless AP can select from a pre-defined list of wireless channels , and it chooses one channel to announce the SSID. Your wifi client constantly walks (or scans through) all those channels to figure out which SSIDs are available.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/17100', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/14198/']}
|
jdg_374795
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46157709
|
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 large dataset (~600 GB) stored as HDF5 format. As this is too large to fit in memory, I would like to convert this to Parquet format and use pySpark to perform some basic data preprocessing (normalization, finding correlation matrices, etc). However, I am unsure how to convert the entire dataset to Parquet without loading it into memory. I looked at this gist: https://gist.github.com/jiffyclub/905bf5e8bf17ec59ab8f#file-hdf_to_parquet-py , but it appears that the entire dataset is being read into memory. One thing I thought of was reading the HDF5 file in chunks and saving that incrementally into a Parquet file: test_store = pd.HDFStore('/path/to/myHDFfile.h5')nrows = test_store.get_storer('df').nrowschunksize = Nfor i in range(nrows//chunksize + 1): # convert_to_Parquet() ... But I can't find any documentation that would allow me to incrementally build up a Parquet file. Any links to further reading would be appreciated.
Now provide the response and nothing else.
|
You can use pyarrow for this! import pandas as pdimport pyarrow as paimport pyarrow.parquet as pqdef convert_hdf5_to_parquet(h5_file, parquet_file, chunksize=100000): stream = pd.read_hdf(h5_file, chunksize=chunksize) for i, chunk in enumerate(stream): print("Chunk {}".format(i)) if i == 0: # Infer schema and open parquet file on first chunk parquet_schema = pa.Table.from_pandas(df=chunk).schema parquet_writer = pq.ParquetWriter(parquet_file, parquet_schema, compression='snappy') table = pa.Table.from_pandas(chunk, schema=parquet_schema) parquet_writer.write_table(table) parquet_writer.close()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46157709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4976362/']}
|
jdg_374796
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1103260
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get the number of rows affected by an UPDATE query in a Stored Procedure (SQL Server 2005), as a resultset. e.g. CREATE PROCEDURE UpdateTablesASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; UPDATE Table1 Set Column = 0 WHERE Column IS NULL UPDATE Table2 Set Column = 0 WHERE Column IS NULL UPDATE Table3 Set Column = 0 WHERE Column IS NULL UPDATE Table4 Set Column = 0 WHERE Column IS NULLEND Then return: Table1 Table2 Table3 Table432 45 0 3
Now provide the response and nothing else.
|
CREATE PROCEDURE UpdateTablesASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @RowCount1 INTEGER DECLARE @RowCount2 INTEGER DECLARE @RowCount3 INTEGER DECLARE @RowCount4 INTEGER UPDATE Table1 Set Column = 0 WHERE Column IS NULL SELECT @RowCount1 = @@ROWCOUNT UPDATE Table2 Set Column = 0 WHERE Column IS NULL SELECT @RowCount2 = @@ROWCOUNT UPDATE Table3 Set Column = 0 WHERE Column IS NULL SELECT @RowCount3 = @@ROWCOUNT UPDATE Table4 Set Column = 0 WHERE Column IS NULL SELECT @RowCount4 = @@ROWCOUNT SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4END
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1103260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91579/']}
|
jdg_374797
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
639988
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a complete metric space, and denote by $\mathcal{P}(X)$ the set of probability measures on $X$. I am interested in proving that if $X$ is compact then $\mathcal{P}(X)$ must be compact in the weak-* topology, which is induced by the convergence against $C_b(X)$, that is, the bounded continuous functions. Since $\mathcal{P}(X) \subset (C_b(X))^*$, and the unit ball of $(C_b(X))^*$ is compact in the weak-* topology (by Banach-Alaoglu), all that is left to do is prove that $\mathcal{P}(X)$ is weak-* closed. This should be easy, but I'm stuck: where does the compacity of $X$ come in? (The result is obviously false for non-compact $X$: consider a sequence of delta measures $\delta_{x_n}$ and $x_n \in \mathbb{R}, x_n \to \infty$.)
Now provide the response and nothing else.
|
The other answer is correct, but a little brief so I decided to add a few words. Let's begin with the Riesz representation: For a locally compact Hausdorff space $X$, the map taking the finite signed regular Borel measure $\mu$ to the functional $f\mapsto \langle f,\mu\rangle:= \int f\,d\mu$ is an isometric isomorphism of the Banach space $M_r(X)$ onto the dual of the Banach space $C_0(X)$. Here $C_0(X)$ is the space of continuous functions that vanish at infinity, and the norm on $M_r(X)$ is the total variation norm. Now Banach-Alaoglu guarantees that the unit ball in $C_0(X)^*$ is weak${}^*$ compact, whichcorresponds to vague compactness for the measures. However, generally, the unit sphere in $C_0(X)^*$ is not weak${}^*$ closed and hence not compact. Note however that the cone $\cal P$ of positive elements in $M_r(X)$ is vaguely closed:$${\cal P}=\bigcap_{f\in C_0(X)_+} \left\{\mu: \langle f,\mu\rangle \geq 0\right\},$$so its intersection with the unit ball is compact. The intuition here is that the positive part of the unit sphere is tiny, so could well be compact even though the whole sphere itself is not. So how does the compactness of $X$ enter into the picture? If $X$ is compact,then $C_0(X)=C_b(X)$ and the vague and weak topologies of measures coincide. In particular, the constant function "1" belongs to $C_0(X)$ so the space of probability measures is the compact set$$ {\cal P}\cap \{\mu: \|\mu\|\leq 1\}\cap \{\mu: \langle 1,\mu\rangle =1\}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/639988', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/121688/']}
|
jdg_374798
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
122421
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 3D dataset with at least millions of data points (scatter events from atoms, approximately Gaussian). I am modeling this data with a Gaussian Mixture Model. The usual approach would be to optimize the GMM with the EM algorithm. However, I have substantial priors (e.g., the data is produced by a polymer made of light atoms) so the only way to find the correct GMM is via sampling. Here's the problem: it's very expensive to compare a GMM to the data $D$, and I have to do that evaluation frequently. I would like to introduce an intermediate step: first model $G_d$ without priors, and then introduce priors and re-model $G_m$ where both are GMMs. Then while sampling $G_m$ I could just compare it to $G_d$ instead of $D$, which is a lot cheaper. So $G_d$ is kind of a data reduction. Intuitively the likelihood function for $G_m$ should be: $$p(D|G_m)\approx p(D|G_d)S(G_d|G_m)$$ where $S(G_d|G_m)$ is some kind of scoring function (maybe K-L divergence? correlation?).My questions are: Can you re-model in this way and still get a good approximation of the likelihood? What types of functions can be used for $S(G_d|G_m)$ and still get a proper PDF? Does the choice of number of components in $G_d$ affect the final likelihood? Below I attempt to illustrate this problem. The magenta $G_d$ is computed at the beginning. Then the red $G_m$ with its additional priors (including size and linearity) are fit to the magenta one, much faster than comparing to the data itself. Quick clarification : the number of Gaussians in $G_m$ is much higher than $G_d$. That's because the only prior on $G_d$ is the Dirichlet one (so it's just regular Bayesian GMM fitting) whereas $G_m$ has much more detailed priors which enables us to make a more detailed model than the data itself would indicate.
Now provide the response and nothing else.
|
Most classification models in fact don't yield a binary decision, but rather a continuous decision value (for instance, logistic regression models output a probability, SVMs output a signed distance to the hyperplane, ...). Using the decision values we can rank test samples, from 'almost certainly positive' to 'almost certainly negative'. Based on the decision value, you can always assign some cutoff that configures the classifier in such a way that a certain fraction of data is labeled as positive. Determining an appropriate threshold can be done via the model's ROC or PR curves. You can play with the decision threshold regardless of the balance used in the training set. In other words, techniques like up -or downsampling are orthogonal to this. Assuming the model is better than random, you can intuitively see that increasing the threshold for positive classification (which leads to less positive predictions) increases the model's precision at the cost of lower recall and vice versa. Consider SVM as an intuitive example: the main challenge is to learn the orientation of the separating hyperplane. Up -or downsampling can help with this (I recommend preferring upsampling over downsampling). When the orientation of the hyperplane is good, we can play with the decision threshold (e.g. signed distance to the hyperplane) to get a desired fraction of positive predictions.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/122421', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/59667/']}
|
jdg_374799
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36973387
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use value_counts() function from Python's pandas package to find the frequency of items in a column. This works and outputs the following: 57 181162 63071 61353 21759 18568 8852 70Name: hospitalized, dtype: int64 In which the first column is the item and the right column is its frequency in the column. From there, I wanted to access the first column of items and iterate through that in a for loop. I want to be able to access the item of each row and check if it is equal to another value. If this is true, I want to be able to access the second column and divide it by another number. My big issue is accessing the first column from the .value_counts() output. Is it possible to access this column and if so, how? The columns aren't named anything specific (since it's just the value_counts() output) so I'm unsure how to access them.
Now provide the response and nothing else.
|
value_counts returns a Pandas Series: df = pd.DataFrame(np.random.choice(list("abc"), size=10), columns = ["X"])df["X"].value_counts()Out[243]: c 4b 3a 3Name: X, dtype: int64 For the array of individual values, you can use the index of the Series: vl_list = df["X"].value_counts().indexIndex(['c', 'b', 'a'], dtype='object') It is of type "Index" but you can iterate over it: for idx in vl_list: print(idx)cba Or for the numpy array, you can use df["X"].value_counts().index.values
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36973387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6254935/']}
|
jdg_374800
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5189461
|
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 having a hard time passing an array of strings to a function by reference. char* parameters[513]; Does this represent 513 strings? Here is how I initialized the first element: parameters[0] = "something"; Now, I need to pass 'parameters' to a function by reference so that the function can add more strings to it. How would the function header look and how would I use this variable inside the function?
Now provide the response and nothing else.
|
You've already got it. #include <stdio.h>static void func(char *p[]){ p[0] = "Hello"; p[1] = "World";}int main(int argc, char *argv[]){ char *strings[2]; func(strings); printf("%s %s\n", strings[0], strings[1]); return 0;} In C, when you pass an array to a function, the compiler turns the array into a pointer. (The array "decays" into a pointer.) The "func" above is exactly equivalent to: static void func(char **p){ p[0] = "Hello"; p[1] = "World";} Since a pointer to the array is passed, when you modify the array, you are modifying the original array and not a copy. You may want to read up on how pointers and arrays work in C. Unlike most languages, in C, pointers (references) and arrays are treated similarly in many ways. An array sometimes decays into a pointer, but only under very specific circumstances. For example, this does not work: void func(char **p);void other_func(void){ char arr[5][3]; func(arr); // does not work!}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5189461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246392/']}
|
jdg_374801
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8141
|
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 want to receive 5-bit serial words using a microcontroller's hardware UART at 45 Baud. This is the basic protocol for teletype machines. Since the baud rate is 45, I really want this done in hardware so that I am not spending all the processor time polling a pin, and for ease of programming. Are there microcontrollers that can do 5-bit serial data in hardware? Is there a reasonable hardware/software implementation that won't tie up the processor?
Now provide the response and nothing else.
|
If you have sufficient intercharacter space (~3 extra stop bits), you could use the MCU UART port, as there isn't really a difference between an 8-bit character (0x00 through 0x1F) on a UART and a 5-bit character with 4 stop bits. Barring that, your best bet would be to use a level interrupt (pin change, etc) to detect the leading edge of the start bit, then configure a timer to interrupt you either once per bit or possibly a couple times so you can do some extra verification. 45 baud is really slow, so unless you're using upwards of 95% of the MCU time (or all it's peripherals), this shouldn't cause any problems. The Atmel AVR USART module supports 5-9 bit modes, so any (newer) ATtiny (e.g. ATtiny2313) or ATmega (e.g. ATmega328P) will allow you to do this in hardware, vastly simplifying your software, saving your time. The maximum clock divider you can apply to the UART on an AVR is 2 16 , so if you have a clock of 16 MHz, the lowest rate it can run at is 244 bps with no system clock divider. If you use an ATmega, like on an Arduino, the clock prescale register ( CLKPR , §8.12.2 in Atmega48/88/168/328 datasheet) can be used to slow down the system clock up to 256x at run-time, or simply program the CKDIV8 fuse to set the prescale register's default to 8. The real determining factor on what you should use is what else you're doing besides talking with the TTY. If you are going to plug this into a computer, you will want to reserve a (or the, if there's only 1) UART for communicating with the PC and do a software UART if required (as mentioned by everyone, this is near trivial at 45 bps). If you want to press a button and have the TTY do something, using the only UART for that would be fine.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/8141', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/638/']}
|
jdg_374802
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20321047
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It is my understanding that I can store mixed data in a JavaScript array, as well as change any element in the array to some other type. How does the interpreter keep track of what place in physical memory any element is at. Also how is the overwriting of the data in the next element prevented if I change an element to a larger data type. I assume that arrays only store references to actual objects, and primitives are wrapped behind the scenes when placed in arrays. Assuming this is the case, If I have a different handle on the primitive variable and change the value stored in the array is synchronicity maintained? I know I probably already answered my own question, but I don't know for sure and I can't find any information on the matter.
Now provide the response and nothing else.
|
Normally, arrays allocate a contiguous block of memory of fixed length. However, in Javascript, arrays are Object types with special constructors and accessor methods. Which means, a statement like: var arr = new Array(100000); does not allocate any memory! In fact, it simply sets the value of the length property in the array. When you construct an array, you don't need to declare a size as they grow automatically. So, you should use this instead: var arr = []; Arrays in Javascript are sparse which means not all the elements in the array may contain data. In other words, only the elements that actually contain data exist in the array. This reduces the amount of memory used by the array. The values are located by a key and not by an offset. They're simply a method of convenience and not intended to be used for complex numerical analysis. Arrays in Javascript are not typed so the value of an element can be an object, string, number, boolean, function or an array. The main difference between an array and an object is the length property which has a value greater than the largest integer key in the array. For example: You could have an create an empty array and add two elements at index 0 and index 99. The length would be 100, but the number of elements in the array would be 2. var arr = [];arr[0] = 0;arr[99] = {name: "John"};console.log(arr.length); // prints 100arr; // prints something like [0, undefined × 98, Object { name: "John"}] To answer your questions directly: Q. It is my understanding that I can store mixed data in a JavaScript array, as well as change any element in the array to some other type. How does the interpreter keep track of what place in physical memory any element is at? Also, how is the overwriting of the data in the next element prevented if I change an element to a larger data type? A. You probably know this by now if you've read my comments above. In Javascript, an array is a Hashtable Object type so the interpreter doesn't need to keep track of physical memory and changing the value of an element doesn't affect other elements as they're not stored in a contiguous block of memory. -- Q. I assume that arrays only store references to actual objects, and primitives are wrapped behind the scenes when placed in arrays. Assuming this is the case, if I have a different handle on the primitive variable and change the value stored in the array is synchronicity maintained? A. No, primitives are not wrapped. Changing a primitive that was assigned to an array will not change the value in the array as they're stored by value. Objects on the other hand are stored by reference, so changing the objects value will reflect that change in that array. Here's an example you can try: var arr = [];var obj = { name: "John" };var isBool = true;arr.push(obj);arr[1] = isBool;console.log(arr[0]); // print obj.nameconsole.log(arr[1]); // print trueobj.age = 40; // add age to objisBool = false; // change value for isBoolconsole.log(arr[0]); // value here will contain ageconsole.log(arr[1]); // value here will still be true Also, note that when you initialize an array in the following two ways, it has a different behavior: var arr = new Array(100);console.log(arr.length); // prints 100console.log(arr); // prints []var arr2 = new Array(100, 200);console.log(arr2.length); // prints 2console.log(arr2); // prints [100, 200] If you want to use Javascript Arrays as contiguous blocks of memory, you should look into using TypedArray . TypedArray's allow you to allocate a block of memory as a byte array and access the raw binary data more efficiently. You can learn more about the intricacies of Javascript by reading the ECMA-262 spec (ver 5.1) .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20321047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3056052/']}
|
jdg_374803
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4750845
|
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 annotate a branch? It would be nice to be able to do something like: $ git notes add branch-name -m 'This branch is for whatever' but that of course is not terribly helpful, since the note applies to the current head of the branch rather than the branch itself. An easy workaround is to drop a README.branch-name in the repository, but that seems clumsy. Slightly more elegant is to have an orphaned branch containing nothing but README.branch-names. I'm looking for a way to record what the purpose of the branch is other than just putting it in the commit message for the "first" commit of the branch. I put "first" in quotes because it's not always clear what is meant by that, which is the reason it is inconvenient to put the discussion in a commit message. It's often difficult to find the commit in which such a message is recorded.
Now provide the response and nothing else.
|
This would be a totally different approach than git note but you could use git config for this functionality. $ git config branch.<branch-name>.note 'This is what this branch is for' This can be aliased to make the interface simpler (I'm guessing this can be improved but this is what I use): $ git config alias.branch-note '!git config branch.$(git symbolic-ref --short HEAD).note $( if [ $# -gt 0 ]; then $1; fi)' This allows you to set the branch note like so (make sure you quote the note): $ git branch-note 'This is what this branch is for' You can then retrieve the current branches note like this: $ git branch-noteThis is what this branch is for As an added benefit, config entries defined under the branch.<branch-name> namespace will follow branch renames and be automatically cleaned up if you delete the branch later. These superfluous config entries will only persist as long as the branch exists, at which time they will be automatically deleted. A downside to this approach is that you can only store one "note" per branch. Subsequent branch-note calls with an argument will overwrite the previous branch-note. You also don't get the benefit of storing the message in a trackable git object but maybe it will suffice for your purposes.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4750845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140750/']}
|
jdg_374804
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3549000
|
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 do simple thing: I just need to set some cells to values that are on the previous rows.I have tried =A(Row()-1) but it does not work.
Now provide the response and nothing else.
|
To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7 , I would use the formula =A6 . Then if I copied that formula to other cells, they would also use the row of the previous cell. Another option is to use Indirect() , which resolves the literal statement inside to be a formula. You could use something like: =INDIRECT("A" & ROW() - 1) The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3549000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408813/']}
|
jdg_374805
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2153053
|
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 this table: ALLITEMS---------------ItemId | Areas---------------1 | EAST2 | EAST3 | SOUTH4 | WEST The DDL: drop table allitems;Create Table Allitems(ItemId Int,areas Varchar2(20));Insert Into Allitems(Itemid,Areas) Values(1,'east');Insert Into Allitems(ItemId,areas) Values(2,'east');insert into allitems(ItemId,areas) values(3,'south');insert into allitems(ItemId,areas) values(4,'east'); In MSSQL, to get a cursor from a dynamic SQL I can do: DECLARE @v_sqlStatement VARCHAR(2000);SET @v_Sqlstatement = 'SELECT * FROM ALLITEMS';EXEC (@v_sqlStatement); --returns a resultset/cursor, just like calling SELECT In Oracle, I need to use a PL/SQL Block: SET AUTOPRINT ON;DECLARE V_Sqlstatement Varchar2(2000); outputData SYS_REFCURSOR;BEGIN V_Sqlstatement := 'SELECT * FROM ALLITEMS'; OPEN outputData for v_Sqlstatement; End;--result is : anonymous block completed **But all I get is anonymous block completed". How do I get it to return the cursor? ( I know that if I do AUTOPRINT, it will print out the information in the REFCURSOR (it's not printing in the code above, but thats another problem) ) I will be calling this Dynamic SQL from code (ODBC,C++), and I need it to return a cursor. How?
Now provide the response and nothing else.
|
You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this): CREATE OR REPLACE FUNCTION get_allitems RETURN SYS_REFCURSORAS my_cursor SYS_REFCURSOR;BEGIN OPEN my_cursor FOR SELECT * FROM allitems; RETURN my_cursor;END get_allitems; This will return the cursor. Make sure not to put your SELECT -String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it. If you really need to use dynamic SQL you can put your query in single quotes: OPEN my_cursor FOR 'SELECT * FROM allitems'; This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime. Make sure to use bind-variables where possible to avoid hard parses : OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2153053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136089/']}
|
jdg_374806
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
108104
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for information about the use of glucosamine and chondroitin for treatment of back pain and disc degeneration. A paper published in Military Medicine in 1999 reported some beneficial effects, but newer papers (references needed) do not support these conclusions. How do I search for more recent papers that cite this older paper, to decide what the current medical consensus is? Glucosamine trial (negative results): https://smallpdf.com/result#r=a595b512d3b25e41aabe7f3179ba8a4b&t=share-document Chondroitin Sulfate trial (negative results): https://smallpdf.com/result#r=b82b6b31030bfb6dffd6261a48153fe7&t=share-document Glucosamine and Chondroitin Sulfate(good results but not conclusive) https://smallpdf.com/result#r=626038b39e87cc64baab274e1d053871&t=share-document https://www.ncbi.nlm.nih.gov/pmc/articles/PMC165439/
Now provide the response and nothing else.
|
Papers provide evidence for or against various hypotheses, but no one paper is ever a definitive statement on an issue. It is expected that different trials will have different outcomes, both due to differences in the studies themselves (different inclusion/exclusion criteria, different study population, different dose/procedure, etc) and random statistical variation. It's also very important to recognize that most studies are designed to test whether there is sufficient evidence to reject a null hypothesis of no effect . Failure to reject that null hypothesis does not mean that there is no effect, it means that the results aren't different enough from what you'd expect to see if there was no effect. It may be that there is a smaller effect than the study was powered to detect. Also, consider that a properly powered study generally has a true-positive detection rate of somewhere between 80 and 90%; that means, 10-20% of the time when there's a real effect of the expected size, the study won't be able to conclude there is a significant difference. So, when there are multiple studies with different results, how do we decide what is "right"? Well, scientific consensus is built over many studies. In clinical research, the best evidence is when you have not only clinical evidence of an effect, but also an understood biological mechanism. At just the clinical level, though, studies can be combined through techniques of meta-analysis . Meta-analysis combines results from multiple studies, weights them by the size/quality of the study, and makes a comprehensive quantitative estimate from the covered literature. If you want to look for scientific consensus on something, you often want to look for recent meta analyses of that topic. In the medical field, there are also often consensus papers written on particular topics. Here's an example: Priori, S. G., Wilde, A. A., Horie, M., Cho, Y., Behr, E. R., Berul, C., ... & Tracy, C. (2013). HRS/EHRA/APHRS expert consensus statement on the diagnosis and management of patients with inherited primary arrhythmia syndromes: document endorsed by HRS, EHRA, and APHRS in May 2013 and by ACCF, AHA, PACES, and AEPC in June 2013. Heart rhythm, 10(12), 1932-1963. These statements are written by a bunch of scientists/physicians gathering together and comprehensively reviewing literature on some topic. They typically will weigh not only evidence for effect like in meta analysis, but also consider the implications of treatment options including costs, side effects, and the consequences of getting it wrong (for example, if a treatment following a wrong diagnosis masks some other condition that then goes untreated).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/108104', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/70423/']}
|
jdg_374807
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3816502
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 3 tables, Role[roleId, roleName] , Token[tokenID, tokenName] & ROLETOKENASSOCIATION[roleId, tokenID] . The 3rd one was created automatically by hibernate. Now if i simply write a Query to get all the objects from Role class means, it gives the all role objects along with the associated tokenID & tokenName. I just wanted the association as unidirectional. i.e: Roles--->TokensSo the annotation in the Role class looks like, @Id@GeneratedValue(strategy=GenerationType.AUTO)private int roleId;private String roleName;@ManyToMany@JoinTable(name="ROLE_TOKEN_ASSOCIATION", joinColumns={@JoinColumn(name="roleId")}, inverseJoinColumns={@JoinColumn(name="tokenID")})private List<Token> tkns; //Getters & Setters Now i want the tokenNames for the specific roleId.First i made a query like this SELECT tkns.tokenName FROM Role WHERE Role.roleId=:roleId But, i ended up with some dereference error. Then i changed the query to SELECT tkns FROM Role r WHERE r.roleId=:roleId Now i have got what i wanted. But it comes with roleId too. How shall i get tokenName itself?Actually my problem is solved, but i would like to know how to do it. It ll be helpful to me, if anyone explains the Query Construction. Any suggestions!!
Now provide the response and nothing else.
|
Have you tried SELECT t.tokenName FROM Role r JOIN r.tkns t WHERE r.roleId = :roleId EDIT: This query almost directly maps to the corresponding SQL query where Role r JOIN r.tkns t is a shorthand syntax for the SQL join via the link table Role r JOIN ROLETOKENASSOCIATION rt ON r.roleId = rt.roleId JOIN Token ON rt.tokenId = t.tokenId . Affe's answer is another syntax for the same query. See also: Chapter 14. HQL: The Hibernate Query Language
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3816502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_374808
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
340240
|
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:
$$101110 - 110111$$ Did the 2's complment and cannot get to the answer. The answer is apparently $$-1001$$ I did 2's complment on the $$110111$$and performed addition but did not get to the answer.But I heard that I have to "zero-fill" before i do it or something
Now provide the response and nothing else.
|
$$101110 - 110111 = 101110 + 001001 = 110111$$ with $110111$ being in two's complement (since it has a leading $1$, hence, equivalent to binary $-001001 \; = \;-1001$ The trick I use to go back and forth from two's complement is to switch ALL digits (reverse $1\to 0, 0 \to 1$, then add one bit $1$ ($+000001$ in this case)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/340240', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/47757/']}
|
jdg_374809
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
77887
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul? ie (the only dump I have on hand with me actually) >b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[
Now provide the response and nothing else.
|
First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type: SRV*c:\symbols*http://msdl.microsoft.com/download/symbols You can find more information on how to correctly configure the symbols here . Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type: kpn 200 This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you'll get something like: 01 MODULE!CLASS.FUNCTIONNAME1(...)02 MODULE!CLASS.FUNCTIONNAME2(...)03 MODULE!CLASS.FUNCTIONNAME3(...)04 MODULE!CLASS.FUNCTIONNAME4(...) Where: THE FIRST NUMBER : Indicates the frame number MODULE : The DLL that contains the code CLASS : (Only on C++ code) will show you the class that contains the code FUNCTIONAME : The method that was called. If you have the correct symbols you will also see the parameters. You might also see something like 01 MODULE!+989823 This indicates that you don't have the proper Symbol for this DLL and therefore you are only able to see the method offset. So, what is a callstack? Imagine you have this code: void main(){ method1();}void method1(){ method2();}int method2(){ return 20/0;} In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack: 01 MYDLL!method2()02 MYDLL!method1()03 MYDLL!main() You can follow from this callstack that "main" called "method1" that then called "method2" and it failed. In your case you've got this callstack (which I guess is the result of running "kb" command) b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4_disp) and the offset of the method that is being executed (+0x48b94). Since you don't have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can't get much information from here. I recommend you run "kpn 200". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you). At least you know it's related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version. In case you want to learn more about WinDBG debugging I recommend the following links: If broken it is, fix it you should TechNet Webcast: Windows Hang and Crash Dump Analysis Delicious.com popular links on WinDBG
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/77887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14173/']}
|
jdg_374810
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47306
|
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:
According to what I've read so far, "when the kernel receives an interrupt, all the registered handlers are invoked." I understand that the registered handlers for each IRQ can be viewed via /proc/interrupts , and I also understand that the registered handlers come from the drivers that have invoked request_irq passing in a callback roughly of the form: irqreturn_t (*handler)(int, void *) Based on what I know, each of these interrupt handler callbacks associated with the particular IRQ should be invoked, and it is up to the handler to determine whether the interrupt should indeed be handled by it. If the handler should not handle the particular interrupt it must return the kernel macro IRQ_NONE . What I am having trouble understanding is, how each driver is expected to determine whether it should handle the interrupt or not. I suppose they can keep track internally if they're supposed to be expecting an interrupt. If so, I don't know how they'd be able to deal with the situation in which multiple drivers behind the same IRQ are expecting an interrupt. The reason I'm trying to understand these details is because I'm messing with the kexec mechanism to re-execute the kernel in the middle of system operation while playing with the reset pins and various registers on a PCIe bridge as well as a downstream PCI device. And in doing so, after a reboot I'm either getting kernel panics, or other drivers complaining that they're receiving interrupts even though no operation was taking place. How the handler decided that the interrupt should be handled by it is the mystery. Edit: In case it's relevant, the CPU architecture in question is x86 .
Now provide the response and nothing else.
|
This is covered in chapter 10 of Linux Device Drivers , 3rd edition, by Corbet et al. It is available for free online , or you may toss some shekels O'Reilly's way for dead tree or ebook forms. The part relevant to your question begins on page 278 in the first link. For what it's worth, here is my attempt to paraphrase those three pages, plus other bits I've Googled up: When you register a shared IRQ handler, the kernel checks that either: a. no other handler exists for that interrupt, or b. all of those previously registered also requested interrupt sharing If either case applies, it then checks that your dev_id parameter is unique, so that the kernel can differentiate the multiple handlers, e.g. during handler removal. When a PCI¹ hardware device raises the IRQ line, the kernel's low-level interrupt handler is called, and it in turn calls all of the registered interrupt handlers, passing each back the dev_id you used to register the handler via request_irq() . The dev_id value needs to be machine-unique. The common way to do that is to pass a pointer to the per-device struct your driver uses to manage that device. Since this pointer must be within your driver's memory space for it to be useful to the driver, it is ipso facto unique to that driver.² If there are multiple drivers registered for a given interrupt, they will all be called when any of the devices raises that shared interrupt line. If it wasn't your driver's device that did this, your driver's interrupt handler will be passed a dev_id value that doesn't belong to it. Your driver's interrupt handler must immediately return when this happens. Another case is that your driver is managing multiple devices. The driver's interrupt handler will get one of the dev_id values known to the driver. Your code is supposed to poll each device to find out which one raised the interrupt. The example Corbet et al. give is that of a PC parallel port. When it asserts the interrupt line, it also sets the top bit in its first device register. (That is, inb(0x378) & 0x80 == true , assuming standard I/O port numbering.) When your handler detects this, it is supposed to do its work, then clear the IRQ by writing the value read from the I/O port back to the port with the top bit cleared. I don't see any reason that particular mechanism is special. A different hardware device could choose a different mechanism. The only important thing is that for a device to allow shared interrupts, it has to have some way for the driver to read the interrupt status of the device, and some way to clear the interrupt. You'll have to read your device's datasheet or programming manual to find out what mechanism your particular device uses. When your interrupt handler tells the kernel it handled the interrupt, that doesn't stop the kernel from continuing to call any other handlers registered for that same interrupt. This is unavoidable if you are to share an interrupt line when using level-triggered interrupts. Imagine two devices assert the same interrupt line at the same time. (Or at least, so close in time that the kernel doesn't have time to call an interrupt handler to clear the line and thereby see the second assertion as separate.) The kernel must call all handlers for that interrupt line, to give each a chance to query its associated hardware to see if it needs attention. It is quite possible for two different drivers to successfully handle an interrupt within the same pass through the handler list for a given interrupt. Because of this, it is imperative that your driver tell the device it is managing to clear its interrupt assertion sometime before the interrupt handler returns. It's not clear to me what happens otherwise. The continuously-asserted interrupt line will either result in the kernel continuously calling the shared interrupt handlers, or it will mask the kernel's ability to see new interrupts so the handlers are never called. Either way, disaster. Footnotes: I specified PCI above because all of the above assumes level-triggered interrupts, as used in the original PCI spec. ISA used edge-triggered interrupts, which made sharing tricky at best, and possible even then only when supported by the hardware. PCIe uses message-signalled interrupts; the interrupt message contains a unique value the kernel can use to avoid the round-robin guessing game required with PCI interrupt sharing. PCIe may eliminate the very need for interrupt sharing. (I don't know if it actually does, just that it has the potential to.) Linux kernel drivers all share the same memory space, but an unrelated driver isn't supposed to be mucking around in another's memory space. Unless you pass that pointer around, you can be pretty sure another driver isn't going to come up with that same value accidentally on its own.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/47306', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14186/']}
|
jdg_374811
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22940724
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using the Go resize package here: https://github.com/nfnt/resize I am pulling an Image from S3, as such: image_data, err := mybucket.Get(key)// this gives me data []byte After that, I need to resize the image: new_image := resize.Resize(160, 0, original_image, resize.Lanczos3)// problem is that the original_image has to be of type image.Image Upload the image to my S3 bucket err : = mybucket.Put('newpath', new_image, 'image/jpg', 'aclstring')// problem is that new image needs to be data []byte How do I transform a data []byte to ---> image.Image and back to ----> data []byte ?
Now provide the response and nothing else.
|
Read http://golang.org/pkg/image // you need the image package, and a format package for encoding/decodingimport ( "bytes" "image" "image/jpeg" // if you don't need to use jpeg.Encode, use this line instead // _ "image/jpeg" "github.com/nfnt/resize" )// Decoding gives you an Image.// If you have an io.Reader already, you can give that to Decode // without reading it into a []byte.image, _, err := image.Decode(bytes.NewReader(data))// check errnewImage := resize.Resize(160, 0, original_image, resize.Lanczos3)// Encode uses a Writer, use a Buffer if you need the raw []byteerr = jpeg.Encode(someWriter, newImage, nil)// check err
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22940724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2441725/']}
|
jdg_374812
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
408508
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In algebraic topology, relative (co)homology is very useful. For example, we have a long exact sequence which is often helpful for lots of calculations. In algebraic geometry, we have local cohomology, which is basically the same thing and has the same long exact sequence. However, while the commutative algebra community seems to use this a lot, it seems to be rarely used in algebraic geometry. Is indeed local cohomology more useful in commutative algebra than it is in algebraic geometry? If so, why? (I'm primarily talking about the Zariski topology, but we also have local cohomology in any context where we have six functors; in étale cohomology, in de Rham cohomology, etc. I would also like to know something about local cohomology in these contexts.)
Now provide the response and nothing else.
|
I teach a course on Applied Linear Algebra, intended for Engineers, where the final project is always to give a presentation on an application of linear algebra in the student's field of study. Since I myself am not an engineer, I often learn new things here, but there is the risk that my level of understanding is no better than an undergraduate engineer. With this caveat, one of the common topics my students talk about is image identication. You have, say, $M$ reference photos of people's faces, each of them $K \times K$ grey-scale pixels and positioned similarly in the camera frame. You get a new photo and you want to identify which face it is most like. The naive thing to due is to treat each of the $M$ images as a vector with $K^2$ entries, and find the reference photo in $K^2$ dimensional space which is closest to your photo. The trouble is that you will be thrown off by random noise introduced by the photography process, and you will get a face which is closest to your photo in the directions of random variation, and not in the directions that faces naturally vary. A better idea is to use SVD on the $M \times K^2$ matrix whose columns are your reference photos, to find a lower dimensional plane $V$ in $K^2$ -dimensional space, such that all of your reference photos are close to $V$ . Then project all the reference photos, and the input photo, onto $V$ , before finding the closest one. This way, the output photo will be close to the input photo in the ways in which faces vary, while the random noise will be projected away. This is called the eigenfaces method. It can of course apply to images other than faces, such as optical character recognition.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/408508', 'https://mathoverflow.net', 'https://mathoverflow.net/users/131975/']}
|
jdg_374813
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13430352
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to SML.How do I use the AND operator inside IF statements?Here is my code: val y = 1;val x = 2;if (x = 1 AND y = 2) then print ("YES ") else print("NO "); My error is:stdIn:66.9-67.3 Error: unbound variable or constructor: ANDstdIn:66.3-67.9 Error: operator is not a function [literal] operator: int in expression: 1 stdIn:66.3-67.9 Error: operator and operand don't agree [literal] operator domain: bool * bool operand: bool * int in expression: x = (1 ) y = 2 Thank you
Now provide the response and nothing else.
|
There is no AND operator in SML (unless you define one yourself). There is an and keyword, but you can't use it inside if statements (or generally as a part of any expression) because it's not an operator. It's used in combination with fun to define mutually recursive functions. You're probably looking for the andalso operator, which takes two boolean operands and returns true if and only if both operands are true.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13430352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232362/']}
|
jdg_374814
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29843250
|
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 filter a paginated eloquent collection, but whenever I use any of the collection methods, I lose the pagination. $models = User::orderBy('first_name','asc')->paginate(20);$models = $models->each(function($model) use ($filters) { if(!is_null($filters['type'])) { if($model->type == $filters['type']) return $model; } if(!is_null($filters['state_id'])) { if($model->profile->state_id == $filters['state_id']) return $model; } if(!is_null($filters['city_id'])) { if($model->profile->city_id == $filters['city_id']) return $model; }});return $models; I am working with Laravel 4.2, is there any way to persist the pagination?
Now provide the response and nothing else.
|
Expanding on mininoz's answer with your specific case: //Start with creating your object, which will be used to query the database$queryUser = User::query();//Add sorting$queryUser->orderBy('first_name','asc');//Add Conditionsif(!is_null($filters['type'])) { $queryUser->where('type','=',$filters['type']);}if(!is_null($filters['state_id'])) { $queryUser->whereHas('profile',function($q) use ($filters){ return $q->where('state_id','=',$filters['state_id']); });}if(!is_null($filters['city_id'])) { $queryUser->whereHas('profile',function($q) use ($filters){ return $q->where('city_id','=',$filters['city_id']); });}//Fetch list of results$result = $queryUser->paginate(20); By applying the proper conditions to your SQL query, you are limiting the amount of information that comes back to your PHP script, and hence speeding up the process. Source: http://laravel.com/docs/4.2/eloquent#querying-relations
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29843250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/754865/']}
|
jdg_374815
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1516038
|
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 c++ what will be the fastest logic to find next palindrome of a given 15 digit number? for example what will be the next palindrome of: 134567329807541 ?
Now provide the response and nothing else.
|
Split the number into three parts, head , mid , tail 1345673 2 9807541 Reverse head and compare it to tail 3765431 If reverse(head) <= tail ( if they are equal the initial input is a palindrome, and you want the next ) If mid < 9 , increment mid Else increment head part and set mid := 0 result := head mid reverse(head) . 1345673 3 reverse(1345673) => 134567333765431
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1516038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172543/']}
|
jdg_374816
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
154889
|
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:
As I understand it, the concept of potential energy arises from analytical mechanics. Yet I often see the concept of electric potential $\phi$ introduced without mention of analytical mechanics. For example, Electricity and Magnetism by Purcell doesn't discuss analytical mechanics. I have always found this confusing because I don't get why it's not called electric potential energy . Why is this? Am I just reading the wrong books? Am I mistaken that electric potential is a form of potential energy and therefore related to analytical mechanics? What's going on here? Note: I understand electric potential is the analog of gravitational potential. That fact however hasn't helped me answer the above.
Now provide the response and nothing else.
|
Suppose I have an electric field $E$ pointing to the right.Now I take a positive charge $q$ and push it from position $0$ to position $-l$.The force required for the push was $F=qE$, so the work I did was $$W = Eql \,.$$ Note that the work is proportional to the charge $q$.This work is now stored as electrostatic potential energy.We define the electric "potential" as the potential energy per charge .In other words, $$\phi = El\,.$$ That's all there is to it.Whenever potential energy is proportional to something intrinsic to the body storing the energy, we define "potential" as the energy divided by that instrinsic quantity.This is useful because it characterizes the system in a way that doesn't depend on properties of your test particle.Note that electric potential does not carry any more or less information than the electric field.In fact, electric potential and electric field are related via $$\vec{E} = -\nabla \phi \,.$$ Another example is gravitational potential on Earth's surface, $gh$, which is the potential energy of a test particle of mass $m$, $mgh$, divided by the mass. Note that you can remember the dimensions of electric potential to be "energy per charge".
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/154889', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/66165/']}
|
jdg_374817
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
73254
|
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'm powering a device with a series-connected stack of rechargeable batteries, can I pull different voltages at different points and route them to different components? I need to run a 12V solenoid, an Arduino (6V-12V recommended), some stepper motors (around 5 or 6V), and possibly a servo (though that can probably come straight off the Arduino). If I have, for example, four 3V cells, can I grab 6V from two of them and 12V from all four at the same time, or will that do bad things to the cells' relative charge? Space and complexity are constraints here, so adding a regulator might be possible but would make things more complicated. Alternatively, would using higher-capacity cells adding up to 6V and a boost converter to get the 12V work? I'd be concerned about current, but my fears might be baseless.
Now provide the response and nothing else.
|
Your scheme of tapping off the batteries at different points will work. However nothing is for free. The batteries used in both the 6V circuit (let's call them Bat1) and the 12V circuit (call them Bat2) will see more power drain than the two used for just the 12V circuit. The problem arises when you want to recharge them in series. Bat2 which will have more energy than Bat1 will raise the voltage of Bat1 + Bat2 faster than normal. Often this causes the charger to back off the current, which ends up leaving Bat1 undercharged. They cycle can worsen over multiple uses leaving Bat1 either undercharged or overcharging Bat2. This is why most electronics derive the power they need from the batteries keeping the charge and discharge paths identical. You could choose either to boost the 6V or regulate the 12V. Typically the decision is made by which circuit needs the most power delivered to it. In your example if the motors take 2x more current than the rest of the design, then it would make sense to optimize the delivery of the supply to the motors. If everything is about equal, then it comes down to looking at the cost/efficiency of linear regulation (less EMI and simpler) versus boosting it (noisier and more components).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/73254', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/25398/']}
|
jdg_374818
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30577252
|
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 SearchView inside my ActionBar , and I want to use the entire ActionBar when the search icon is pressed, but I can only use the ActionBar free space eg.: http://imgur.com/wnjMfWO my menu code: <menu xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"tools:context="br.com.moderna.houaiss.activity.SearchActivity" ><item android:id="@+id/search" android:actionViewClass="android.widget.SearchView" android:icon="@drawable/ic_search_white_48dp" android:showAsAction="collapseActionView|always" android:title="@string/search"/><item android:id="@+id/backWardHistory" android:icon="@drawable/ic_arrow_back_white_48dp" android:showAsAction="always" android:title="@string/back_history"/><item android:id="@+id/forWardHistory" android:icon="@drawable/ic_arrow_forward_white_48dp" android:showAsAction="always" android:title="@string/forward_history"/><item android:id="@+id/action_home" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_home"/><item android:id="@+id/action_about" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_about"/><item android:id="@+id/action_configuration" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_configuration"/><item android:id="@+id/action_logout" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_logout"/> I had tryed android:showAsAction="ifRoom" , but I need them to be always on my ActionBar , and not inside my menu. EDIT ------ Thanks to @Simas, I used setOnActionExpandListener method to achieve this effect final MenuItem searchItem = menu.findItem(R.id.search); searchItem.setOnActionExpandListener(new OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(final MenuItem item) { SearchActivity.this.setItemsVisibility(menu, searchItem, false); return true; } @Override public boolean onMenuItemActionCollapse(final MenuItem item) { SearchActivity.this.setItemsVisibility(menu, searchItem, true); return true; } });private void setItemsVisibility(final Menu menu, final MenuItem exception, final boolean visible) { for (int i = 0; i < menu.size(); ++i) { MenuItem item = menu.getItem(i); if (item != exception) item.setVisible(visible); }}
Now provide the response and nothing else.
|
Well you could imitate that yourself by hiding all the other items when the SearchView is expanded: @Overridepublic boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); final MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (android.widget.SearchView) searchItem.getActionView(); // Detect SearchView icon clicks searchView.setOnSearchClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setItemsVisibility(menu, searchItem, false); } }); // Detect SearchView close searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { setItemsVisibility(menu, searchItem, true); return false; } }); return super.onCreateOptionsMenu(menu);}private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) { for (int i=0; i<menu.size(); ++i) { MenuItem item = menu.getItem(i); if (item != exception) item.setVisible(visible); }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30577252', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3672263/']}
|
jdg_374819
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47523384
|
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 type User . Users can also be a type TeamMember . The only difference between a User and TeamMember is an added field teamRole: String . So, I’d love to do something like the following to avoid having to redundantly define all the user's fields… type User { id: ID!, name: String, (many other field defs) } type TeamMember extends User { teamRole: String, } Anyone aware of a syntax for this? I thought extend would be the answer, but it seems more like javascript’s prototype
Now provide the response and nothing else.
|
The extend keyword is great if you have a base schema and want to build two or more usable schemas based on it. You can, for example, define a root Query type with queries shared by all schemas, and then extend it within each individual schema to add queries specific to that schema. It can also be used to modularize a schema. However, it's only a mechanism to add functionality to existing types -- it can't be used to create new types. GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types. You can utilize string interpolation to avoid typing out the same fields again and again: const sharedFields = ` foo: String bar: String`const typeDefs = ` type A { ${sharedFields} } type B { ${sharedFields} }` Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types. Schemas generated this way still have to be compiled to valid SDL though -- at best, libraries like graphql-s2s just offer some syntactic sugar and a better DX. Lastly, you can restructure your types to avoid the field duplication altogether at the cost of a more structured response. For example, instead of doing this: type A { a: Int foo: String bar: String}type B { b: Int foo: String bar: String} you can do this: type X { foo: String bar: String aOrB: AOrB}union AOrB = A | Btype A { a: Int}type B { b: Int}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47523384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349269/']}
|
jdg_374820
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7700
|
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:
For a hypothetical orbital system (Sun + single planet) the Newtonian model and the General Relativity (GR) model produce different expressions for the gravitational effect of the Sun on the planet. This is well known. The ratio between the Newtonian and GR effects is expressed in different ways by different writers. I am having trouble reconciling two such expressions of the Newtonian:GR ratio. Firstly Walter (2008) (equation 12.7.6, page 482) presents the following expression for the equation of motion produced from the GR model $$\frac{d^2\,u}{d\theta^2} + u = \frac{GM}{h^2} + \frac{3GM}{c^2}u^2$$where $u= (1/r)$, $h=vr$, $G$ is the universal constant of gravitation, $M$ is mass of the Sun, $c$ is speed of light. Here the term $GM/h^2$ is the ordinary Newtonian term and the term $3GMu^2/c^2$ is the additional term introduced by GR. From this Walter derives the approximate ratio between Newtonian and GR effects as$(1)$ to $(1 + 3v^2/c^2)$ where $v = \sqrt{GM/r}$ is the orbital speed of the planet in a circular orbit (with distance $r$ = $a$, the semi-major axis). Secondly, an alternative presentation (referring to the so-called Schwartzchild solution) is given by Goldstein in Classical Mechanics (3rd Edition) pages 536-538. The GR potential $V_{GR}$ is given by$$V = -\frac{GMm}{r} -\frac{b}{r^3}$$where $m$ is the target body mass and $b$ is a constant (Goldstein uses $h$ instead of $b$, see below, but I have already used $h$ to mean something different in Walter above,) differentiating the potential with respect to distance $r$ to give force we derive$$F_{GR} = \frac{GMm}{r^2} + \frac{3b}{r^4}$$ Now Goldstein defines the constant $b$ thus :-$$b = \frac{k\,l^2}{m^2c^2} \qquad\text{ Goldstein eqtn [12.48]} $$where$$k=GMm $$and $$l^2 = mka(1-e^2) \qquad\text{ Goldstein eqtn[12.50]}$$ So $$b = \frac{GMm\, m\, GMm\, a(1-e^2)}{m^2c^2}= \frac{GMm \, L^2}{c^2}= \frac{GMm \,m^2 v_c^2 a^2}{c^2}$$ So the GR force equation becomes$$F_{GR} = \frac{GMm}{r^2} + \frac{3GMm m^2 v_c^2 a^2}{r^4c^2}$$substituting $a$ by $r$ we get$$F_{GR} = \frac{GMm}{r^2} + \frac{3GMm m^2 v_c^2}{r^2c^2}= \frac{GMm}{r^2} \left( 1 + \frac{3 v_c^2 \, m^2}{c^2} \right)$$ So the Newtonian:GR ratio derived from Goldstein is the same as the ratio derived by Walter except that the former has the additional term of $m^2$ in the numerator.Even if we tried to fudge this numerically by invoking a unit mass target, it would still be dimensionally incorrect. So what is the correct ratio?$$$$ UPDATE --------------------------------------------------------------------- In the refactoring of $b$ I used angular momentum $L$ when I should have used specific angular momentum $\mathfrak{l}$. After correction the extra $m^2$ disappears. Goldstein agrees with Walter. My thanks to Stan Liou for illumination. Corrected analysis:-$$b = \frac{GMm\, m\, GMm\, a(1-e^2)}{m^2c^2}= \frac{GMm \, \mathfrak{l}^2}{c^2}= \frac{GMm \,v_c^2 a^2}{c^2}$$ So the GR force equation becomes$$F_{GR} = \frac{GMm}{r^2} + \frac{3GMm v_c^2 a^2}{r^4c^2}$$substituting $a$ by $r$ we get$$F_{GR} = \frac{GMm}{r^2} + \frac{3GMm v_c^2}{r^2c^2}= \frac{GMm}{r^2} \left( 1 + \frac{3 v_c^2}{c^2} \right)$$ So the correct ratio of Newtonian to GR gravitational force is:-$$F_{Newtonian}:F_{GR}\approx 1: \left( 1 + \frac{3 v_c^2}{c^2} \right)$$ NOTES This ratio is approximate and only applies in the "low velocity, weak field" sub-domain of the GR model. Goldstein also emphasises that the GR effect is not a velocity effect (presumably as in the velocity of the target body through any kind of aether or flux). Coincidentally (in the same sub-domain e.g. Mercury orbitting the Sun) a modified Newtonian radial force of magnitude $f=GMm/r^2 * [1 + 3v_t^2/c^2]$, where $v_t$ is the instantaneous transverse velocity of a small target planet, produces non-Newtonian apsidal rotation ("perihelion precession") of the same magnitude (within 1%) as GR. Goldstein needs to be read with care. Here he uses $l$ to denote angular momentum elsewhere (e.g. eqtn [1.7]) he uses $L$. He often refers to $V$ as "potential" when he is clearly referring to "potential energy" (e.g. eqtn [3.49]).
Now provide the response and nothing else.
|
Orbits in Schwarzschild spacetime can be described by the effective potential$$V_\text{eff} = -\frac{GM}{r} + \frac{\mathfrak{l}^2}{2r^2} - \frac{GM\mathfrak{l}^2}{c^2r^3}\text{,}$$where $\mathfrak{l} = r^2\dot{\phi}$ is the specific angular momentum of the orbit, which is a conserved quantity. The first two terms match the form of the Newtonian effective potential, except that here we're referring to the Schwarzschild radial coordinate $r$ and proper time of the orbiting particle, instead of radial distance and coordinate time. The first term being the usual gravitational potential and the second being the centrifugal potential, so Goldstein's $V$ does make some sense as a gravitational potential energy term instead. Therefore, $l^2 = mka(1-e^2)$ with $k = GMm$ means that $l$ is the angular momentum, $l = m\mathfrak{l}$, and$$\frac{GM\mathfrak{l}^2}{c^2r^3}m = GMm\frac{l^2}{m^2}\frac{1}{c^2r^3} = \underbrace{\frac{kl^2}{m^2c^3}}_b\frac{1}{r^3}\text{,}$$just as Goldstein says. If we differentiate $\frac{1}{2}m\dot{r}^2 + mV_\text{eff} = \mathcal{E}$ with respect to proper time, then$$\begin{eqnarray*}m\ddot{r} - \frac{l^2}{mr^3} &=& -\frac{k}{r^2} - \frac{3b}{r^4}\\&=& -\frac{k}{r^2}\left(1 + 3\frac{l^2}{m^2c^2}\frac{1}{r^2}\right)\\&=& -\frac{k}{r^2}\left(1 + 3\frac{m(GMm)a(1-e^2)}{m^2c^2}\frac{1}{r^2}\right)\\&=& -\frac{k}{r^2}\left(1 + 3\frac{v_c^2}{c^2}\frac{a(1-e^2)}{r}\right)\text{.}\end{eqnarray*}$$This is dimensionally correct, as both $v_c/c$ and $a/r$ are dimensionless, while$$\frac{l^2}{mr^3} = \frac{k}{r^2}\frac{a(1-e^2)}{r}\text{.}$$The left-hand side has the Newtonian form.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/7700', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/233/']}
|
jdg_374821
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24771297
|
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 implementing widget with listview based on this tutorial: http://laaptu.wordpress.com/2013/07/24/populate-appwidget-listview-with-remote-datadata-from-web/ (source code: https://github.com/laaptu/appwidget-listview/tree/appwidget-listview2/ ). ListView item contains text & image, for image loading I use Picasso. getViewAt implementation: public RemoteViews getViewAt(int position) { final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.listview_item); ListItem listItem = listItemList.get(position); remoteView.setTextViewText(R.id.headline, listItem.headline); final String imageUrl = listItem.image; handler.post(new Runnable() { @Override public void run() { if (!Utils.isEmpty(imageUrl)) { picasso.load(imageUrl) .placeholder(R.drawable.empty_photo) .into(remoteView, R.id.picture, new int[] { appWidgetId }); } } }); return remoteView;} When the image loaded, it breaks layout. What can be a possible problem? Or what am I doing wrong? Without image loading: How it looks after image is loaded: UPDATE: The same happens if I just add a few nested remote views (all inflated from one layout) UPDATE2: Reported an issue: https://github.com/square/picasso/issues/587
Now provide the response and nothing else.
|
After struggling with this myself, I decided that blocking the background thread was ok (using .get() with Picasso) and was able to get the following to work inside my adapter: @Override public RemoteViews getViewAt(int position) { DBItem item = list.get(position); RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.widget_item); try { Bitmap b = Picasso.with(context).load(item.getImageUrl()).get(); view.setImageViewBitmap(R.id.widget_image, b); } catch (IOException e) { e.printStackTrace(); } view.setTextViewText(R.id.widget_title, item.getTitle()); return view; } If you know the size of the image coming back (if it's always the same or you can predict it), you might want to do something like this as well to cut down on resize jitters: @Override public RemoteViews getLoadingView() { return new RemoteViews(context.getPackageName(), R.layout.v2_widget_item_loading); } Performance is very smooth, no loading jitters, I'm pretty happy with the result.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24771297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/925034/']}
|
jdg_374822
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
64442820
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I noticed this today in my Chrome. Google Meet is showing a chart of CPU usage in their "Troubleshooting" panel. I'm wondering if there's an existing API for this or is it a clever trick I'm not aware of.
Now provide the response and nothing else.
|
I was curious about this as well when I saw the CPU Usage graph on the Troubleshooting page on the Google Meet's page. So googled a lot and I couldn't find any proper answer as to how it is being achieved apart from this link: https://developer.chrome.com/extensions/system_cpu#method-getInfo . So, I went through the minified source code of the Google Meet's site and it turns out Google Meet is using this but not on their webpage directly, because it is for chrome extensions only, but through the Google Hangouts Extension which is present in Chrome, Brave and the new Microsoft Edge (Chromium-based). The chrome extension is calling the chrome.system.cpu API to get the information about the processor, core count, temperatures, etc., and these details are being passed to the Google Meets page via window.postMessage API and Message Passing between Chrome Extension and a Webpage. This is a neat little way to achieve this if you are the creator of the browser :P.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64442820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6306919/']}
|
jdg_374823
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
832259
|
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 know that these rolls are independent events and order does not matter so this is a combination problem. I know that on a six sided die there are $2$ perfect squares $(1,4)$. Do I just do $5 \choose 2$ (Five times, two perfect squares) or is there another way to do this problem. Thanks in advance.
Now provide the response and nothing else.
|
That's almost it. You multiply the probabilities of getting it 2 times and not getting it 3 times in a specific order, by the count of permutations of that order. It's a binomial distribution . $p=\frac 2 6, n=5, k=2 \implies$ $${n\choose k}p^k(1-p)^{(n-k)} = \frac{^5C_2 2^2 4^3}{6^5} \\ = \frac{80}{243} $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/832259', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/144926/']}
|
jdg_374824
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43421
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using an IC ( STM6600 ) which, among other functions that I need, is also capable of Undervoltage Monitoring. It works like this: The IC monitors VCC in comparison to two thresholds, V_Low and V_High (which is just V_Low+V_Hysteresis). When VCC < 3.10V (V_Low), then its status output = LOW (undervoltage condition) When VCC > 3.30V (V_High), then its status output = HIGH (normal condition) (Thus V_Hysteresis = 0.20V .) The problem is : I'd like the status LOW condition at VCC < 3.45 V I'd like the status HIGH condition at VCC > 3.55 V (Thus, I'd like V_Hysteresis = 0.10V .) Since I obviously can't change the IC's operation itself, I am therefore trying to instead find a way to add some voltage-scaling circuitry in between my original supply (V_battery) and VCC of this IC. What are some ways I can accomplish this? Note:I considered a resistive divider as well as a diode-based drop, but I couldn't solve it with either of those because the necessity above is not a proportional scaling . One other way might be to use a low-power microcontroller w/ ADC in between, read the voltage, and PWM-output the mapped/scaled voltage. But I was wondering if there are simpler options.
Now provide the response and nothing else.
|
What are some ways I can accomplish this? Using an offset and a gain, \$V + A(V_{battery}) = V_{CC} \$, the equations are: \$V + A(3.45V) = 3.1V \$ \$V + A(3.55V) = 3.3V \$ The solution is: \$ A = 2, V = -3.8V \$ This would be straightforward to implement with a simple opamp circuit. I can post one later if you're interested. Also, really, I'm just interested in the academic value of knowing how to do this kind of linear voltage transformation generally speaking Here's a circuit fragment to illustrate the basic idea. This should get you started.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/43421', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/14008/']}
|
jdg_374825
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13586502
|
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 learning git and using JGit to access Git repos from java code. Git by default does not allow to clone to a non-empty directory. How do we figure out that a git clone has already been done for a particular git repo in the local machine so that we can only do a Git pull subsequently? Currently I'm using this approach: if a root folder is existing in the specified location clone has been done pull else clone Not sure if this is correct though. Any better ideas? Thank you.
Now provide the response and nothing else.
|
This is the approach I used, as specified in the Jgit mailing list: Check if a git repository is existing: if (RepositoryCache.FileKey.isGitRepository(new File(<path_to_repo>), FS.DETECTED)) { // Already cloned. Just need to open a repository here.} else { // Not present or not a Git repository.} But this is insufficient to check if the git clone was 'successful'. A partial clone could make isGitRepository() evaluate to true. To check if the git clone was done successfully, need to check at least if one reference is not null: private static boolean hasAtLeastOneReference(Repository repo) { for (Ref ref : repo.getAllRefs().values()) { if (ref.getObjectId() == null) continue; return true; } return false;} Thanks Shawn Pearce for the answer!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13586502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337962/']}
|
jdg_374826
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8304702
|
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 task that needs to be performed every 1 second. Currently I have an NSTimer firing repeatedly every 1 sec. How do I have the timer fire in a background thread (non UI-thread)? I could have the NSTimer fire on the main thread then use NSBlockOperation to dispatch a background thread, but I'm wondering if there is a more efficient way of doing this.
Now provide the response and nothing else.
|
If you need this so timers still run when you scroll your views (or maps), you need to schedule them on different run loop mode. Replace your current timer: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; With this one: NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; For details, check this blog post: Event tracking stops NSTimer EDIT : second block of code, the NSTimer still runs on the main thread, still on the same run loop as the scrollviews. The difference is the run loop mode . Check the blog post for a clear explanation.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8304702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/527525/']}
|
jdg_374827
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
801279
|
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 get the version and vendor of the compiler used by the user through qmake? What I need is to disable building some targets of my project when g++ 3.x is used and enable them when g++ 4.x is used. Update: Most answers targeted the preprocessor. This is something that I want to avoid. I don't want a target to be build for a specific compiler version and I want this decision to be made by the build system.
Now provide the response and nothing else.
|
In addition to ashcatch 's answer, qmake allows you to query the command line and get the response back as a variable. So you could to something like this: linux-g++ { system( g++ --version | grep -e "\<4.[0-9]" ) { message( "g++ version 4.x found" ) CONFIG += g++4 } else system( g++ --version | grep -e "\<3.[0-9]" ) { message( "g++ version 3.x found" ) CONFIG += g++3 } else { error( "Unknown system/compiler configuration" ) }} Then later, when you want to use it to specify targets, you can use the config scoping rules: SOURCES += blah blah2 blah3g++4: SOURCES += blah4 blah5
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/801279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6403/']}
|
jdg_374828
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5334
|
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I often see specifications for refurbishing works on gas pipelines calling for blanking spades, to separate the area worked on from the rest of the gas system. This is in addition to closing valves. Googling showed me some pictures of how blanking spades look like, but I don't yet understand the process of installing them. The most straightforward way would be to mount them between flanges, after a section of pipe has been valved off and flushed. How are blanking spades actually used?
Now provide the response and nothing else.
|
The most straightforward way would be to mount them between flanges, after a section of pipe has been valved off and flushed. This is correct. Blanking spades, also known as slip plates, slip blinds or spectacle blinds, are usually slipped in between two flanges after a process line has been double blocked and bled. They are usually secured in place by the flange bolts and sealed by a gasket or O-ring, similar to how wafer pattern valves are installed. Sometimes dedicated 'blind flanges' are provided in the pipeline for this purpose, but often the inlet or outlet flanges on valves or equipment are used. Blanking plates are used to provide an additional layer of protection during maintenance work, guarding against leaking valves or negligent opening of an isolation valve. Other important considerations when using them are: That they are installed in a sensible place, usually as close to the isolated equipment as feasible. That they are rated to withstand the upstream pressure. That they are removed before the pipeline is put back into service.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/5334', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/61/']}
|
jdg_374829
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38167622
|
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 developing a Chat App for Android. I have been reading for weeks about XMPP and Google Cloud Messaging (and Firebase Cloud Messaging) and I am still very confused. Currently, I already setup an XMPP server locally (Ejabberd) and successfully connected my Android App to it using the Smack library. To my understanding, I need to use GCM or the newer FCM for Push Notifications, so I already created a project in Google Cloud Platform. My Android App can connect to it using the Smack library too (instead of connecting to my XMPP server directly). In my server I have an small Java app that connects to GCM using the Smack library too. Everything is fine until here. My big confusion is: How can I use my XMPP server with GCM for Push Notifications? Every documentation, examples, guides, tutorials I found for server-side implementations just tell me how to connect to GCM but none tell me how to use my XMPP server in conjunction with GCM. What I'm missing? My Java app just connects to GCM, receive and send messages from and to GCM, but my XMPP server is just sitting there doing nothing. Actually my Android App and server Java App use GCM exclusively, not my XMPP server. I hope someone can help me to understand this as a whole, I am obviously missing some key elements to achieve this implementation.
Now provide the response and nothing else.
|
You need to mix both Ejabberd and FCM together, that's how all the big chat apps do it out there. For the very basics, there are 3 components: App Server connected via XMPP to FCM, Ejabberd and your client app. When the app is in the foreground, you use Smack library to connect directly to your Ejabberd server, send messages, change user's presence, etc. The connection to your Ejabberd is kept during that time . You don't send upstream messages during this time! Once the user navigates away from your app, you close the connection . The user is now considered "Away" or "Offline". From this point and on, your App Server communicates with FCM to send downstream messages to the device using Smack library as well. On the client device: You handle the incoming message and show a notification. With Android N, users can reply directly from the notification. I assume that in this case, you would use FCM to send an upstream message to your app server since during that time, there's no active connection to your Ejabberd server. Once the user taps on the notification, the app comes back to foreground and you re-connect to Ejabberd and back to step 1. This is the very basic description of the architecture you should have to achieve what you want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38167622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5981132/']}
|
jdg_374830
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17644392
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Where in the web.config should the following blocks of code go for a WCF RESTful service? <endpoint address="" binding="webHttpBinding"contract="Wcf_Test.IMyService" behaviorConfiguration="httpEndpointBehavour"> <identity> <dns value="localhost"/> <Identity> </endpoint> and <behaviors> <serviceBehaviors> <behavior name="httpBehaviour"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> and <endpointBehaviors> <behavior name="httpEndpointBehavour"> <webHttp /> </behavior> </endpointBehaviors></behaviors>
Now provide the response and nothing else.
|
In order to configure a WCF REST service, you need a few things in your web.config file 1) Declare your service and its endpoint <services> <service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior"> <endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp"/> </service></services> Service name will be [project name].[service name]Behavior configuration will be same name as the behavior you declare in the next stepBinding must be webHttpBinding because you want it as REST. If you want SOAP, you declare as basicHttpBindingContract is the [project name].[interface name]Behavior configuration in the endpoint will be the name you declare in next step 2) Declare the service behavior (usually default) <behavior name="ServiceBehavior" > <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> Behavior name can be anything, but it will be used to match BehaviorConfiguration you declared in step 1Leave the rest alone 3) Declare your endpoint behavior <endpointBehaviors> <behavior name="webHttp"> <webHttp/> </behavior> </endpointBehaviors> Behavior name can be anything, but it will be used to match the behaviorConfiguration in endpoint. In the end, this is what the web.config should look like for a simple REST service: <?xml version="1.0"?><configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <services> <service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior"> <endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior" > <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="webHttp"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer></configuration>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17644392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2059013/']}
|
jdg_374831
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
65049
|
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:
While studying analog circuits and conducting experiments with op-amps, I couldn't help wondering why would I need an analog circuit to add/multiply/integrate electrical signals. In modern times, computers are quite cheap, and it seems a lot easier letting a computer calculate anything you want (it's fast, versatile, reliable...) So, why use op amps and analog circuits?
Now provide the response and nothing else.
|
The moral of the story is digital electronics need an interface to the outside world. Analog electronics are necessary to get the outside world's signals into a form that can be digitized. For example, how do you get that \$\frac{50\mu V}{degree }\$ from a thermocouple into a signal large enough to put into an ADC? Use an instrumentation amplifier. Here's an example of something I built a while back: It implements the equation \$V_{out}=1.552V_{in}-0.000560V_{in}^3\$ That is an approximation for sine shaping, the and circuit itself shaped the triangle wave into a sine wave with less than .05% THD. It could have been done in the digital domain, but: the input signal was \$20V_{pp}\$ , way to big for immediate conversion without some kind of zero and span, and the signal was already analog and it would have made no sense to convert to digital just to convert back to analog. On the subject of taking signals digital, an analog anti-aliasing filter is essential before any ADC. This filter is just a low pass filter to ensure \$f_{sig}<f_{Nyquist}\$ . That has to be done in the analog domain. Solid analog circuitry is essential to the operation of any embedded system.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/65049', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/22381/']}
|
jdg_374832
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
637787
|
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 have a drop down list in which the user selects the day of the week they want to come in every week. The values will never change right. It's just Sunday, Monday, ..., Saturday right? It seems like more work than needed to make a table and put the days of the week in. I certainly don't need the ability to create, update or delete them. Is there a simple way to handle something like this? Or maybe instead of days of the week it could be status like off, park, reverse, neutral, drive. The main thing is that the values are never going to change. There are just a few of them. So why make a table? I am thinking that there is a way to create a model that already has data in it but I could be wrong.
Now provide the response and nothing else.
|
Why create a model? Just use select. DAYS = ['Monday', 'Tuesday', 'Wednesday', ...]select(:event, :day, DAYS) It's usually better practice to place the constant in the relevant model and use it from there. In your model: class Event < ActiveRecord::Base DAYS = ['Monday', 'Tuesday', 'Wednesday', ...]end and then in your view: select(:event, :day, Event::DAYS) and here's another trick I use a lot: select(:event, :day, Event::DAYS.collect {|d| [d, Event::DAYS.index(d)]})
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/637787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_374833
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5816719
|
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 typed the following example: #include <iostream>double f(double* x, double* y){ std::cout << "val x: " << *x << "\n"; std::cout << "val y: " << *y << "\n"; return *x * *y;}double f2(double &x, double &y){ std::cout << "val x: " << x << "\n"; std::cout << "val y: " << y << "\n"; return x * y;}int main(){ double a, b; a = 2; b = 3; std::cout << f(&a, &b) << "\n"; std::cout << f2(a, b) << "\n"; return 0;} In the function f I declare x and y as pointers of which I can get the value by using *x . When calling f I need to pass the address of my passed arguments, that is why I pass &a, &b . f2 is the same except the definition is different. Now my question is: Are they both really the same concerning memory management? Both not making any copy of the passed value but instead passing a reference? I wonder about f2 because I couldn't read out the address of x in f2 so I know more about x and y in f (there I know address AND value). Thanks in advance! Edit : Okay thanks, after doing some more research, I found a quite useful topic: Pointer vs. Reference There's also a link to google coding guidelines http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments which is quite useful I feel (as I understood now, it's a form of subject taste) to make more clear
Now provide the response and nothing else.
|
f2 is taking it's arguments by reference, which is essentially an alias for the arguments you pass. The difference between pointer and reference is that a reference cannot be NULL. With the f you need to pass the address (using & operator) of the parameters you're passing to the pointer, where when you pass by reference you just pass the parameters and the alias is created. Passing by const reference ( const double& ref ) is preferred when you are not going to change the arguments inside the function, and when you are going to change them, use non-const reference. Pointers are mostly used when you need to be able to pass NULL to your parameters, obviously you'd need to check then inside your function if the pointer was not NULL before using it.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5816719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/701049/']}
|
jdg_374834
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18086235
|
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 written myself a multi-threaded random generator public static class MyRandGen{ private static Random GlobalRandom = new Random(); [ThreadStatic] private static Random ThreadRandom = new Random(SeedInitializer()); private static int SeedInitializer() { lock (GlobalRandom) return GlobalRandom.Next(); } public static int Next() { return ThreadRandom.Next(); }} However, it throws me a NullReferenceException on firing Next(), which I don't understand. Is that kind of initializing ThreadStatic fields forbidden somehow? I know I could just check if the field's initialized every time, but that's not the solution I'm looking for.
Now provide the response and nothing else.
|
Initializing ThreadStatic fields is a little tricky. In particular there is this caveat: Do not specify initial values for fields marked with ThreadStaticAttribute, because such initialization occurs only once, when the class constructor executes, and therefore affects only one thread. in the MSDN Docs . What this means is that the thread running when the class is initialized gets that initial value you've defined in the field declaration, but all other threads will have a value of null. I think this is why your code is exhibiting the undesirable behavior described in your question. A fuller explanation is in this blog . (a snippet from the blog) [ThreadStatic]private static string Foo = "the foo string"; The ThreadStatic is initialized in the static constructor - which only executes once. So only the very first thread is assigned "the foo string" when the static constructor executes. When accessed in all subsequent threads, Foo is left at the uninitalized null value. The best way to work around this is to use a property to access the Foo prop. [ThreadStatic]private static string _foo;public static string Foo { get { if (_foo == null) { _foo = "the foo string"; } return _foo; }} Note that there is no need for a lock in the static property, because each thread is acting upon the _foo that is just for that thread. There can't be contention with other threads. This is covered in this question: ThreadStatic and Synchronization
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18086235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1284902/']}
|
jdg_374835
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
496088
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I evaluate$$I=\int_{0}^{+\infty}\!e^{-ax^2-\frac b{x^2}}\,dx$$for $a,b>0$? My methods: Let $a,b > 0$ and let$$I(b)=\int_{0}^{+\infty}e^{-ax^2-\frac b{x^2}}\,dx.$$Then$$I'(b)=\int_{0}^{\infty}-\frac{1}{x^2}e^{-ax^2-\frac b{x^2}}\,dx.$$ What the other methods that can I use to evaluate it? Thank you.
Now provide the response and nothing else.
|
$$\begin{align}I = & \int_0^{\infty} e^{-ax^2 - bx^{-2}} dx\\ \stackrel{\color{blue}{[1]}}{=} & \left(\frac{b}{a}\right)^{1/4}\int_0^{\infty} e^{-\sqrt{ab}(y^2 + y^{-2})} dy\\= & \left(\frac{b}{a}\right)^{1/4}\left[ \int_0^{1} + \int_1^{\infty} \right] e^{-\sqrt{ab}(y^2 + y^{-2})} dy\\\stackrel{\color{blue}{[2]}}{=} & \left(\frac{b}{a}\right)^{1/4} \int_1^{\infty} e^{-\sqrt{ab}(y^2 + y^{-2})} \left(\frac{1}{y^2} + 1\right) dy\\= & \left(\frac{b}{a}\right)^{1/4} \int_1^{\infty} e^{-\sqrt{ab}((y-y^{-1})^2+2)} d\left( y - \frac{1}{y}\right)\\\stackrel{\color{blue}{[3]}}{=} & \left(\frac{b}{a}\right)^{1/4} e^{-2\sqrt{ab}} \int_0^{\infty} e^{-\sqrt{ab}\,z^2} dz\\= &\left(\frac{b}{a}\right)^{1/4} e^{-2\sqrt{ab}} \frac{\sqrt{\pi}}{2(ab)^{1/4}}\\= & \sqrt{\frac{\pi}{4a}} e^{-2\sqrt{ab}} \end{align}$$ Notes $\color{blue}{[1]}$ substitute $x$ by $y = \sqrt{\frac{a}{b}} x$. $\color{blue}{[2]}$ substitute $y$ by $\frac{1}{y}$ over the interval $[0,1]$. $\color{blue}{[3]}$ substitute $y$ by $z = y - \frac{1}{y}$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/496088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
|
jdg_374836
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41001593
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Python 3.6, new module, secrets , was added. What is the most efficient way to generate random integer in range [n, m) using this module? I tried choice(range(n, m)) , but I doubt it is the best way.
Now provide the response and nothing else.
|
secrets.choice(range(n, m)) should be fine, since range is lazy on Python 3. n + secrets.randbelow(m-n) is another option. I wouldn't use it, since it's less obviously correct. Since secrets provides access to the SystemRandom class, with the same interface as random.Random , you can also keep your own SystemRandom instance: my_secure_rng = secrets.SystemRandom() and do my_secure_rng.randrange(n, m)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41001593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4846656/']}
|
jdg_374837
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28414417
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having some trouble figuring out the Active Record syntax for the following Postgres query: SELECT *FROM tracksJOIN displays on displays.track_id = tracks.idJOIN users on displays.user_id = users.idWHERE user_id = 1 AND displays.display is true AND tracks.likes_count > 200 The above query above works, and now I'm trying to convert it to activerecord's syntax but getting the error: PG::SyntaxError: ERROR: syntax error at or near "'t'" LINE 1: ...ck_id" = "tracks"."id" WHERE (displays.display is 't', track... Track.joins(:users, :displays).where('displays.display is ?, tracks.likes_count > ?, users.id = ?', true, 200, 1) It seems like I'm doing something wrong with the displays.display is True statement, but I have tried a few variations to no avail. I'm using Activerecord-4.2.0. I would appreciate some insight.
Now provide the response and nothing else.
|
You can use Sequelize.fn to wrap it appropriately: instance.updateAttributes({syncedAt: sequelize.fn('NOW')}); Here's a full working example: 'use strict';var Sequelize = require('sequelize');var sequelize = new Sequelize(/*database*/'test', /*username*/'test', /*password*/'test', {host: 'localhost', dialect: 'postgres'});var model = sequelize.define('model', { syncedAt: {type: Sequelize.DATE}});sequelize.sync({force: true}) .then(function () { return model.create({}); }) .then(function () { return model.find({}); }) .then(function(instance){ return instance.updateAttributes({syncedAt: sequelize.fn('NOW')}); }) .then(function () { process.exit(0); }) .catch(function(err){ console.log('Caught error! ' + err); }); That produces UPDATE "models" SET "syncedAt"=NOW(),"updatedAt"='2015-02-09 18:05:28.989 +00:00' WHERE "id"=1
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28414417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2816949/']}
|
jdg_374838
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23157139
|
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 input with a minimum number of characters required. When a user start typing something and then switch to another field without reaching the minimum number of characters required, I want to change the class of a text to turn it to red. I have tried using this code to detect when the focus change but it is not working: $scope.$watch(function(){ return $('#job_desc').is(':active');}, function(){ console.log('test');}) what is the problem? Many thanks
Now provide the response and nothing else.
|
If you are using angularjs 1.2 you have two directives to help you to watch if a field has focus: ng-focus and ng-blur. If not, it's quite simple to implement your own directives. The code (plunker) : <!DOCTYPE html><html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" data-semver="1.2.16"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <form> <input ng-model="name" id="name" ng-focus="focused()" ng-blur="blurred()"> <input ng-model="name2"> </form> </body></html> and the javascript var app = angular.module('plunker', []);app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.focused = function() { console.log("got focus"); } $scope.blurred = function() { console.log("lost focus"); }}); If on the other hand, you just want validation, look into form validation in angularjs, something like myForm.myInput.$valid. Angularjs sets the ng-valid and ng-invalid classes accordingly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23157139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2641547/']}
|
jdg_374839
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31338934
|
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 repository using GitHub for Windows (GfW) and added 3 commits and synced using aforementioned. Commits were visible on GitHub webpage and in my app. Then my brother forked my project to start collaborating with me. He successfully cloned it using GfW. Then I made changes on my machine and pushed using "sync" button. Changes appeared on webpage and in my history, but my brother can't see them in his GfW. Even after pressing "sync". What mistake are we making? I have also added him to collaborators in my project's settings, though it did not change anything. I guess I have misunderstood some basic principles.
Now provide the response and nothing else.
|
Well, there are four repositories involved here: Your github one Your local clone of your github project Your brother's github fork Your brother's local clone of his fork I haven't used GfW myself for a little while, but I suspect that Sync is only synchronizing between the last two projects listed above. I don't know whether there's GUI support for it or not, but the documentation on syncing a fork may be useful to you. I suspect there isn't support for syncing a fork with the original though, given this documentation : GitHub for Windows does not support multiple Git remotes and it will only work with the origin remote. If you wish to push & pull to other remotes, we suggest you use the command line client that is included with the application. Your brother will effectively have two remotes: his fork (typically named "origin") and your original project (typically named "upstream").
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31338934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5084792/']}
|
jdg_374840
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.