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
14002954
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to write the full contents of a file into a buffer. The file actually only contains a string which i need to compare with a string. What would be the most efficient option which is portable even on linux. ENV: Windows Now provide the response and nothing else.
Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library. However, if you want to stick to the standard, you can write something like this: #include <stdio.h>#include <stdlib.h>FILE *f = fopen("textfile.txt", "rb");fseek(f, 0, SEEK_END);long fsize = ftell(f);fseek(f, 0, SEEK_SET); /* same as rewind(f); */char *string = malloc(fsize + 1);fread(string, fsize, 1, f);fclose(f);string[fsize] = 0; Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14002954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/966739/']}
jdg_70841
stackexchange
llm_judgeable_groundtruth_similarity
60444100
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know if I can use setState hook multiple times in same function.For example, like this import React, { useEffect, useState } from 'react';function(props) {const [color, setColor] = useState(0)const [size, setSize]= useState(0)const [weight, setWeight] = useState(0)const onClickRandomButton = () => { setColor(Math.random() * 10) setSize(Math.random() * 10) setWeight(Math.random() * 10)}return <div> <button onClick = {onClickRandomButton}>random</button></div>} I have tested, but it doesn't work as expected.To set multiple values at once using hook, how should I do?Thanks Now provide the response and nothing else.
You can use one useState with object value for updating the styles at once: import React, { useEffect, useState } from 'react';export default function (props) { const [style, setStyle] = useState({ color: 0, size: 0, weight: 0 }); const onClickRandomButton = () => { setStyle({ color: Math.random() * 10, size: Math.random() * 10, weight: Math.random() * 10, }); }; return ( <div> <button onClick={onClickRandomButton}>random</button> </div> );} And if in any method you want to update just one property, for example: color, you could do something like this: ... const handleEditColor = color => { setStyle({ ...style, color }); };...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60444100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7122343/']}
jdg_70842
stackexchange
llm_judgeable_groundtruth_similarity
10577374
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 cant get my mysql to start on os x 10.7. It is located in /usr/local/mysql/bin/mysql I get command not found when I type mysql --version in the terminal. I tried this can't access mysql from command line mac but still get command not found. I tried installing mysql with the dmg and i have tried to install it through homebrew and I cant get it to work. When I try to start mysql with homebrew I get MySQL won't start This is my $PATH : /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/Users/Victoria/bin:/usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin Now provide the response and nothing else.
This is the problem with your $PATH: /usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin . $PATH is where the shell searches for command files. Folders to search in need to be separated with a colon. And so you want /usr/local/mysql/bin/ in your path but instead it searches in /usr/local//usr/local/mysql/bin/private/var/mysql/private/var/mysql/bin , which probably doesn't exist. Instead you want ${PATH}:/usr/local/mysql/bin . So do export PATH=${PATH}:/usr/local/mysql/bin . If you want this to be run every time you open terminal put it in the file .bash_profile , which is run when Terminal opens.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/10577374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1022672/']}
jdg_70843
stackexchange
llm_judgeable_groundtruth_similarity
19619539
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 spring and I am creating a simple web application. I have been reading about contexts in Spring MVC. I am using STS plugin for eclipse. I created aSpring MVC project using the plugin. Now I have three xml documents in the project, web.xml, root-context.xml and servlet-context.xml. These were created by STS for me. In web.xml, dispatcher servlet is pointed towards servlet-context.xml and I understand the dispatcher servlets job is to create a web application context which knows how to resolve views and is a place for controller beans to exist. Is my understanding correct? If so, what other job is accomplished by this context? Now, there is a file called root-context.xml which has a component scan on my projects default package. My understanding is this context needs to have global beans which many servlets might use. Is my understanding correct? What else does this do? What kind of context is created using this file? Now, I am further along in the project and I have several *-context.xml files (dao-context.xml, security-context.xml etc) which are loaded using contextLoaderListner (in web.xml). Is this a good idea? Or should everything go into servlet-context.xml? I think it's a good idea to have different contexts as it provides separation of concern. Comments? Also, what kind of context is created from these *-context.xml files? What is the proper folder location for these files? Web.xml is for the servlet container like tomcat etc and all other xml files in the project are for the spring container. Is that correct? All these files are separated to provide separation of concern? How many application contexts and web application contexts exists in the current scenario? Why would anyone need more than one dispatcher servlet? Why would anyone need more than one application context? Thoughts? Comments? Corrections? Best practices? Now provide the response and nothing else.
The whole idea behind this design is to handle different architectural layers in a typical web application and provide for inheritance / override mechanism for beans across contexts. Each type of context in Spring is related to different architectural layer for e.g, web layer, service layer etc. A Spring based web application can have multiple dispatcher servlet configured (although in majority of cases its a single servlet - but dispatcher serlvet is a servlet nonetheless and there could be multiple configured in web.xml). These can be configured to handle different url patterns. So obviously each is a different servlet and hence can have different Spring web Application context. Each of these can contain different configurations for Spring web layer like controllers,interceptors,view resolvers,locale resolvers etc. as these typically belong to the web layer of an application. All these configurations and beans are private to each dispatcher servlet so they are not visible to each other. Hence having a seperate spring web application context makes sense to enable this privacy. However there are other beans which are designed to be shared hence belong to a root context. So all the shareable things belong to the root context and it can be considered global for this web application. Each dispatcher servlet inherits all the beans defined in the root context. However the important point to note is that the shared beans can be overridden by respective dispatcher servlet specific beans. So in web applications root context can be viewed as something which is inherited but can be overridden.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19619539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343569/']}
jdg_70844
stackexchange
llm_judgeable_groundtruth_similarity
43302720
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 that the -Xms flag of JVM process is to allow the JVM process to use a specific amount of memory to initialize its process. And in regard to performance of a Java application, it is often recommended to set the same values to both -Xms and -Xmx when starting the application, like -Xms2048M -Xmx2048M . I'm curious whether the -Xms and -Xmx flags mean that the JVM process makes a reservation for the specific amount of memory to prevent other processes in the same machine from using it. Is this right? Now provide the response and nothing else.
Xmx merely reserves virtual address space. Xms actually allocates (commits) it but does not necessarily prefault it. How operating systems respond to allocations varies. Windows does allow you to reserve very large chunks of address space (Xmx) but will not allow overcommit (Xms). The limit is defined by swap + physical. The exception are large pages (which need to be enabled with a group policy setting), which will limit it by physical ram. Linux behavior is more complicated, it depends on the vm.overcommit_memory and related sysctls and various flags passed to the mmap syscall, which to some extent can be controlled by JVM configuration flags. The behavior can range from a) Xms can exceed total ram + swap to b) Xmx is capped by available physical ram.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43302720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1718984/']}
jdg_70845
stackexchange
llm_judgeable_groundtruth_similarity
25845689
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 Button and I bind this button to a command in ViewModel say OpenWindowCommand . When I click on the button I want to open a new window. But creating a window instance and showing a window from view model is a violation of MVVM. I have created interface like interface IWindowService{ void showWindow(object dataContext);} and WindowService implements this interface like class WindowService : IWindowService{ public void showWindow(object dataContext) { ChildWindow window=new ChildWindow(); window.DataContext=dataContext; window.Show(); }} In this class I have specified ChildWindow . So this class is tightly coupled with showing ChildWindow . When I want to show another window, I have to implement another class with the same interface and logic. How can I make this class generic so that I can just pass an instance of any window and the class will be able to open any window? I am not using any built MVVM frameworks. I have read many articles on StackOverflow but I could not found any solution for this. Now provide the response and nothing else.
You say "creating window instance and showing window from view model is violation of MVVM". This is correct. You are now trying to create an interface that takes a type of view specified by the VM. This is just as much of a violation. You may have abstracted away the creation logic behind an interface, but you are still requesting view creations from within the VM. VM's should only care about creating VM's. If you really need a new window to host the new VM, then provide an interface as you have done, but one that does NOT take a view. Why do you need the view? Most (VM first) MVVM projects use implicit datatemplates to associate a view with a particular VM. The VM knows nothing about them. Like this: class WindowService:IWindowService{ public void ShowWindow(object viewModel) { var win = new Window(); win.Content = viewModel; win.Show(); }} Obviously you need to make sure you have your VM->View implicit templates set up in app.xaml for this to work. This is just standard VM first MVVM. eg: <Application x:Class="My.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:My.App.ViewModels" xmlns:vw="clr-namespace:My.App.Views" StartupUri="MainWindow.xaml"> <Application.Resources> <DataTemplate DataType="{x:Type vm:MyVM}"> <vw:MyView/> </DataTemplate> </Application.Resources></Application>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25845689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3045854/']}
jdg_70846
stackexchange
llm_judgeable_groundtruth_similarity
52023498
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 event notification when files with multiple extensions like .log, .txt, etc has been added to AWS s3 bucket. Can we add multiple suffix in s3 event notification from console ? Now provide the response and nothing else.
You can create an Event in the Amazon S3 console, which can then trigger a Lambda function or send a message via SNS or SQS. This configuration accepts a prefix (effectively a directory) and a suffix (eg .jpg ). Simply open the bucket, go to the Properties tab and click Events (down the bottom). See: Configuring Amazon S3 Event Notifications - Amazon Simple Storage Service You can create multiple Events, each of which has a different suffix. But you can't create one Event with multiple suffixes. An alternative is to create an Event for any suffix (any file type), and have the Lambda function examine the filename and exit if it has an uninteresting suffix.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52023498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4032207/']}
jdg_70847
stackexchange
llm_judgeable_groundtruth_similarity
29915467
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing an XML validator with XSD. Below is what I did, but when the validator reached the line while (list.Read()) it gives me the error There is no Unicode byte order mark. Cannot switch to Unicode. Can anybody help me fix it? public class Validator { public void Validate(string xmlString) { Boolean bRet = true; string xmlPath = @"C:\x.xml"; string xsdPath = @"C:\general.xsd"; XmlReaderSettings Settings = new XmlReaderSettings(); Settings.Schemas.Add("", xsdPath); Settings.ValidationType = ValidationType.Schema; Settings.ValidationEventHandler += new ValidationEventHandler(SettingsValidationEventHandler); XmlReader list = XmlReader.Create(xmlPath, Settings); //StringBuilder output = new StringBuilder(); while (list.Read()) { } //File.WriteAllText(@"D:\Output.xml", output.ToString()); } static void SettingsValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning) { MessageBox.Show( "WARNING: "); MessageBox.Show(e.Message); } else if (e.Severity == XmlSeverityType.Error) { MessageBox.Show("ERROR: "); MessageBox.Show(e.Message); } } } XML <?xml version="1.0" encoding="utf-16"?><FlashList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" vin="xxxxxxxxxxxxx"> <flash ECUtype="xxx" /></FlashList> XSD <?xml version="1.0" encoding="utf-16"?><xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="FlashList"> <xs:complexType> <xs:sequence> <xs:element name="flash" maxOccurs="unbounded" minOccurs="0"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:string" name="ECUtype" use="optional"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element name="Error" maxOccurs="unbounded" minOccurs="0"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute type="xs:byte" name="code" use="optional" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute type="xs:string" name="vin"/> </xs:complexType> </xs:element></xs:schema> Now provide the response and nothing else.
The reality of your file's encoding appears to conflict with that specified by your XML declaration. If your file actually uses one-byte characters, declaring encoding="utf-16" won't change it to use two-byte characters, for example. Try removing the conflicting encoding from the XML declaration. Replace <?xml version="1.0" encoding="utf-16"?> with <?xml version="1.0"?> You may also be able to load the file into a string as a work-around using LoadXML().
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29915467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3122648/']}
jdg_70848
stackexchange
llm_judgeable_groundtruth_similarity
33811498
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 Dropzone.js to allow users to upload files to server, according to the specs you can change the thumbnail width as shown below, however I want to change the width to 100% instead of using px, Is this possible? Because if I do thumbnailWidth: 100% it will not recognize % char. dzImageOptions = Dropzone.options.myDropzone = { thumbnailWidth: 314, //I want to change width to 100% instead thumbnailHeight: 314, init: function (file) { }} //Also have to change css or thumbnail won't resize properly .dropzone.song-image .dz-preview .dz-image { border-radius: 1px; width: 314px; height: 314px;}<div class="dropzone song-image"></div> Now provide the response and nothing else.
You cannot specify a percentage on thumbnailWidth and thumbnailHeight . Dropzone uses these values to create the image source to show it as a preview. But you can leave the thumbnail at the original width and height, setting these values to null ( Note that this can cause a bit of lag with high resolution images ) and then use the <img> width and height attributes to display the image with the size you want and adjusting the .dz-image container with css. html: <div class="dropzone" id="myDropzone"></div> js: Dropzone.autoDiscover = false;Dropzone.options.myDropzone = { url: "yourUrl", thumbnailWidth: null, thumbnailHeight: null, init: function() { this.on("thumbnail", function(file, dataUrl) { $('.dz-image').last().find('img').attr({width: '100%', height: '100%'}); }), this.on("success", function(file) { $('.dz-image').css({"width":"100%", "height":"auto"}); }) }};var myDropzone = new Dropzone('div#myDropzone');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33811498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5252988/']}
jdg_70849
stackexchange
llm_judgeable_groundtruth_similarity
19383248
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 find if a user entered number is a power of two or not. My code doesn't work. public class power_of_two{ public static void main(String args[]) { Scanner in=new Scanner(System.in); System.out.println("Enter the number : "); int num = in.nextInt(); int other = 1; if(((~num) & 1) == 1) { System.out.println("The number is a power of two"); } else { System.out.println("The number is a NOT A power of two"); } } } Let me know how can I find the power of two number. For example 8 is a power of 2. 22 is not a power of 2, etc.. Now provide the response and nothing else.
You can test if a positive integer n is a power of 2 with something like (n & (n - 1)) == 0 If n can be non-positive (i.e. negative or zero) you should use (n > 0) && ((n & (n - 1)) == 0) If n is truly a power of 2, then in binary it will look like: 10000000... so n - 1 looks like 01111111... and when we bitwise-AND them: 10000000...& 01111111... ----------- 00000000... Now, if n isn't a power of 2, then its binary representation will have some other 1s in addition to the leading 1, which means that both n and n - 1 will have the same leading 1 bit (since subtracting 1 cannot possibly turn off this bit if there is another 1 in the binary representation somewhere). Hence the & operation cannot produce 0 if n is not a power of 2, since & ing the two leading bits of n and n - 1 will produce 1 in and of itself. This of course assumes that n is positive. This is also explained in "Fast algorithm to check if a positive number is a power of two" on Wikipedia. Quick sanity check: for (int i = 1; i <= 100; i++) { if ((i & (i - 1)) == 0) System.out.println(i);} 1248163264
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/19383248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/778942/']}
jdg_70850
stackexchange
llm_judgeable_groundtruth_similarity
91
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A 1998 Jeep Grand Cherokee has gone through 3 batteries in the last 3 months. While they have all been replaced by warranties, it'd be nice to get the problem solved permanently. I've tested the alternator, and it's not defective. I'm suspecting it might be a short somewhere in the system. How can I track down if this is a short, and if so, where the short is occuring? Now provide the response and nothing else.
Standard digital multimeters can measure current and help you identify what in your vehicle is consuming your battery's juice. Get an electrical diagram of your vehicle and try to narrow it down by doing current measurements in the various major paths of flow. When your car is off, no (or only trace) current should be flowing. Every time the path of electricity splits, you'll have to test each to determine which one is drawing the juice. There's no telling how many of these you'll have to check before you reach the problem. This answer of course assumes the juice is being drained while the vehicle is off. I suppose it is possible that it is draining while on also. Either the alternator is bad or it isn't able to produce enough juice to keep up with your vehicle's demand (which probably includes some defective component that is sucking lots of juice). If it keeps running normally, it might be worth checking the leads coming to the battery (while still disconnected) with a meter to ensure it is being fed properly by the alternator. By the way, please do this before doing any more battery exchanges. You are making the price of my next battery go up by taking advantage of the return policy like this.
{}
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/91', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/75/']}
jdg_70851
stackexchange
llm_judgeable_groundtruth_similarity
37876166
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 working on a Laravel application in which I need to find all the products within a certain radius of the user's coordinates. Products have a one-to-many relationship with users so that users can have multiple products. I've found that the haversine algorithm can calculate the distance between two points, but I can't seem to make it work. I've got the following query. Controller $latitude = 51.0258761;$longitude = 4.4775362;$radius = 20000;$products = Product::with('user')->selectRaw("*, ( 6371 * acos( cos( radians(" . $latitude . ") ) * cos( radians(user.latitude) ) * cos( radians(user.longitude) - radians(" . $longitude . ") ) + sin( radians(" . $latitude . ") ) * sin( radians(user.latitude) ) ) ) AS distance")->having("distance", "<", $radius)->orderBy("distance")->get(); I've set the radius to 20000 for testing purposes, and it appears all products have a distance of 5687,... The problem seems to be that the latitude and longitude of the products are stored in the User table, but I'm not sure how I can access those in my query. I've tried user.latitude and 'user->latitude' , but nothing seems to work. Product model class Product extends Model{ protected $fillable = [ 'soort', 'hoeveelheid', 'hoeveelheidSoort', 'prijsPerStuk', 'extra', 'foto', 'bio' ]; public function User() { return $this->belongsTo('App\User'); } public $timestamps = true;} User model use Illuminate\Auth\Authenticatable;use Illuminate\Database\Eloquent\Model;use Illuminate\Auth\Passwords\CanResetPassword;use Illuminate\Foundation\Auth\Access\Authorizable;use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract{ use Authenticatable, Authorizable, CanResetPassword; protected $table = 'users'; protected $fillable = [ 'firstName', 'lastName', 'adres', 'profilepic', 'description', 'longitude', 'latitude', 'email', 'password' ]; protected $hidden = ['password', 'remember_token']; public function product() { return $this->hasMany('App\Product'); }} Now provide the response and nothing else.
This was my implementation of it. I've chosen to alias my query out ahead of time, this way I can take advantage of Pagination . Furthermore, you need to explicitly select the columns that you wish to retrieve from the query. add them at the ->select() . Such as users.latitude, users.longitude, products.name , or whatever they may be. I have created a scope which looks something like this: public function scopeIsWithinMaxDistance($query, $location, $radius = 25) { $haversine = "(6371 * acos(cos(radians($location->latitude)) * cos(radians(model.latitude)) * cos(radians(model.longitude) - radians($location->longitude)) + sin(radians($location->latitude)) * sin(radians(model.latitude))))"; return $query ->select() //pick the columns you want here. ->selectRaw("{$haversine} AS distance") ->whereRaw("{$haversine} < ?", [$radius]);} You can apply this scope to any model with a latitude and longitude . Replace the $location->latitude with your latitude that you wish to search against, and replace the $location->longitude with the longitude that you wish to search against. Replace the model.latitude and model.longitude with the Models you wish to find around the $location based on the distance defined in the $radius . I know you have a functioning Haversine formula, but if you need to Paginate you can't use the code you've supplied. Hopefully this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37876166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3615701/']}
jdg_70852
stackexchange
llm_judgeable_groundtruth_similarity
7409565
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my test example: struct base { virtual ~base(){} int x;};struct derived: public virtual base { base * clone() { return new derived; } derived(): s("a") {} std::string s;};int main () { derived d; base * b = d.clone(); derived * t = reinterpret_cast<derived*>(b); std::cout << t->s << std::endl; return 0;} It crashes at the line where I print s. Since "b" is a pointer to the derived class, reinterpret_cast should just work. I wonder why it crashes. At the same time, if I replace reinterpret_cast with dynamic_cast, then it works. Now provide the response and nothing else.
Even if b is here dynamically of type derived , you have to use dynamic_cast . This is what dynamic_cast is for, to dynamically convert a pointer of a base class into a derived class at runtime. reinterpret_cast takes the raw pointer and considers it as being of the derived type. However, because of the virtual inheritance, a slight adjustment must be done to the pointer to point to the correct method dispatch table, and that's precisely what dynamic_cast will do.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7409565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/943559/']}
jdg_70853
stackexchange
llm_judgeable_groundtruth_similarity
39635184
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 wanted to write a simple TCP echo server application. I managed to do the echo part, but have some problems with sending files between client and server. The idea is simple: despite sending ordinary messages, client can send a special command to server (\SENDFILE filename.txt), and after receiving such command, server should ask client for this file, and get the file from client. (Further I would like to get a file from one client, and later send it to another one). I think "the protocol" here is simple, however, after typing \SENDFILE at client's side, client hangs up, and does not receive any further messages from server. Moreover (server and client are in different directories) at server's side there's only an empty file from client, with no content inside. Any ideas what can be wrong here? client.c #include<stdio.h> //printf#include<string.h> //#include <sys/stat.h>#include<sys/socket.h> //socket#include<arpa/inet.h> //inet_addr#include <fcntl.h>#define SERVER_PORT 9034#define BUFF_SIZE 2000int sendall(int s, char *buf, int len){ int total = 0; int bytesleft = len; int n; while(total < len) { n = send(s, buf+total, bytesleft, 0); if (n == -1) break; total += n; bytesleft -= n; } return n==-1?-1:0;}void SendMsgToSender(char *msg, int connfd){ write(connfd, msg, strlen(msg)); memset(msg, 0, BUFF_SIZE);}int main(int argc , char *argv[]){ int sock; struct sockaddr_in server; char bufferOUT[BUFF_SIZE] , bufferIN[BUFF_SIZE]; struct stat file_stat; memset(bufferOUT, 0, BUFF_SIZE); memset(bufferIN, 0, BUFF_SIZE); //Create socket sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) { printf("Could not create socket"); } // puts("Socket created"); server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons( SERVER_PORT ); //Connect to remote server if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) { perror("Connect failed. Error"); return 1; } // puts("Connected\n"); int read_size = 10; //keep communicating with server while(1) { printf("> "); fgets(bufferOUT, BUFF_SIZE, stdin); //Send some data if( send(sock , bufferOUT , BUFF_SIZE , 0) < 0) { perror("Send failed"); return 1; } //Receive a reply from the server if( (read_size = recv(sock , bufferIN , BUFF_SIZE , 0)) < 0) { perror("Recv failed"); break; } if(read_size == 0) break; if(bufferIN[0] == '\\') { char tmp[BUFF_SIZE], filename[BUFF_SIZE], *param; memset(filename, BUFF_SIZE, 0); strcpy(tmp, bufferIN); param = strtok(tmp, " "); if(param != NULL) { if(!strcmp(param, "\\GIVEMEFILE")) { param = strtok(NULL, " "); if(param != NULL) { strcpy(filename, param); FILE * fp; int nBytes; char buffer[BUFF_SIZE], *s; memset(buffer, 0, BUFF_SIZE); fp = fopen(filename, "r"); if(fp == NULL) { perror("fopen"); fflush(stdout); break; } int remain_data = file_stat.st_size; do { s = fgets(buffer, BUFF_SIZE, fp); if(s != NULL && buffer[0] != EOF) { nBytes = sendall(sock, buffer, BUFF_SIZE); remain_data -= nBytes; } else break; } while((s != NULL) && (nBytes > 0) && (remain_data > 0)); fclose(fp); memset(bufferOUT, 0, BUFF_SIZE); memset(bufferIN, 0, BUFF_SIZE); continue; } } } } else { printf("%s\n", bufferIN); fflush(stdout); } memset(bufferOUT, 0, BUFF_SIZE); memset(bufferIN, 0, BUFF_SIZE); } close(sock); return 0;} server.c #include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>#include <time.h>#include <fcntl.h>#define SERVER_PORT 9034#define BUFF_SIZE 2000void StripNewline(char *s){ while(*s != '\0') { if(*s == '\r' || *s == '\n') { *s = '\0'; } s++; }}void SendMsgToSender(char *msg, int connfd){ write(connfd, msg, strlen(msg)); memset(msg, 0, BUFF_SIZE);}// get sockaddr, IPv4 or IPv6:void *get_in_addr(struct sockaddr *sa){ if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr);}int GetFileFromClient(int connfd, char *filename){ FILE * fp = NULL; int bytes; char buffer[BUFF_SIZE]; memset(buffer, 0, BUFF_SIZE); fp = fopen(filename, "w"); if(fp == NULL) return 0; memset(buffer, 0, BUFF_SIZE); sprintf(buffer, "\\GIVEMEFILE %s \r\n", filename); SendMsgToSender(buffer, connfd); while(1) { memset(buffer ,0 , BUFF_SIZE); if((bytes = recv(connfd , buffer , BUFF_SIZE , 0) ) <= 0) return 0; else fprintf(fp, "%s\n", buffer); } fclose(fp); sleep(1); memset(buffer, 0, BUFF_SIZE); sprintf(buffer, "\r\n"); SendMsgToSender(buffer, connfd); return 1;}int main(void){ fd_set master; fd_set read_fds; int fdmax; int listener; int client_sock; struct sockaddr_storage remoteaddr; socklen_t addrlen; char bufferIN[BUFF_SIZE], bufferOUT[BUFF_SIZE], tmp[BUFF_SIZE], *datetime; int nbytes; char remoteIP[INET6_ADDRSTRLEN]; int yes=1; int i, j, rv; struct addrinfo hints, *ai, *p; FD_ZERO(&master); FD_ZERO(&read_fds); memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); memset(tmp, 0, BUFF_SIZE); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; char port[16] = "9034"; if (getaddrinfo(NULL, port, &hints, &ai) < 0) { fprintf(stderr, "selectserver: %s\n", gai_strerror(rv)); exit(1); } for(p = ai; p != NULL; p = p->ai_next) { listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listener < 0) { continue; } setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) continue; break; } if (p == NULL) exit(2); freeaddrinfo(ai); if (listen(listener, 10) == -1) { perror("listen"); exit(3); } FD_SET(listener, &master); fdmax = listener; printf("Server is running ...\n\n"); for(;;) { read_fds = master; if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { if (i == listener) { addrlen = sizeof remoteaddr; client_sock = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen); if (client_sock == -1) { perror("accept"); } else { FD_SET(client_sock, &master); if (client_sock > fdmax) fdmax = client_sock; } } else { if ((nbytes = recv(i, bufferIN, BUFF_SIZE, 0)) <= 0) { if (nbytes == 0) close(i); else if(nbytes == -1) { perror("recv"); fflush(stdout); } close(i); FD_CLR(i, &master); } else { bufferIN[nbytes-1] = '\0'; StripNewline(bufferIN); strcpy(tmp, bufferIN); if(bufferIN[0] == '\\') { char *command, *param; command = strtok(bufferIN, " "); if(!strcmp(command, "\\QUIT")) { close(i); FD_CLR(i, &master); break; } else if(!strcmp(command, "\\SENDFILE")) { param = strtok(tmp, " "); if(param != NULL) { param = strtok(NULL, " "); if(param != NULL) { printf("Client is sending me a file '%s'...\n", param); GetFileFromClient(i, param); } } } else { SendMsgToSender(bufferIN, i); } memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); } else { SendMsgToSender(bufferIN, i); } } } // END handle data from client } // END got new incoming connection } // END looping through file descriptors } // END for(;;) memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); return 0;} Now provide the response and nothing else.
strcpy(tmp, bufferIN); Here you are assuming that whatever was read was null-terminated. param = strtok(tmp, " "); if(param != NULL) { if(!strcmp(param, "\\GIVEMEFILE")) Here you are assuming that an entire message has been received. strcpy(filename, param); Ditto. memset(buffer, 0, BUFF_SIZE); Pointless. Remove. do { s = fgets(buffer, BUFF_SIZE, fp); Here you are assuming that the file consists of lines. if(s != NULL && buffer[0] != EOF) Testing buffer[0] !=EOF is meaningless. If you had reached EOF, s would have been null, assuming the file consists of lines, but there is nothing about a line that says anything about what its first character can be, other than that it isn't a line terminator. memset(bufferOUT, 0, BUFF_SIZE); memset(bufferIN, 0, BUFF_SIZE); Both pointless. Remove. memset(bufferOUT, 0, BUFF_SIZE); memset(bufferIN, 0, BUFF_SIZE); Ditto. void StripNewline(char *s) This method appears completely pointless. Remove. void SendMsgToSender(char *msg, int connfd){ write(connfd, msg, strlen(msg)); Here you are sending a string to the peer without the trailing null , which the peer is looking for at strlen() above. Have a good think about what your application protocol actually entails. memset(msg, 0, BUFF_SIZE); Pointless. Remove. int GetFileFromClient(int connfd, char *filename){ FILE * fp = NULL; int bytes; char buffer[BUFF_SIZE]; memset(buffer, 0, BUFF_SIZE); Pointless. Remove. memset(buffer, 0, BUFF_SIZE); Ditto. sprintf(buffer, "\\GIVEMEFILE %s \r\n", filename); SendMsgToSender(buffer, connfd); while(1) { memset(buffer ,0 , BUFF_SIZE); Pointless. Remove. if((bytes = recv(connfd , buffer , BUFF_SIZE , 0) ) <= 0) return 0; Here you need to distinguish between (1) bytes == 0 , which means the peer disconnected, and (2) byte == -1 , which indicates an error , which you need to log , via errno , strerror() , and friends. else fprintf(fp, "%s\n", buffer); Change to fprintf(fp, "%.*s\n", bytes, buffer) . You are assuming throughout that all messages are null-terminated by TCP. They aren't. sleep(1); Pointless. Remove. memset(buffer, 0, BUFF_SIZE); Ditto. sprintf(buffer, "\r\n"); SendMsgToSender(buffer, connfd); Sending a line terminator to the peer appears completely pointless. memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); memset(tmp, 0, BUFF_SIZE); All pointless. Remove. if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) continue; Here you need to print an error mesage instead of just ignoring the condition. if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) You haven't put the listening socket into non-blocking mode. Using select() is therefore pointless. bufferIN[nbytes-1] = '\0'; StripNewline(bufferIN); Why? strcpy(tmp, bufferIN); Why? What's wrong with continuing to use bufferIN ? if(bufferIN[0] == '\\') { char *command, *param; command = strtok(bufferIN, " "); Here again you are assuming a complete command was received, complete with trailing null. memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); Both pointless. Remove. This is jut cargo-cult programming. recv() returns a length. Use it. memset(bufferIN, 0, BUFF_SIZE); memset(bufferOUT, 0, BUFF_SIZE); Ditto, in spades. Basically you have an application protocol problem. Specifically, you don't have an application protocol. Just a whole lot of unwarranted assumptions. If you want a trailing null, (a) send a trailing null, and (b) loop reading until you receive it. You also have an assumption about the content of the files being sent, which is completely unnecessary. Just read bytes from the file and send them to the server. No assumption about lines or line terminators necessary. If you're sending multiple files over the same connection you will need to send the file size ahead of the file, so the receiver will know exactly how many bytes to read and copy to the file. In essence, you need to rethink this completely.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39635184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1582481/']}
jdg_70854
stackexchange
llm_judgeable_groundtruth_similarity
36545118
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 React app like this. var X = React.createClass({ componentDidMount: function() { fetch(this.props.feed).then(...); } render: function() { return <div>{this.props.feed}</div> }}); The feed prop is used to get a JSON feed in componentDidMount that's unique for a particular customer. It would be convenient to pass data into my React app from the HTML to parameterise it: <html> <body> <div id="app" feed='custom_feed.json'></div> </body></html My current solution looks like this: var root = document.getElementById('app');var feed = root.getAttribute('feed')ReactDOM.render(<X feed={feed}/>, root); This obviously works, but it feels like there ought to be a more idiomatic solution. Is there a more React way to do this? Now provide the response and nothing else.
I have used data- attributes for various props, then passed all the props using destructuring {...dataset} , for example: HTML: <div id="app" data-feed='custom_feed.json' data-someprop='value'></div> JS: var root = document.getElementById('app');ReactDOM.render(<X {...(root.dataset)} />, root); Edit: demo fiddle Edit 2018: updated fiddle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36545118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/687677/']}
jdg_70855
stackexchange
llm_judgeable_groundtruth_similarity
248254
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: When an object is at a certain height, it has some energy stored in it as we have done some work on it to get it to that height. So when it already has energy, then why doesn't it fall off from the table top onto the ground by itself? Why does it need a slope or a push to fall down the edge? Where does the stored energy stay in the object, and why does it only convert into vertical motion and not horizontal motion? Now provide the response and nothing else.
It is wrong to think potential energy is stored in the object. The earth pulls the object down, but the object pulls the earth up. They share the potential energy. The object fails to fall down because the tabletop pushes it up. The earth fails to fall up because the bottom of the table legs push the earth down. The table pushes up and down because it is squished a bit and squished things push outwards a bit. So for a moment the object did go down and the earth did go up, but as they moved closer the table got squished and so they moved less and less. They stopped when the table was squished enough to counter the gravitational forces. Why did I bring that all up? Because your focus on just one object is simply a bias. If you had two equally sized objects and you thought each had the potential energy then you'd get the wrong answer by a factor of two. Since the earth is so much more massive, and the object and earth gain equal and opposite amounts of momentum, the earth gets way less kinetic energy as they move towards each other. So almost all of the change in potential energy is given to the object as kinetic energy, but only because the object it is so much much smaller. The potential energy belongs to the system, and it gets shares between the parts when it changes. For gravity it changes when the positions change, so they have to move to release energy to divide up. And neither can move because that pesky table is in the way. Otherwise they indeed would fall towards each other. If you wanted the object to move sidewise to fall off the table it needs some sidewise velocity, so it either has to start with that velocity or you need a sidewise force. And gravity attracts, so doesn't point sidewise.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/248254', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/113235/']}
jdg_70856
stackexchange
llm_judgeable_groundtruth_similarity
1800056
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 we solve this given $f'(0)=-1$. It does not look separable. I can integrate both sides but end up with a functional equation with is not helpful. Now provide the response and nothing else.
I will assume that $f:\mathbb{R}\to\mathbb{R}$ is supposed to be $C^1$, so $f'$ exists and is continuous everywhere. Now note that for any $x\in \mathbb{R}$, $f'(x)=f'(x/2)=f'(x/4)=f'(x/8)=\cdots$. But $x/2^n$ converges to $0$ as $n\to\infty$, so continuity of $f'$ now implies $$-1=f'(0)=\lim_{n\to \infty}f'(x/2^n)=f'(x).$$ So $f'(x)=-1$ for all $x$, and thus $f(x)=-x+C$ for some constant $C$. In fact, the assumption that the derivative is continuous can be eliminated, as explained in detail in Robert Israel's answer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1800056', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229023/']}
jdg_70857
stackexchange
llm_judgeable_groundtruth_similarity
1466554
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find the limit $$\lim_{n \rightarrow \infty} \int _0^n (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n})) dx$$ and justify the answer. I think that the Dominated Convergence Theorem can be applied to this problem. Since $$\int _0^n (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n})) dx = \int _0^\infty (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n}))1_{[0, n]}(x) dx,$$if I can find the dominating function, I will then apply DCT. After applying DCT, we will have $$\lim \int _0^\infty (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n}))1_{[0, n]}(x) dx = \int _0^\infty \lim (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n}))1_{[0, n]}(x) dx = \int _0^\infty e^{-x} \log (3) dx = \log(3)e^{-x}|_{x=\infty, x=0} = - \log (3).$$ But I am not sure if $$\Big| (1 - \frac{x}{n})^n \log (2 + \cos(\frac{x}{n})) \Big| \leq 3e^{-x}$$ with $3e^{-x}$ integrable on $[0, \infty).$ Can someone check if my dominating function is alright ? Prove that $$\sum_{k = 1}^\infty \frac{1}{(p + k)^2} = - \int_0^1 \frac{x^p}{1-x}\log (x) dx$$ for $p>0.$(This problem is allow to use the Fundamental Theorem of Calculus) I suppose that I should apply FTC with DCT. But I have no ideas about doing this, any hints please ? Now provide the response and nothing else.
As Moya stated in the comment section, your dominating function is correct. Indeed it can be shown (and it is in fact well known) that $$\Big(1 - \frac xn\Big)^{n} \uparrow e^{-x}.$$ For the other term notice that the argument in the $\log$ is allowed to range from in $[1,3]$ and $\log x$ in this interval is a positive increasing function, so that you can estimate it with $\log 3$ (you have $3$ multiplying the exponential which is fine, the estimate doesn't have to be sharp.) Notice that you missed a minus sign when evaluating the integral, the result indeed should be $\log 3$ To answer your second question, notice that for $x \in (0,1)$ we can write $\frac{1}{1 - x}$ as a geometric series, indeed \begin{align} - \int_0^1\frac{x^p}{1 - x}\log x\,dx = &\ - \int_0^1\sum_{k = 0}^{\infty}x^{k + p}\log x\,dx \\= &\ \sum_{k = 0}^{\infty} \int_0^1-x^{k + p}\log x\,dx \tag 1\\= &\ \sum_{k = 0}^{\infty}\frac{1}{(k + p + 1)^2} \\= &\ \sum_{k = 1}^{\infty}\frac{1}{(k + p)^2}\end{align} Notice that the crucial step here is $(1)$: to move the sum out of the integral you need to apply the Monotone convergence theorem to the partial sums. This can be done since $-x^{k + p}\log x$ is positive making the partial sums a nonnegative increasing sequence.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1466554', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/173846/']}
jdg_70858
stackexchange
llm_judgeable_groundtruth_similarity
25891387
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 C standard says variable names should not match with standard C keywords and standard function names. Then why does the code below compile with no errors? #include <stdio.h>int main(){ int main = 10; printf("Magic is %d", main); return 0;} See also http://codepad.org/OXk4lZZE In an answer below, ouah writes main is not a reserved identifier and it is allowed to name variables as main in C so considering the program below, does that mean that fopen is likewise not reserved? #include <stdio.h>int main(){ int fopen = 10; printf("Magic is %d", fopen); return 0;} Now provide the response and nothing else.
You program is a valid C program. main is not a reserved identifier and it is allowed to name variables as main in C. What you cannot do is name a variable main at file scope but this is the same as with other variables that would conflict with a function of the same name: This is not valid: int main = 0;int main(void){} For the same reasons this is not valid: int foo = 0;int foo(void){ return 0;} EDIT: to address the OP question edit, the second program in OP question is also valid as C says (C11, 7.1.3p1) "All identifiers with external linkage in any of the following subclauses (including the future library directions) and errno are always reserved for use as identifiers with external linkage." but the fopen variable identifier has block scope and none linkage in the example program.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25891387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775964/']}
jdg_70859
stackexchange
llm_judgeable_groundtruth_similarity
68527897
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Note: I have already seen these two: How do I run my CI steps in a specific folder in github action How to specify node's path in Github action? But I still cant get it to work, thats why I am asking how I am able to set the working directory for a uses command. My yaml currently looks as follows: # This workflow will build a Java project with Maven# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-mavenname: Java CI with Mavenon: push: branches: [ main, Create-.yml-file ] pull_request: branches: [ main, Create-.yml-file ]jobs: javatest: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: java-version: '16' distribution: 'adopt' - name: Cache Maven packages uses: actions/cache@v2 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - name: Build with Maven run: | mvn -f ./backend/pom.xml -B test #mvn -f ./notification/pom.xml -B test - name: Generate JaCoCo Badge uses: cicirello/jacoco-badge-generator@v2 with: generate-branches-badge: true on-missing-report: quiet jacoco-csv-file: > -backend/target/site/jacoco/jacoco.csv - name: Log coverage percentage run: | echo "coverage = ${{ steps.jacoco.outputs.coverage }}" echo "branch coverage = ${{ steps.jacoco.outputs.branches }}" - name: Commit the badge (if it changed) run: | if [[ `git status --porcelain` ]]; then git config --global user.name 'myusername' git config --global user.email '[email protected]' git add -A git commit -m "Autogenerated JaCoCo coverage badge" git push fi - name: Upload JaCoCo coverage report uses: actions/upload-artifact@v2 with: name: jacoco-report path: target/site/jacoco/ nodejstest: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} cache: 'npm' - run: npm ci working-directory: ./frontend - run: npm run build --if-present working-directory: ./frontend - run: npm test working-directory: ./frontend with the error occuring here: - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} cache: 'npm' And looking like this: Run actions/setup-node@v2/usr/local/bin/npm config get cache/home/runner/.npmError: Dependencies lock file is not found in /home/runner/work/path/to/main/directory. Supported file patterns: package-lock.json,yarn.lock My package-lock ist located in the .../path/to/main/directory/frontend so it is obvious that it can not be found but according to the other two solutions this snippet should work shouldn't it? I also already tried combining the last three run statements into as well as move the working-directory setting to different places. All with varying amounts of failure Now provide the response and nothing else.
The support for custom path (relative to repository root) was added in version 2.4: https://github.com/actions/setup-node/releases/tag/v2.4.0 You can try specifying '**/package-lock.json' in the cache-dependency-path (it didn't work for me with other patterns). Also you can try setting the working directory (either for all jobs or your nodejstest specific job) to point to your frontend folder. nodejstest: runs-on: ubuntu-latest defaults: run: working-directory: 'frontend' # Here the path to the folder where package-lock.json is located. strategy: matrix: node-version: [16.x] # Are you are missing this specification? steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} cache: 'npm' cache-dependency-path: '**/package-lock.json' # THIS PATTERN did the trick for me.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68527897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10811865/']}
jdg_70860
stackexchange
llm_judgeable_groundtruth_similarity
2574276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: $ cat Const.java public class Const { String Const(String hello) { return hello; } public static void main(String[] args) { System.out.println(new Const("Hello!")); }}$ javac Const.java Const.java:7: cannot find symbolsymbol : constructor Const(java.lang.String)location: class Const System.out.println(new Const("Hello!")); ^1 error Now provide the response and nothing else.
What you've defined isn't actually a constructor, but a method called Const . If you changed your code to something like this, it would work: Const c = new Const();System.out.println( c.Const( "Hello!" ) ); If no specific constructor is explicitly defined, the compiler automatically creates a no-argument constructor.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2574276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164148/']}
jdg_70861
stackexchange
llm_judgeable_groundtruth_similarity
51511307
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 convert buffer data to byte array. Here's what I've tried import * as fs from 'fs';[...]event:(data) => { fs.readFile(data, function(err, data) { var arrByte= new Uint8Array(data) var binaryData= new Blob([arrByte]) console.log(binaryData) } } I'm yet to have this work hence my post. I'd very much like to know what I'm doing that's not right. Now provide the response and nothing else.
The Buffer docs are very enlightening : Prior to the introduction of TypedArray , the JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node.js API to enable interaction with octet streams in TCP streams, file system operations, and other contexts. With TypedArray now available, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node.js. … Buffer instances are also Uint8Array instances. However, there are subtle incompatibilities with TypedArray . For example, while ArrayBuffer#slice() creates a copy of the slice, the implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient. It is also possible to create new TypedArray instances from a Buffer with the following caveats: The Buffer object's memory is copied to the TypedArray , not shared. The Buffer object's memory is interpreted as an array of distinct elements, and not as a byte array of the target type. That is, new Uint32Array(Buffer.from([1, 2, 3, 4])) creates a 4-element Uint32Array with elements [1, 2, 3, 4] , not a Uint32Array with a single element [0x1020304] or [0x4030201] . They go on to mention TypedArray.from , which in node accepts Buffer s, so the 'correct' way is: var arrByte = Uint8Array.from(data) ...however, this shouldn't be necessary at all since a Buffer is a Uint8Array and new UintArray(someBuffer) does work just fine. There's also no context in your question, but Blob doesn't exist in node, and you shouldn't need it anyway, since Buffer already gives you raw access to binary data and the other fs methods let you read and write files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51511307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10131377/']}
jdg_70862
stackexchange
llm_judgeable_groundtruth_similarity
24608
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I see that institutions still use backtesting by computing P&Ls over historical data and then compute some aggregating ratios to see whether a trading strategy is good or not even though it is not a rigourous approach at all. I mean, how can a trading strategy that happened to perform well in one sample path be guaranteed to perform as well out of sample ? Now provide the response and nothing else.
How can a trading strategy that happened to perform well in one sample path be guaranteed to perform as well out of sample? I think you are having it backwards - this is how I do it: Intuition about some economic, psychological, behavioral, technical etc. phenomenon. Trying to make my intuition precise in the form of a hypothesis. Trying to translate my hypothesis into a trading strategy. Backtesting the trading strategy. In case it does not work: Falsification of my intuition in case it does work: More tests (robustness), and with some refined intuition back to step 1. Basically this is how the scientific method works when doing research on the stock market. At least this is how it should be, so I somewhat agree with your insinuation that just data mining stock market data to find something is bad science ("Torture the data until they confess" ;-) So, yes, it is not perfect - but it is the best we have to try to find the signal in the noise (and there is a lot of noise...) A good starting point to understand more about this approach is this book: Evidence-based technical analysis by David Aronson It explains the whole process (including the complete statistical background). See for a short summary of important points here: CXO Advisory See for a comprehensive review here: Automated trading system
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/24608', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/19693/']}
jdg_70863
stackexchange
llm_judgeable_groundtruth_similarity
29975835
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 data frame like this: value identifier2007-01-01 0.781611 552007-01-01 0.766152 562007-01-01 0.766152 572007-02-01 0.705615 552007-02-01 0.032134 56 2007-02-01 0.032134 572008-01-01 0.026512 552008-01-01 0.993124 562008-01-01 0.993124 572008-02-01 0.226420 552008-02-01 0.033860 562008-02-01 0.033860 57 So I do a groupby per identifier: df.groupby('identifier') And now I want to generate subplots in a grid, one plot per group. I tried both df.groupby('identifier').plot(subplots=True) or df.groupby('identifier').plot(subplots=False) and plt.subplots(3,3)df.groupby('identifier').plot(subplots=True) to no avail. How can I create the graphs? Now provide the response and nothing else.
Here's an automated layout with lots of groups (of random fake data) and playing around with grouped.get_group(key) will show you how to do more elegant plots. import pandas as pdfrom numpy.random import randintimport matplotlib.pyplot as pltdf = pd.DataFrame(randint(0,10,(200,6)),columns=list('abcdef'))grouped = df.groupby('a')rowlength = grouped.ngroups/2 # fix up if odd number of groupsfig, axs = plt.subplots(figsize=(9,4), nrows=2, ncols=rowlength, # fix as above gridspec_kw=dict(hspace=0.4)) # Much control of gridspectargets = zip(grouped.groups.keys(), axs.flatten())for i, (key, ax) in enumerate(targets): ax.plot(grouped.get_group(key)) ax.set_title('a=%d'%key)ax.legend()plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29975835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307283/']}
jdg_70864
stackexchange
llm_judgeable_groundtruth_similarity
2097901
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It seems evident from infinitely many primitive pythagorean triples $(a,b,c)$ that there are infinitely many rational points $\left(\frac{a}{c}, \frac{b}{c}\right)$ on the unit circle. But how would one go about, and show that they are dense, in the sense that for two rational points $x$ and $y$ of angles $α$ and $β$ on the unit circle, if $α<β$ there is a third rational point $z$ of angle $γ$ on the unit circle, such that $α<γ$ and $γ<β$. Is it to expect that this conjecture holds and that it isn't an unsolved number theory problem? Now provide the response and nothing else.
Consider a nonvertical line through the point $(1, 0)$ of slope $m$. This line meets the circle at exactly one other point, and it's not hard to show that the coordinates of that point are $$P_m=\left({m^2-1\over m^2+1}, {-2m\over m^2+1}\right).$$ As long as $m$ is rational, $P_m$ has rational coordinates; so now think about the lines through $(1, 0)$ of rational slope . . .
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2097901', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_70865
stackexchange
llm_judgeable_groundtruth_similarity
1484
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm building an image with a Nagios server. One of the problems of the raspberry pi is that the memory is quite small on the raspberry pi. So I'll be using a light weight interface based on php-apc instead of the standard one. I was wondering what lightweight webserver is recommended to use? I was considering a minimum webserver that can do php and provide SSL. I was thinking of Apache2 or Nginx. Although I think Apache will still outperform Nginx since the content is dynamic. Now provide the response and nothing else.
The real question here is "Do you need all the features that Apache provides?" (or more importantly, "Are you willing to use up memory for these features?") -- You can custom-compile a VERY stripped-down Apache + mod_perl or mod_php to run your Nagios web interface (or an Über-Stripped apache that just runs the perl CGIs), but even in a minimalist form Apache will probably take more memory than nginx to do the same job - It just wasn't built to be small. To be 100% sure you may want to do a bake-off (compile both nginx and Apache and see which eats less RAM), but my experience on "normal" servers tells me that nginx is probably the better choice for a low-memory configuration: You give up some of the flexibility of Apache, but if you didn't need that anyway (and most sites don't ) you'll never notice the difference. Performance (time) wise I doubt you'll be limited by your web server -- All the contrived benchmarks aside, if you're doing enough volume where the performance of the server engine handing out the pages is that critical you're probably going to be baking your Raspberry Pi (and really, how many people are going to be looking at your monitoring data at once? :-). It's pretty much an axiom that you can optimize a system for space or time, but never both - and on a Raspberry Pi space is probably your limiting constraint.
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/1484', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/203/']}
jdg_70866
stackexchange
llm_judgeable_groundtruth_similarity
104751
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: Using Linux, I would like to track the executables that are executed in my name, including the whole command line (in practice, every exec*() done as my own user). A program I do not control is supposed, in order to handle a task, to execute the program I pass in, but I want make sure it does so, and what options it uses. The program I don't control is sneaky, and seems to change behavior depending on the name of the program it is supposed to execute for the task, so I can't pass in a shell script that would log the info and invoke the real program. Is it possible for me to be informed of all exec*()s done as my user on the system on Linux, including full command line? Short of running ps in a loop, that is. I'd rather do it directly on the system on which I work and not require root access, but if need be I can spawn a system on which I have root access, install the programs and investigate there. Using Ubuntu 12.4 LTS. Now provide the response and nothing else.
You need to configure auditd to record execve events. Example on RHEL5: [root@ditirlns01 ~]# auditctl -a always,entry -S execveWARNING - 32/64 bit syscall mismatch, you should specify an arch[root@ditirlns01 ~]# I ignore the arch warning and it doesn't seem to matter but you can use -F arch=b64 or -F arch=b32 to set it if you want. The result of the above is: [root@ditirlns01 ~]# ls /tmp/whateverls: /tmp/whatever: No such file or directory[root@ditirlns01 ~]# grep whatever /var/log/audit/audit.logtype=EXECVE msg=audit(1386797915.232:5527206): argc=3 a0="ls" a1="--color=tty" a2="/tmp/whatever"type=EXECVE msg=audit(1386797927.133:5527241): argc=3 a0="grep" a1="whatever" a2="/var/log/audit/audit.log"[root@ditirlns01 ~]# That's obviously quick and dirty but that's the basics of how you do it. What you need to do exactly probably depends heavily on what you're trying to do exactly. You can reduce audit flow using various filters in the auditctl command but I don't know any of that information so I don't know what to include. If you need something more specific, I'd suggest you either check the man page or post a comment to this answer and I'll update it some more. Hope that helps push you in the right direction. EDIT: Since your question involves looking at a particular user I can show you that: [root@ditirlns01 ~]# auditctl -a always,entry -S execve -F euid=16777216WARNING - 32/64 bit syscall mismatch, you should specify an arch Identical to the above, but only execve 's by someone running with the effective user ID of 16777216 will get logged. If you need to specify the user's loginuid value (who they initially logged into the system as) then you filter by auid instead: [root@ditirlns01 ~]# auditctl -a always,entry -S execve -F auid=16777216WARNING - 32/64 bit syscall mismatch, you should specify an arch AUID/loginuid filters would be useful for example if the user will do a su or sudo to root. In that situation there will be a lot of stuff running as root, but you're only concerned with the stuff that got kicked off by the user in question. auditctl also lets you stack filters so you can filter by both euid and auid : [root@ditirlns01 ~]# auditctl -a always,entry -S execve -F auid=16777216 -F euid=0WARNING - 32/64 bit syscall mismatch, you should specify an arch[root@ditirlns01 ~]# ls /tmp/nashly -ltarls: /tmp/nashly: No such file or directory[root@ditirlns01 ~]# grep nashly /var/log/audit/audit.logtype=EXECVE msg=audit(1386798635.199:5529285): argc=4 a0="ls" a1="--color=tty" a2="/tmp/nashly" a3="-ltar"type=EXECVE msg=audit(1386798646.048:5529286): argc=3 a0="grep" a1="nashly" a2="/var/log/audit/audit.log"
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/104751', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/54340/']}
jdg_70867
stackexchange
llm_judgeable_groundtruth_similarity
7124969
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 is it possible to create a recursive variadic template to print out the contents of a paramater pack?I am trying with this, but it fails to compile: template <typename First, typename ...Args>std::string type_name () { return std::string(typeid(First).name()) + " " + type_name<Args...>();}std::string type_name () { return "";} How shall I end the recursion? Now provide the response and nothing else.
You need to use partial specialisation to end the recursion, but since you can't partially specialise free functions in C++, you need to create an implementation class with a static member function. template <typename... Args>struct Impl;template <typename First, typename... Args>struct Impl<First, Args...>{ static std::string name() { return std::string(typeid(First).name()) + " " + Impl<Args...>::name(); }};template <>struct Impl<>{ static std::string name() { return ""; }};template <typename... Args>std::string type_name(){ return Impl<Args...>::name();}int main(){ std::cout << type_name<int, bool, char, double>() << std::endl; // "i b c d" return 0;} That first declaration of Impl is just a workaround for a shortcoming in g++ 4.6 (and below). It won't be necessary once it implements variadic templates correctly. Check it out in action at ideone.com
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7124969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/820676/']}
jdg_70868
stackexchange
llm_judgeable_groundtruth_similarity
18014392
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 query my sql server to only get the size of database? I used this : use "MY_DB"exec sp_spaceused I got this : database_name database_size unallocated spaceMy_DB 17899.13 MB 5309.39 MB It returns me several column that i don't need, maybe there is a trick to select database_size column from this stored procedure ? I also tried this code : SELECT DB_NAME(database_id) AS DatabaseName, Name AS Logical_Name, Physical_Name, (size * 8) / 1024 SizeMBFROM sys.master_filesWHERE DB_NAME(database_id) = 'MY_DB' It gives me this result: DatabaseName Logical_Name Physical_Name SizeMBMY_DB MY_DB D:\MSSQL\Data\MY_DB.mdf 10613MY_DB MY_DB_log D:\MSSQL\Data\MY_DB.ldf 7286 So i wrote this: SELECT SUM(SizeMB)FROM ( SELECT DB_NAME(database_id) AS DatabaseName, Name AS Logical_Name, Physical_Name, (size * 8) / 1024 SizeMB FROM sys.master_files WHERE DB_NAME(database_id) = 'MY_DB') AS TEMP I got: 1183 So it works but maybe there is a proper way to get this? Now provide the response and nothing else.
Try this one - Query: SELECT database_name = DB_NAME(database_id) , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2)) , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2)) , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))FROM sys.master_files WITH(NOWAIT)WHERE database_id = DB_ID() -- for current db GROUP BY database_id Output: -- my queryname log_size_mb row_size_mb total_size_mb-------------- ------------ ------------- -------------xxxxxxxxxxx 512.00 302.81 814.81-- sp_spaceuseddatabase_name database_size unallocated space---------------- ------------------ ------------------xxxxxxxxxxx 814.81 MB 13.04 MB Function: ALTER FUNCTION [dbo].[GetDBSize] ( @db_name NVARCHAR(100))RETURNS TABLEASRETURN SELECT database_name = DB_NAME(database_id) , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2)) , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2)) , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2)) FROM sys.master_files WITH(NOWAIT) WHERE database_id = DB_ID(@db_name) OR @db_name IS NULL GROUP BY database_id UPDATE 2016/01/22: Show information about size, free space, last database backups IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL DROP TABLE #spaceCREATE TABLE #space ( database_id INT PRIMARY KEY , data_used_size DECIMAL(18,2) , log_used_size DECIMAL(18,2))DECLARE @SQL NVARCHAR(MAX)SELECT @SQL = STUFF(( SELECT ' USE [' + d.name + '] INSERT INTO #space (database_id, data_used_size, log_used_size) SELECT DB_ID() , SUM(CASE WHEN [type] = 0 THEN space_used END) , SUM(CASE WHEN [type] = 1 THEN space_used END) FROM ( SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024) FROM sys.database_files s GROUP BY s.[type] ) t;' FROM sys.databases d WHERE d.[state] = 0 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')EXEC sys.sp_executesql @SQLSELECT d.database_id , d.name , d.state_desc , d.recovery_model_desc , t.total_size , t.data_size , s.data_used_size , t.log_size , s.log_used_size , bu.full_last_date , bu.full_size , bu.log_last_date , bu.log_sizeFROM ( SELECT database_id , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2)) , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2)) , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2)) FROM sys.master_files GROUP BY database_id) tJOIN sys.databases d ON d.database_id = t.database_idLEFT JOIN #space s ON d.database_id = s.database_idLEFT JOIN ( SELECT database_name , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END) , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END) , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END) , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END) FROM ( SELECT s.database_name , s.[type] , s.backup_finish_date , backup_size = CAST(CASE WHEN s.backup_size = s.compressed_backup_size THEN s.backup_size ELSE s.compressed_backup_size END / 1048576.0 AS DECIMAL(18,2)) , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC) FROM msdb.dbo.backupset s WHERE s.[type] IN ('D', 'L') ) f WHERE f.RowNum = 1 GROUP BY f.database_name) bu ON d.name = bu.database_nameORDER BY t.total_size DESC Output: database_id name state_desc recovery_model_desc total_size data_size data_used_size log_size log_used_size full_last_date full_size log_last_date log_size----------- -------------------------------- ------------ ------------------- ------------ ----------- --------------- ----------- -------------- ----------------------- ------------ ----------------------- ---------24 StackOverflow ONLINE SIMPLE 66339.88 65840.00 65102.06 499.88 5.05 NULL NULL NULL NULL11 AdventureWorks2012 ONLINE SIMPLE 16404.13 15213.00 192.69 1191.13 15.55 2015-11-10 10:51:02.000 44.59 NULL NULL10 locateme ONLINE SIMPLE 1050.13 591.00 2.94 459.13 6.91 2015-11-06 15:08:34.000 17.25 NULL NULL8 CL_Documents ONLINE FULL 793.13 334.00 333.69 459.13 12.95 2015-11-06 15:08:31.000 309.22 2015-11-06 13:15:39.000 0.011 master ONLINE SIMPLE 554.00 492.06 4.31 61.94 5.20 2015-11-06 15:08:12.000 0.65 NULL NULL9 Refactoring ONLINE SIMPLE 494.32 366.44 308.88 127.88 34.96 2016-01-05 18:59:10.000 37.53 NULL NULL3 model ONLINE SIMPLE 349.06 4.06 2.56 345.00 0.97 2015-11-06 15:08:12.000 0.45 NULL NULL13 sql-format.com ONLINE SIMPLE 216.81 181.38 149.00 35.44 3.06 2015-11-06 15:08:39.000 23.64 NULL NULL23 users ONLINE FULL 173.25 73.25 3.25 100.00 5.66 2015-11-23 13:15:45.000 0.72 NULL NULL4 msdb ONLINE SIMPLE 46.44 20.25 19.31 26.19 4.09 2015-11-06 15:08:12.000 2.96 NULL NULL21 SSISDB ONLINE FULL 45.06 40.00 4.06 5.06 4.84 2014-05-14 18:27:11.000 3.08 NULL NULL27 tSQLt ONLINE SIMPLE 9.00 5.00 3.06 4.00 0.75 NULL NULL NULL NULL2 tempdb ONLINE SIMPLE 8.50 8.00 4.50 0.50 1.78 NULL NULL NULL NULL
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18014392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2207842/']}
jdg_70869
stackexchange
llm_judgeable_groundtruth_similarity
337233
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider the Lie algebra inclusions $\mathfrak{gl}(n) \subset \mathfrak{so}(2n)$ and $\mathfrak{gl}(n) \subset \mathfrak{sp}(2n)$ . Let $\mathfrak{c} \subset \mathfrak{gl}(n)$ denote the centre. Thinking of it as a subspace of $\mathfrak{so}(2n)$ or $\mathfrak{sp}(2n)$ , let $\mathfrak{c}^\perp$ denote the orthogonal complement (with respect to the Killing form). Note that $\mathfrak{c}^\perp$ is not a Lie subalgebra of $\mathfrak{so}(2n)$ or $\mathfrak{sp}(2n)$ , but it contains various subalgebras (e.g. $\mathfrak{sl}(n) \subset \mathfrak{c}^\perp$ ). What are the (maximal) Lie subalgebras of $\mathfrak{c}^\perp$ ? Are there any for which the induced $2n$ -dimensional representation is simple? The specific case I care about is when $n=28$ , and I look at $\mathfrak{sp}(56)$ . Then I want to know if $\mathfrak{c}^\perp$ contains a subalgebra of type $\mathfrak{e}_7$ . I suspect it does not, but I cannot prove it. Now provide the response and nothing else.
This must be "well-known": If we have $G = AB$ when $G$ is a finite group, and $A,B$ are proper subgroups of $G$ , then we may suppose that $A$ and $B$ are both maximal. For if $A$ is not maximal, and $A < C$ with $C$ maximal, then we still have $G = CB,$ and $B \not \leq C$ , so we may replace $A$ by $C$ and assume that $A$ is maximal. Now if $B$ is not maximal, but $B < D$ with $D$ maximal, then we have $G = AD$ and $A,D$ are both proper and maximal, so we can replace $B$ by $D$ and assume, $A,B$ are both maximal. Hence the finite group $G$ has no factorization if and only if $|AB| < |G|$ whenever $A$ and $B$ are maximal subgroups of $G$ , ie if and only if $[G:A] > [B:A \cap B]$ whenever $A,B$ are maximal subgroups of $G$ . In particular, since the Frattini subgroup $\Phi(G)$ is the intersection of the maximal subgroups of $G$ we conclude that $G$ has a factorization if and only if $G/\Phi(G)$ has a factorization. Since $G/\Phi(G)$ has trivial Frattini subgroup, we conclude from the argument you gave in the question, that if $G$ has no factorization, then $G/\Phi(G)$ is a simple group. Later edit: By the way, this answers the subquestion in the negative. If we take a nonsplit extension $H$ of a non-Abelian finite simple group $G$ which itself has no factorization by a finite irreducible $G$ -module $M$ , then we obtain a non-simple finite group $H$ which is neither simple nor cyclic of prime-power order, yet there is is no factorization of $H$ (and there are examples of such non-split extensions- note that $\Phi(H) = M$ in that case. For example, $J_{3}$ admits no factorization, and it has a (non-split) triple cover which also admits no factorization). Even later edit: In fact, we can now further restrict all finite groups $G$ which admit no factorization. By a slight extension of the argument above, we deduce that $G$ has no factorization if and only if $G/X$ has no factorization whenever $X \lhd G$ with $X \leq \Phi(G)$ . If G has no factorization, we know that $G/\Phi(G)$ is a simple group without a factorization. If $G/\Phi(G)$ is cyclic of prime order, then $G$ is cyclic, and $G$ must be a cyclic $p$ -group for some prime $p$ . If $G/\Phi(G)$ is non-Abelian simple, then we may take $X \lhd G$ with $X < \Phi(G)$ and $[\Phi(G):X]$ minimal. Let $V = \Phi(G)/X.$ Then $V = \Phi(G/X)$ and $G/X$ is a non-split extension of the simple group $G/\Phi(G)$ by the irreducible $G/\Phi(G)$ -module $V.$ Hence the finite group $G$ admits no factorization if and only if either $G$ is cyclic of prime power order or else $G/\Phi(G)$ is a non-Abelian simple group with no factorization which admits a non-split extension by a finite (possibly trivial) irreducible $G/\Phi(G)$ -module $V$ occurring as a "top" $G$ -chief factor within $\Phi(G)$ (that is to say $V$ occurs as $\Phi(G)/X$ where $X$ is maximal subject to being normal in $G$ and properly contained in $\Phi(G)$ ).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/337233', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
jdg_70870
stackexchange
llm_judgeable_groundtruth_similarity
395414
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: What does it mean when people say that alternating current reverses direction? Do they mean that the electricity starts travelling in the opposite direction (away from the houses and towards the power plant, then back towards the houses)? If so then how would the electricity ever reach the house? Now provide the response and nothing else.
The electricity, or more precisely, electric current is flowing in a loop. When the electricity is delivered to your house, the loop is formed by a generator (the source of the electricity), an electric device in your house (the load) and two wires. In reality the picture is a little more complicated, but the idea is the same. When we say that an alternating current reverses its direction, we mean that, every 16.7ms (for 60Hz system), it changes its direction in that loop, from clockwise to counterclockwise and back. At a given moment, if the current flows toward your house in one of the two wires, it flows away from your house in the other wire. Regardless of the direction of the flow, CW or CCW, this current will be delivering electrical power to your house, heating a stove or spinning a fan. In that sense, we can say that the electricity or, more precisely, electrical power is always flowing toward your house (unless you have a solar panel and are sending electricity, electric power, back to the grid). To summarize, we can say that the electric power is always flowing from a power source to a load, while the electric current is moving in a loop and, in case of AC, its direction in the loop is alternating from CW to CCW.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/395414', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/180969/']}
jdg_70871
stackexchange
llm_judgeable_groundtruth_similarity
1524315
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question involves long division. I calculated the value. However, I want to ask two concept questions: 1) Why am I doing long division rather than writing out the form of the partial fraction decomposition of the function. 2) When utilizing long division do I place a constant at the end and if not why? Here is my set up $\dfrac{x^4+0x^3+0x^2+0x+1}{x-1}$ Now provide the response and nothing else.
Partial fractions will only work if the degree of the numerator is strictly less than the degree of the denominator. Hence why you need to do long division. You should not add the +1 at the end on the numerator. This changes the value of the fraction. If you remember differences of squares you can do the division without long division as: $$\frac{x^4}{x-1}=\frac{x^4-1}{x-1}+\frac{1}{x-1}$$$$=\frac{(x^2-1)(x^2+1)}{x-1}+\frac{1}{x-1}$$$$=\frac{(x-1)(x+1)(x^2+1)}{x-1}+\frac{1}{x-1}$$$$=(x+1)(x^2+1)+\frac{1}{x-1}$$ Alternatively you could substitution to make the division easier. Let $y=x-1$, hence $dy=dx$ and the integral becomes: $$\int{\frac{(y+1)^2}{y}dy}=\int\frac{y^4+4y^3+6y^2+4y+1}{y}dy$$$$=\int y^3+4y^2+6y+4+\frac{1}{y}dy$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1524315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/268263/']}
jdg_70872
stackexchange
llm_judgeable_groundtruth_similarity
461
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How should I store tick data? For example, if I have an IB trading account, how should I download and store the tick data directly to my computer? Which software should I use? Now provide the response and nothing else.
Using IBrokers from R is going to be the easiest route. A quick example of capturing data to disk would be: library(IBrokers)tws <- twsConnect()aapl.csv <- file("AAPL.csv", open="w")# run an infinite-loop ( <C-c> to break )reqMktData(tws, twsSTK("AAPL"), eventWrapper=eWrapper.MktData.CSV(1), file=aapl.csv)close(aapl.csv)close(tws) This will send CSV style output to disk. Additionally the data can be stored in xts objects within the loop which can be appended to/filled to provide a constant in-memory object to use for analytics. Objects can be shared with many tools - including using the RBerkeley package on CRAN to share objects with other programs with Berkeley DB bindings. This latter approach, if managed intelligently is very, very fast. Given the symbol limit of IB (100 concurrent more or less) and the 250ms updates - R can typically handle all of this without breaking a sweat (i.e. the JVM running IB's TWS or even IBGateway client is likely to be far surpassing the R/IBrokers process in terms of CPU usage). You can even extend the syntax above to record more than one symbol by passing a list of Contracts, increasing the number on the eWrapper, and making sure you have a suitable list of files to write to. In terms of something closer to long-term storage/access, the packages Josh referred to (mmap and indexing) are also very useful. I've given talks with some basic options data examples that are 3-4GB in size without derived columns (12GB total), and I can pull using R-style subsetting syntax any subset I need nearly instantly. e.g. finding 90k+ contracts for AAPL in 2009 (out of 70MM rows) took tens of milliseconds. All without keeping anything in RAM, and all running on a laptop with 2GB of RAM. I'll likely get some more presentation material for the latter packages put together soon, and will be giving some talk(s) at the upcoming R/Finance conference in Chicago. I am also planning on some public workshops through lemnica related to R and IB for 2011.
{}
{'log_upvote_score': 5, 'links': ['https://quant.stackexchange.com/questions/461', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/354/']}
jdg_70873
stackexchange
llm_judgeable_groundtruth_similarity
37628
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: How does harmonic mean handle zero values? what would the harmonic mean of {3, 4, 5, 0} be since $1/0=\infty$? Now provide the response and nothing else.
Just as the geometric mean of anything and $0$ is $0$, it is usually natural to define the harmonic mean of anything and $0$ to be $0$. One physical interpretation of the harmonic mean is that if you have resistors in parallel, the total resistance is as though each resistor had the harmonic mean resistance. If one of the resistors has no resistance, there is no resistance over all (a short), and this is the same as if all resistors had no resistance. If for some reason you are considering the harmonic means of numbers so that some are negative and some are positive, then it might be better to say that a harmonic mean of $0$ with itself is not defined. However, in the applications I know for the harmonic mean, it is used on nonnegative numbers.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/37628', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12883/']}
jdg_70874
stackexchange
llm_judgeable_groundtruth_similarity
252308
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've recently read several articles about the advantages of the composition over inheritance. Their authors said that you can always replace inheritance with composition (to be precise, they say they don't know such situations where it can't be done). However, I can't think how to do this in the following case: abstract class Reader{ public Int32 ReadSum() { return this.ReadValue() + this.ReadValue(); } public Int32 ReadSub() { return this.ReadValue() - this.ReadValue(); } public Int32 ReadMul() { return this.ReadValue() * this.ReadValue(); } public Int32 ReadDiv() { return this.ReadValue() / this.ReadValue(); } public abstract Int32 ReadValue();}class RandomSource: Reader{ public Int32 ReadValue() { return Math.RandomInt32(); }}class UserSource: Reader{ public Int32 ReadValue() { return Console.ReadInt32(); }} Is this at all possible? Now provide the response and nothing else.
This example is a bit contrived but here's one way. You seem to have things going on here - operations and reading. The reading should be done by Reader and the operations can be performed by a different class. class ReadOperations { private Reader reader; public Int32 ReadSum() { return reader.ReadValue() + reader.ReadValue(); } public Int32 ReadSub() { return reader.ReadValue() - reader.ReadValue(); } public Int32 ReadMul() { return reader.ReadValue() * reader.ReadValue(); } public Int32 ReadDiv() { return reader.ReadValue() / reader.ReadValue(); }}interface Reader { public Int32 ReadValue();}class RandomSource: Reader{ public Int32 ReadValue() { return Math.RandomInt32(); }}class UserSource: Reader{ public Int32 ReadValue() { return Console.ReadInt32(); }} Depending on what you want there are other ways to do this. You should have to find a way to inject the reader - probably with a constructor. Disclaimer - for practical purposes you don't "need" to use composition, but doing so is extensible and you should use it whenever you think your program can evolve in a certain direction. In this case, if you think your operations will evolve independently from the way you "read".
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/252308', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/-1/']}
jdg_70875
stackexchange
llm_judgeable_groundtruth_similarity
54022
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the cartesian coordinates for two molecules that are in a stacked position and I want to be able to calculate the potential energy at 0.2 angstrom steps from when the top molecule is 3.0 angstroms to 7.0 angstroms away in the z direction. My professor told me gaussian has a scan function to do this but I'm having trouble figuring some things out. I have the basis set/ correlation methods I need to use and the cartesian coordinates for all the atoms when they are arranged 3.0 angstroms apart. I tried following this site's advice; but I'm not sure I constructed the input file correctly. Here is what I have . From my understanding, this should just move up all of the atoms of the top molecule by 0.2 angstroms in the Z direction. Questions: Do I just throw this stuff anywhere into the input file? What about the original cartesian coordinate array? Surely it has to stay since the "step" array calls back to atoms 101-112. Do I have to change any other commands? The only parameters set are the resource limits and "#P BP86/6-311++G**" Update: I think I may have been unclear. I have already optimized my two molecules. One is a nanotube and the other is an arene and my task was to basically generate this plot . I'm trying to find the distance apart where the two molecules are stabilized. Before, I just ran the "#P BP86/6-311++G**"" with my arene @ 3.0 angstrom apart and made new input files changing the arene z coordinates in 0.5 angstrom increments but I can't capture that potential energy well. I decided to try smaller increments to increase the resolution but I have quite a few more situations to test so I wanted to just have Gaussian change the increments and recalculate the potential energy. Thankfully a full relaxed scan is not necessary in most cases. Oftentimes a nice little rigid scan will give you a decent result. Have a look at the scan keyword. The only downside to this approach is, that you need a z-matrix to make it work. And putting your brain to that task is also a bit tedious. That's what I initially came across but with ~100 atoms, I just let Chemcraft generate the z matrix from my cartesian coordinates. The thing is, I'm not sure quite how to edit the z-matrix (relevant part below) with the scan commands. Specifically I want to keep all bond angles the same but move atoms 101-112 in 0.2 A steps in the z direction, and calculate the potential energy. I guess my question is now if this is a plausible approach. I'll try to look up how to construct the proper z-matrix if that is indeed the best way to do things. Thanks @Martin Now provide the response and nothing else.
Firstly, the Gaussian format, while annoyingly unlabeled, has a strict ordering which you can find here . (Aside from your ordering problem, I highly recommend you check out the Link 0 commands in the Gaussian manual, particularly %OldChk=file which means that it copies the checkpoint file before using it.) Secondly, I would use (and, actually, have used with an SWNT+arene system) an IRC scan for this: I know it's not quite what you asked about, but if you can start from a reasonably aligned geometry that you think is close to somewhere on the potential valley, it should automatically generate points backward and forward on that valley, without you having to manually specify any coordinates. Using IRC(Report=Read) will spit out the coordinates along with the energy, and from one or two of those sets of coordinates that look close to the minimum, you can perform an optimisation to get the actual minimum. Depending on what you're doing, you may also want to fix many of the nanotube carbons in place before doing this -- it'll dramatically speed up your gradient calculations if I recall correctly. (This is much easier to do if you skip the Z-matrices and just use Cartesian coordinates.)
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/54022', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/31282/']}
jdg_70876
stackexchange
llm_judgeable_groundtruth_similarity
6607410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was recently surprised to note that compiling with /GS (Enable buffer security check) in MSVC++ 2010 seems to have a non-negligible effect on run-time performance in some cases. Has anyone else had this experience?? For a large scientific-style application (a mesh generation library) it seems that compiling with /GS- can lead to almost 10% improvements in run-time for several of the large benchmarks in my test suite ("large" being >= 1 second worth of run-time). /GS is on by default at all levels of optimisation in MSVC++ 2010. I must admit that I'd never paid too much attention to this option before, and I'm wanting a bit of clarification as to what it actually does. The online documentation seems to talk extensively about string buffers, but since I don't use string or char[] buffers anywhere I must be missing something. This paragraph (from the online doc) seems to indicate that the performance degradation I'm seeing is a bit unusual: A performance tradeoff for using security checks in an application must be made. The Visual C++ compiler team focused on making the performance degradation small. In most cases, the performance should not degrade more than 2 percent. In fact, experience has shown that most applications, including high-performance server applications, have not noticed any performance impact. Of course I can just turn it off, and get faster code, but I want to understand the implications before I do that. Now provide the response and nothing else.
/GS adds code that tries to detect if a write overrun or similar stack attack has happend during a function, and to stop execution after a write overrun. The patterns that it aims to find are ones that have been seen in real-world attacks. There are a bunch of real world security bulletins that would not have happened if today's /GS had been in use at the time. In this case a write overrun can happen on structures, arrays and various other entities. Changes and improvements to /GS are made in each version of VS. More /GS protection generally has cost, although in some cases newer VS may have learnt how to do the same protection cheaper. I'd recommend leaving /GS on unless your code doesn't ship to others - generally the protection is worth the cost; at most you might choose to disable it for specific functions where there is no risk and high impact - just as you might hand-optimise the most critical parts of your program in other ways. Martyn
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6607410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/566274/']}
jdg_70877
stackexchange
llm_judgeable_groundtruth_similarity
345288
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We're in the process of migrating a monolithic application to microservice architecture. Due to some regulatory requirements, we have to keep client's data from different countries in separate (country specific) databases. I.e US db for US customers, UK db for UK customers... The following designs that we are considering are as follows: Option 1: A multi-tenant application with hibernate multi-tenant support that can be scaled to N number of times dependending on demand (think of kubernetes pods). A single instance of this application will be able to connect to all databases. Option 2: Deploy 1 microservice instance per country database. With an API gateway in front of them routing traffic If you were to design this type of system, what would your choices be? Now provide the response and nothing else.
I think option 2 is not a bad one, but may not be needed. Micro services are for letting you deal with the needs of multiple applications. A big factor here, is if there is any difference between the two schemas, and if there ever will be in the future. Usually, I think using interfaces for repositories is unnecessary; however, it might be worth the effort in this instance. Repository factories will be important for you. My issue with option 1 is that it is too specific. You should be able to go from the setup which you described, to two separate instances each pointing to its own DB easily. The application should NOT CARE WHERE IT IS GETTING ITS DATA FROM. While the schema does not differ for your two different database, you can have one repository easily deal with both, without the application knowing the difference: public class MyEntityRepository : ISavesMyEntity, IGetsMyEntity{ public MyEntityRepository(string connectionString) { _connectionString = connectionString; }}public class MyEntitySaverFactory{ public ISavesMyEntity GetSaver(User user) { if (user.IsUK) return new MyEntityRepository(Config.Get("UKConnString")); if (user.IsUS) return new MyEntityRepository(Config.Get("USConnString")); throw new NotImplementedException(); }}//USEISavesMyEntity saver = factory.GetSaver(currentUser);saver.Save(myEntityInstance); If the DB schemas ever become disparate between the US and UK, then you would then split the functionality into two completely different repositories. This would be easy, since all you would have to do is change your factory.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/345288', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/266714/']}
jdg_70878
stackexchange
llm_judgeable_groundtruth_similarity
1182179
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This may be a naive question but I would like to know whether we can determine if a fraction (say $1/3$) will produce a rational number with an infinite number of digits after the decimal when computed (without actually computing it). Of course computers cannot store such rational numbers accurately and they are difficult to detect after calculations have been performed and the result truncated. Similar to how we can perform integral calculations on improper fractions to get their remainder, I wonder if we can do something similar to determine if a proper fraction will compute to an irrational number. Now provide the response and nothing else.
A rational number has terminating decimal expansion if the denominator (in lowest terms) has prime factors only $2$ or $5$ or both. Any other factors in the denominator yield a non-terminating decimal expansion. Examples$$\frac{1}{1024} = 0.0009765625\quad\text{(exactly)}$$terminates because $1024 = 2^{10}$. $$\frac{1}{6} = 0.16666666666\cdots$$is non-terminating, because $6=2\cdot3$ has a prime factor $3$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1182179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31055/']}
jdg_70879
stackexchange
llm_judgeable_groundtruth_similarity
932867
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $A$ is a positive semi definite matrix, is $\left[ \begin{matrix}c_1A & c_2A \\ c_3A & c_4A\end{matrix} \right]$ positive semi definite? ($c_1, c_2, c_3, c_4 > 0)$ In general, what about $\left[ \begin{matrix}c_{1,1}A & c_{1,2}A & \ldots & c_{1,n} A\\ \vdots & \vdots & \ddots & \vdots\\c_{n,1}A & c_{n,2}A & \ldots & c_{n,n}A\end{matrix} \right]$ ? ($c_{i,j} > 0$) If the above block matrices are not semi-definite in general, is it possible to gain constraints on the constants, under which they will be semi definite? Now provide the response and nothing else.
Not necessarily. Certainly, this fails if $c_2 \neq c_3$. Even if $c_2 = c_3$, take $A = 1$ and consider $c_1 = 1, c_2 = c_3 = 10, c_4 = 1$. The general matrix you describe can be written in the form$$\left[ \begin{matrix}c_{1,1}A & c_{1,2}A & \ldots & c_{1,n} A\\ \vdots & \vdots & \ddots & \vdots\\c_{n,1}A & c_{n,2}A & \ldots & c_{n,n}A\end{matrix} \right] = C \otimes A$$Where $C$ is the matrix with entries $c_{ij}$ and $\otimes$ denotes the Kronecker product . For vectors $u,v$ of appropriate size, we have$$(u \otimes v)^*(C \otimes A)(u \otimes v) = (u^*Cu)(v^*Av)$$So, at the very least, $C$ must be positive semidefinite as well. In fact, this condition is sufficient, as can be deduced from the properties of the Kronecker product given in the link. Namely: if $A,C$ are both symmetric, then so is $C \otimes A$, and if both have only non-negative eigenvalues, then so does $C \otimes A$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/932867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29755/']}
jdg_70880
stackexchange
llm_judgeable_groundtruth_similarity
54469571
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following scenario (Angular v7): Load configuration parameters (API server URL and Auth server URL) from an external endpoint (JSON), before the AppModule is loaded Pass configuration to AppModule (OAuth2 module) Compile the app with AOT Point 2 is key here, and looks like this: @NgModule({ imports: [ ... OAuthModule.forRoot({ resourceServer: { allowedUrls: [API_SERVER_URL], // <== we need to set the value that we loaded from the external endpoint (JSON) here sendAccessToken: true } }), ... ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule { } What I've tried to far: A solution with APP_INITIALIZER . This doesn't work, as the OAuthModule.forRoot() is triggered before the APP_INITIALIZER can download the external configuration JSON. Load the config with an async function in the main.ts into the Angular environment variables, then bootstrap the AppModule. Also doesn't work due to the import { AppModule } from './app/app.module'; statement in main.ts , which causes the AppModule to load and fire OAuthModule.forRoot() before the external config is loaded ( this comment confirms this behavior). Load the AppModule dynamically in main.ts , so without the import statement on top. This is the StackBlitz example given in that comment. It works , but 1) breaks lazy loading WARNING in Lazy routes discovery is not enabled. and 2) doesn't work with AOT compiling. It does come very close to what I need. Curious to hear if someone is aware of another method to get external configuration loaded before the AppModule loads. StackBlitz for option 3 (Load the AppModule dynamically): https://stackblitz.com/edit/angular-n8hdty Now provide the response and nothing else.
Angular documentation has a great chapter called NgModule FAQs which contains the following section: What if two modules provide the same service? ... If NgModule A provides a service for token 'X' and imports an NgModule B that also provides a service for token 'X', then NgModule A's service definition "wins". In other words, you can override OAuthModuleConfig for your library in AppModule: main.ts (async () => { const response = await fetch('https://api.myjson.com/bins/lf0ns'); const config = await response.json(); environment['allowedUrls'] = config.apiBaseURL; platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));})(); app.module.ts import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppComponent } from './app.component';import { OAuthModule, OAuthModuleConfig } from 'angular-oauth2-oidc';import { HttpClientModule } from '@angular/common/http';import { environment } from '../environments/environment';@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, OAuthModule.forRoot(), ], providers: [ { provide: OAuthModuleConfig, useFactory: () => ({ resourceServer: { allowedUrls: [environment['allowedUrls']], sendAccessToken: true } }) } ], bootstrap: [AppComponent]})export class AppModule {} Note that we should also use useFactory instead of useValue so we don't depend on when AppModule is imported.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54469571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337765/']}
jdg_70881
stackexchange
llm_judgeable_groundtruth_similarity
6963779
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Google Analytics async code uses a very distinct design pattern for javascript code execution. The code depends on a library and it doesn't know if the library has loaded or not. If the library didn't load yet it just queues all the commands into an Array object. When the library loads it just creates the _gaq object and executes all commands in the sequence it was included. It then overwrites the push function so future commands are executed right away. The idea is to make the commands run very fast when they are queued. The code is only really evaluated later when the library is loaded. They also load the library with a parameters async=true . This causes almost no impact on the actual page loading time. The commands look just like the sync versions of it, but the first string is a function name and the next parameters are that function parameters. You can also push functions into this array and the functions will be executed in sequence as well with a null context. So if you need to do something synchronous with the library you can push a function to do this inside _gaq. I think this is a very clever solution but I have never seen it before. Does anyone know the name of this design pattern or where it's used besides the Google Analytics tracking code? Now provide the response and nothing else.
I've referred to it as "asynchronous function queuing", but its not quite a catchy name, and certainly not the formal name of the design pattern. What's interesting is that, though I hadn't seen this particular pattern used before, since Google adopted it for Google Analytics, its been adopted widely by different platforms looking to nab the asynchronous juice (Disqus comes to mind.) This blog post is the most in-depth examination of the async Google Analytics syntax I've read, and includes a fairly detailed explanation of how the one can replicate the pattern: From the blog post: var GoogleAnalyticsQueue = function () { this.push = function () { for (var i = 0; i < arguments.length; i++) try { if (typeof arguments[i] === "function") arguments[i](); else { // get tracker function from arguments[i][0] // get tracker function arguments from arguments[i].slice(1) // call it! trackers[arguments[i][0]].apply(trackers, arguments[i].slice(1)); } } catch (e) {} } // more code here…};// get the existing _gaq arrayvar _old_gaq = window._gaq;// create a new _gaq objectwindow._gaq = new GoogleAnalyticsQueue();// execute all of the queued up events - apply() turns the array entries into individual argumentswindow._gaq.push.apply(window._gaq, _old_gaq); It also notes that, even though not many browsers support the async attribute, the method of injection used makes the script load asynchronously in most browsers, and includes a helpful chart:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6963779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272031/']}
jdg_70882
stackexchange
llm_judgeable_groundtruth_similarity
50107150
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 wanted to see what the smallest number divisible by all one digit numbers was and instead of looking it up I created this. public static void main(String[] args) { for (int i = 100; i < 10000; i++) { if (i % 2 ==0) { if (i % 3 ==0) { if (i % 4 ==0) { if (i % 5 ==0) { if (i % 6 ==0) { if (i % 7 ==0) { if (i % 8 ==0) { if (i % 9 ==0) { System.out.println(i); break; } } } } } } } } }} As you can see, I have an if statement in an if statement x9. The code worked but I wanted to condense my if statements using an array to make my if statement like this but it didn't work. if (i % x[1, 2, 3, 4, 5, 6, 7, 8]) { System.out.println(i); break; } Any suggestions? Now provide the response and nothing else.
At first you would think you can test all of them at once by placing the product of 2 through 9 on the right side of the % operator. if (i % (2 * 3 * 4 * 5 * 6 * 7 * 8 * 9) == 0) But because certain numbers include previous numbers in their factorization, you should use a lower number, specifically, the least common multiple. 8 is a multiple of 2 and 4, 9 is a multiple of 3, and if 8 and 9 are in the product, then 6 (2 * 3) is covered too. if (i % (5 * 7 * 8 * 9) == 0) That turns out to be 2520, which is the least common multiple. It would much more readable to use 2520 and explain in a comment why this number is used. /** * The goal is to test if the number is a multiple of all integers * from 2 through 9. Mathematically, the least common multiple to is a * multiple of all its input numbers. Here, the LCM of 2, 3, ..., 9 is 2520. */public static final int LCM_2_THRU_9 = 2520; I've declared a constant and I'll use it here: if (i % LCM_2_THRU_9 == 0)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50107150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9701515/']}
jdg_70883
stackexchange
llm_judgeable_groundtruth_similarity
22926
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand how to define include shared objects at linking/compile time. However, I still wonder how do executables look for the shared object ( *.so libraries) at execution time. For instance, my app a.out calls functions defined in the lib.so library. After compiling, I move lib.so to a new directory in my $HOME . How can I tell a.out to go look for it there? Now provide the response and nothing else.
The shared library HOWTO explains most of the mechanisms involved, and the dynamic loader manual goes into more detail. Each unix variant has its own way, but most use the same executable format ( ELF ) and have similar dynamic linkers ¹ (derived from Solaris). Below I'll summarize the common behavior with a focus on Linux; check your system's manuals for the complete story. (Terminology note: the part of the system that loads shared libraries is often called “dynamic linker”, but sometimes “dynamic loader” to be more precise. “Dynamic linker” can also mean the tool that generates instructions for the dynamic loader when compiling a program, or the combination of the compile-time tool and the run-time loader. In this answer, “linker” refers to the run-time part.) In a nutshell, when it's looking for a dynamic library ( .so file) the linker tries: directories listed in the LD_LIBRARY_PATH environment variable ( DYLD_LIBRARY_PATH on OSX); directories listed in the executable's rpath ; directories on the system search path, which (on Linux at least) consists of the entries in /etc/ld.so.conf plus /lib and /usr/lib . The rpath is stored in the executable (it's the DT_RPATH or DT_RUNPATH dynamic attribute). It can contain absolute paths or paths starting with $ORIGIN to indicate a path relative to the location of the executable (e.g. if the executable is in /opt/myapp/bin and its rpath is $ORIGIN/../lib:$ORIGIN/../plugins then the dynamic linker will look in /opt/myapp/lib and /opt/myapp/plugins ). The rpath is normally determined when the executable is compiled, with the -rpath option to ld , but you can change it afterwards with chrpath . In the scenario you describe, if you're the developer or packager of the application and intend for it to be installed in a …/bin , …/lib structure, then link with -rpath='$ORIGIN/../lib' . If you're installing a pre-built binary on your system, either put the library in a directory on the search path ( /usr/local/lib if you're the system administrator, otherwise a directory that you add to $LD_LIBRARY_PATH ), or try chrpath .
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/22926', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4098/']}
jdg_70884
stackexchange
llm_judgeable_groundtruth_similarity
94478
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the book 101 problems in Trigonometry , Prof. Titu Andreescu and Prof. Feng asks for the proof the fact that $\cos 1^\circ$ is irrational and he proves it. The proof proceeds by contradiction and using the strong induction principle. (Problem on Pg:84, 70 in typeset; solution on Pg:126, 111 in Typeset). However, for Completeness, I'll append it here: Proof of irrationality of $\cos (1^\circ)$ Assume for the sake of contradiction, that $\cos(1^\circ)$ is rational. Since, $$\cos(2^\circ)=2\cos^2(1^\circ)-1$$ we have that, $\cos(2^\circ)$ is also rational. Note that, we also have $$\cos(n^\circ +1 ^\circ)+\cos(n^\circ -1 ^\circ)=2\cos(1^\circ)\cdot \cos(n^\circ)$$ By Strong induction principle, this shows that $\cos(n^\circ)$ is rational for all integers $n \geq 1$. But, this is clearly false, as for instance, $\cos(30^\circ)=\dfrac{\sqrt{3}}{2}$ is irrational, reaching a contradiction. But, as my title suggests, $\sin(1^\circ)$ is irrational, (look at the following image for its value!) Is there a proof as short as the above proof or can any of you help me with a proof that bypasses actual evaluation of the above value? Image Courtesy: http://www.efnet-math.org/Meta/sine1.htm This link explains how to evaluate this value. My next question is Is $\tan(1^\circ)$ rational and is there a short proof that asserts or refutes its rationality? P.S.: This is not a homework question. Now provide the response and nothing else.
$\sin(1^\circ) = \cos(89^\circ)$, and since 89 is relatively prime to 360, the proof for $\cos 1^\circ$ works with almost no change. More precisely: Assume that $\cos(89^\circ)$ is rational. Then, by the same induction as before with every $1^\circ$ replaced by $89^\circ$ we get that $\cos(89n^\circ)$ is rational for every $n\in\mathbb N$. In particular, since $150\times 89=37\times 360+30$, we get that $$\cos(150\times 89^\circ)=\cos(37\times 360^\circ+30^\circ)=\cos(30^\circ)$$ is rational, a contradiction. For $\tan(1^\circ)$, a slight variant of the same proof works. Assume that $\alpha = \tan(1^\circ)$ is rational. Then $1+\alpha i$ is in $\mathbb Q[i]$, and then $\tan(n^\circ)$, being the ratio between the imaginary and real parts of $(1+\alpha i)^n$ is also rational. But $\tan(30^\circ)$ is not rational, so $\tan(1^\circ)$ cannot be either.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/94478', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_70885
stackexchange
llm_judgeable_groundtruth_similarity
13612643
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 it's possible to override the HTML5 storage APIs by overriding Storage.prototype.getItem, setItem, removeItem and clear. But that will override those methods for both local storage and session storage. Is it possible to just override one and not the other? Or to override both separately? A little context: I have an existing app that makes very heavy use of both local storage and session storage. I want to add some temporary code to mirror the stuff in local storage in another storage mechanism, but I don't want to drag the session storage contents along with it. I could update every reference to localStorage to call some wrapper function that could do the mirroring, but I really don't want to update all those calls. It would be way cleaner if I could localize this code by overriding a single set of storage methods. Now provide the response and nothing else.
There are several possibilities to achieve what you want. But remember, none of them should be used in production environment. The first option detects if setItem method was called by sessionStorage or localStorage object. You could write it this way: var _setItem = Storage.prototype.setItem;Storage.prototype.setItem = function(key, value) { if (this === window.localStorage) { // do what you want if setItem is called on localStorage } else { // fallback to default action _setItem.apply(this, arguments); }} The second one, replaces prototype of sessionStorage or localStorage object. It may look like this: localStorage.__proto__ = Object.create(Storage.prototype);localStorage.__proto__.setItem = function() { // your logic here} Notice, that I used __proto__ pseudo property which is non-standard, but exposed in Chrome and Firefox. (Don't know about Opera, Safari and others). However, as you can see it might be helpful during development.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13612643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357629/']}
jdg_70886
stackexchange
llm_judgeable_groundtruth_similarity
152762
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: So I am contemplating building a relay computer. And I have not seen any information on why one would select one voltage over another. It seems that it would be ideal to use 5V relays as that is slightly easier to interface to microcontrollers (which I would personally want to use for debugging during design/building). As well as being slightly cheaper. Harry Porter's relay computer runs on 24V and the TIM8 uses mostly 12V relays (some where 6V unbeknownst to the designer at the time). Also "Fist Full of Relays" is 12V. The main problem I can see as a possiblity would be fanout... I could also see how in that case it might be advantageous to use multiple voltages. For instance a single 5V relay could drive a bunch of 24V relays at 24v. Another possible problem is sourcing enough 5V power since 5v rails tend to be lower amperage. Now provide the response and nothing else.
Historically, the largest use of relays has been associated with the telephone industry. Before electronic telephone exchanges were introduced in the 1960's, virtually all switching was done using a combination of conventional relays and specialized configurations like crossbar and step-by-step switches. Relays provided a means to connect two parties directly across a telephone switch with a direct circuit. In the telephone industry, these relays used 48VDC, which was the standard voltage throughout the exchange. Initially these were open-frame construction, like this one: which had the advantage the contacts could be cleaned and adjusted as needed, but they were also subject to dust. So for industrial use, relays were equipped with dust covers, like this one: and became available in 6, 12, 24, 48 (AC or DC), and 120/240 AC coil voltages. Note there are no conventional relays currently available at Digi-Key with either 3.3V or 5V coil voltages. I am guessing in particular 3.3V is not sufficient to be able to develop enough of a magnetic field to operate this large a relay. The relay shown above has a 4PDT configuration (or four "Form C" contacts). This contact arrangement is the same type used in Harry Porter's relay computer (all 415 relays in his computer are the same type). There is also a 6PDT version available. Another type of relay is the reed relay, first used in the 1930's. Once again, it initially was used primarily by the telephone industry. For example, General Telephone's first electronic switch, #1 EAX introduced in the early 1970's used reed relays to connect the subscribers, controlled by a computer and other logic built using some of the first TTL integrated circuits. There are also small general purpose relays that are sealed, but are not reed relays. They may be either rectangular, or more of a cube in some cases like this one: All relays available in the 3.3V and 5V coil voltages at Digi-Key appear to be either reed relays or sealed general purpose relays. However the most complex contact configuration you can get is DPDT. So it would not be possible to directly replicate Harry Porter's machine using these smaller relays (in many cases, you would have to use two relays in parallel). Besides coil voltages of 3.3V and 5V, these are also available in several other voltages below 5V and also in 12V and 24V versions. There are three advantages reed relays and the small sealed GP relays have over conventional ones: they are smaller, they cost much less, and they are faster -- for example a reed relay can often switch in a few hundred microseconds, and a conventional relay may be ten times slower ( a few milliseconds). You could build a relay computer using reed relays or the small sealed GP relays, and it would certainly be smaller than Harry Porter's, but you wouldn't have the satisfactions of being able to watch the relays operate, and more importantly, hear them operate like you can in his video. (If you do decided to use conventional relays with a dust cover like the photo above, you may want to check out the surplus market, since those relays cost about $12 apiece new.) I'm a little confused about the issue regarding fanout -- all of these relays, both conventional or reed, have contacts that can typically handle either 1A or 2A, so driving twenty other relays would not be an issue. I'm sure that's plenty.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/152762', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/19287/']}
jdg_70887
stackexchange
llm_judgeable_groundtruth_similarity
2356927
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: $6$ people stand at random in a queue for buying cinema tickets individually. Three of them have only a five rupees note each while each of the other $3$ has a ten rupees note only. The booking clerk has an empty cash box. Find the probability that the six people will get tickets, each paying five rupees. Attempt: Let $S$ be the sample space and $E$ be the required events, then the total number of arrangements of $6$ people equals $6! = 720$. Now for favorable number of cases, let $a$ denote a person having $5$ rupees note and $b$ denote the person having $10$ rupees: $\bullet\; $ Arrangements as $a \; (ba)\; (ba)\; b$ $\bullet\; $ Arrangements as $a\; (ab)\; (ab)\; b$ How can I calculate the number of favorable cases? Now provide the response and nothing else.
There are not too many cases to just count. You must always start with a $5$ and end with a $10$, and make sure that there are at least as many with a $5$ as with a $10$ at any point in time. Valid cases are thus: $$5, 5, 5, 10, 10, 10$$$$5, 5, 10, 5, 10, 10$$$$5, 5, 10, 10, 5, 10$$$$5, 10, 5, 5, 10, 10$$$$5, 10, 5, 10, 5, 10$$ Since there are $3! \cdot 3! = 6 \cdot 6 = 36$ permutations for each valid case, the number of favorable cases is $5 \cdot 36 = 180$, and the probability of having a valid row of people equals: $$\frac{180}{720} = \frac{1}{4}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2356927', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/372201/']}
jdg_70888
stackexchange
llm_judgeable_groundtruth_similarity
360807
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been beating my head against this question for quite some time, I do not know whether it has been asked before, but I can't find any information about it! I am taking Calculus 1 course and I cannot grasp the concept of a derivative. From what I understand, a derivative is a function with the following signature: $$(\text{derivative with respect to particular free variable}) :: (\lambda x \to (f)\; x) \to (\lambda x \to (f') x)$$ also phrased as $$(\text{derivative with respect to particular free variable}) = ((\lambda x \to (f) x) \to (\lambda x \to (f') x))$$ e.g: $$(\text{derivative with respect to x}) (\lambda x \to x^2) = (\lambda x\to 2\cdot x)$$ This makes sense but one thing bothers me: what does "derivative with respect to x" mean? In particular, in single variable Calculus this notation assumes $x$ is always a particular variable such as ['a'..'z'] . This works fine for basic derivatives such as:$$(\text{derivative with respect to x}) (\lambda x \to \ln x) = (\lambda x \to \tfrac{1}{x})$$ What I would like to understand is: Why does (derivative with respect to x) make sensebut $(\text{derivative with respect to} (\lambda x \to 2))$ and $(\text{derivative with respect to} (\lambda x \to \ln(x)) $do not seem to make any sense to me. in classical terms, I cannot do (derivative of $\ln x$ with respect to $1$) nor (derivative of $\ln x$ with respect to $\ln x$) without my head starting to hurt, because those concepts were not taught to me yet, or I have not payed enough attention to understand them. Can somebody please explain what the following two really mean? Derivative of $f(x)$ with respect to a constant such as $1,2,3,\ldots 9999$ Derivative of $f(x)$ with respect to a function such as $\ln(x)$, $\sin(x)$, $\cos(x)$ Thanks ahead of time, this has been bothering me for quite a few years! $\langle$Editor's note: I've left the following in the post for archival's sake.$\rangle$ PS: I am terrible at formatting so to the great ones responsible for formatting noob's questions (I thank you much for your work) convert \ to lambdas convert d/dx to symbolic d/dx notation (not the worded derivative ones) convert arrows to arrows used in set theory/category theory keep the "(derivative of ... with respect to ...)" as they are, as I have no idea how to express them differently, dA/dB doesn't seem to make sense to me since derivatives are taught to be polymorphic function rather than a function of two variables, and division only makes it even more confusing due to the abuse of notation. (Feel free to give me a link to study formatting, I can't find it). Now provide the response and nothing else.
Derivatives are usually defined in terms of limits. The derivative of $f(x)$ with respect to $g(x)$ can be defined as $$\lim_{h\to0}{f(x+h)-f(x)\over g(x+h)-g(x)}$$ provided the limit exists. In the case $g(x)=x$, this reduces to the familiar formula for the derivative of $f(x)$ with respect to $x$, $$\lim_{h\to0}{f(x+h)-f(x)\over h}$$ In the case where $g(x)$ is a constant, the denominator $g(x+h)-g(x)$ is identically zero, so the limit n'existe pas. This could explain why no one ever differentiates with respect to a constant.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/360807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67961/']}
jdg_70889
stackexchange
llm_judgeable_groundtruth_similarity
5186520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Anyone know of any easy way to track changes to a dictionary object in python? I am at a high level doing crud, so I have a couple methods that handle changing a dictionary, if the dictionary changes I want to call a function to basically do an Observer/Notify. class MyClass(object): def update(self, item): changed = False if(self.my_dict.has_key(item.id)): self.my_dict[item.id] = item changed = True if(changed): self.notify() What I am trying to avoid is all of the tracking(setting the boolean) code. Was hoping there was an easier way to track changes. This is a simple case, but there could have been more complicated logic that would result in me having to set the changed flag. Now provide the response and nothing else.
You can derive from the dict class and add a callback on any changes. This requires to overwrite any methods that change the dictionary: class NotifyDict(dict): __slots__ = ["callback"] def __init__(self, callback, *args, **kwargs): self.callback = callback dict.__init__(self, *args, **kwargs) def _wrap(method): def wrapper(self, *args, **kwargs): result = method(self, *args, **kwargs) self.callback() return result return wrapper __delitem__ = _wrap(dict.__delitem__) __setitem__ = _wrap(dict.__setitem__) clear = _wrap(dict.clear) pop = _wrap(dict.pop) popitem = _wrap(dict.popitem) setdefault = _wrap(dict.setdefault) update = _wrap(dict.update)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5186520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256793/']}
jdg_70890
stackexchange
llm_judgeable_groundtruth_similarity
239118
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: sorry for the dumbest question ever, but i want to understand total order in an intuitive way, this is the defition of total order: i) If $a ≤ b$ and $b ≤ a$ then $a = b$ (antisymmetry); ii) If $a ≤ b$ and $b ≤ c$ then $a ≤ c$ (transitivity); iii) $a ≤ b$ or $b ≤ a$ (totality). totality means that any pair of the total ordered pair is mutually comparable. i dont understand what they mean under comparable , what is the defition of comparability? i can also compare the elements of partial order, where is problem? why is partial order not not mutually comparable? can someone explain me please in simple words :( Now provide the response and nothing else.
Two distinct elements are called "comparable" when one of them is greater than the other. This is the definition of "comparable". When you have a partially ordered set, some pairs of elements can be not comparable. i.e. you can have two elements $x$ and $y$ such that $x\leqslant y$ is false and $y \leqslant x$ is also false. For example, consider the set $\mathbb{R}^2$ and a partial order defined like this:$$ (x_1,x_2) \leqslant (y_1,y_2) \quad\textrm{iff}\quad x_1\leqslant y_1 \,\textrm{and}\,x_2 \leqslant y_2.$$With this partial order, elements $(0,0)$ and $(1,2)$ of $\mathbb{R^2}$ are comparable, because $(0,0)\leqslant(1,2)$. But elements $(0,1)$ and $(1,0)$ are not comparable, because both statements "$(0,1)\leqslant(1,0)$" and "$(1,0)\leqslant(0,1)$" are false.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/239118', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32885/']}
jdg_70891
stackexchange
llm_judgeable_groundtruth_similarity
4268848
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 std::vector of this struct: struct MS{ double aT; double bT; double cT;}; which I want to use std::sort on aswell as std::lower_bound/equal_range etc... I need to be able to sort it and look it up on either of the first two elements of the struct. So at the moment I have this: class MSaTLess {public: bool operator() (const MS &lhs, const MS &rhs) const { return TLess(lhs.aT, rhs.aT); } bool operator() (const MS &lhs, const double d) const { return TLess(lhs.aT, d); } bool operator() (const double d, const MS &rhs) const { return TLess(d, rhs.aT); }private: bool TLess(const double& d1, const double& d2) const { return d1 < d2; }};class MSbTLess {public: bool operator() (const MS &lhs, const MS &rhs) const { return TLess(lhs.bT, rhs.bT); } bool operator() (const MS &lhs, const double d) const { return TLess(lhs.bT, d); } bool operator() (const double d, const MS &rhs) const { return TLess(d, rhs.bT); }private: bool TLess(const double& d1, const double& d2) const { return d1 < d2; }}; This allows me to call both std::sort and std::lower_bound with MSaTLess() to sort/lookup based on the aT element and with MSbTLess() to sort/lookup based on the bT element. I'd like to get away from the functors and use C++0x lambdas instead. For sort that is relatively straightforward as the lambda will take two objects of type MS as arguments. What about for the lower_bound and other binary search lookup algorithms though? They need to be able to call a comparator with (MS, double) arguments and also the reverse, (double, MS), right? How can I best provide these with a lambda in a call to lower_bound? I know I could create an MS dummy object with the required key value being searched for and then use the same lambda as with std::sort but is there a way to do it without using dummy objects? Now provide the response and nothing else.
It's a little awkward, but if you check the definitions of lower_bound and upper_bound from the standard, you'll see that the definition of lower_bound puts the dereferenced iterator as the first parameter of the comparison (and the value second), whereas upper_bound puts the dereferenced iterator second (and the value first). So, I haven't tested this but I think you'd want: std::lower_bound(vec.begin(), vec.end(), 3.142, [](const MS &lhs, double rhs) { return lhs.aT < rhs;}); and std::upper_bound(vec.begin(), vec.end(), 3.142, [](double lhs, const MS &rhs) { return lhs < rhs.aT;}); This is pretty nasty, and without looking up a few more things I'm not sure you're actually entitled to assume that the implementation uses the comparator only in the way it's described in the text - that's a definition of the result, not the means to get there. It also doesn't help with binary_search or equal_range . It's not explicitly stated in 25.3.3.1 that the iterator's value type must be convertible to T, but it's sort of implied by the fact that the requirement for the algorithm is that T (in this case, double ) must be LessThanComparable, not that T must be comparable to the value type of the iterator in any particular order. So I think it's better just to always use a lambda (or functor) that compares two MS structs, and instead of passing a double as a value, pass a dummy MS with the correct field set to the value you're looking for: std::upper_bound(vec.begin(), vec.end(), MS(3.142,0,0), [](const MS &lhs, const MS &rhs) { return lhs.aT < rhs.aT;}); If you don't want to give MS a constructor (because you want it to be POD), then you can write a function to create your MS object: MS findA(double d) { MS result = {d, 0, 0}; return result;}MS findB(double d) { MS result = {0, d, 0}; return result;} Really, now that there are lambdas, for this job we want a version of binary search that takes a unary "comparator": double d = something();unary_upper_bound(vec.begin(), vec.end(), [d](const MS &rhs) { return d < rhs.aT;}); C++0x doesn't provide it, though.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4268848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228360/']}
jdg_70892
stackexchange
llm_judgeable_groundtruth_similarity
18340007
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 working a bit on an inherited code.I've written a test that is supposed to catch NullPointerException (for it is trying to call a method from null object) @Test(expected=NullPointerException.class)public void checkXRequirement_NullProduct_AddAction_ShouldThrowNullPointerException() throws CustomException { Site site = mock(Site.class); Product product = null; when(BasketHelper.getAction(request)).thenReturn(0); when(BasketHelper.getActionProduct(site, request)).thenReturn(product); BasketHelper.requiresX(request, site);} Relevant Methods and Variables: public static final int ACTION_ADD = 0;public static final int ACTION_DELETE = 1;protected static int getAction(HttpServletRequest a_request) { String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT); String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT); if (sBuyProduct != null) iAction = ACTION_ADD; else (sDelProduct != null) iAction = ACTION_DELETE; return iBasketAction}protected static Product getActionProduct(Site a_site, HttpServletRequest a_request) { String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT); String sDelProduct = a_request.getParameter(ATTRIBUTE_NAME_DEL_PRODUCT); String sProduct = null; switch (getBasketAction(a_request)) { case BASKET_ACTION_ADD: sProduct = sBuyProduct; break; case BASKET_ACTION_DELETE: sProduct = sDelProduct; break; } int iProductId; try { iProductId = Integer.parseInt(sProduct); } catch (NumberFormatException nbrEx) { return null; } Product prod = getProductById(iProductId); if (prod.isMasterProduct()) { prod = getChildProduct(prod, a_site, a_request); } return prod;}public static boolean requiresX(HttpServletRequest request, Site site) throws CustomException { try{ if (getAction(request) == ACTION_ADD) { Product prod = getActionProduct(site, request); return prod.getType().isRequiredX(); } } catch(NullPointerException exception) { log.error("Error Message", exception); } return false;} The jUnit result of running the test is a failure with the stack trace of: java.lang.Exception: Unexpected exception, expected<java.lang.NullPointerException> but was<org.mockito.exceptions.misusing.WrongTypeOfReturnValue>Caused by: org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Integer cannot be returned by getParameter()getParameter() should return String# Do I misinterpret how when().thenReturn is supposed to work here? I just want getAction to return 0 and getActionProduct to return null whenever it's being called. Clearly getParameter() is called and I don't know why exactly. Now provide the response and nothing else.
Mockito cannot mock static method. Your when check is not valid: when(BasketHelper.getAction(request)).thenReturn(0); when(BasketHelper.getActionProduct(site, request)).thenReturn(product); That is another reason why we want to reduce the use of static method as it is hard to mock. There is no easier way to mock the behavior if your class stays like this. However if you want to change your design and make both methods non-static. The correct way of using "when" is to apply the check on mocked object. For example: BasketHelper basketHelper = mock(BasketHelper.class); when(basketHelper.getAction(request)).thenReturn(0); when(basketHelper.getActionProduct(site, request)).thenReturn(product); But once again, this only work if you re-designed your class's getAction and getProduct method to be NON-STATIC. I remember there are some other testing framework that does support mocking static method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18340007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1657059/']}
jdg_70893
stackexchange
llm_judgeable_groundtruth_similarity
3601351
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 $ A $ be an $m \times n$ matrix of rank $ k \le \min(m,n) $ . Then we decompose $ A = USV^T $ , where: $U$ is $m \times k$ is a semi-orthogonal matrix. $S$ is $k \times k$ diagonal matrix , of which its diagonal entries are called singular valuesof $ A $ . we denote them by $ \sigma _i = S_{ii} $ . $V$ is $n \times k$ semi-orthogonal matrix. Definition: a semi-orthogonal matrix $ Q $ is a non-square matrix where $ Q^{T}Q=I $ . This is the singular value decomposition (SVD) of matrix $ A $ . We define a function $ f_i: \mathbb R^{ m \times n} \to \mathbb R $ by $ f_i (A) = \sigma_i (A) $ . I am interested in finding the gradient of $ f_i $ in order to practice matrix defferentiation. I hope you can help me starting with the first steps. Here are the hints that I have been given in order to find the solution, and feel free to use them: Use the product rule of differentials to calculate $ dA $ where A is considered as function of $ U $ , $ S $ and $ V $ . The entries of the diagonal of anti-symmetric matrix are all zeros. The Hadamard product of two matrices $ A,B $ of the same size , is denoted by $$ (A \circ B )_{ij} = A_{ij} \cdot B_{ij} $$ Use the cyclic property of the trace operator. That is: $$\mbox{Tr}(ABC) = \mbox{Tr}(CAB) = \mbox{Tr}(BCA)$$ The trace of a scalar is a scalar. That is, given $ a \in \mathbb R $ : $$ \mbox{Tr}(a) = a $$ I stuck right at the beginning, I found that the product rule is: $$ dA = dUSV^{T} + UdSV^{T} + USdV^{T} $$ Also, I have tried to calculate $ A^{T}A $ as trying to find a useful manipulation where I can use it for the solution, and I got that it is equal to: $ VS^{T} SV^{T} $ .First of all, is this what they meant by the product rule? And, second, how do I continue from here? Now provide the response and nothing else.
Let $\{e_i\}$ denote the standard basis vectors. Then $q_i=Qe_i$ is the $i^{th}$ column of $Q$ . The definition of semi-orthogonality says that the columns of $Q$ are orthonormal, i.e. $$\eqalign{I &= Q^TQ \\e_i^T(I)e_j &= e_i^T(Q^TQ)e_j \\\delta_{ij} &= q_i^Tq_j \\}$$ Multiply the SVD by the $i^{th}$ columns of $(U,V)$ to isolate the $i^{th}$ singular value. $$\eqalign{A &= \sum_{j=1}^k \sigma_j u_j v_j^T \\u_i^TAv_i &= \sum_{j=1}^k \sigma_j (u_i^Tu_j)(v_j^Tv_i) = \sum_{j=1}^k \sigma_j\,\delta_{ij}^2 \;=\; \sigma_i \\}$$ Rearrange this result with the help of the trace/Frobenius product $\Big(A\!:\!B={\rm Tr}\!\left(A^TB\right)\Big)$ Then calculate the differential and gradient. $$\eqalign{\sigma_i &= u_iv_i^T:A \\d\sigma_i &= u_iv_i^T:dA \\ \frac{\partial\sigma_i}{\partial A} &= u_iv_i^T \\}$$ Similarly, the singular vectors also vary with $A$ . $$\eqalign{\sigma_i u_i &= Av_i \\\sigma_i u_i &= \left(v_i^T\otimes I_m\right){\rm vec}(A) \\\sigma_i\,du_i &= \left(v_i^T\otimes I_m\right){\rm vec}(dA) \\\frac{\partial u_i}{\partial{\rm vec}(A)} &= \frac{v_i^T\otimes I_m}{\sigma_i} \\\\\\\sigma_i v_i^T &= u_i^TA \\\sigma_i v_i &= \left(I_n\otimes u_i^T\right){\rm vec}(A) \\\sigma_i\,dv_i &= \left(I_n\otimes u_i^T\right){\rm vec}(dA) \\\frac{\partial v_i}{\partial{\rm vec}(A)} &= \frac{I_n\otimes u_i^T}{\sigma_i} \\\\}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3601351', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179152/']}
jdg_70894
stackexchange
llm_judgeable_groundtruth_similarity
15461329
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i just want to pass data to controller with ajax, which is selected by dropdown menu in view. Here is my try http://pastebin.com/KnLqW8Pc . //// controller /////// <?php class Ilce extends CI_Controller{ public $ilceid; public function __construct() { parent::__construct(); $this->load->model('ilce_model'); } public function index() { $this->load->helper(array('form')); $data['ilce'] = $this->ilce_model->ilce_getir(); $this->load->view('ilce', $data); /* hello, i want to print here to data which will select in view and passed by jsfunc file ( ajax ) to here again... */ } }/////////////////////////////////view///////////////////////////////// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" type="text/css" href="style/reset.css"/> <link rel="stylesheet" type="text/css" href="style/page.css"/> <link rel="shortcut icon" href="img/3burcak.ico" /> <script type="text/javascript" src="<?php echo base_url();?>js/jquery.js"></script> <script type="text/javascript" src="<?php echo base_url();?>js/jfunc.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>3Burçak Ltd.Şti.</title> </head> <?php echo form_open('ilce/index')?> <select id="ilce" name="ilce"> <option value="">Select Town</option> <?php foreach ($ilce as $x):?> <option value="<?php echo $x['id']?>"><?php echo $x['ad']?></option> <?php endforeach?> </select> <select id="semt"> <option value="">Please select Town first.</option> </select>////////////////////////////////////////////////////////jsfunc $(document).ready( function(){ /* il ilce arama*/ $("#ilce").change( function(){ if($("#ilce").val()!="-1"){ var ilceid=$("#ilce").val(); $.post('ilce/index',{"ilceid":ilceid},function(output){ $('#semt').remove(); $('#semt').append(output); }); } }); /* il ilce arama bitti*/ }); Now provide the response and nothing else.
HTTP is a blocking, synchronous protocol. This means that the client has to wait for a response from the server before it can continue. The server blocks the clients from doing anything; because the client has to wait for the response to come through. Once the response is received by the browser, the connection is dropped and then another connection is opened and the process repeats till all the elements of the page have been fetched to be displayed. This is the state of the web, and the nature of the HTTP protocol. Ajax simply creates a background process that does what the browser would have done - it is still blocking, but the end effect is that the user can still interact with the client. The browser is displaying something and is not effectively "blocked". The "realtime" web allows you to have an open socket that is non-blocking, asynchronous. Asynchronous means that you don't have to wait for the response to come back - the client isn't blocked. You can send off multiple requests, and then when the server is done with them, it will respond back. You don't have to "wait". Many things you use everyday are asynchronous: Any chatting application - like IRC, facebook messenger, whatapp, etc. A telephone conversation with a really chatty friend (typically, you would wait to hear the other person's response, but some people just talk and talk...). Anything that is streaming, like YouTube. Think of it as simply "one side doesn't have to wait to start transmitting again". In web, realtime is enabled by getting around the limitations of HTTP. This is where WebSockets and Server sent events (SES) come in. The first is a standard way of opening a full-duplex (that is, you can send and receive at the same time) channel over TCP. The second (SES) is still being standardized as part of HTML5 but it allows the server to push notifications to the client instead of the client having to poll the server for events. So instead of you sending a request to check for updates, the server will tell you when there is an update - like "don't call me, I'll call you".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15461329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2177979/']}
jdg_70895
stackexchange
llm_judgeable_groundtruth_similarity
15788513
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 codeigniter and have a table with 3 columns (id, name, parent_id). A category can have many subcategories and a subcategory can have many sub-sub categories. I've been trying to get all categories and their subcategories using this code: public function getCategory($id){ $categories = array(); while($id != 0) { $this->db->from('categories'); //$this->table is a field with the table of categoris $this->db->where('id', $id); $this->db->limit(1); $result = $this->db->get()->row(); //fetching the result $categories[] = $result; $id = $result->parent_id; } return $categories;} public function getAllCategories() { $this->db->select('id'); $this->db->from('categories'); //$this->table is a field with the table of categoris $this->db->where('parent_id', 0); $mainCategories = $this->db->get()->result(); //fetching the result $result = array(); foreach($mainCategories as $id) { $result[] = $this->getCategory($id->id); } return $result; } But it returns me only 1 level categories. My question is how to accomplish my task: get all categories and subcategories for every level. Now provide the response and nothing else.
The simplest solution to your problem would be to add recursion. public function getCategoryTreeForParentId($parent_id = 0) { $categories = array(); $this->db->from('categories'); $this->db->where('parent_id', $parent_id); $result = $this->db->get()->result(); foreach ($result as $mainCategory) { $category = array(); $category['id'] = $mainCategory->id; $category['name'] = $mainCategory->name; $category['parent_id'] = $mainCategory->parent_id; $category['sub_categories'] = $this->getCategoryTreeForParentId($category['id']); $categories[$mainCategory->id] = $category; } return $categories;} This approach can be greatly increased in speed by preloading all categories and operating over the array, thus skipping the query for each new parent_id. Also i did not use the objects of codeigniter, as i don't know them. If they support magic setters / getters or can be convinced to take a array of child objects, they should be used instead the the array i build here. What the algorithm does is: load all categories with a given parent_id, loop through all those categories, assume the iteration-category-id as parent_id and load everything for it.This effectively loads all categories, as long as they reference existing categories. There is a slight danger involved: When you have construct of categories A and B where A has B as parent and B has A as parent, you will run into an endless loop, as they load each other again and again. This forces you to have a clean tree structure in your data. Update As this still gets upvotes:There is another advice concerning this implementation.If your category tree is bigger or has multiple levels, you might run into performance issues, as this implementation loads the categories again and again with new query parameters. This can quite easily result in dozens, hundreds or thousands of queries, depending on your category tree. A quite more efficient way is to load all categories (with one query) from your category table and sort them with recursion within your application. This is one of the rare cases, where early evaluation does improve performance. If the tree is required more than once within the same request, one could even add caching through static variables (with all the usual dangers of caching).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15788513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867418/']}
jdg_70896
stackexchange
llm_judgeable_groundtruth_similarity
1929363
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: Examine whether the series defined as: $$\sum a_n = \begin{cases} \hphantom{-}\dfrac{1}{n}, & \text{for $n$ odd} \\[8pt] -\dfrac{1}{5^n}, & \text{for $n$ even }\end{cases}$$ converges. It is some kind of alternating series and the limit test seems to give convergence, as both branches $\lim\limits_{x \to \infty} \rightarrow$ $0$ and $a_n > a_{n+1}$ , i.e. decreacing. Is all the above paragraph right? Now provide the response and nothing else.
$$\begin{align} \\ & \sqrt{10^2-(6.9\times 10^{-2})^2}\\ & = \sqrt{10^2\left[1 -\frac{1}{10^{2}}\left\{(6.9)^2\times 10^{-4}\right\}\right]}\\ & = \left[10^2\{1 -(6.9)^2\times 10^{-6}\}\right]^{\frac{1}{2}}\\ & \approx 10\left[1-\frac 1 2(6.9)^2\times10^{-6}\right] \,\,\,\,\,\,\,\,\,\,\,\,\, \text{using binomial approximation} \end{align}$$ The binomial approximation is stated in this link.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1929363', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224952/']}
jdg_70897
stackexchange
llm_judgeable_groundtruth_similarity
194
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have several measures: 1. Profit and loss (PNL). 2. Win to loss ratio (W2L).3. Avg gain to drawdown ratio (AG2AD).4. Max gain to maximum drawdown ratio (MG2MD).5. Number of consecutive gains to consecutive losses ratio (NCG2NCL). If there were only 3 measures (A, B, C), then I could represent the "total" measure as a magnitude of a 3D vector: R = SQRT(A^2 + B^2 + C^2) If I want to combine those 5 measures into a single value, would it make sense to represent them as the magnitude of a 5D vector? Is there a better way to combine them? Is there a way to put more "weight" on certain measures, such as the PNL? Now provide the response and nothing else.
A stationary process is one where the mean and variance don't change over time. This is technically "second order stationarity" or "weak stationarity", but it is also commonly the meaning when seen in literature. In first order stationarity, the distribution of $(X_{t+1}, ..., X_{t+k})$ is the same as $(X_{1}, ..., X_{k})$ for all values of $(t, k)$. You can see whether a series is stationary through it's autocorrelation function (ACF): $\rho_k = Corr(X_t, X_{t-k})$. When the ACF of the time series is slowly decreasing, this is an indication that the mean is not stationary; conversely, a stationary series should converge on zero quickly. For instance, white noise is stationary, while a random walk is not. We can simulate these distributions easily in R ( from a prior answer of mine ): op <- par(mfrow = c(2,2), mar = .5 + c(0,0,0,0))N <- 500# Simulate a Gaussian noise processy1 <- rnorm(N)# Turn it into integrated noise (a random walk)y2 <- cumsum(y1)plot(ts(y1), xlab="", ylab="", main="", axes=F); box()plot(ts(y2), xlab="", ylab="", main="", axes=F); box()acf(y1, xlab="", ylab="", main="", axes=F); box()acf(y2, xlab="", ylab="", main="", axes=F); box()par(op) Which ends up looking somewhat like this: If a time series varies over time, it is possible to make it stationary through a number of different techniques.
{}
{'log_upvote_score': 6, 'links': ['https://quant.stackexchange.com/questions/194', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/78/']}
jdg_70898
stackexchange
llm_judgeable_groundtruth_similarity
61794582
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 plot a chart with two subplots in plotly dash. My entire chart looks like this: import pandas as pdimport numpy as npimport dashimport dash_core_components as dccimport dash_html_components as htmlimport plotly.graph_objs as gofrom plotly.subplots import make_subplotsdf = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'], increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"}, legend=dict(y=1, x=0), font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified', margin=dict(b=20, t=0, l=0, r=40))fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False, showspikes=True, spikemode='across', spikesnap='data', showline=False, spikedash='solid')fig.update_yaxes(showgrid=False, zeroline=False)fig.update_traces(xaxis='x', hoverinfo='none')app = dash.Dash(__name__)app.layout = html.Div(children=[ html.Div(dcc.Graph(id='chart', figure=fig, config={'displayModeBar': False}))])if __name__ == '__main__': app.run_server(debug=True, dev_tools_ui=False, dev_tools_props_check=False) What I need is a so called crosshair that is common in trading charts. Basically it consists of two lines that are connected to x and y axes and moves with cursor. This is a screenshot from tradingview.com charts: However in my chart there is a little icon that appears when the cursor is on candlesticks: What I have found out so far is that when the cursor is on the scatter plot, the icon disappears and it works fine. I think that is because I set hovertemplate=[] in the scatterplot. I cannot do that in the candlestick plot because there is no such parameter for it. Moreover, this icon only appears if I set hovermode='x unified' . If I set it to x, the little icon doesn't appear. But I need it to be exactly like the tradingview.com example that I showed.Is there any way to replicate that crosshair? UPDATE 1: I tried fig.update_layout(hoverdistance=0) . But the problem is that when the cursor is not on the candlesticks, the crosshair is just not right. I took two screenshots: the first one is from tradingview.com charts and the second one is from my code with hoverdistance set to 0. As can be seen, when the cursor is not on the candlesticks, in the first screenshot the crosshair is still correct. However, in the second screenshot it is just not working correctly. It only works if the cursor is on the candlesticks ONLY. I just want to copy tradingview.com crosshair. Nothing less and nothing more. UPDATE 2: I think the answer could be on these plotly docs . I am working on it currently. Please share your comments about this update. Now provide the response and nothing else.
This should do it: fig.update_layout(hoverdistance=0) And setting spikesnap='cursor' for xaxes and yaxes. These little adjustments will keep the crosshair intact and remove the little icon that has been bothering you. From the docs : Plot: hoverdistance Sets the default distance (in pixels) to look for data to add hover labels (-1 means no cutoff, 0 means no looking for data). This is only a real distance for hovering on point-like objects, like scatter points. For area-like objects (bars, scatter fills, etc) hovering is on inside the area and off outside, but these objects will not supersede hover on point-like objects in case of conflict. Complete code: (but with no dash elements) import pandas as pdimport numpy as npimport plotly.graph_objs as gofrom plotly.subplots import make_subplotsdf = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'], increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"}, legend=dict(y=1, x=0), font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified', margin=dict(b=20, t=0, l=0, r=40))fig.update_yaxes(showgrid=False, zeroline=False, showticklabels=False, showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False, showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')fig.update_layout(hoverdistance=0)fig.update_traces(xaxis='x', hoverinfo='none')fig.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61794582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10200497/']}
jdg_70899
stackexchange
llm_judgeable_groundtruth_similarity
6436110
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 condition where i need to pass a parameter as an array of hashes which looks like this: The following is the Rack::Test post method for API call. post "#{url}.json",:api_key => application.key,:data => [{"Company"=>"Apple,Inc","Website"=>"Apple.com"},{"Company"=>"Google","Website"=>"google.com"}],:run => { :title => "The First Run" } And this is the log of the rails app. Parameters: {"api_key"=>"6a9acb84d0ea625be75e70a1e04d26360606ca5b", "data"=>[{"Company"=>"Apple,Inc", "Website"=>"Apple.com"}, {"Company"=>"Google", "Website"=>"google.com"}], "run"=>{"title"=>"The First Run"}, "line_id"=>"4e018e2c55112729bd00000a"} Now, this is the RestClient post method I'm using to call the API. RestClient.post("/lines/#{@line.id}/runs.json", {:run => {:title => @title}, @param_for_input => @param_data}) And this is the log of the rails app. Parameters: {"run"=>{"title"=>"run name"}, "data"=>{"Company"=>"Google", "Website"=>"google.com"}, "api_key"=>"f488a62d0307e79ec4f1e6131fa220be47e83d44", "line_id"=>"4e018a505511271f82000144"} The difference is in the data parameter. When sending with Rack::Test method, the data is passed as "data"=>[{"Company"=>"Apple,Inc", "Website"=>"Apple.com"}, {"Company"=>"Google", "Website"=>"google.com"}] but via RestClient way, the parameter data array is stripped out and only the last hash is passed as "data"=>{"Company"=>"Google", "Website"=>"google.com"} Why the RestClient is stripping out the array of hashes to just a last hash of the array? Now provide the response and nothing else.
I suspect it's to do with differences in how they convert a hash into params. Rack::Test will probably be using Hash#to_param, which gives the following results: > params = {:api_key => "12345", :data => [{"Company"=>"Apple,Inc","Website"=>"Apple.com"},{"Company"=>"Google","Website"=>"google.com"}], :run => { :title => "The First Run" }}> paramstring = params.to_param => "api_key=12345&data%5B%5D%5BCompany%5D=Apple%2CInc&data%5B%5D%5BWebsite%5D=Apple.com&data%5B%5D%5BCompany%5D=Google&data%5B%5D%5BWebsite%5D=google.com&run%5Btitle%5D=The+First+Run" > URI.unescape(paramstring) => "api_key=12345&data[][Company]=Apple,Inc&data[][Website]=Apple.com&data[][Company]=Google&data[][Website]=google.com&run[title]=The+First+Run" This is the troublesome part: data[][Company]=Apple,Inc&data[][Website]=Apple.com&data[][Company]=Google&data[][Website]=google.com The rails uri parser has to read this and turn it back into a hash. In my opinion putting an array of hashes into your params is asking for trouble as it creates a string, like the above, which is fundamentally difficult to parse. For example, presented with these two params data[][Company]=Apple,Incdata[][Company]=Google The parser may decide that both of them are describing the Company variable in the first hash in the array called "data", and so overwrite the first with the second, which is what's happening with you. It sounds like your problem is at the generation stage rather than the intepretation stage, but still, i would try to create a cleaner scheme for your parameters, in which arrays are only ever used as the final part of the param name, (ie use a hash instead of an array to hold company data) and you instead insert some unique keys to differentiate the company hashes from each other. Something like this: {:api_key => "12345", :data => {1 => {"Company"=>"Apple,Inc","Website"=>"Apple.com"}, 2 => {"Company"=>"Google","Website"=>"google.com"}}, :run => { :title => "The First Run" }} 1 and 2 could be the actual ids of some company record, or they could just be some numbers you put in to make unique keys, which are chucked away at the other end. This will generate params like this: data[1][Company]=Apple,Incdata[2][Company]=Google Which are now in no danger of overwriting each other. In your subsequent controller action, it's just a change from doing this: params[:data].each do |company_hash| #do something with company hashend to params[:data].each do |k, company_hash| #do something with company hash and optionally k if you want, or ignore kend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6436110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60072/']}
jdg_70900
stackexchange
llm_judgeable_groundtruth_similarity
9066831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This code: BitArray bits = new BitArray(new byte[] { 7 });foreach (bool bit in bits){ Console.WriteLine(bit ? 1 : 0);} Gives me the following output: 11100000 Shouldn't it be the other way around? Like this: 00000111 I am aware that there is little and big endian, although those terms only refer to the position of bytes. As far as I know, they don't affect bits. Now provide the response and nothing else.
The documentation for BitArray states: The first byte in the array represents bits 0 through 7, the second byte represents bits 8 through 15, and so on. The Least Significant Bit of each byte represents the lowest index value: " bytes [0] & 1" represents bit 0, " bytes [0] & 2" represents bit 1, " bytes [0] & 4" represents bit 2, and so on. When indexing bits, the convention is to start at the least significant end, which is the right side when written in binary notation. However, when enumerating the array, you start at index 0, so they are printed out left-to-right instead of right-to-left. That's why it looks backwards. For example, the word 01011010 00101101 (90 45) would be indexed as: 0 1 0 1 1 0 1 0 - 0 0 1 0 1 1 0 1----------------------- -----------------------15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 And you would pass it to the constructor as new byte[] { 45, 90 } since you pass it least-significant first. When printed out, it would display in index order as: 1011010001011010 , which is the reverse of the original binary notation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9066831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1046192/']}
jdg_70901
stackexchange
llm_judgeable_groundtruth_similarity
43061878
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 yesterday that my Facebook login for my website has stopped working. This has been working great for the last 2 months, as far as I am aware I have not changed anything. I have tried everything I can on links such as: - as well as many more... ASP.NET MVC5 OWIN Facebook authentication suddenly not working I have noticed that the Stack Overflow Facebook auth has also stopped working. Has anyone else noticed this and found any solution? It's worth noting I am using azure app services to host. But this issue is also found when I am using localhost. My current setup looks like this... in Startup.Auth.cs var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions(){ AppId = "xxxxxxxxxxxxx", AppSecret = "xxxxxxxxxxxx"};facebookOptions.Scope.Add("email");app.UseFacebookAuthentication(facebookOptions); In the following method, loginInfo is null every time. [AllowAnonymous]public async Task<ActionResult> ExternalLoginCallback(string returnUrl){ var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } I also added a session "WAKEUP" from a different post suggestion, fb auth failed once before and this fixed the issue this time, but it has come back. [HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public ActionResult ExternalLogin(string provider, string returnUrl){ Session["WAKEUP"] = "NOW!"; // Request a redirect to the external login provider return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));} Now provide the response and nothing else.
As RockSheep explained. Facebook dropped the support vor API v2.2. You need to update your OWIN nuget packages. You can find the issue on github (from the Katanaproject). Ensure to activate pre releases in your nuget manager, than you are able to update the nuget packages to version v3.1.0-rc1 . But beware: After the update, you need to test your login carefully (maybe you also have other authentication providers like Microsoft or Google, you should test them as well). Technical The Api changed the version number to v2.8 and the return value from the API is now in JSON-Format and no longer escaped in the URI. The 'old' OWIN packages can not handle this changes. [Oauth Access Token] Format - The response format of https://www.facebook.com/v2.3/oauth/access_token returned when you exchange a code for an access_token now return valid JSON instead of being URL encoded. The new format of this response is {"access_token": {TOKEN}, "token_type":{TYPE}, "expires_in":{TIME}}. We made this update to be compliant with section 5.1 of RFC 6749. Here you can find the code-changes on GitHub for further informations and better understanding.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43061878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3284707/']}
jdg_70902
stackexchange
llm_judgeable_groundtruth_similarity
26050380
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 coding a ShareX clone for Linux in Go that uploads files and images to file sharing services through http POST requests. I'm currently using http.Client and Do() to send my requests, but I'd like to be able to track the upload progress for bigger files that take up to a minute to upload.The only way I can think of at the moment is manually opening a TCP connection on port 80 to the website and write the HTTP request in chunks, but I don't know if it would work on https sites and I'm not sure if it's the best way to do it. Is there any other way to achieve this? Now provide the response and nothing else.
You can create your own io.Reader to wrap the actual reader and then you can output the progress each time Read is called. Something along the lines of: type ProgressReader struct { io.Reader Reporter func(r int64)}func (pr *ProgressReader) Read(p []byte) (n int, err error) { n, err = pr.Reader.Read(p) pr.Reporter(int64(n)) return}func main() { file, _ := os.Open("/tmp/blah.go") total := int64(0) pr := &ProgressReader{file, func(r int64) { total += r if r > 0 { fmt.Println("progress", r) } else { fmt.Println("done", r) } }} io.Copy(ioutil.Discard, pr)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26050380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1050517/']}
jdg_70903
stackexchange
llm_judgeable_groundtruth_similarity
209691
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 what differential equations (DEs) are, but what exactly are partial differential equations (PDEs)? I know the Schrödinger equation is a PDE. I'm also looking for an intuitive understanding. Also, what are good resources which explain PDEs for beginners? Now provide the response and nothing else.
Given that the Wiki definition may be too mathematically formal for the OP, let me give some intuition of the partial differential equation starting from the first order case. First, consider a first order ordinary differential equation$$ \frac{\mathrm{d}}{\mathrm{d}t} X = F(t,X) $$where $X$ takes values in, say, $\mathbb{R}^n$ and $F(t,X)$ is some Lipschitz continuous function. (In other words, this is a dynamical system.) What it says is that it tells us how $X$ ought to change, at an instant in time $t$, based on the time $t$ and the current value of $X$. This is what we call an "evolutionary point of view". The analogue of a partial differential equation that is "evolutionary" is an equation for $X$, which now depends on not only the time $t$ but also some spatial coordinates $(x_1, \ldots, x_N)$ would be something like $$ \frac{\partial}{\partial t} X = F\left(t,x_1, \ldots, x_N, X, \frac{\partial}{\partial x_1} X, \ldots, \frac{\partial}{\partial x_N} X\right) $$ Now, we have that how $X$ ought to change at an instant in time $t$ and at position $(x_1,\ldots, x_N)$, is based on a function of not only the coordinate values of $t$ and $(x_1, \ldots, x_N)$, but also the value of $X$ at that space-time point, and also the value of its spatial directional derivatives at that space-time point. There is a different point of view, however, for ordinary differential equations. This is the "constraint point of view". For this we consider the equation $$ X'' = F(s,X) $$and try to solve it while prescribing boundary conditions $X(0) = f_1$ and $X(1) = f_2$. What we should think of is that the differential equation describe some "compatibility condition" for a certain physical system in stasis. For example, the above equation can be used to describe the distribution of temperature along a rod that is kept at temperature $f_1$ at one end and temperature $f_2$ at the other. The equation says that the second derivative of the temperature function depends on the physical characteristic of the rod at the point $s$ as well as the current temperature at that point $x$. In other words, the laws of nature constrains what temperature profiles are possible. From this point of view, we also get a type of partial differential equations that describes a constraint. In this case, the PDE is usually written as an analytic expression relating the various partial derivatives of a function. What this says is that for the question we are considering, not all functions are admissible as solutions. That some law (most frequently a physical law) requires that the only admissible functions describing the situation (this is a constraint) obey certain relationships imposed upon their Taylor coefficients up to some order $k$ at every point . In other words, the function is not allowed to wiggle willy-nilly. Its rates of changes between the various different directions are tied together. Intuition aside, the mathematical formulation of a PDE can be stated relatively simply. A partial differential equation is a equation which expresses an equality between expressions involving partial derivatives of a given function. More precisely, taking one of the simpler cases, a partial differential equation on a scalar function $u$ defined on some subset $U\subseteq \mathbb{R}^N$ is the equation $$ F(x,u,\nabla u, \nabla^2 u, \ldots , \nabla^k u) = 0 $$where $x\in U\subseteq \mathbb{R}^N$ are the independent variables, $\nabla^ju$ are the tensors representing the $j$-th fold partial derivatives of $u$ ($\nabla^2 u$ is the Hessian matrix, $\nabla u$ is the gradient vector), and $F$ is some function $$ F: U \times \mathbb{R} \times \mathbb{R}^N \times \mathbb{R}^{N^2} \times \cdots \times \mathbb{R}^{N^k} \to \mathbb{R} $$The number $k$, the maximum order of the derivatives involved in the equation, is called the "order" of the equation. For some simple examples: The transport equation (or linear advection equation) are cases where $k = 1$, and where $$ F(x,u,p) = V(x)\cdot p $$where $p\in \mathbb{R}^N$ and $V(x)$ is some vector field on $U$. The Laplace equation is when $k = 2$ and $$F(x,u,p,q) = \operatorname{trace} q $$ where $p\in\mathbb{R}^N$ and $q\in \mathbb{R}^{N^2}$ is interpreted as an $N\times N$ matrix. The wave equation is when $k = 2$ and $$F(x,u,p,q) = \operatorname{trace} q - T^\dagger q T $$ where $\dagger$ is the matrix transpose, $T$ is a vector with $\|T\|^2 > 1$ The linear Schroedinger equation is also when $k = 2$ and $$F(x,u,p,q) = \operatorname{trace} q - T^\dagger q T - i T\cdot p $$ where $T$ is a vector with $\|T\|^2 = 1$. If we remove the imaginary $i$ from the equation, we end up with the linear heat equation instead. Note that necessarily for Schrodinger's equation we need $u$ to take values in the complex number $\mathbb{C}$, and so its gradient and Hessian will be complex-valued vector and complex-valued matrix. And now, for an extremely high-brow definition (which is a bit beyond the "beginner's scope" asked by the original poster, but nonetheless interesting): A partial differential relation (of which a partial differential equation is a special type) for a fibre-bundle $F$ over some smooth manifold $M$ is a subset $\mathcal{R}\subseteq F^{(r)}$ of the $r$-th jet bundle of $F$ over $M$. A partial differential equation is one where $\mathcal{R}$ has co-dimension 1. To bring it back to the simplest case defined above the cut: a class of simple fibre-bundles are the trivial bundles $F = M\times N$. Here $M$ is the domain of independent variables (what is $U$ in the definition above). $N$ is the domain of dependent variables (what is $\mathbb{R}$ or $\mathbb{C}$ above, but we can also think of vector valued dependent variables taking values in, say, $\mathbb{R}^n$ or $\mathbb{C}^n$, then we get what are sometimes called systems of partial differential equations). The $k$-th jet bundle is, roughly speaking, the set of all possible $k$-th order Taylor expansions; in other words, it represents the space $\mathbb{R}\times \mathbb{R}^N \times \mathbb{R}^{N^2}\times \cdots \times \mathbb{R}^{N^k}$ of the value of the function and all its (partial) derivatives up to order $k$. Then the single equation $F(x,u,p,q,r,\ldots,s) = 0$, the partial differential equation, should carve out a codimension 1 subset of $U \times \mathbb{R} \times \cdots \times\mathbb{R}^{N^k}$. (See my question on MO for some tangentially related discussions.) Further readings Sergiu Klainerman's essay , an abridged version of which appeared in the Princeton Companion to Mathematics . It assume a little bit more than absolute beginner, but not too much more. Jürgen Jost's Partial Differential Equations textbook, while on the whole may be a bit too advanced for the OP, has a short introductory chapter titled "What are Partial Differential Equations?", which should also give some intuition. Ka Kit Tung's Partial differential equations and Fourier analysis - A short introduction is a textbook aimed at students who have had one year of calculus and one course of ordinary differential equations. It has a decent first chapter reviewing ODEs, and a second chapter explaining the physical origins of partial differential equations while comparing and contrasting them to ordinary differential equations which the OP understood better. This may be a reasonable first book for the OP to consult.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/209691', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39770/']}
jdg_70904
stackexchange
llm_judgeable_groundtruth_similarity
512356
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: Here is quite challenging problem from Enderton's popular textbook A Mathematical Introduction to Logic . In 1977 it was proved that every planar map can be colored with four colors. Of course, the definition of "map" requires that there be only finitely many countries. But extending the concept, suppose we have an infinite (but countable) planar map with countries $C_1, C_2, C_3, ...$. Prove that this infinite planar map can still be colored with four colors. (Suggestion: Partition the sentence symbols into four parts. One sentence symbol, for example, can be used to translate, "Country $C_7$ is colored red." Form a set $\Sigma_1$ of wffs that say, for example, $C_7$ is exactly one of the colors. Form another set $\Sigma_2$ of wffs that say, for each pair of adjacent countries, that they are not the same color. Apply compactness to $\Sigma_1 \cup \Sigma _2$ Since I'm not much of the math logician, it's difficult for me to make a rigorous proof. My attempt would be to first check the satisfiability of every finite subset of $\Sigma_1$ and $\Sigma_2$. Then, take the union of those sets and finally apply compactness theorem, which states that A set of wffs is satisfiable iff every finite subset is satisfiable. The thing is: I wonder how the proof goes since Enderton's textbook is sometimes brief in some topics and the way he proves theorems and examples. He skips steps to the readers, assuming that they can prove them by themselves. Thus, I am a bit lost of how I should prove this. Any suggestions or advices or comments? Now provide the response and nothing else.
Consider the following set of propositional variables $\{P_{n,i}:1\leq i\leq4\ \wedge\ n\in\mathbb N\}$. We are interpreting $P_{n,i}$ as the $n$-th country has colour $i$. Let $\Sigma$ be the following set of sentences: $1$. $P_{n,1}\vee P_{n,2}\vee P_{n,3}\vee P_{n,4}$ for all $n\in\mathbb N$, $2$. $\neg(P_{n,i}\wedge P_{n,j})$ for all $1\leq i<j\leq4$ and $n\in\mathbb N$, $3$. $\neg(P_{n,i}\wedge P_{m,i})$ for all $1\leq i\leq 4$ and all pair of adjacent countries $C_n$ and $C_m$. says that every country gets a colour, says that each country gets at most one colour and, says that no two adjacent countries get the same cloud. $\Sigma$ is finitely satisfiable by hypothesis, so by compactness, is satisfiable.Any truth valuation witnessing gives you the decided colouring.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/512356', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67036/']}
jdg_70905
stackexchange
llm_judgeable_groundtruth_similarity
21421701
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 understand module.export and require mannner: Requiring external js file for mocha testing Although it's pretty usable as long as it's a module, I feel this manner is inconvenient since what I intends to do now is to test a code in a file. For instance, I have a code in a file: app.js 'use strict';console.log('app.js is running');var INFINITY = 'INFINITY'; and now, I want to test this code in a file: test.js var expect = require('chai').expect;require('./app.js'); describe('INFINITY', function() { it('INFINITY === "INFINITY"', function() { expect(INFINITY) .to.equal('INFINITY'); }); }); The test code executes app.js , so the output is; app.js is running then ReferenceError: INFINITY is not defined This is not what I expected. I do not want to use module.export and to write like var app = require('./app.js'); and app.INFINITY and app.anyOtherValue for every line in the test code. There must be a smart way. Could you tell me? Thanks. Now provide the response and nothing else.
UPDATE: FINAL ANSWER: My previous answer is invalid since eval(code); is not useful for variables. Fortunately, node has a strong mehod - vm http://nodejs.org/api/vm.html However, according to the doc, The vm module has many known issues and edge cases. If you run into issues or unexpected behavior, please consult the open issues on GitHub. Some of the biggest problems are described below. so, although this works on the surface, extra care needed for such an purpose like testing... var expect = require('chai') .expect;var fs = require('fs');var vm = require('vm');var path = './app.js';var code = fs.readFileSync(path);vm.runInThisContext(code);describe('SpaceTime', function(){ describe('brabra', function() { it('MEMORY === "MEMORY"', function() { expect(MEMORY) .to.equal('MEMORY'); }) });}); AFTER ALL;The best way I found in this case is to write the test mocha code in the same file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21421701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70906
stackexchange
llm_judgeable_groundtruth_similarity
45547293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just saw the following change in a pull request: - .ok_or(Error::new(ErrorKind::Other, "Decode error"));+ .ok_or_else(|| Error::new(ErrorKind::Other, "Decode error")); The only differences I know are: In ok_or we have already created Error by Error::new and passed it into a adaptor. In ok_or_else we have passed a closure which will produce such a value but it may not be called if there is Some data in the Option . Did I miss anything? Now provide the response and nothing else.
The primary reason to use ok_or_else or any of the ..._or_else methods is to avoid executing a function when it's not needed. In the case of Option::ok_or_else or Option::unwrap_or_else , there's no need to run extra code when the Option is Some . This can make code faster, depending on what happens in the error case In this example, Error::new likely performs allocation, but it could also write to standard out, make a network request, or anything any piece of Rust code can do; it's hard to tell from the outside. It's generally safer to place such code in a closure so you don't have to worry about extraneous side effects when the success case happens. Clippy lints this for you as well: fn main() { let foo = None; foo.unwrap_or("hello".to_string());} warning: use of `unwrap_or` followed by a function call --> src/main.rs:3:9 |3 | foo.unwrap_or("hello".to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| "hello".to_string())` | = note: `#[warn(clippy::or_fun_call)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45547293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1750757/']}
jdg_70907
stackexchange
llm_judgeable_groundtruth_similarity
9755556
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 generating dummy data for a database, one attribute is using TIMESTAMP(6) . Can anyone give me an example of how the value looks? Also I would like to be able to insert the date along i.e 03/18/2012 02:35 AM so that it looks like INSERT INTO FLIGHT VALUES (1,'London Heathrow','Miami Airport','03/18/2012 02:35 AM','04/18/2012 13:35 PM'); Is this possible? Thanks alot... EDIT---- How can i get rid of the timestamp column massive space Now provide the response and nothing else.
Whenever you are dealing with DATE or TIMESTAMP data types, you should always insert DATE or TIMESTAMP values. You should not be inserting strings and relying on implicit conversions to convert the string to a DATE or a TIMESTAMP . You should be explicitly calling TO_DATE or TO_TIMESTAMP . Your INSERT statement should also be explicitly listing the names of the columns you're inserting into. You'd want your INSERT statement to look something like this INSERT INTO FLIGHT( <<list of columns>> ) VALUES (1, 'London Heathrow', 'Miami Airport', to_timestamp( '03/18/2012 02:35 AM', 'MM/DD/YYYY HH:MI AM'), to_timestamp( '04/18/2012 13:35 PM', 'MM/DD/YYYY HH:MI AM') ); You can adjust how SQL*Plus displays the data in a particular column by changing the format mask. For E.g. SQL> column dept_time format a30;SQL> column arrv_time format a30; will cause SQL*Plus to display both DEPT_TIME and ARRV_TIME in 30 horizontal characters (your current NLS_TIMESTAMP_FORMAT appears to generate 28 character strings, if you change your NLS_TIMESTAMP_FORMAT , you may want to change the width of the column you're asking SQL*Plus to display).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9755556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1206087/']}
jdg_70908
stackexchange
llm_judgeable_groundtruth_similarity
3002867
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What debugging tools are available for directshow filters? Presently, I have a project that compiles and registers a video source filter that I then setup a graph in GraphEdit. I am using c++ in visual studio 2008. Is it possible to get a debugger attached to the filter in any way where I could set break points, inspect variables, etc? Barring that is there a way to log diagnostic information somewhere that I can view in real time? Now provide the response and nothing else.
There should be no problem with attaching a debugger. Set graphedt.exe as the debug target in your filter's Visual Studio project and you should be able to set breakpoints in your code. If you're having difficulty with this, it might be because of the anti-debugging logic in some decoders — you'll have to avoid using those. You can also get useful debug information by logging the deliveries and their timestamps and latency. The best way I find to do ths is to use a pass-through filter. There is an example monitor filter like this available in source and binary form from www.gdcl.co.uk/mobile (win32 and win mobile). G
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3002867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122229/']}
jdg_70909
stackexchange
llm_judgeable_groundtruth_similarity
400468
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've read that generally it's easier to write an interpreter than a compiler.If that's true, what's the reason? Writing an interpreter seems to me equivalent in the level of difficulty as writing a compiler, provided that the compiler simply translates the code to another high-level language (like c), and then uses an already existing compiler (like gcc) to that high-level language.I'd very much appreciate a clarification about this issue, please. Now provide the response and nothing else.
Yes, it is ! But only if you have a LL(k) grammar, where k is 0 or 1 . The reason is that you can parse the language using an easy functional decomposition corresponding roughly to the grammar terms. The functions then processes the input string from left to right: You may then interpret as you parse. But with slow performance. If you're more advanced, you may build an abstract syntax tree using for example the interpreter pattern and interpret the tree after the parsing. This leads to a more performant interpretation, since you do not need to reparse the input code every time you reexecue it. Writing a compiler needs much more knowledge and skills: you would need to translate the syntax tree in assembler or VM instructions, or some other kind of intermediate format; this is a level of complexity really higher rather than just doing the stuff in the interpreter and requires you to cope with the limitations of the target machine (limited number of registers, etc...). You'd also have to do the optimization one would expect from a decent compiler (at least constant propagation and loop optimization). This requires some understanding of graph algorithms. The output must then be produced for allowing integration into a tool suite that you do not control. This may also involve knowledge about linking process, and calling conventions needed to work with other languages or libraries... On the other side, writing compiler usually involves parser generators, that can digest much more complex grammars than LL(1) (e.g. LALR(1) ). This allows you to put more focus on the code generation rather than on routine parsing issues. Edit: If you consider transpilers that convert source code from one language to another, it will depend on how close the source and target languages are, including from a semantic point of view. A general statement is therefore difficult to make. At best, you'd have a complexity comparable with an interpreter (instead of interpreting, rewriting the code with some simple transformations). But in many cases , semantic analysis and additional code-generation mechanisms will be required to cope with language gaps (e.g. different object models and lifecycles, run-time vs-compile time, ect...); you'll then face at least some of the complexities of full compilers.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/400468', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/350096/']}
jdg_70910
stackexchange
llm_judgeable_groundtruth_similarity
54901
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The following is the molecule I am confused about. Earlier in my textbook it gives an example of how to name benzenes with 2 or more hydroxyl groups: My textbook (Nelson 12 Chemistry) is infamous for its crappiness but my school is too lazy to change it, so I've been asking a few of these questions in recent weeks. What is the proper, IUPAC name of the first molecule depicted in this question? Are there any other commonly accepted names for this molecule and under what convention are they named? Personally, I would name the first molecule benzene-1,2,4-triol, but the textbook gives the name 1,2,4-trihydroxybenzene, using the hydroxyl groups as substituents. Now provide the response and nothing else.
The compounds given in the question contain the characteristic group $(\ce{-OH})$. Since there is only one characteristic group, the seniority order of classes is not relevant in this case; thus, the $\ce{-OH}$ substituent corresponds to the principal characteristic group that is expressed as a suffix (‘ol’). Therefore, the preferred IUPAC name (PIN) for compound (e) is benzene-1,2,4-triol . Various traditional names exist for hydroxy compounds. According to the current version of Nomenclature of Organic Chemistry – IUPAC Recommendations and Preferred Names 2013 (Blue Book) , only the name ‘phenol’ is retained as a PIN. P-63.1.1.1 Only one name is retained, phenol, for $\ce{C6H5-OH}$, both as a preferred name and for general nomenclature. The structure is substitutable at any position. Locants 2, 3, and 4 are recommended, not o , m , and p . Therefore, the PIN for compound (c) is indeed phenol . Furthermore, according to Subsection P-63.1.1.2, the names pyrocatechol (benzene-1,2-diol), resorcinol (benzene-1,3-diol), and hydroquinone (benzene-1,4-diol) are retained but only for general nomenclature and only when unsubstituted. Therefore, the PIN for compound (d) is the systematic name benzene-1,2-diol (the traditional name ‘pyrocatechol’ may be used in general nomenclature).
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/54901', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/30897/']}
jdg_70911
stackexchange
llm_judgeable_groundtruth_similarity
44115681
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 way to check if timezone name valid or not in JavaScript without using external library? When user enters timezone name in text field I want to verify whether zone is valid or not? I know we can do it easily using moment-timezone library. But I don't want to use any extra library. I'm looking for pure JavaScript way. isValidTimeZone(name) {//return true/false }isValidTimeZone('Asia/Colombo'); //returns trueisValidTimeZone('America/Los_Angeles'); //returns trueisValidTimeZone('MyTimeZone/ME'); //returns false Now provide the response and nothing else.
In environments that fully support IANA time zone identifiers in ECMA-402 (ECMAScript Internationalization API), you can try using a time zone in a DateTimeFormat (or in the options of to toLocaleString ) and it will throw an exception if it is not a valid time zone. You can use this to test for validity, but only in environments where it is supported. function isValidTimeZone(tz) { if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) { throw new Error('Time zones are not available in this environment'); } try { Intl.DateTimeFormat(undefined, {timeZone: tz}); return true; } catch (ex) { return false; }}// Usage:isValidTimeZone('America/Los_Angeles') // trueisValidTimeZone('Foo/Bar') // false If you cannot be assured of your environment, then the best way would be with moment-timezone !!moment.tz.zone('America/Los_Angeles') // true!!moment.tz.zone('Foo/Bar') // false Of course, you could always extract your own array of time zone names (perhaps with moment.tz.names() and test against that.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44115681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2742156/']}
jdg_70912
stackexchange
llm_judgeable_groundtruth_similarity
439003
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question says it all really, the default is for it to map as a string but I need it to map as an int . I'm currently using PersistenceModel for setting my conventions if that makes any difference. Thanks in advance. Update Found that getting onto the latest version of the code from the trunk resolved my woes. Now provide the response and nothing else.
The way to define this convention changed sometimes ago, it's now : public class EnumConvention : IUserTypeConvention{ public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(x => x.Property.PropertyType.IsEnum); } public void Apply(IPropertyInstance target) { target.CustomType(target.Property.PropertyType); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/439003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6369/']}
jdg_70913
stackexchange
llm_judgeable_groundtruth_similarity
38269648
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 install Hexo globally using npm. When I run npm install -g hexo-cli I'm informed that it was installed to /Users/myusername/.node/bin/hexo -> /Users/myusername/.node/lib/node_modules/hexo-cli/bin/hexo The problem comes in when I run hexo init blog and the hexo command is not found. I installed Node and npm with Homebrew, so when I run which node and which npm , the results are /usr/local/bin/node and /usr/local/bin/npm respectively. I'm thinking that I still have leftover files and directories from when I installed Node without homebrew, but I don't want to start deleting things without fully knowing the repercussions. Would I be safe to delete all files located in the /Users/myusername/.node/ directory? I can't figure out why npm is not installing to the proper directory. Now provide the response and nothing else.
After a little digging, I found that my npm prefix variable was pointing do the wrong directory, left behind by the old Node installation. I ran npm config get prefix to see where it was pointing. I set the new prefix value using npm config set prefix /usr/local . Homebrew is symlinked with this directory via /usr/local/bin . I uninstalled hexo-cli and reinstalled through npm, and now it works perfectly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38269648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6565845/']}
jdg_70914
stackexchange
llm_judgeable_groundtruth_similarity
19033818
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 I have this class that spawns a thread: import threadingclass SomeClass(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: pass def doSomething(self): pass def doSomethingElse(self): pass I want to someClass = SomeClass()someClass.start()someClass.doSomething()someClass.doSomethingElse()someClass.doSomething() How can I do this? I know I can call a function inside the run() function, but that's not what I am aiming for. Now provide the response and nothing else.
You can't directly do what you want. The background thread is running its run function, which just loops forever, so it can't possibly do anything else. You can, of course, call the class's methods on your own thread, but that presumably isn't what you want here. The reason frameworks like Qt, .NET, or Cocoa can offer runOnOtherThread -type methods is that each thread runs an "event loop", so all they're really doing is posting an event. You can do that yourself, if you rewrite the run method into an event loop. For example: import queueimport threadingclass SomeClass(threading.Thread): def __init__(self, q, loop_time = 1.0/60): self.q = q self.timeout = loop_time super(SomeClass, self).__init__() def onThread(self, function, *args, **kwargs): self.q.put((function, args, kwargs)) def run(self): while True: try: function, args, kwargs = self.q.get(timeout=self.timeout) function(*args, **kwargs) except queue.Empty: self.idle() def idle(self): # put the code you would have put in the `run` loop here def doSomething(self): pass def doSomethingElse(self): pass Now, you can do this: someClass = SomeClass()someClass.start()someClass.onThread(someClass.doSomething)someClass.onThread(someClass.doSomethingElse)someClass.onThread(someClass.doSomething) If you want to simplify the calling interface a bit, at the cost of more code in the class, you can add wrapper methods like this: def _doSomething(self): # put the real code here def doSomething(self): self.onThread(self._doSomething) However, unless your idle method has work to do, you're really just building the equivalent of a single-thread thread pool here, and there are much easier ways to do this than to build it from scratch. For example, using the futures module off PyPI (a backport of the Python 3 concurrent.futures module): import futuresclass SomeClass(object): def doSomething(self): pass def doSomethingElse(self): passsomeClass = SomeClass()with futures.ThreadPoolExecutor(1) as executor: executor.submit(someClass.doSomething) executor.submit(someClass.doSomethingElse) executor.submit(someClass.doSomething) Or, with just the stdlib: from multiprocessing import dummy as multithreadingclass SomeClass(object): def doSomething(self): pass def doSomethingElse(self): passsomeClass = SomeClass()pool = multithreading.Pool(1)pool.apply(someClass.doSomething)pool.apply(someClass.doSomethingElse)pool.apply(someClass.doSomething)pool.close()pool.join() Pools have some other advantages, and executors even more. For example, what if the methods returned values, and you want to kick off two functions, then wait for the results, then kick off a third with the results of the first two? Easy: with futures.ThreadPoolExecutor(1) as executor: f1 = executor.submit(someClass.doSomething) f2 = executor.submit(someClass.doSomethingElse) futures.wait((f1, f2)) f3 = executor.submit(someClass.doSomethingElser, f1.result(), f2.result()) result = f3.result() Even if you later switch to a pool of 4 threads, so f1 and f2 may be waiting concurrently and f2 may even return first, you're guaranteed to kick off doSomethingElser as soon as both of them are finished, and no sooner. There's another possibility here. Do you really need the code to run in that thread, or do you just need it to modify variables that thread depends on? If it's the latter, just synchronize access to the variables. For example: class SomeClass(threading.Thread): def __init__(self): self.things_lock = threading.Lock() self.things = [] while True: with self.lock: things = self.things[:] for thing in things: # pass def doSomething(self): with self.lock: self.things.append(0)someClass = SomeClass()someClass.start()someClass.doSomething() There's nothing magical about being on the main thread here. If, in addition to needing to modify variables that SomeClass depends on, you also wanted to just kick doSomething off the main thread so you can do more important things than just waiting around for it to finish, you can create a short-lived extra thread just to doSomething : someClass = SomeClass()someClass.start()somethingThread = threading.Thread(target=someClass.doSomething)somethingThread.start()doOtherImportantStuffWithSomethingIsHappening()somethingThread.join()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19033818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1401560/']}
jdg_70915
stackexchange
llm_judgeable_groundtruth_similarity
123188
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 have a PCB that has 2 traces on one corner who's width only supports a ~10a load. I need support for a 20a load. Actually, it really only needs to support a 15amp load but I'm trying to build in some healthy breathing room. Can I just solder a wire between the two leads in parallel with the trace? The terminal block and the relay both support 20amps and these are the only parts touched by the load. I know it's messy but I figure it's not as messy as having to wire all of this up off the PCB. Now provide the response and nothing else.
Yes. Fixing production errors by using jumper wire is a time honored tradition by those blessed with hindsight. For Power rails or low speed GPIO (Think Push Buttons inputs or LED outputs), a simple wire would work. As a precaution, you could cut the trace, and carry the full load on the jumper you are adding. If the jumper fails, the load would try to go over the 10A trace, and can cause issues (i.e. fire). High Speed Signaling or Protocols with tight tolerances, RF signal traces, Traces that require uninterrupted ground/vcc planes under them, matched impedance, etc, require significantly more thought into it. Then again, some have wider tolerances than stated. There are many hobbyist projects/hacks that add high speed USB ports to a board with a CPU that supports it, using nothing but regular wires and protoboard, not to spec.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/123188', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50288/']}
jdg_70916
stackexchange
llm_judgeable_groundtruth_similarity
48316
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: HD 84406 , is a star approximately 241 light-years away in the constellation of Ursa Major. HD 84406 will be the first star to be imaged by the James Webb Space Telescope in order to test the focus of the telescope. The star is a spectral type G star and has a high proper motion. Why aren't the other more popular stars like Alpha Centauri or Betelgeuse chosen for the first light instead? Which properties of HD 84406 make it beneficial to the telescope mirror testing? Spectral type? Magnitude? Distance? Does the star have any interesting stuff? Or is it just for the reason that the position of the star is the most convenient for JWST to locate during the test process? Now provide the response and nothing else.
The most important selection criterion is that the star should be available for observation for a prolonged time. Because James Webb observes in the infrared, it must hide the Sun (and Earth and the Moon) behind its sunshield, and can hence only observe some 39% of the sky at any given time (source: NASA ). Webb needs around three months for its optical alignment, so we need a star that has just entered its field of view $^\dagger$ . In addition to this, we also don't want a star in a field that is too crowded, and HD 84406 is located in a rather isolated region in the NW part of Ursa Major: Credit: IAU/S&T/Roger Sinnott/Rick Fienberg with my own annotations. The star should be bright, but probably not too bright (like Betelgeuse), since we don't want to burn MIRI off from the beginning. EDIT : After discussing with several colleagues, damaging MIRI permanently is probably not going to be an issue. Bright sources can however damage the detector temporarily, showing a "ghost image" of the star in subsequent exposures. I've done that myself on a 1.5 m Earth-based telescope, and JWST has a ~20 times larger area, and ~10 times higher resolution, meaning several 1000 times more photons per pixel. Anyway, as you see there are some important constraints, but many other stars would fit as well; there are quite a lot to choose from. And the best part: HD 84406 is a magnitude 6.9 star, so while you can't see it with your naked eye, it should be visible in a pair of regular binoculars. $\dagger$ Stars too close to the ecliptic are only available for a more limited time, so a star that is close to the poles is preferred.
{}
{'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/48316', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/30814/']}
jdg_70917
stackexchange
llm_judgeable_groundtruth_similarity
215788
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In one of my physics classes, we are using slow motion video to analyze the falling motion of an object and then find out the drag coefficient of that object etc. I noticed while doing this that if I dropped our object (a styrofoam bowl with a cone of sorts attached to the top) from any position, it would always flip and fall tip down if dropped from high enough. There was of course a certain height when it would not flip and would fall slowly to the floor. I asked my question to the professor and he said he wasn't completely sure and that the only relevant knowledge he had was that some high-atmosphere ice crystals which are basically square shaped fall with the square side down, rather than sideways. No doubt there are many examples of objects not falling in their most aerodynamic position, so here's the way I'm picturing this. I imagine it is something like each object which falls in a particular orientation has reached a minimum (or maximum) on a potential energy curve. Except that I guess this curve would represent minimums in the drag force. And the reason then that many objects would not fall in their most aerodynamic position is because the energy barriers between that position and the next minimum are very small. I'm picturing a piece of paper falling for instance. Paper would fall fastest with its edge to the ground, yet it often teeters back and forth between that position and falling with its full area facing downwards. So, any thoughts on this idea and just general answers to what determines which direction an object will face while falling? Now provide the response and nothing else.
The answer to this question is "hard" in the sense that a general object falling from general initial conditions may or may not reorient into a lowest drag orientation. However, one can make some educated guesses by comparing the locations of the center of drag (more generally, the center of pressure ) and the center of mass of the object. Consider one commenter's example of a parachute -- nearly all the drag force is on the inner surface of the parachute -- meaning the center of drag is near the "middle" of the parachute. However, the center of mass (since parachutes are generally much lighter than people) is below the parachute, near the person. This has the effect of the person being suspended under the parachute. If the person swings a little one way or the other, the center of drag is still above the center of mass and the system does not tumble. For a styrofoam bowl with a conical top, the styrofoam is very likely to have little impact on the center of mass of the cone, but a large effect on the center of drag. Once again, the falling preferred orientation is center of mass below center of drag. However, this can be defeated -- make the cone out of styrofoam. Another way to defeat this is to start with a very large angular velocity, so that the tendency of the mass to fall below the drag is overcome by the angular momentum. The preferred orientation will eventually prevail, but there may be many revolutions before this happens. (There is an optimization problem lurking here: Make the cone too dense and its angular momentum will be hard to dissipate. Make the cone too light and the centers of mass and drag will coincide so there will be no preferred orientation.) An easy way to see that this should be hard is this. The drag of the system depends on the orientation of the system, so the center of drag depends on the orientation of the system. A good parachute will be designed so that a small swing by the person will lead to a small central force to bring the person back under the center of drag. A bad parachute design would lack that small central force -- it could, even worse, lower net drag so that the parachute begins to fall faster, perhaps even faster than the person. (This actually happens. It's the worst scenario in what is called "stalling a parachute.") Nevertheless, we can design for this. Recall that SpaceShipOne was designed so that in its feather configuration it would fall in a particular orientation -- i.e., small displacements from that orientation would be passively corrected by the change in the center of drag.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/215788', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/86244/']}
jdg_70918
stackexchange
llm_judgeable_groundtruth_similarity
7562786
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 make a popup dialog that only shows after the app's first run that will alert users of the new changes in the app. So I have a dialog popup like this: new AlertDialog.Builder(this).setTitle("First Run").setMessage("This only pops up once").setNeutralButton("OK", null).show(); Once they dismiss it, it won't come back until the next update or they reinstall the app. How can I set the dialog code above to run only once? Now provide the response and nothing else.
Use SharedPreferences to store the isFirstRun value, and check in your launching activity against that value. If the value is set, then no need to display the dialog. If else, display the dialog and save the isFirstRun flag in SharedPreferences. Example: public void checkFirstRun() { boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true); if (isFirstRun){ // Place your dialog code here to display the dialog getSharedPreferences("PREFERENCE", MODE_PRIVATE) .edit() .putBoolean("isFirstRun", false) .apply(); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7562786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/779920/']}
jdg_70919
stackexchange
llm_judgeable_groundtruth_similarity
30739161
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 a particular window when I move cursor, I want to get the cursor position and want to display it in window just like tooltip. Is it possible? However I am able to get the co-ordinates by using PointerX() and PointerY() method but how should I display it like tooltip? Now provide the response and nothing else.
Both connection:canAuthenticateAgainstProtectionSpace: and connection:didReceiveAuthenticationChallenge: are deprecated in iOS 8 anyway so you should use other methods. What I am using in my projects is a delegate method of NSURLSessionDelegate. Adhere to that protocol then add this method: func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))} Then, when you use initialize NSURLSession with delegate set to self. For example: var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue()) Then use that session instance to call dataTaskWithRequest method on: var task = session.dataTaskWithRequest(request){ (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in if error != nil { callback("", error.localizedDescription) } else { var result = NSString(data: data, encoding: NSASCIIStringEncoding)! }}task.resume() Complete working example can be found here . For security reasons, if you use a self-signed certificate I recommend also implementing public key pinning ( https://gist.github.com/edwardmp/df8517aa9f1752e73353 )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30739161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1747756/']}
jdg_70920
stackexchange
llm_judgeable_groundtruth_similarity
43625341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to create a plot of POSIXct times using ggplot, and would like to reverse the axis, but am struggling to make it work.I've been using scale_y_datetime , because in my real application, it's important that I have control of the breaks on this axis. Here's an example of my problem, first with normal ordering, and then my attempt to reverse the axis. # Some random dates and values to plotMyData <- structure(list(Date = structure(c(1492979809.99827, 1492602845.68722, 1493093428.90318, 1492605578.0691, 1492961342.65056, 1492771976.83545, 1493020588.88485, 1493057018.85104, 1492852011.23873, 1492855996.55059 ), class = c("POSIXct", "POSIXt")), Value = c(4.52885504579172, 6.0024610790424, 8.96430060034618, 7.06435370026156, 5.08460514713079, 3.47828012891114, 6.29844291834161, 0.898315710946918, 1.44857675535604, 5.74641009094194)), .Names = c("Date", "Value"), row.names = c(NA, -10L), class = "data.frame")library(ggplot2)library(scales)ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_datetime(limits=c(min(MyData$Date),max(MyData$Date))) which produces this: If I attempt to reverse the Y axis, by reversing limits, I lose all breaks and data, like this: ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_datetime(limits=c(max(MyData$Date),min(MyData$Date))) Is there a simple way to reverse the datetime axis? Now provide the response and nothing else.
With the help from this post from Hadley Wickham here is how you can get a reverse datetime scale: library(scales)c_trans <- function(a, b, breaks = b$breaks, format = b$format) { a <- as.trans(a) b <- as.trans(b) name <- paste(a$name, b$name, sep = "-") trans <- function(x) a$trans(b$trans(x)) inv <- function(x) b$inverse(a$inverse(x)) trans_new(name, trans, inverse = inv, breaks = breaks, format=format)}rev_date <- c_trans("reverse", "time")ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_continuous(trans = rev_date) Here is the plot:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43625341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1911526/']}
jdg_70921
stackexchange
llm_judgeable_groundtruth_similarity
3016897
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: A normed space $X$ is said to be smooth if for $x \in X$ with $||x||=1$ there exists a unique bounded linear functional $f$ such that $||f||=1$ and $f(x)=||x||$ . Why the term "smooth" comes? Now provide the response and nothing else.
Let us consider the space $X=\mathbb R^2$ with the $\ell^p$ -norm. Then for $p=1$ or $p=\infty$ we can see that the unit ball has kinks, and does not look smooth.It can be shown, that there are points $x\in X$ such that there is more than one functional $f$ with $\|f\|=1$ and $f(x)=\|x\|=1$ .(For example, if $p=1$ consider the point $x=(1,0)$ , then $g(x)=x_1$ and $h(x)=x_1+x_2$ are possible choices for $f$ .) For $p$ with $1<p<\infty$ the unit ball looks smooth (its boundary is differentiable).And it is possible to show that for each $x\in X$ there is exactly one functional $f$ with $\|f\|=f(x)=\|x\|=1$ . I hope this is sufficient motivation for the term "smooth" for a normed space.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3016897', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/402183/']}
jdg_70922
stackexchange
llm_judgeable_groundtruth_similarity
8115192
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 the native application that works with Android via the NDK.I need to call the backtrace() function when there is a crash. The problem is that there is no <execinfo.h> for the NDK. Is there any other way to get that back trace? Now provide the response and nothing else.
Android have no backtrace() , but unwind.h is here to serve. Symbolization is possible via dladdr() . The following code is my simple implementation of backtrace (with no demangling): #include <iostream>#include <iomanip>#include <unwind.h>#include <dlfcn.h>namespace {struct BacktraceState{ void** current; void** end;};static _Unwind_Reason_Code unwindCallback(struct _Unwind_Context* context, void* arg){ BacktraceState* state = static_cast<BacktraceState*>(arg); uintptr_t pc = _Unwind_GetIP(context); if (pc) { if (state->current == state->end) { return _URC_END_OF_STACK; } else { *state->current++ = reinterpret_cast<void*>(pc); } } return _URC_NO_REASON;}}size_t captureBacktrace(void** buffer, size_t max){ BacktraceState state = {buffer, buffer + max}; _Unwind_Backtrace(unwindCallback, &state); return state.current - buffer;}void dumpBacktrace(std::ostream& os, void** buffer, size_t count){ for (size_t idx = 0; idx < count; ++idx) { const void* addr = buffer[idx]; const char* symbol = ""; Dl_info info; if (dladdr(addr, &info) && info.dli_sname) { symbol = info.dli_sname; } os << " #" << std::setw(2) << idx << ": " << addr << " " << symbol << "\n"; }} It may be used for backtracing into LogCat like #include <sstream>#include <android/log.h>void backtraceToLogcat(){ const size_t max = 30; void* buffer[max]; std::ostringstream oss; dumpBacktrace(oss, buffer, captureBacktrace(buffer, max)); __android_log_print(ANDROID_LOG_INFO, "app_name", "%s", oss.str().c_str());}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8115192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/836628/']}
jdg_70923
stackexchange
llm_judgeable_groundtruth_similarity
20222583
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created a UIView programmatically and added a UIButton as it's subview. I want a UIViewController to be the target of that button action. How would I do that? If it was created by Interface Builder then it was easy by using IBAction . Now provide the response and nothing else.
If you are adding the button programmatically to a subclass of UIView, then you can do it one of two ways: You can make the button a property of the view, and then in the viewController that instantiates the view you can set the target of the button as follows: [viewSubclass.buttonName addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; This will set the button's target to a method of buttonTapped: in the viewController.m You can create a protocol in your subview, which the parent viewController will conform to. In your view, when you add your button set it to call a method in your view. Then call the delegate method from that view so that your viewController can respond to it: In the top your view subclass .h create the protocol: @protocol ButtonProtocolName- (void)buttonWasPressed;@end Create a property for the delegate: @property (nonatomic, assign) id <ButtonProtocolName> delegate; In the subclass .m set your button selector: [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; In the buttonTapped: method call the delegate method: - (void)buttonTapped:(id)sender { [self.delegate buttonWasPressed];} In your viewController.h you'll need to make sure it conforms to the protocol: @interface someViewController : UIViewController <SomeButtonProtocolName> In your viewController.m when you init your subview, you'll have to set the delegate: SomeView *view = ... // Init your view// Set the delegateview.delegate = self; Finally, add the delegate method buttonWasPressed to the viewController.m: - (void)buttonWasPressed { // Put code here for button's intended action.} Updated to provide Swift example // Simple delegate protocol.protocol SomeViewDelegate: class { // Method used to tell the delegate that the button was pressed in the subview. // You can add parameters here as you like. func buttonWasPressed()}class SomeView: UIView { // Define the view's delegate. weak var delegate: SomeViewDelegate? // Assuming you already have a button. var button: UIButton! // Once your view & button has been initialized, configure the button's target. func configureButton() { // Set your target self.button.addTarget(self, action: #selector(someButtonPressed(_:)), for: .touchUpInside) } @objc func someButtonPressed(_ sender: UIButton) { delegate?.buttonWasPressed() }}// Conform to the delegate protocolclass SomeViewController: UIViewController, SomeViewDelegate { var someView: SomeView! func buttonWasPressed() { // UIViewController can handle SomeView's button press. }} Additionally, here is a quick example using a closure instead of a delegate. (This can approach also be implemented in ObjC using blocks.) // Use typeAlias to define closuretypealias ButtonPressedHandler = () -> Voidclass SomeView: UIView { // Define the view's delegate. var pressedHandler: ButtonPressedHandler? // Assuming you already have a button. var button: UIButton! // Once your view & button has been initialized, configure the button's target. func configureButton() { // Set your target self.button.addTarget(self, action: #selector(someButtonPressed(_:)), for: .touchUpInside) } @objc func someButtonPressed(_ sender: UIButton) { pressedHandler?() }}class SomeViewController: UIViewController { var someView: SomeView! // Set the closure in the ViewController func configureButtonHandling() { someView.pressedHandler = { // UIViewController can handle SomeView's button press. } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20222583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1611375/']}
jdg_70924
stackexchange
llm_judgeable_groundtruth_similarity
190153
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've been going over practice problems, and I ran into this one. I was wondering if anyone could help me out with the following problem. Let $X$ be a metric space of all bounded sequences $(a_n) \subset \mathbb{R}$ with the metric defined by $$d( (a_n), (b_n)) = \sup\{ |a_n - b_n| : n = 1, 2, \ldots \}.$$ Let $Y \subset X$ be the subspace of all sequences converging to zero. Determine whether or not $X$ and $Y$ are separable. Thanks in advance! Now provide the response and nothing else.
Suppose that $A=\{\alpha_n:n\in\Bbb N\}$ is a countable subset of $X$, where $\alpha_n$ is the sequence $\langle a_{n,k}:k\in\Bbb N\rangle$. Note that for any $x\in\Bbb R$ there is always a $y\in[-1,1]$ such that $|x-y|\ge 1$. Thus, we can construct a sequence $\beta=\langle b_k:k\in\Bbb N\rangle$ such that $b_k\in[-1,1]$ and $|b_k-a_{k,k}|\ge 1$ for each $k\in\Bbb N$. Clearly $\beta\in X$, but for each $n\in\Bbb N$ we have $\sup_{k\in\Bbb N}|b_k-a_{n,k}|\ge|b_n-a_{n,n}|\ge 1$, so the distance between $\beta$ and $\alpha_n$ is at least $1$. Thus, $A$ is not dense in $X$, and $X$ is not separable. $Y$, on the other hand, is separable. Let $D$ be the set of sequences of rational numbers that are $0$ from some point on, i.e., that have only finitely many non-zero terms. Show that $D$ is both countable and dense in $Y$. For the latter, start with any $\langle a_k:k\in\Bbb N\rangle\in Y$ and any $\epsilon>0$ and construct an element of $D$ that is less than $\epsilon$ away from $\langle a_k:k\in\Bbb N\rangle\in Y$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/190153', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19784/']}
jdg_70925
stackexchange
llm_judgeable_groundtruth_similarity
34594641
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to create simple summary statistics using dplyr from multiple variables? Using the summarise_each function seems to be the way to go, however, when applying multiple functions to multiple columns, the result is a wide, hard-to-read data frame. Now provide the response and nothing else.
Use dplyr in combination with tidyr to reshape the end result. library(dplyr)library(tidyr)df <- tbl_df(mtcars)df.sum <- df %>% select(mpg, cyl, vs, am, gear, carb) %>% # select variables to summarise summarise_each(funs(min = min, q25 = quantile(., 0.25), median = median, q75 = quantile(., 0.75), max = max, mean = mean, sd = sd))# the result is a wide data frame> dim(df.sum)[1] 1 42# reshape it using tidyr functionsdf.stats.tidy <- df.sum %>% gather(stat, val) %>% separate(stat, into = c("var", "stat"), sep = "_") %>% spread(stat, val) %>% select(var, min, q25, median, q75, max, mean, sd) # reorder columns> print(df.stats.tidy) var min q25 median q75 max mean sd1 am 0.0 0.000 0.0 1.0 1.0 0.40625 0.49899092 carb 1.0 2.000 2.0 4.0 8.0 2.81250 1.61520003 cyl 4.0 4.000 6.0 8.0 8.0 6.18750 1.78592164 gear 3.0 3.000 4.0 4.0 5.0 3.68750 0.73780415 mpg 10.4 15.425 19.2 22.8 33.9 20.09062 6.02694816 vs 0.0 0.000 0.0 1.0 1.0 0.43750 0.5040161
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34594641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2795440/']}
jdg_70926
stackexchange
llm_judgeable_groundtruth_similarity
25886480
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 mark up <div id="wrapper"> <input type="file" id="file" accept="image/*" capture="camera"> <a href="#" id="capture">Submit Cleanup</a></div> and jQuery as follow jQuery(function($){ $('#capture').on('click', function(e){ e.preventDefault(); $('#file').trigger('click'); });}); the script works as expected on PC browser, but when i try on mobile device the camera doesnt prompt. also i already tried using click() , but same result. what could be the problem? Now provide the response and nothing else.
It's a security feature. Some browsers don't allow a non-manual click on file inputs. You can read more about it here and here . Why isn't it possible to programmatically trigger the file input selection? Most browsers prevent submitting files when the input field didn'treceive a direct click (or keyboard) event as a security precaution.Some browsers (e.g. Google Chrome) simply prevent the click event,while e.g. Internet Explorer doesn't submit any files that have beenselected by a programmatically triggered file input field. Firefox 4(and later) is so far the only browser with full support for invoking"click"-Events on a completely hidden (display: none) file inputfield.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25886480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2503356/']}
jdg_70927
stackexchange
llm_judgeable_groundtruth_similarity
2181
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to group my buffer list in ibuffer by project. Project is meant in the Projectile sense of the word. I don't want to change my Emacs configuration every time I'm working on a new project. Is there a way to achieve this automatically? Now provide the response and nothing else.
You can define filter groups for known projects using something like this: ;; Define ibuffer filter groups for each known project(defun my/define-projectile-filter-groups () (when (boundp 'projectile-known-projects) (setq my/project-filter-groups (mapcar (lambda (it) (let ((name (file-name-nondirectory (directory-file-name it)))) `(,name (filename . ,(expand-file-name it))))) projectile-known-projects))));; Set up default ibuffer filter groups(setq ibuffer-saved-filter-groups (list (cons "default" (append (my/define-projectile-filter-groups) ;; ... whatever other groups you want, e.g. '(("dired" (mode . dired-mode)) ("erc" (mode . erc-mode))) ))));; Enable default groups by default(add-hook 'ibuffer-mode-hook (lambda () (ibuffer-switch-to-saved-filter-groups "default")));; You probably don't want to see empty project groups(setq ibuffer-show-empty-filter-groups nil) Update Since I originally wrote this answer, @sanityinc has created a variant of ibuffer-vc that creates filter groups by projectile project root. You can find ibuffer-projectile on MELPA or on GitHub .
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/2181', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2037/']}
jdg_70928
stackexchange
llm_judgeable_groundtruth_similarity
41165448
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 pretty new building directives with Angular2. What I want is to create a popup directive that will wrap the content with some css classes. Content Content can be pure text and headers like: <div class="data"> <h2>Header</h2> Content to be placed here.</div> Then I want to give this a directive attribute like: popup <div class="data" popup> <h2>Header</h2> Content to be placed here.</div> What the directive should do, is to wrap the div inside, lets say: <div class="some class"> <div class="some other class"> <div class="data"> <h2>Header</h2> Content to be placed here. </div> </div></div> The case i described so far, is this a attribute or structural directives. import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({ selector: `[popup]`})export class PopupDirective {} Now provide the response and nothing else.
The other answer is related but different. For something closer, see this: How to conditionally wrap a div around ng-content - my solution is for Angular 4, but the linked question has some hints about how this might be doable for Angular 2. I solved this problem with a component and a directive combined. My component looks something like this: import { Component, Input, TemplateRef } from '@angular/core';@Component({ selector: 'my-wrapper-container', template: `<div class="whatever"> <ng-container *ngTemplateOutlet="template"></ng-container></div>`})export class WrapperContainerComponent { @Input() template: TemplateRef<any>;} and my directive like this: import { Directive, OnInit, Input, TemplateRef, ComponentRef, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';@Directive({ selector: '[myWrapperDirective]'})export class WrapperDirective implements OnInit { private wrapperContainer: ComponentRef<WrapperContainerComponent>; constructor( private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver ) { } ngOnInit() { const containerFactory = this.componentFactoryResolver.resolveComponentFactory(WrapperContainerComponent); this.wrapperContainer = this.viewContainerRef.createComponent(containerFactory); this.wrapperContainer.instance.template = this.templateRef; }} To be able to load your component dynamically, you need to list your component as an entryComponent inside your module : @NgModule({ imports: [CommonModule], declarations: [WrapperContainerComponent, WrapperDirective], exports: [WrapperContainerComponent, WrapperDirective], entryComponents: [WrapperContainerComponent]})export class MyModule{} so the HTML in the end is: <some_tag *myWrapperDirective /> Which renders as: <my-wrapper-container> <div class="whatever"> <some_tag /> </div></my-wrapper-container>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41165448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4424380/']}
jdg_70929
stackexchange
llm_judgeable_groundtruth_similarity
1308992
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 Taylor expansion itself can be derived from mean value theorems which themselves are valid over the entire domain of the function. Then why doesn't the Taylor series converge over the entire domain? I understand the part about the convergence of infinite series and the various tests. But I seem to be missing something very fundamental here.. Now provide the response and nothing else.
It is rather unfortunate that in calc II we teach Taylor series at the same time as we teach Taylor polynomials , all the while not doing a very good job of stressing the distinction between an infinite series and a finite sum. In the process we seem to teach students that Taylor series are a much more powerful tool than they are, and that Taylor polynomials are a much less powerful tool than they are. The main idea is really the finite Taylor polynomial. The Taylor series is just a limit of these polynomials, as the degree tends to infinity. The Taylor polynomial is an approximation to the function based on its value and a certain number of derivatives at a certain point. The remainder formulae tell us about the error in this approximation. In particular they tell us that higher degree polynomials provide better local approximations to a function. But the issue is that "local" has a different meaning for different values of the degree $n$ . To explain what I mean by that, you can look at the Lagrange remainder, which tells you that the error in an approximation of degree $n$ is $$\frac{f^{(n+1)}(\xi_n) (x-x_0)^{n+1}}{(n+1)!}$$ where $\xi_n$ is between $x_0$ and $x$ . So the ratio of the error with degree $n$ to the error with degree $n-1$ is* $$\frac{f^{(n+1)}(\xi_n) (x-x_0)}{f^{(n)}(\xi_{n-1}) (n+1)}$$ where similarly $\xi_{n-1}$ is between $x$ and $x_0$ . So the error is smaller where this quantity is less than $1$ . From this form we can see that if $|x-x_0|<(n+1) \left | \frac{f^{(n)}(\xi_{n-1})}{f^{(n+1)}(\xi_n)} \right |$ then the error with degree $n$ is less than that with degree $n-1$ . That looks good because we have that growing factor of $n+1$ , but what if $\frac{f^{(n)}(\xi_{n-1})}{f^{(n+1)}(\xi_n)}$ goes to zero, maybe even doing so really fast? Then the interval where the error is reduced by adding another term will shrink, potentially contracting down to just the point of expansion as $n$ tends to infinity. In other words, if the derivatives near $x_0$ ( not necessarily just at $x_0$ , because we have to evaluate the derivatives at these $\xi$ 's) grow way too fast with $n$ , then Taylor expansion has no hope of being successful, even when the derivatives needed exist and are continuous. *Here I am technically assuming that $f^{(n)}(\xi_{n-1}) \neq 0$ . This assumption can fail even when $f$ is not a polynomial; consider $f=\sin,x_0=\pi/2,n=1$ . But this is a "degenerate" situation in some sense.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1308992', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/100448/']}
jdg_70930
stackexchange
llm_judgeable_groundtruth_similarity
1337424
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 you set the event listener for a Spinner when the selected item changes? Basically what I am trying to do is something similar to this: spinner1.onSelectionChange = handleSelectionChange;void handleSelectionChange(Object sender){ //handle event} Now provide the response and nothing else.
Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the Spinner widget clearly states: A spinner does not support item click events. Calling this method will raise an exception. Better use OnItemSelectedListener() instead: spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { // your code here } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here }}); This works for me. Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside onCreate() method call.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/1337424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93141/']}
jdg_70931
stackexchange
llm_judgeable_groundtruth_similarity
11569535
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Would somebody please explain the behavior of a nested loop using generators? Here is an example. a = (x for x in range(3))b = (x for x in range(2))for i in a: for j in b: print (i,j) The outer loop is not evaluated after the first iteration for some reason. The result is, (0, 0)(0, 1) On the other hand, if generators are directly inserted into the loops, it does what I expect. for i in (x for x in range(3)): for j in (x for x in range(2)): print (i,j) giving all 3x2 pairs. (0, 0)(0, 1)(1, 0)(1, 1)(2, 0)(2, 1) Now provide the response and nothing else.
It's because the b generator is exhausted during the first iteration of the outer for loop. Subsequent iterations will in effect have an empty inner loop (like for x in () ) so what's inside is never executed. This gives the false impression that it's the outer loop that fails, somehow. Your second example works because there the inner generator is created anew for each outer loop. To fix your first example, you have to do the same: a = (x for x in range(3))for i in a: b = (x for x in range(2)) for j in b: print (i,j)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11569535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/524526/']}
jdg_70932
stackexchange
llm_judgeable_groundtruth_similarity
14381895
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'email_subscription' AND COLUMN_NAME = 'subscribe_all') THEN ALTER TABLE email_subscription ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1, ADD COLUMN subscribe_category varchar(512) DEFAULT NULL; I had a look at huge amount of examples. but this query doesn't work, I got error of: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =' at line 1 Now provide the response and nothing else.
you can create a procedure for the query, DELIMITER $$CREATE PROCEDURE Alter_Table()BEGIN DECLARE _count INT; SET _count = ( SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'email_subscription' AND COLUMN_NAME = 'subscribe_all'); IF _count = 0 THEN ALTER TABLE email_subscription ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1, ADD COLUMN subscribe_category varchar(512) DEFAULT NULL; END IF;END $$DELIMITER ;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14381895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1219868/']}
jdg_70933
stackexchange
llm_judgeable_groundtruth_similarity
58075427
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Getting the error This iPhone 6 is running iOS 12.4.1 (16G102), which may not be supported by this version of Xcode. while trying to run the app on iPhone after updating the iPhone. I know that I can update the Xcode and System both and the issue will be resolved but I want to be able to install the apps on iPhone without updating the Xcode and MacOS. Please help. Tried nothing yet. Can not share the code. No code to show here. Now provide the response and nothing else.
Issue: This iPhone 6 is running iOS 12.4.1 (16G102), which may not be supported by this version of Xcode. Resolution: a). If the issue is not replicated on your another device with latest Xcode version We need to add the support files in the Xcode. The files can be found on a system with latest Xcode on the path - Go to Applications. Right click on Xcode, click on "Show Package Contents". Go to Contents -> Developer -> Platforms -> iPhoneOS.platforms -> DeviceSupport Copy support files for the iPhone version. Paste the file into the system in which you are facing the issue in same path as of above. Close the Xcode and run the code again to refresh the files. b). If you don't have a system with latest Xcode. Download the file "iOS 12.4 Developer Disk Image" from the https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases and unzip the file. Rename the folder to "12.4.1 (16G102)" and paste the file into the system in which you are facing the issue in below path: Go to Applications. Right click on Xcode, click on "Show Package Contents". Go to Contents -> Developer -> Platforms -> iPhoneOS.platforms -> DeviceSupport Close the Xcode and run the code again to refresh the files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58075427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12111529/']}
jdg_70934
stackexchange
llm_judgeable_groundtruth_similarity
25870923
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 square a 2D numpy array (elementwise) and I have tried the following code: import numpy as npa = np.arange(4).reshape(2, 2)print a^2, '\n'print a*a that yields: [[2 3][0 1]][[0 1][4 9]] Clearly, the notation a*a gives me the result I want and not a^2 . I would like to know if another notation exists to raise a numpy array to the power of 2 or N? Instead of a*a*a*..*a . Now provide the response and nothing else.
The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower. np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a , which become important in cases where you have small tolerances. I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below: In [29]: a = np.random.random((1000, 1000))In [30]: timeit a*a100 loops, best of 3: 2.78 ms per loopIn [31]: timeit a**2100 loops, best of 3: 2.77 ms per loopIn [32]: timeit np.power(a, 2)10 loops, best of 3: 71.3 ms per loop
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25870923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4022541/']}
jdg_70935
stackexchange
llm_judgeable_groundtruth_similarity
27750901
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 started dealing with preferences in a PreferenceFragment . Here's what I have: I'm trying to: get rid of the dividers between items. I suppose this can be defined from styles, but I can't figure out how. I tried getting thepreference ListView at runtime calling findViewById(android.R.id.list) , as I read somewhere, but itreturns null. set new, full width dividers right on top of the headers, as seen here . For example in this case I want a full width divider right above "Statistiche", but not above "Generali" which is on top of the list. The only way that comes to my mind is setting dividers as fake preferences, like with: <Preference android:layout="@layout/divider" //here I set width and a divider resource /><PreferenceCategory ... /> The main issue here is that my PreferenceFragment (or the ActionBarActivity it's in) has some left/right padding, that make any divider I add into preferences.xml not cover the entire width. So my question are: How can I get rid of default, item-item dividers that you can see in the image? How can I set full width dividers right above headers, or how can I get rid of internal fragment/activity padding? Of course my activity layout has no (explicit) padding whatsoever. Now provide the response and nothing else.
AndroidX makes it simple, but I wish it was better documented. In XML To add/remove dividers between preferences in XML, use the following attributes: <androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"> <Preference ... app:allowDividerAbove="true/false" app:allowDividerBelow="true/false" ... /></androidx.preference.PreferenceScreen> Note, a divider will only be shown between two preferences if the top divider has allowDividerBelow set to true and the bottom divider has allowDividerAbove set to true . In Code You can also change/remove dividers programmatically using the following methods in onActivityCreated of your PreferenceFragmentCompat : @Overridepublic void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // To remove: setDivider(null); // To change: setDivider(ContextCompat.getDrawable(getActivity(), R.drawable.your_drawable)); setDividerHeight(your_height);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27750901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4288782/']}
jdg_70936
stackexchange
llm_judgeable_groundtruth_similarity
74147
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: How can achieve something like this? a * b /. {a -> {1, 2, 3}, b -> {10, 100}} I want {10,100,20,200,30,300} or something like that (I don't care the order, or sublist) to be returned. What is the right syntaxis? In my real problem, I have a more complex expresion ComputeMean[S0_, r_, s_, T_, NPaths_] := Sum[f[S0 Exp[(r - 1/2 s^2) T + s Sqrt[T] RandomVariate@NormalDistribution[0, 1]]], {i, 1, NPaths}] /NPathsComputePrice[S0_, r_, s_, T_, NPaths_] := Exp[-r T] ComputeMean[s0, r, s, T, NPaths]ComputePrice[S0,r,s,T,NPaths] /. { S0 -> {values for S0}, r -> {values for r}, ... } Now provide the response and nothing else.
You say you need a pure function to accept substitution values. My interpretation of this would be that you want the following: t = Take[#1, {#2, Length[#1]}] &[V3, #] & This defines t as a function that accepts the values as follows: t /@ Range[8](*==> {{1, 2, 3, 4, 5, 6, 7, 8}, {2, 3, 4, 5, 6, 7, 8}, {3, 4, 5, 6, 7, 8}, {4, 5, 6, 7, 8}, {5, 6, 7, 8}, {6, 7, 8}, {7, 8}, {8}}*) The slot # at the end is filled with the "substitution value", whereas the slot #1 in the first part (which is taken without modification from your original definition) is filled with V3 . Sometimes cascades of # and & denoting pure functions can be a little hard to read. In that case, it could be better to use Function .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/74147', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4800/']}
jdg_70937
stackexchange
llm_judgeable_groundtruth_similarity
18748349
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 created a pssession on a remote computer and entered that possession. From within that session I use start-process to start notepad. I can confirm that notepad is running with the get-process command, and also with taskmgr in the remote computer. However, the GUI side of the process isn't showing. This is the sequence I've been using: $server = New-PSSession -ComputerName myserver -Credential mycredsEnter-PSSession $server[$server]: PS C:\>Start-Process notepad -Wait -WindowStyle Maximized The process is running, but while RDP'd to the box, notepad does not open. If I open notepad from the server, a new notepad process begins. I also tried by using the verb parameter like this: [$server]: PS C:\>Start-Process notepad -Wait -WindowStyle Maximized -Verb Open Same result tho... Process starts, but no notepad shows. I've tried this while remoted into the box (but issued from my local host) as well as before remoting into the server. Now provide the response and nothing else.
That is because your powershell session on the remote machine does not go to any visible desktop, but to an invisible system desktop. The receiving end of your powershell remote session is a Windows service. The process is started, but nor you nor anyone else can ever see it. And if you think about it, since multiple users could RDP to the same machine, there is really no reason to assume a remote powershell session would end up showing on any of the users desktops. Actually, in almost all cases you wouldn't want it anyway. psexec with the -i parameter is able to do what you want, but you have to specify which of the sessions (users) you want it to show up in.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18748349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2679666/']}
jdg_70938
stackexchange
llm_judgeable_groundtruth_similarity
393732
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I do not understand the macro concept well. What is a macro? I do not understand how is it different from function? Both function and macro contain a block of code. So how does macro and function differ? Now provide the response and nothing else.
Unfortunately, there are multiple different uses of the term "macro" in programming. In the Lisp family of languages, and languages inspired by them, as well as many modern functional or functional-inspired languages like Scala and Haskell, as well as some imperative languages like Boo, a macro is a piece of code that runs at compile time (or at least before runtime for implementations without a compiler) and can transform the Abstract Syntax Tree (or whatever the equivalent in the particular language is, e.g. in Lisp, it would be the S-Expressions) into something else during compilation. For example, in many Scheme implementations, for is a macro which expands into multiple calls to the body. In statically-typed languages, macros are often type-safe, i.e. they cannot produce code that is not well-typed. In the C family of languages, macros are more like textual substitution. Which also means they can produce code that is not well-typed, or even not syntactically legal. In macro-assemblers, "macros" refer to "virtual instructions", i.e. instructions that the CPU does not support natively but that are useful, and so the assembler allows you to use those instructions and will expand them into multiple instructions that the CPU understands. In application scripting, a "macro" refers to a series of actions that the user can "record" and "play back". All of those are in some sense kinds of executable code, which means they can in some sense be viewed as functions. However, in the case of Lisp macros, for example, their input and output are program fragments. In the case of C, their input and output are tokens. The first three also have the very important distinction that they are executed at compile time . In fact, C preprocessor macros, as the name implies, are actually executed before the code even reaches the compiler .
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/393732', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/334821/']}
jdg_70939
stackexchange
llm_judgeable_groundtruth_similarity
395829
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: The Bohr model of the atom is essentially that the nucleus is a ball and the electrons are balls orbiting the nucleus in a rigid orbit. This allowed for chemists to find a model of chemical bonding where the electrons in the outer orbits could be exchanged. And it works pretty well as seen in the Lewis structures: However, electron orbitals were found to be less rigid and instead be fuzzy fields which, instead of being discrete/rigid orbits, look more like: However, in chemistry education like organic chemistry you still learn about chemical reactions using essentially diagrams that are modified lewis structures that take into account information about electron orbitals: What I'm wondering is, if the Bohr model is used essentially throughout college education in the form of these diagrams, it seems like it must be a pretty accurate model, even though it turns out atoms are more fuzzy structures than discrete billiard balls. So I'm wondering what the inaccuracies are, and if there is a better way to understand them than the Bohr model. If you build a computer simulation of atoms with the Bohr model, I'm wondering if it would be "accurate" in the sense of modeling atomic phenomena, or is it not a good model to perform simulations on. If not, I'm wondering what an alternative model is that is better for simulation. Essentially, how good the Bohr model is as a diagram, as a tool for learning, and as a tool for simulation. Now provide the response and nothing else.
In hydrogen: It incorrectly predicts the number of states with given energy. This number can be seen through Zeeman splitting. In particular, it doesn't have the right angular momentum quantum numbers for each energy levels. Most obvious is the ground state, with has $\ell=0$ in Schrodinger's theory but $\ell=1$ in Bohr's theory. It doesn't hold well under perturbation theory. In particular, because of angular momentum degeneracies, the spin-orbit interaction is incorrect. It predicts a single "radius" for the electron rather than a probability density for the position of the electron. What it does do well: a. Correct energy spectrum for hydrogen (although completely wrong even for helium). In particular, one deduces the right value of the Rydberg constant. b. The Bohr radii for various energy levels turn out to be the most probable values predicted by the Schrodinger solutions. c. Also does a lot of chemistry stuff quite well (as suggested in the original question) but I'm not a chemist so can't praise the model for that.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/395829', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16731/']}
jdg_70940