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
3857272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know where to find a reference for boost error codes. In particular, error codes returned by asynchronous socket handlers?, Google and grepping the header files have tuned up empty. Now provide the response and nothing else.
I extracted the error values from asio/error.hpp on Linux (I'm using header only asio not boost::asio by the way), here they are: asio::error::access_denied 13asio::error::address_family_not_supported 97asio::error::address_in_use 98asio::error::already_connected 106asio::error::already_started 114asio::error::broken_pipe 32asio::error::connection_aborted 103asio::error::connection_refused 111asio::error::connection_reset 104asio::error::bad_descriptor 9asio::error::fault 14asio::error::host_unreachable 113asio::error::in_progress 115asio::error::interrupted 4asio::error::invalid_argument 22asio::error::message_size 90asio::error::name_too_long 36asio::error::network_down 100asio::error::network_reset 102asio::error::network_unreachable 101asio::error::no_descriptors 24asio::error::no_buffer_space 105asio::error::no_memory 12asio::error::no_permission 1asio::error::no_protocol_option 92asio::error::not_connected 107asio::error::not_socket 88asio::error::operation_aborted 125asio::error::operation_not_supported 95asio::error::shut_down 108asio::error::timed_out 110asio::error::try_again 11asio::error::would_block 11 If you want to generate your own list, this should save you a few mins of copying and pasting: std::cout << "asio::error::access_denied " << asio::error::access_denied << std::endl;std::cout << "asio::error::address_family_not_supported " << asio::error::address_family_not_supported << std::endl;std::cout << "asio::error::address_in_use " << asio::error::address_in_use << std::endl;std::cout << "asio::error::already_connected " << asio::error::already_connected << std::endl;std::cout << "asio::error::already_started " << asio::error::already_started << std::endl;std::cout << "asio::error::broken_pipe " << asio::error::broken_pipe << std::endl;std::cout << "asio::error::connection_aborted " << asio::error::connection_aborted << std::endl;std::cout << "asio::error::connection_refused " << asio::error::connection_refused << std::endl;std::cout << "asio::error::connection_reset " << asio::error::connection_reset << std::endl;std::cout << "asio::error::bad_descriptor " << asio::error::bad_descriptor << std::endl;std::cout << "asio::error::fault " << asio::error::fault << std::endl;std::cout << "asio::error::host_unreachable " << asio::error::host_unreachable << std::endl;std::cout << "asio::error::in_progress " << asio::error::in_progress << std::endl;std::cout << "asio::error::interrupted " << asio::error::interrupted << std::endl;std::cout << "asio::error::invalid_argument " << asio::error::invalid_argument << std::endl;std::cout << "asio::error::message_size " << asio::error::message_size << std::endl;std::cout << "asio::error::name_too_long " << asio::error::name_too_long << std::endl;std::cout << "asio::error::network_down " << asio::error::network_down << std::endl;std::cout << "asio::error::network_reset " << asio::error::network_reset << std::endl;std::cout << "asio::error::network_unreachable " << asio::error::network_unreachable << std::endl;std::cout << "asio::error::no_descriptors " << asio::error::no_descriptors << std::endl;std::cout << "asio::error::no_buffer_space " << asio::error::no_buffer_space << std::endl;std::cout << "asio::error::no_memory " << asio::error::no_memory << std::endl;std::cout << "asio::error::no_permission " << asio::error::no_permission << std::endl;std::cout << "asio::error::no_protocol_option " << asio::error::no_protocol_option << std::endl;std::cout << "asio::error::not_connected " << asio::error::not_connected << std::endl;std::cout << "asio::error::not_socket " << asio::error::not_socket << std::endl;std::cout << "asio::error::operation_aborted " << asio::error::operation_aborted << std::endl;std::cout << "asio::error::operation_not_supported " << asio::error::operation_not_supported << std::endl;std::cout << "asio::error::shut_down " << asio::error::shut_down << std::endl;std::cout << "asio::error::timed_out " << asio::error::timed_out << std::endl;std::cout << "asio::error::try_again " << asio::error::try_again << std::endl;std::cout << "asio::error::would_block " << asio::error::would_block << std::endl;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3857272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300745/']}
jdg_76841
stackexchange
llm_judgeable_groundtruth_similarity
58267
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $K$ be a finite field and $G$ be a discrete group. Is it true that for every $a,b\in K[G]$ the condition $ab=0$ implies $ba=0$? It does not seem to be related to zero divisor problem, any ideas if this can be true and for which fields? Now provide the response and nothing else.
Let G be non-abelian of order 6, with x of order 2 and y of order 3. In such a group yxy = x, since both x and xy have order 2. Let K be a field with 2 elements. Then (x+y)⋅(1+xy) = x+y + y+yxy = x+y + y+x = 0, but (1+xy)⋅(x+y) = x+y + xyx+xyy = x+y + yy + xyy ≠ 0. You may be thinking of the property: if a⋅b = 0 then there is some non-zero c such that c⋅a = 0. This holds in all (two-sided) Artinian rings (because elements are either units or zero-divisors). I believe this is true for two-sided self-injective rings as well. I don't know if it is possessed by group rings of infinite groups over finite fields. (Thanks to Greg Marks:) The classification of finite group rings over fields where ab=0 implies ba=0 is given in: Gutan, Marin; Kisielewicz, Andrzej. "Reversible group rings." J. Algebra 279 (2004), no. 1, 280–291. MR 2078399 DOI: j.jalgebra.2004.02.011 . In particular, K is a field of order 2 2n-1 and G is the quaternion group of order 8, or G is abelian. Li and Parmenter (2007) extend this to finite group rings over commutative rings with 1 in MR 2372321 .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/58267', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8699/']}
jdg_76842
stackexchange
llm_judgeable_groundtruth_similarity
46601107
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 two interface with same name but in different packages.As I autowired them I have to give them name.My interfaces are com.example.mysql.UserRepository and com.example.mongo.UserRepository . So I have declared them like this: @Repository(value = "mysqlrepo")public interface UserRepository extends JpaRepository<User,Long> ... and @Repository(value = "mongorepo")public interface UserRepository extends MongoRepository<User,String> ... and used them like this: @Autowiredee3.demo.repositories.mysql.UserRepository userRepository;@Qualifier("mongorepo")@AutowiredUserRepository userRepository1; Now I wonder how can I do this with beans configure file.I tried <bean id="mysqlService" lazy-init="true" class="ee3.demo.repositories.mysql.UserRepository"/> but I am getting error interface not allowed for non abstract beans .I wondering what is the correct way of doing this,this question if different with this question as this question have just one interface and don't need to use qualifier to specify which interface he needWhat I have tried so far is HERE Now provide the response and nothing else.
You've got to look carefully at which overload is being invoked: Boolean.valueOf(null) is invoking Boolean.valueOf(String) . This doesn't throw an NPE even if supplied with a null parameter. Boolean.valueOf(modifiedItems.get("item1")) is invoking Boolean.valueOf(boolean) , because modifiedItems 's values are of type Boolean , which requires an unboxing conversion. Since modifiedItems.get("item1") is null , it is the unboxing of that value - not the Boolean.valueOf(...) - which throws the NPE. The rules for determining which overload is invoked are pretty hairy , but they roughly go like this: In a first pass, a method match is searched for without allowing boxing/unboxing (nor variable arity methods). Because null is an acceptable value for a String but not boolean , Boolean.valueOf(null) is matched to Boolean.valueOf(String) in this pass; Boolean isn't an acceptable for either Boolean.valueOf(String) or Boolean.valueOf(boolean) , so no method is matched in this pass for Boolean.valueOf(modifiedItems.get("item1")) . In a second pass, a method match is searched for, allowing boxing/unboxing (but still not variable arity methods). A Boolean can be unboxed to boolean , so Boolean.valueOf(boolean) is matched for Boolean.valueOf(modifiedItems.get("item1")) in this pass; but an unboxing conversion has to be inserted by the compiler to invoke it: Boolean.valueOf(modifiedItems.get("item1").booleanValue()) (There's a third pass allowing for variable arity methods, but that's not relevant here, as the first two passes matched these cases)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/46601107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5040046/']}
jdg_76843
stackexchange
llm_judgeable_groundtruth_similarity
837606
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only. The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better? At the moment I'm running df to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest *.avi files until that condition is met. Now provide the response and nothing else.
Hm. Nadia's answer is closer to what you meant to ask; however, for finding the (single) oldest file in a tree, try this: import osdef oldest_file_in_tree(rootfolder, extension=".avi"): return min( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) With a little modification, you can get the n oldest files (similar to Nadia's answer): import os, heapqdef oldest_files_in_tree(rootfolder, count=1, extension=".avi"): return heapq.nsmallest(count, (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) Note that using the .endswith method allows calls as: oldest_files_in_tree("/home/user", 20, (".avi", ".mov")) to select more than one extension. Finally, should you want the complete list of files, ordered by modification time, in order to delete as many as required to free space, here's some code: import osdef files_to_delete(rootfolder, extension=".avi"): return sorted( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime), reverse=True) and note that the reverse=True brings the oldest files at the end of the list, so that for the next file to delete, you just do a file_list.pop() . By the way, for a complete solution to your issue, since you are running on Linux, where the os.statvfs is available, you can do: import osdef free_space_up_to(free_bytes_required, rootfolder, extension=".avi"): file_list= files_to_delete(rootfolder, extension) while file_list: statv= os.statvfs(rootfolder) if statv.f_bfree*statv.f_bsize >= free_bytes_required: break os.remove(file_list.pop()) statvfs.f_bfree are the device free blocks and statvfs.f_bsize is the block size. We take the rootfolder statvfs, so mind any symbolic links pointing to other devices, where we could delete many files without actually freeing up space in this device. UPDATE (copying a comment by Juan): Depending on the OS and filesystem implementation, you may want to multiply f_bfree by f_frsize rather than f_bsize. In some implementations, the latter is the preferred I/O request size. For example, on a FreeBSD 9 system I just tested, f_frsize was 4096 and f_bsize was 16384. POSIX says the block count fields are "in units of f_frsize" ( see http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/837606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/90545/']}
jdg_76844
stackexchange
llm_judgeable_groundtruth_similarity
391256
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the Abelian-Higgs model, $$S=\int d^{3}x\left\{-\frac{1}{4g^{2}}F_{\mu\nu}F^{\mu\nu}+|D\phi|^{2}-a|\phi|^{2}-b|\phi|^{4}\right\}\tag{5.34}$$ there is a $U(1)$ gauge symmetry. In David Tongs' lecture notes The Quantum Hall Effect , chapter 5, on page 169, he says that there is also a less obvious global symmetry, with the current $$\star j=\frac{1}{2\pi}db.\tag{5.35}$$ I understand that the current is conserved for an obvious reason. But why is the flux corresponding to a global $U(1)$ symmetry? What is this global $U(1)$ symmetry? Now provide the response and nothing else.
Any abelian gauge theory has a $\mathrm{U(1)}$ global symmetry with current $j = \star F$ by virtue of the Bianchi identity, $$\mathrm{d} \star j = \mathrm{d} F = 0.$$ First suppose the theory is 4-dimensional, in which case this symmetry is a little more familiar. In this case $j$ is a 2-form. The associated charge $$ Q=\int_{S^2}\star j = \int_{S^2} F$$ measures the magnetic flux of a line operator $H(C)$ (the "`t Hooft line operator") which is supported on a line $C$ which links the $S^2$. It corresponds to the worldline of a probe magnetic monopole, and $Q$ measures the magnetic flux of the monopole in the same way that $\int_{S^2} \star F$ measures the electric flux on the worldline of an electric charge. These are called 1-form global symmetries, because the charged operators are supported on lines. The same story goes through in any dimension $d>2$. We obtain a $(d-3)$-form global symmetry, meaning the charged operators are supported on $(d-3)$-manifolds which link a 2-sphere over which we measure the charge $\int_{S^2} F$. In 3 dimensions, $j=\star F$ is a 1-form, so this is an ordinary global symmetry. The 't Hooft operators are pointlike magnetic monopole operators, whose charge is again the magnetic flux.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/391256', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/185558/']}
jdg_76845
stackexchange
llm_judgeable_groundtruth_similarity
4309364
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a sample test page showing the problem. Boiled down, the problem is: var id = someContext.getImageData(0,0,1,1);id.data[0]=id.data[3]=64; // 25% red, 25% alphaid.data[1]=id.data[2]=0; // No blue or greensomeContext.putImageData(id,0,0);var newData = someContext.getImageData(0,0,1,1);console.log( newData.data[0] ); On Chrome v8, the red value comes back as 63 ; on Firefox v3.6, Safari v5, and IE9 the red value comes back as 67 (all on Windows). On OS X, Chrome v7, Safari v5, and Firefox v3.6 also come back as 67 . None of them come back as the 64 value originally set! Using setTimeout to delay between setting and re-fetching makes no difference. Changing the background of the page makes no difference. Using save() and restore() on the context (per this unlikely article ) makes no difference. Now provide the response and nothing else.
ImageData is defined in HTML5 as being unpremultiplied, but most canvas implementations use a premultiplied backing buffer to speed up compositing, etc. This means that when data is written and then read from the backing buffer it can change. I would assume that Chrome v8 picked up a buggy version of the [un]premultiplying code from webkit.org (It has been broken before, although i don't recall any recent occurances, and that doesn't explain the windows only variance) [edit: it could be worth checking a webkit nightly on windows? as the imagedata implementation doesn't have anything platform specific it's shared between all webkit browsers and could simply be broken in MSVC based builds]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4309364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405017/']}
jdg_76846
stackexchange
llm_judgeable_groundtruth_similarity
22424747
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 question has been asked before [here] . At the time, it was a bug, and a feature has been requested, later on it was fixed and supposedly it should work. but in my case it still isn't.I have been trying and googling for about a week, yet still, I couldn't get it to work My system is: Arch Linux Pycharm 3.1.1 Build #PC-133.881 Python 3.3.4 pygobject 3.10.2 Is there something I'm missing or is it a bug ?? Now provide the response and nothing else.
To help debug this problem you can use the service_log_path and service_args arguments to the selenium webdriver to see output from the chromedriver: service_log_path = "{}/chromedriver.log".format(outputdir)service_args = ['--verbose']driver = webdriver.Chrome('/path/to/chromedriver', service_args=service_args, service_log_path=service_log_path) I was getting this same exception message and found two ways to get past it; I'm not sure if the OP's problem is the same, but if not, the chromedriver log will hopefully help. Looking at my log, I discovered that the chromedriver (I tried 2.9 down to 2.6 while trying to fix this problem) decides which browser to run in a very unexpected way. In the directory where my chromedriver is located I have these files: $ ls -l /path/to/-rwx------ 1 pjh grad_cs 5503600 Feb 3 00:07 chromedriver-2.9drwxr-xr-x 3 pjh grad_cs 4096 Mar 28 15:51 chromium When I invoke the chromedriver using the same python code as the OP: driver = webdriver.Chrome('/path/to/chromedriver-2.9') This leads to the exception message. In the chromedriver.log I found this message: [1.043][INFO]: Launching chrome: /path/to/chromium ... Unbelievable! The chromedriver is trying to use /path/to/chromium (which is not an executable file, but a directory containing source code) as the browser to execute! Apparently chromedriver tries to search the current directory for a browser to run before searching my PATH . So, one easy solution to this problem is to check the directory where the chromedriver is located for files/directories like chrome and chromium and move them to a different directory than the chromedriver . A better solution is to explicitly tell selenium / chromedriver which browser to execute by using the chrome_options argument: options = webdriver.ChromeOptions()options.binary_location = '/opt/google/chrome/google-chrome'service_log_path = "{}/chromedriver.log".format(outputdir)service_args = ['--verbose']driver = webdriver.Chrome('/path/to/chromedriver', chrome_options=options, service_args=service_args, service_log_path=service_log_path) The chromedriver.log now shows: [0.999][INFO]: Launching chrome: /opt/google/chrome/google-chrome ... as expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22424747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3423276/']}
jdg_76847
stackexchange
llm_judgeable_groundtruth_similarity
8909823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When loading through NH the default constructor is used and then every property in the map is set. That is fine by me. But what if I have some logic in the constructor? Could I register a method to be called after the NH construction? e.g. (it could me more complicated and involves several properties) public class Person{ string name; int? age; DateTime ageStamp; public Person(string name, int? age) { this.name = name; if (age!=null) { this.age = age; ageStamp = DateTime.Now; } }} Now provide the response and nothing else.
One thing worth noting here, is that the overridden version is called each time. Change the override to: public override void MyMethod(string s = "bbb"){ Console.Write("derived: "); base.MyMethod(s);} And the output is: derived: bbbderived: aaa A method in a class can do one or two of the following: It defines an interface for other code to call. It defines an implementation to execute when called. It may not do both, as an abstract method does only the former. Within BBB the call MyMethod() calls a method defined in AAA . Because there is an override in BBB , calling that method results in an implementation in BBB being called. Now, the definition in AAA informs calling code of two things (well, a few others too that don't matter here). The signature void MyMethod(string) . (For those languages that support it) the default value for the single parameter is "aaa" and therefore when compiling code of the form MyMethod() if no method matching MyMethod() can be found, you may replace it with a call to `MyMethod("aaa"). So, that's what the call in BBB does: The compiler sees a call to MyMethod() , doesn't find a method MyMethod() but does find a method MyMethod(string) . It also sees that at the place where it is defined there's a default value of "aaa", so at compile time it changes this to a call to MyMethod("aaa") . From within BBB , AAA is considered the place where AAA 's methods are defined, even if overridden in BBB , so that they can be over-ridden. At run-time, MyMethod(string) is called with the argument "aaa". Because there is a overridden form, that is the form called, but it is not called with "bbb" because that value has nothing to do with the run-time implementation but with the compile-time definition. Adding this. changes which definition is examined, and so changes what argument is used in the call. Edit: Why this seems more intuitive to me. Personally, and since I'm talking of what is intuitive it can only be personal, I find this more intuitive for the following reason: If I was coding BBB then whether calling or overriding MyMethod(string) , I'd think of that as "doing AAA stuff" - it's BBB s take on "doing AAA stuff", but it's doing AAA stuff all the same. Hence whether calling or overriding, I'm going to be aware of the fact that it was AAA that defined MyMethod(string) . If I was calling code that used BBB , I'd think of "using BBB stuff". I might not be very aware of which was originally defined in AAA , and I'd perhaps think of this as merely an implementation detail (if I didn't also use the AAA interface nearby). The compiler's behaviour matches my intuition, which is why when first reading the question it seemed to me that Mono had a bug. Upon consideration, I can't see how either fulfils the specified behaviour better than the other. For that matter though, while remaining at a personal level, I'd never use optional parameters with abstract, virtual or overridden methods, and if overriding someone else's that did, I'd match theirs.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8909823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514069/']}
jdg_76848
stackexchange
llm_judgeable_groundtruth_similarity
2324125
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 distance as a float and I'm looking for a way to format it nicely for human readers. Ideally, I'd like it to change from m to km as it gets bigger, and to round the number nicely. Converting to miles would be a bonus. I'm sure many people have had a need for one of these and I'm hoping that there's some code floating around somewhere. Here's how I'd like the formats: 0-100m: 47m (as a whole number) 100-1000m: 325m or 320m (round to the nearest 5 or 10 meters) 1000-10000m: 1.2km (round to nearest with one decimal place) 10000m +: 21km If there's no code available, how can I write my own formatter? Thanks Now provide the response and nothing else.
None of these solutions really met what I was looking for, so I built on them: #define METERS_TO_FEET 3.2808399#define METERS_TO_MILES 0.000621371192#define METERS_CUTOFF 1000#define FEET_CUTOFF 3281#define FEET_IN_MILES 5280- (NSString *)stringWithDistance:(double)distance { BOOL isMetric = [[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue]; NSString *format; if (isMetric) { if (distance < METERS_CUTOFF) { format = @"%@ metres"; } else { format = @"%@ km"; distance = distance / 1000; } } else { // assume Imperial / U.S. distance = distance * METERS_TO_FEET; if (distance < FEET_CUTOFF) { format = @"%@ feet"; } else { format = @"%@ miles"; distance = distance / FEET_IN_MILES; } } return [NSString stringWithFormat:format, [self stringWithDouble:distance]];}// Return a string of the number to one decimal place and with commas & periods based on the locale.- (NSString *)stringWithDouble:(double)value { NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setLocale:[NSLocale currentLocale]]; [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [numberFormatter setMaximumFractionDigits:1]; return [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]];}- (void)viewDidLoad { [super viewDidLoad]; double distance = 5434.45; NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]); distance = 543.45; NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]); distance = 234234.45; NSLog(@"%f meters is %@", distance, [self stringWithDistance:distance]); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2324125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74118/']}
jdg_76849
stackexchange
llm_judgeable_groundtruth_similarity
519560
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need prove that: $$\int_{0}^{2\pi} \frac{R^{2}-r^{2}}{R^{2}-2Rr\cos \theta +r^{2}} d\theta= 2\pi$$ By deformation theorem, with $0<r<R$. Professor gave us the hint to use the function $f(z)= \frac{R+z}{z(R-z)}$, and define an adequate $\gamma : [a,b]\rightarrow \mathbb{C}$ circular curve and with deformation theorem, we could find the integral. But I have been able to find the curve $\gamma$. Any advice is very helpful Now provide the response and nothing else.
The integrand is the famous Poisson kernel function! Here's a sketch of how to integrate it using the Residue Theorem: Show that $$\frac{R^2-r^2}{R^2-2Rr\cos\theta +r^2} = \text{Re}\left(\frac{R+re^{i\theta}}{R-re^{i\theta}}\right)$$ and hence $$\int_0^{2\pi}\frac{R^2-r^2}{R^2-2Rr\cos\theta +r^2} \,d\theta= \int_0^{2\pi}\text{Re}\left(\frac{R+re^{i\theta}}{R-re^{i\theta}}\right)\,d\theta= \text{Re}\int_0^{2\pi}\frac{R+re^{i\theta}}{R-re^{i\theta}}\,d\theta.$$View this integral as an integral along the contour $\gamma(\theta) = re^{i\theta}$ and evaluate$$\int_\gamma \frac{R+z}{iz(R-z)}\,dz$$using the Residue Theorem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/519560', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91423/']}
jdg_76850
stackexchange
llm_judgeable_groundtruth_similarity
2992882
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 code Calendar c = new GregorianCalendar(); c.add(Calendar.DAY_OF_YEAR, 1); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 22); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); // We want the alarm to go off 30 seconds from now. long firstTime = SystemClock.elapsedRealtime(); firstTime += 30*1000; long a=c.getTimeInMillis(); // Schedule the alarm! AlarmManager am = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, c.getTimeInMillis(), 1*60*60*1000, sender); It is not executed at 23:22h What I am doing wrong? I noticed firstTime and c.getTimeInMillis() differs a lot in size and length. When I use firstTime, so when set to 30 seconds, the alarm is executed well. Now provide the response and nothing else.
You are using the AlarmManager.ELAPSED_REALTIME_WAKEUP flag, but you are using a Calendar object. These two things don't go together. You need to use AlarmManager.RTC or AlarmManager.RTC_WAKEUP if you are specifying the alarm time using a Calendar or Date object (milliseconds since 1970). You use AlarmManager.ELAPSED_REALTIME or AlarmManager.ELAPSED_REALTIME_WAKEUP when you are specifying the alarm time via SystemClock.elapsedRealtime() (milliseconds since the phone booted).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2992882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243782/']}
jdg_76851
stackexchange
llm_judgeable_groundtruth_similarity
2111424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: // Remove element with ID of 1 var userIds = from user in document.Descendants("Id") where user.Value == "1" select user; userIds.Remove(); SaveAndDisplay(document); // Add element back var newElement = new XElement("Id", "0", new XElement("Balance", "3000")); document.Add(newElement); SaveAndDisplay(document); The add element back block is the problem. As when it gets to the add it states: This operation would create an incorrectly structured document. What stupid mistake am I making? Edit: Yes, I was reading as an XDocument , not XElement . Any advice on when to favour one or the other? Now provide the response and nothing else.
It looks like you are trying to add a new element as a child of your document's root. If so, then you need to change your Add statement to the following. var newElement = new XElement("Id", "0", new XElement("Balanace", "3000"));document.Root.Add(newElement); Adding directly to the document adds another root element, which violates the XML structure.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2111424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102482/']}
jdg_76852
stackexchange
llm_judgeable_groundtruth_similarity
1220760
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading sets and came to some reserved letters for a few sets.Two of them really confused me. They were - $\mathbb N$ : For the set of natural numbers. $\mathbb Z^+$ : For the set if all positive integers. In my sense, both the sets contain $\{1,2,3,\dots\}$ Then, why are they considered different? I searched a little on this topic and got this , but it doesn't tell anything about significance of two different sets. Now provide the response and nothing else.
You should be aware that some authors define $\mathbb{N}$ to include zero. This isn't of much consequence in itself since the properties of the set are preserved: there is a bijection between $\mathbb{N}$ with zero and $\mathbb{N}$ without zero, both are well-ordered, and so forth—effectively, we've done nothing but "relabel" the elements. Only when we start adding structure to these elements does the distinction become important. For instance, if we define an addition $+: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$, we might make $0$ an additive identity. Therefore, when one writes "$\mathbb{N}$" in such a scenario (most scenarios), then it should be made clear which definition is intended. Now, if we take both to mean the set $\{1, 2, 3, \cdots\}$, then whether one writes $\mathbb{N}$ or $\mathbb{Z}^+$ is immaterial. However, using $\mathbb{Z}^+$ removes ambiguity since $\mathbb{Z}^+$ definitively does not include zero, and we would not have to go out of our way defining $\mathbb{N}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1220760', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/212632/']}
jdg_76853
stackexchange
llm_judgeable_groundtruth_similarity
1269990
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 seen that some authors are defing the number field as a subfield of $ \mathbb C$ which is a finite extension of the rational numbers $ \mathbb Q $, while some others without referering to complex numbers $ \mathbb C$ .I think we don't need $ K$ to be a subfield of $ \mathbb C$ in the definition.So, my question is the follwing: Is it neceserily to define $K$ as a subfield of $ \mathbb C$ or not ? And if no why ? Is it true that if we omit this in the definition, that then $K$ will turn out to be a subfield of $ \mathbb C$? I came up with this question, when I saw that in order to define infinite primes in a number field then these are determined by the embeddings $ K \to \mathbb C $ Any idea would be really appreciated. Thank you in advance. Now provide the response and nothing else.
Usually there will be more than one way to consider $K$ as a subfield of $\mathbb{C}$ - or more precisely, to embed $K$ in $\mathbb{C}$. For example, take $K:=\mathbb{Q}[X]/(X^3-2)$, which is to say the extension field of $\mathbb{Q}$ of degree $3$ containig a root of the polynomial $X^3-2$ (which root we choose is irrelevant for now).Then we can embed $K$ into $\mathbb{C}$ by mapping that fixed abstract root of the polynomial to the complex number $\sqrt[3]{2}$, which is also a real number, or the complex number $\sqrt[3]{2}\cdot \exp(\frac{2\pi i}{3})$, which is a non-real complex number. So we have embedded $K$ into $\mathbb{C}$ in two disctinct ways. This distinction would have been "lost", had we considered $K$ as a subfield of the complex numbers from the start.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1269990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23187/']}
jdg_76854
stackexchange
llm_judgeable_groundtruth_similarity
204035
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm specifying some SMD chip capacitors for the first time and I note there are several manufacturers out there: muRata, Yageo, Vishay, AVX, Kemet in particular, perhaps others. Is there any good reason to prefer one of these manufacturers over the others for chip capacitors? They all look the same from the pictures, of course, and the prices seem to be quite comparable. Are these just a pure commodity or are there real differences? If there are differences, how would one typically go about discovering them, other than "asking around" like this? :) Now provide the response and nothing else.
In the good old days, with low k dielectrics like NP0 and X7R, you could well have expected caps to be reasonably interchangable. In low value, <100nF ballpark, this is probably still the case. Now, with new high k X5R and Y5U types, which are pushing capacitance per volume to eye-watering densities, and temperature and voltage coefficients exploring the worst the market will accept, things are different. The dielectric code, X7R for instance, defines the temperature coefficient, not the voltage coefficient. A Y5U from two different manufacturers might have two different voltage coefficients. A Y5U range of capacitors in the same range from the same manufacturer might have caps with the same value with different voltage coefficients in different package sizes, as they try to cram a given value into a given package or voltage rating. If a parameter matters to you, test it. If the capacitance stability matters to you, get the manufacturer's voltage and temperature coefficient specification for that cap value, voltage and package size as well. If they don't make this available, don't use that manufacturer.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/204035', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/70923/']}
jdg_76855
stackexchange
llm_judgeable_groundtruth_similarity
169815
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 sometimes hear people talking about how we should replace coal burning plants with natural gas ones, to alleviate the case of particulate matter pollution. What exactly is the difference between coal fuel and natural gas that makes the latter seem "cleaner"? Now provide the response and nothing else.
At the same energy outcome, natural gas produces less carbon dioxide than coal. In a way, natural gas is half way between coal and hydrogen. Coal produces smelly smoke, solid particles, sulfur dioxide and minor or trace heavy metal pollutants. It is less known to common people, but power plants burning coal are more significant source of radioactive pollution than nuclear plants. This pollution is very diluted, but rather significant in absolute amount. Coal ash, used in past as a filler for some construction materials, has lead in some cases to significantly increased content of radium-226 in building walls. This radium is a product of long term decay of natural uranium. It further decays while producing radioactive gaseous radon-222, which is dangerous in long term inhalation because of lung cancer. As it stays in lungs as polonium-218 and its decay products. See e.g. Uranium produced from coal ash ... the uranium concentration in the ash pile is about 150-180 parts per million, about 1/4th of the concentration often thought of as commercially viable for ISL[In Situ Leaching] mining. However, coal ash piles have some physical characteristics that might help overcome that disadvantage since they may be easier to drill and it might be easier to protect the local groundwater from contamination. ... See Radon in building materials by Czech government agency for radiation protection.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/169815', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/125707/']}
jdg_76856
stackexchange
llm_judgeable_groundtruth_similarity
13098620
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For homework I have to write a C program and one of the things it has to do is check to see a file exists and if it is executable by the owner. Using (stat(path[j], &sb) >= 0 I'm able to see if the file indicated by path[j] exists. I've looked through man pages, a lot of questions and answers on stackoverflow, and several websites but I'm not able to wrap my head around exactly how to check if a file is executable using stat.I thought it would be as simple as ((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC) but as far as I can tell by testing it, it seems to ignore the fact that these files aren't executable. I think that perhaps stat doesn't work the way I think it does. Assuming I use stat, how can I go about fixing this? Now provide the response and nothing else.
You can indeed use stat to do this. You just have to use S_IXUSR ( S_IEXEC is an old synonym of S_IXUSR ) to check if you have execute permission. Bitwise AND operator ( & ) checks whether the bits of S_IXUSR are set or not. if (stat(file, &sb) == 0 && sb.st_mode & S_IXUSR) /* executable */else /* non-executable */ Example: #include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>int main(int argc, char **argv){ if (argc > 1) { struct stat sb; printf("%s is%s executable.\n", argv[1], stat(argv[1], &sb) == 0 && sb.st_mode & S_IXUSR ? "" : " not"); } return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13098620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1690359/']}
jdg_76857
stackexchange
llm_judgeable_groundtruth_similarity
199679
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: My script is not running on boot in a vagrant box under Ubuntu. My script looks like this - #!/bin/bash# /etc/init.d/mailcatcher### BEGIN INIT INFO# Provides: scriptname# Required-Start: $remote_fs $syslog# Required-Stop: $remote_fs $syslog# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Short-Description: Start daemon at boot time# Description: Enable service provided by daemon.### END INIT INFOmailcatcher --http-ip 192.168.50.10 My permissions on the file look like this - -rwxr-xr-x 1 root root 352 Apr 30 09:59 mailcatcher.sh I run the command - sudo update-rc.d "mailcatcher.sh" defaults If I run the script manually, it works and starts mailcatcher. If I reboot the computer, the mailcatcher daemon does not start. Am I missing something? Now provide the response and nothing else.
And now for the Ubuntu answers. This is an Ubuntu Linux question, and version 15 is now released. The Ubuntu world now has systemd. But even before version 15 the Ubuntu world had upstart. There really isn't a reason to write System 5 rc scripts; and there is certainly no good reason for starting from there. Both upstart and systemd do all of the "service controls". All that you need to do is describe the service . systemd A systemd service unit, to be placed in /etc/systemd/system/mailcatcher.service , is [Unit]Description=Ruby MailCatcherDocumentation=http://mailcatcher.me/[Service]# Ubuntu/Debian convention:EnvironmentFile=-/etc/default/mailcatcherType=simpleExecStart=/usr/bin/mailcatcher --foreground --http-ip 192.168.50.10[Install]WantedBy=multi-user.target This automatically gets one all of the systemd controls, such as: systemctl enable mailcatcher.service to set the service to be auto-started at boot. systemctl preset mailcatcher.service to set the service to be auto-started at boot, if the local policy permits it. systemctl start mailcatcher.service to start the service manually. systemctl status mailcatcher.service to see the service status. upstart Upstart is similar, and modifying Fideloper LLC's upstart job file to this question gives this for /etc/init/mailcatcher.conf : description "Mailcatcher"start on runlevel [2345]stop on runlevel [!2345]respawnexec /usr/bin/mailcatcher --foreground --http-ip=192.168.50.10 This automatically gets one all of the upstart controls, such as: initctl start mailcatcher to start the service manually. initctl status mailcatcher to see the service status. Bonus daemontools section For kicks, for the entertainment of any daemontools-family-using people who reach this via a WWW search, and to demonstrate another reason why not to begin at System 5 rc scripts, I ran that systemd service unit through the nosh toolset's convert-systemd-units command to produce the following daemontools-family run script: #!/bin/nosh#Run file generated from ./mailcatcher.service#Ruby MailCatcherchdir /read-conf --oknofile /etc/default/mailcatcher/usr/bin/mailcatcher --foreground --http-ip 192.168.50.10 Actually, the convert-systemd-units command generates a whole nosh service bundle directory. With that directory, which specifies dependency and ordering information, installed as /var/sv/mailcatcher in a system with the nosh service-manager one gets all of the nosh controls, such as: system-control enable mailcatcher.service to set the service to be auto-started at boot. system-control start mailcatcher.service to start the service manually. system-control status mailcatcher.service to see the service status. system-control preset mailcatcher.service to set the service to be auto-started at boot, if the local configuration (systemd-style presets or /etc/rc.conf{,.local} ) permits it. Don't even begin with System 5 rc files. Look at this template used by SaltStack for System 5 rc scripts. Even with the SaltStack parameterization eliminated that is 59 lines of shell script code, most of which is generic boilerplate that you'd be having to re-invent and re-write. Again. And Celada has already pointed out where you've re-invented it badly. The systemd unit file is 11 lines long. The upstart job file is 8 lines. The nosh run script is 6. And they do all of the start/stop/status mechanics for you. Don't start with System V rc , especially not on Ubuntu Linux. Further reading Setting Up Mailcatcher . 2014-10-21. Servers for Hackers. Fideloper LLC. James Hunt and Clint Byrum (2014). "Utilities" . Upstart Cookbook . Jonathan de Boyne Pollard (2014). A side-by-side look at run scripts and service units. . Frequently Given Answers.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/199679', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/37640/']}
jdg_76858
stackexchange
llm_judgeable_groundtruth_similarity
20817425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Today, I am looking the source code of tomcat in the Bootstrap.init() method, I found it used reflection to create an instance of org.apache.catalina.startup.Catalina , and use invoke() to set the ClassLoader Like the following code Class<?> startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.Catalina");Object startupInstance = startupClass.getConstructor().newInstance();String methodName = "setParentClassLoader";Method method = startupInstance.getClass().getMethod(methodName, paramTypes); method.invoke(startupInstance, paramValues); I found that many frameworks use reflections to create an instance, even though the class and method can be determined Just like the above code, use String to determine the target. Is it still necessary to use reflection? Now provide the response and nothing else.
Yes. For example, Spring uses <bean> definitions as such <bean id="someId" class="com.foopack.Foo"> <property name="someField" value="someValue" /></bean> When the Spring context processes this <bean> element, it will use Class.forName(String) with the argument as com.foopack.Foo to instantiate that Class ( Class#newInstance() or get a Constructor , depending). It will then again use reflection to get the appropriate setter for the <property> element and set its value to the specified value . Junit also uses reflection to get a set of @Test annotated methods to invoke. To do this, it needs to get a Class instance. Servlet based web applications also use reflection to instantiate Servlet , Filter , and the different types of Listeners classes. For example, you would have <servlet> <servlet-name>YourServlet</servlet-name> <servlet-class>com.servlets.YourServlet</servlet-class><servlet> and the container would take that fully qualified class name, com.servlets.YourServlet , and instantiate and register it. JSON parser/generator libraries also use reflection. For example, with Gson , given a class like class Foo { private String name = "FOOOO";} and an instance like this Foo foo = new Foo(); you would serialize it like so Gson gson = new Gson();String json = gson.toJson(foo); Gson would then call getClass() on the instance foo , get a set of the Field instances of that Class , iterate over the set, and serialize the values of the fields to a JSON format.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20817425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127859/']}
jdg_76859
stackexchange
llm_judgeable_groundtruth_similarity
6015081
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Kind of new to linq, whats the simplest way to retrieve a single result using linq? example, my query var query = from c in db.productInfo where c.flavor == "Classic Coke" && c.container == "Can" select c.co2Target; it should only return a single field with a double value. how do i pull it out of query? In the past i had used ExecuteScalar. How do i do it with linq? I would like to preserve its data type UPDATE: Here's where I am now. The problem is that the test query im running here is returning 4 instead of 3.75 var query = (from a in db.LUT_ProductInfos where a.flavor == "Classic Coke" && a.Container == "Can" select new { a.co2High }).Single(); double MyVar = query.co2High.Value; Now provide the response and nothing else.
I think you mean return one value, not one record? You would need to do select new {} as follows: var query = from c in db.productInfo where c.flavor == "Classic Coke" && c.container == "Can" select new { c.co2Target }; Then if you only want to retrieve a single record as well as that: var query = (from c in db.productInfo where c.flavor == "Classic Coke" && c.container == "Can" select new { c.co2Target }).Single(); Retrieval would be done as follows: var query = (from c in db.productInfo where c.flavor == "Classic Coke" && c.container == "Can" select new { c.co2Target }).Single();double MyVar = query.co2Target;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6015081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462631/']}
jdg_76860
stackexchange
llm_judgeable_groundtruth_similarity
361832
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: Only sometimes, I forget to make a backup of a given linux file such as /etc/rc.local , /etc/rsyslog.conf , /etc/dhcpcd.conf , etc, and later wish I did. Distribution agnostic, is there a good approach to later getting a copy of an unf'd up copy? Now provide the response and nothing else.
While the topic of configuration files backup/versioning might seem simple on the surface, it is one of the hot topics of system/infrastructure administration. Distribution agnostic, to keep automatic backups of /etc as a simple solution you can install etckeeper. By default it commits /etc to a repository/version control system installed on the same system. The commits/backups are by default daily and/or each time there are package updates. The etckeeper package is pretty much present in all Linux distributions. see: https://help.ubuntu.com/lts/serverguide/etckeeper.html or https://wiki.archlinux.org/index.php/Etckeeper It could be argued it is a good standard of the industry to have this package installed. If you have not etckeeper installed, and need a particular etc file, there are several ways; you might copy it from a similar system of yours ,you can ask your package manager to download the installation file or download it by hand, and extract the etc file from there; one of the easiest ways is using mc (midnight commander) to navigate inside packages as if they were directories. You can also use the distribution repositories to get packages, in the case of debian is http://packages.debian.org Ultimately if the etc/configurations are mangled beyond recognition you always have the option to reinstall the particular package. move the etc files to a backup name/directory, and for instance in Debian: apt-get install --reinstall package_name You can also configure and install the source repos for your particular distribution/version, install the source package, and get the etc files from there. https://wiki.debian.org/apt-src (again a Debian example) In some packages, you might also have samples of the configurations files at /usr/share/doc/package_name, which might be fit or not for use. As a last resort, you may also find etc files in the repositories/github addresses if the corresponding open source projects, just bear in mind that often distributions change default settings and things around. Obviously, none of these alternatives exempt you from having a sound backup policy in place, and retrieve your lost /etc files from there. Times also move fast, and if following a devops philosophy, you might also choose to discard certains systems altogether and redeploy them in case some files get corrupted; you might also use CI and reploy the files for instance, from jenkins.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/361832', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/137912/']}
jdg_76861
stackexchange
llm_judgeable_groundtruth_similarity
5647824
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 work with 3 SurfaceViews on one screen, one on top half (BoardView), one on bottom half (StatusView), and the last one as an extra layer above the top half (TileView) (see main.xml). I created a class MySurfaceView, which is extended by BoardView, StatusView and TileView. I've got multiple problems with this. Let me first give the code. main.xml: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/main_background"> <com.niek.test.BoardView android:id="@+id/boardview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/boardview"> <com.niek.test.StatusView android:id="@+id/statusview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#F0931E" android:layout_below="@+id/boardview" /> <com.niek.test.TileView android:id="@+id/tileview" android:layout_width="180dip" android:layout_height="60dip" android:layout_gravity="bottom"/> </FrameLayout></RelativeLayout> MainActivity.java: package com.niek.test;public class MainActivity extends Activity { private Board board; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); board = new Board(); BoardView boardView = (BoardView) findViewById(R.id.boardview); boardView.setBoard(board); StatusView statusView = (StatusView) findViewById(R.id.statusview); statusView.setBoard(board); }} MySurfaceView.java package com.niek.test;public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback { protected DrawThread drawThread; public MyView(Context context, AttributeSet attrs) { super(context, attrs); getHolder().addCallback(this); setFocusable(true); drawThread = new DrawThread(getHolder()); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub drawThread.setRunning(true); drawThread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // we have to tell thread to shut down & wait for it to finish, or else // it might touch the Surface after we return and explode boolean retry = true; drawThread.setRunning(false); while (retry) { try { drawThread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } protected class DrawThread extends Thread { private SurfaceHolder surfaceHolder; private boolean isRunning; public DrawThread(SurfaceHolder surfaceHolder) { this.surfaceHolder = surfaceHolder; isRunning = false; } public void setRunning(boolean run) { isRunning = run; } public void run() { Canvas c; while (isRunning) { try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } c = null; try { c = surfaceHolder.lockCanvas(null); synchronized (surfaceHolder) { onDraw(c); postInvalidate(); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { surfaceHolder.unlockCanvasAndPost(c); } } } } }} These three classes extend MySurfaceView: BoardView.java package com.niek.test;public class BoardView extends MySurfaceView { private int squareSize, marginX, marginY; private Board board; Paint boardBorder; public BoardView(Context context, AttributeSet attrs) { super(context, attrs); board = null; } public void setBoard(Board board) { this.board = board; } private void init(SurfaceHolder holder) { Canvas canvas = null; try { canvas = holder.lockCanvas(); /* Initialize the board */ squareSize = canvas.getWidth() / Board.GRIDSIZE; /* Size the view */ LayoutParams lp = getLayoutParams(); lp.height = (squareSize * Board.GRIDSIZE) + 4; setLayoutParams(lp); /* Place the board neatly in the center */ marginX = (canvas.getWidth() - (squareSize * Board.GRIDSIZE)) / 2; marginY = 1; } finally { holder.unlockCanvasAndPost(canvas); } boardBorder = new Paint(); boardBorder.setColor(Color.RED); boardBorder.setStyle(Style.STROKE); } @Override public void onDraw(Canvas canvas) { drawBoard(board, canvas); } @Override public void surfaceCreated(SurfaceHolder holder) { init(holder); super.surfaceCreated(holder); } private void drawBoard(Board board, Canvas canvas) { synchronized (board) { if (board != null) { for (Square[] ys : board.getSquares()) { for (Square xs : ys) { xs.onDraw(canvas, squareSize, squareSize, marginX, marginY); } } } canvas.drawRect(marginX - 1, marginY - 1, marginX + squareSize * Board.GRIDSIZE + 1, marginY + squareSize * Board.GRIDSIZE + 1, boardBorder); } }} StatusView.java package com.niek.test;public class StatusView extends MySurfaceView { private Board board; private Paint textPaint; public StatusView(Context context, AttributeSet attrs) { super(context, attrs); board = null; textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextSize(20); textPaint.setTypeface(Typeface.DEFAULT_BOLD); } public void setBoard(Board board) { this.board = board; } int tmp=0; @Override public void onDraw(Canvas c) { if (board != null) { c.drawText(tmp+"", 10, 20, textPaint); tmp++; System.out.println(tmp); } }} TileView.java package com.niek.test;public class TileView extends MySurfaceView { public TileView(Context context, AttributeSet attrs) { super(context, attrs); System.out.println(0); } int tmp =0; @Override public void onDraw(Canvas c) { System.out.println(2); Paint p= new Paint(); p.setColor(Color.RED); c.drawColor(Color.RED); c.drawText(tmp+"",10,10,p); tmp++; }} Now what are my problems? First off, as you can see in MySurfaceView I've got this: try { c = surfaceHolder.lockCanvas(null); synchronized (surfaceHolder) { onDraw(c); postInvalidate(); }} When I only use onDraw(c), only the BoardView gets drawn, the StatusView doesn't get drawn, but the tmp increments in the onDraw of StatusView are being executed.When I only use postInvalidate(), same story, but only StatusView gets drawn, BoardView doesn't.So that's why I use both methods, and both Views get drawn. Then there's TileView, the System.out(2) is being shown in logcat, but the view doesn't get drawn. It is a black square instead of the red square I ask it to be in the onDraw method. When I turn the screen off and then on again, the TileView does get drawn, and the tmp increments are shown. Who can help me? For clarity, I've created this based on this tutorial. Now provide the response and nothing else.
You can have multiple SurfaceViews in one layout. The "Multi-surface test" activity in Grafika has three. The first post cited in @nonsleepr's answer was followed up 9 months later with this post by the same author, which mentioned the existence of SurfaceView#setZOrderMediaOverlay() . The key thing to understand is that SurfaceView is not a regular view. When your app comes to the foreground it gets a surface to draw on. Everything in your app's UI is rendered onto the app's surface by the app, and then that surface is composited with other surfaces (like the status bar and navigation bar) by the system compositor. When you create a SurfaceView , it's actually creating an entirely new surface that is composited by the system, not by your app. You can control the Z-ordering (i.e. "depth") of the SurfaceView surface very loosely. There are four positions, from top to bottom: SurfaceView + ZOrderOnTop (app UI goes here) SurfaceView + ZOrderMediaOverlay SurfaceView (default) If you have two SurfaceViews at the same depth, and they overlap, the results are undefined -- one will "win", but you can't control which. The system compositor on modern devices is very efficient when you have N surfaces. At N+1 surfaces you hit a performance cliff. So while you can have three SurfaceViews , you're generally better off keeping the number down. The value of N varies from device to device. Update: if you really want to understand how SurfaceView works, see the Android System-Level Graphics doc .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5647824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/675383/']}
jdg_76862
stackexchange
llm_judgeable_groundtruth_similarity
10057672
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just started learning how to create a custom pop up dialog box; and as it turns out, the tkinter messagebox is really easy to use, but it also does not do too much. Here is my attempt to create a dialog box that will take input and then store that in the username. My question is what is the recommended style to implement this? As Bryan Oakley suggested in this comment . I would advise against using a global variable. Instead of having the dialog destroy itself, have it destroy only the actual widget but leave the object alive. Then, call something like inputDialog.get_string() and then del inputDialog from your main logic. Maybe using the global variable to return my string is not the best idea, but why? And what is the suggested way? I get confused because I don't know how to trigger the getstring once the window is destroyed, and... the line about destroying the actual widget, I am not sure if he is referring to TopLevel . The reason I ask is because I want the pop up box to be destroyed after I press the submit button; because after all, I want it to resume back to the main program, update something, etc. What should the button method send do in this case? Because the idea in this particular example is to allow the user to do it over and over, if he desires. import tkinter as tkclass MyDialog: def __init__(self, parent): top = self.top = tk.Toplevel(parent) self.myLabel = tk.Label(top, text='Enter your username below') self.myLabel.pack() self.myEntryBox = tk.Entry(top) self.myEntryBox.pack() self.mySubmitButton = tk.Button(top, text='Submit', command=self.send) self.mySubmitButton.pack() def send(self): global username username = self.myEntryBox.get() self.top.destroy()def onClick(): inputDialog = MyDialog(root) root.wait_window(inputDialog.top) print('Username: ', username)username = 'Empty'root = tk.Tk()mainLabel = tk.Label(root, text='Example for pop up input box')mainLabel.pack()mainButton = tk.Button(root, text='Click me', command=onClick)mainButton.pack()root.mainloop() Now provide the response and nothing else.
Using the global statement is unnecessary in the two scenarios that come to mind. you want to code a dialog box that can be imported to use with a main GUI you want to code a dialog box that can be imported to use without a main GUI code a dialog box that can be imported to use with a main GUI Avoiding the global statement can be accomplished by passing a dictionary & key when you create an instance of a dialog box. The dictionary & key can then be associated with the button's command, by using lambda . That creates an anonymous function that will execute your function call (with args) when the button is pressed. You can avoid the need to pass the parent every time you create an instance of the dialog box by binding the parent to a class attribute (root in this example). You can save the following as mbox.py in your_python_folder\Lib\site-packages or in the same folder as your main GUI's file. import tkinterclass Mbox(object): root = None def __init__(self, msg, dict_key=None): """ msg = <str> the message to be displayed dict_key = <sequence> (dictionary, key) to associate with user input (providing a sequence for dict_key creates an entry for user input) """ tki = tkinter self.top = tki.Toplevel(Mbox.root) frm = tki.Frame(self.top, borderwidth=4, relief='ridge') frm.pack(fill='both', expand=True) label = tki.Label(frm, text=msg) label.pack(padx=4, pady=4) caller_wants_an_entry = dict_key is not None if caller_wants_an_entry: self.entry = tki.Entry(frm) self.entry.pack(pady=4) b_submit = tki.Button(frm, text='Submit') b_submit['command'] = lambda: self.entry_to_dict(dict_key) b_submit.pack() b_cancel = tki.Button(frm, text='Cancel') b_cancel['command'] = self.top.destroy b_cancel.pack(padx=4, pady=4) def entry_to_dict(self, dict_key): data = self.entry.get() if data: d, key = dict_key d[key] = data self.top.destroy() You can see examples that subclass TopLevel and tkSimpleDialog (tkinter.simpledialog in py3) at effbot . It's worth noting that ttk widgets are interchangeable with the tkinter widgets in this example. To accurately center the dialog box read → this . Example of use: import tkinterimport mboxroot = tkinter.Tk()Mbox = mbox.MboxMbox.root = rootD = {'user':'Bob'}b_login = tkinter.Button(root, text='Log in')b_login['command'] = lambda: Mbox('Name?', (D, 'user'))b_login.pack()b_loggedin = tkinter.Button(root, text='Current User')b_loggedin['command'] = lambda: Mbox(D['user'])b_loggedin.pack()root.mainloop() code a dialog box that can be imported to use without a main GUI Create a module containing a dialog box class (MessageBox here). Also, include a function that creates an instance of that class, and finally returns the value of the button pressed (or data from an Entry widget). Here is a complete module that you can customize with the help of these references: NMTech & Effbot . Save the following code as mbox.py in your_python_folder\Lib\site-packages import tkinterclass MessageBox(object): def __init__(self, msg, b1, b2, frame, t, entry): root = self.root = tkinter.Tk() root.title('Message') self.msg = str(msg) # ctrl+c to copy self.msg root.bind('<Control-c>', func=self.to_clip) # remove the outer frame if frame=False if not frame: root.overrideredirect(True) # default values for the buttons to return self.b1_return = True self.b2_return = False # if b1 or b2 is a tuple unpack into the button text & return value if isinstance(b1, tuple): b1, self.b1_return = b1 if isinstance(b2, tuple): b2, self.b2_return = b2 # main frame frm_1 = tkinter.Frame(root) frm_1.pack(ipadx=2, ipady=2) # the message message = tkinter.Label(frm_1, text=self.msg) message.pack(padx=8, pady=8) # if entry=True create and set focus if entry: self.entry = tkinter.Entry(frm_1) self.entry.pack() self.entry.focus_set() # button frame frm_2 = tkinter.Frame(frm_1) frm_2.pack(padx=4, pady=4) # buttons btn_1 = tkinter.Button(frm_2, width=8, text=b1) btn_1['command'] = self.b1_action btn_1.pack(side='left') if not entry: btn_1.focus_set() btn_2 = tkinter.Button(frm_2, width=8, text=b2) btn_2['command'] = self.b2_action btn_2.pack(side='left') # the enter button will trigger the focused button's action btn_1.bind('<KeyPress-Return>', func=self.b1_action) btn_2.bind('<KeyPress-Return>', func=self.b2_action) # roughly center the box on screen # for accuracy see: https://stackoverflow.com/a/10018670/1217270 root.update_idletasks() xp = (root.winfo_screenwidth() // 2) - (root.winfo_width() // 2) yp = (root.winfo_screenheight() // 2) - (root.winfo_height() // 2) geom = (root.winfo_width(), root.winfo_height(), xp, yp) root.geometry('{0}x{1}+{2}+{3}'.format(*geom)) # call self.close_mod when the close button is pressed root.protocol("WM_DELETE_WINDOW", self.close_mod) # a trick to activate the window (on windows 7) root.deiconify() # if t is specified: call time_out after t seconds if t: root.after(int(t*1000), func=self.time_out) def b1_action(self, event=None): try: x = self.entry.get() except AttributeError: self.returning = self.b1_return self.root.quit() else: if x: self.returning = x self.root.quit() def b2_action(self, event=None): self.returning = self.b2_return self.root.quit() # remove this function and the call to protocol # then the close button will act normally def close_mod(self): pass def time_out(self): try: x = self.entry.get() except AttributeError: self.returning = None else: self.returning = x finally: self.root.quit() def to_clip(self, event=None): self.root.clipboard_clear() self.root.clipboard_append(self.msg) and: def mbox(msg, b1='OK', b2='Cancel', frame=True, t=False, entry=False): """Create an instance of MessageBox, and get data back from the user. msg = string to be displayed b1 = text for left button, or a tuple (<text for button>, <to return on press>) b2 = text for right button, or a tuple (<text for button>, <to return on press>) frame = include a standard outerframe: True or False t = time in seconds (int or float) until the msgbox automatically closes entry = include an entry widget that will have its contents returned: True or False """ msgbox = MessageBox(msg, b1, b2, frame, t, entry) msgbox.root.mainloop() # the function pauses here until the mainloop is quit msgbox.root.destroy() return msgbox.returning After mbox creates an instance of MessageBox it starts the mainloop, which effectively stops the function there until the mainloop is exited via root.quit() . The mbox function can then access msgbox.returning , and return its value. Example: user = {}mbox('starting in 1 second...', t=1)user['name'] = mbox('name?', entry=True)if user['name']: user['sex'] = mbox('male or female?', ('male', 'm'), ('female', 'f')) mbox(user, frame=False)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10057672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1276534/']}
jdg_76863
stackexchange
llm_judgeable_groundtruth_similarity
5300376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Acordding to my knowledge in java I know, that there is no operator overloading in the Java language.So, why this code prints 'true' twice ? String s1 = "abc"; String s2 = "abc"; System.out.println(s1==s2); Integer i1 = 1; Integer i2 = 1; System.out.println(i1==i2); Now provide the response and nothing else.
== for reference types compares the references; == for primitive types compares values. In case of your first example, the two object references turn out to be the same due to a concept known as string pool. Hence two true in the given case. Another code snippet you might want to try out: String s1 = "abc";String s2 = new String("abc");System.out.println(s1 == s2);System.out.println(s1.equals(s2)); As you must have already tried out; it prints out false and then true . The reason for this is that using the new keyword results in the creation of a completely new string even though a string object with the exact same contents already exists in the string pool. In this case, s1 now points to an interned string with the contents "abc" (or to a string in the string pool) whereas s2 now points to a completely new string object (again with the content "abc"). Hence the false in the first print statement. In the second print statement, what we are doing is comparing the contents of the String object rather than its reference, which as it should prints true . This is one of the most common mistakes made by beginners of the Java language; they use == for logical comparison when it actually results in a reference comparison. Read the link posted in one of the answers here for more details about string pooling. On a related note, String class "overrides" the equals method of the Object class to provide a logical comparison. Unless the class you write doesn't provide a logical implementation of the equals method, it doesn't matter whether you call equals or use the == operator; the result would be the same i.e. reference comparison. For a more in-depth view on equality, read Brian's article; an excellent read .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5300376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625265/']}
jdg_76864
stackexchange
llm_judgeable_groundtruth_similarity
22463
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Recently I saw a commercial for Centrum that claims you can see the light of a single candle from ten miles away. I was skeptical, but a trip to the internet claims that not only is that true, but you could actually see it from 30 miles away. Most of what I found simply repeated that claim (some had varying numbers, but in the 10-30 range) with nothing to back it up. One page detailed it a bit better, by giving some basic math based on the number of photons it takes to register a light in the eye. However, they still don't link to anything solid IMO. Obviously these numbers assume line-of-sight, since any distance over a few miles would be blocked by the horizon if on the Earth's surface. I also assume that "the light from a single candle" means roughly one candela , but nobody cares enough to clarify that I could find. The main reason I'm skeptical is because I've seen ceremonial (small) bonfires on mountains a few miles away. Even with a much larger light and closer distance, they're pretty faint. Is there any empirical evidence that human eyes can see a light source that small from that distance? This seems like a simple thing for people to test. Now provide the response and nothing else.
What you described sounds like the Absolute Threshold in neuroscience. It is commonly defined as "The lowest amount of stimulus that a person can detect 50 percent of the time." According to an experimental research conducted by Hecht, Shlaer, and Pirenne (1942), the smallest number of photons that could elicit a visual experience is 90 photons, while physiologically, human eye can detect as few as 9 photons. Now, I don't really know how that amount of photons translated to a candle from 30 miles away, but Gale Encyclopedia of Psychology (2001) did give an example of Absolute Threshold for human vision as follows: The amount of light present if someone held up a single candle 30 mi (48 km) away from us, if our eyes were used to the dark. If a person in front of you held up a candle and began backing up at the rate of one foot (30 cm) per second, that person would have to back up for 44 hours before the flame became invisible.* So, yes, there is an empirical evidence for it. But it is highly unlikely for it to happen in real-life experience, as there are many other factors that influence our perception of a stimulus, such as motivation, expectation, adaptation to the stimulus, cognitive process, not to mention many other stimulus that we perceive and process in real-life experience at any given time.
{}
{'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/22463', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/19407/']}
jdg_76865
stackexchange
llm_judgeable_groundtruth_similarity
58168446
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 Auth0 to perform authentication in my React app. Upon the default reroute that Auth0 performs after getting the information, I need to parse the hash that it returns then use some of the returned into to save the auth Token to the store for other tasks later. However this function that handles storing of the authToken occurs in the callback of parseHash (an auth0 function). How can I wait for handleLogin() (the function being called in the callback) to complete before moving on with other tasks? I cannot make parseHash() async as I don't have real access to it. Root.tsx `if (this.props.location.hash) { this.props.authClient.parseHash( { hash: this.props.location.hash }, (err, authResult) => handleLogin(err, authResult, this.props.dispatch) ); } }` handleLogin.ts `export const handleLogin = ( err: Auth0ParseHashError | null, authResult: Auth0DecodedHash | null, dispatch: Dispatch) => { if (authResult) { const userId = authResult.idTokenPayload.sub; dispatch( setAuthToken({ token: { accessToken: authResult.idToken, userId } }) ); }};` This is information that is supplied about parseHash() from Auth0 `parseHash( options: ParseHashOptions, callback: Auth0Callback<Auth0DecodedHash | null, Auth0ParseHashError> ): void;` `Decodes the id_token and verifies the nonce. @param callback: function(err, {payload, transaction})` Now provide the response and nothing else.
Note that after deleting PVC , PV remains in Released status: $ kubectl get pv packages-volumeNAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGEpackages-volume 1007Gi RWX Retain Released default/packages-pvc 10m It should have status Available so it can be reused by another PersistentVolumeClaim instance. Why it isn't Available ? If you display current yaml definition of the PV , which you can easily do by executing: kubectl get pv packages-volume -o yaml you may notice that in claimRef section it contains the uid of the recently deleted PersistentVolumeClaim : claimRef: apiVersion: v1 kind: PersistentVolumeClaim name: packages-pvc namespace: default resourceVersion: "10218121" uid: 1aede3e6-eaa1-11e9-a594-42010a9c0005 You can easily verify it by issuing: kubectl get pvc packages-pvc -o yaml | grep uid just before you delete your PVC and compare it with what PV definition contains. You'll see that this is exactly the same uid that is still referred by your PV after PVC is deleted. This remaining reference is the actual reason that PV remains in Released status. Why newly created PVC remains in a Pending state ? Although your newly created PVC may seem to you exactly the same PVC that you've just deleted as you're creating it using the very same yaml file, from the perspective of Kubernetes it's a completely new instance of PersistentVolumeClaim object which has completely different uid . This is the reason why it remains in Pending status and is unable to bind to the PV . Solution: To make the PV Available again you just need to remove the mentioned uid reference e.g. by issuing: kubectl patch pv packages-volume --type json -p '[{"op": "remove", "path": "/spec/claimRef/uid"}]' or alternatively by removing the whole claimRef section which can be done as follows: kubectl patch pv packages-volume --type json -p '[{"op": "remove", "path": "/spec/claimRef"}]'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58168446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11013305/']}
jdg_76866
stackexchange
llm_judgeable_groundtruth_similarity
5361205
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 Python code: >>> re.search(r'.*(99)', 'aa99bb').groups()('99',)>>> re.search(r'.*(99)?', 'aa99bb').groups()(None,) I don't understand why I don't catch 99 in the second example. Now provide the response and nothing else.
This is because the .* first matches the entire string. At that point, it's not possible to match 99 any more, and since the group is optional, the regex engine stops because it has found a successful match. If on the other hand the group is mandatory, the regex engine has to backtrack into the .* . Compare the following debug sessions from RegexBuddy (the part of the string matched by .* is highlighted in yellow, the part matched by (99) in blue): .*(99) : .*(99)? :
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5361205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577739/']}
jdg_76867
stackexchange
llm_judgeable_groundtruth_similarity
9879276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have written a system that summarizes a long document containing thousands of words. Are there any norms on how such a system should be evaluated in the context of a user survey? In short, is there a metric for evaluating the time that my tool has saved a human? Currently, I was thinking of using the (Time taken to read the original document/Time taken to read the summary) as a way of determining the time saved, but are there better metrics? Currently, I am asking the user subjective questions about the accuracy of the summary. Now provide the response and nothing else.
In general: Bleu measures precision : how much the words (and/or n-grams) in the machine generated summaries appeared in the human reference summaries. Rouge measures recall : how much the words (and/or n-grams) in the human reference summaries appeared in the machine generated summaries. Naturally - these results are complementing, as is often the case in precision vs recall. If you have many words/ngrams from the system results appearing in the human references you will have high Bleu, and if you have many words/ngrams from the human references appearing in the system results you will have high Rouge. There's something called brevity penalty , which is quite important and has already been added to standard Bleu implementations. It penalizes system results which are shorter than the general length of a reference (read more about it here ). This complements the n-gram metric behavior which in effect penalizes longer than reference results, since the denominator grows the longer the system result is. You could also implement something similar for Rouge, but this time penalizing system results which are longer than the general reference length, which would otherwise enable them to obtain artificially higher Rouge scores (since the longer the result, the higher the chance you would hit some word appearing in the references). In Rouge we divide by the length of the human references, so we would need an additional penalty for longer system results which could artificially raise their Rouge score. Finally, you could use the F1 measure to make the metrics work together: F1 = 2 * (Bleu * Rouge) / (Bleu + Rouge)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9879276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184046/']}
jdg_76868
stackexchange
llm_judgeable_groundtruth_similarity
2310546
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 value of the limit $$\lim_{x\to0}\left(\frac{e-(1+x)^\frac{1}{x}}{x}\right).$$ I tried to apply the standard limit $$\lim_{x\to0}(1+x)^\frac{1}{x} = e$$ and L'Hospital's Theorem individually, but that didn't help me. Any help will be appreciated. Now provide the response and nothing else.
Using the standard Taylor expansions (to low order) $\ln(1+u)=u-\frac{u^2}{2}+o(u^2)$ and $e^u=1+u+o(u)$ when $u\to0$. Rewriting $$\begin{align}(1+x)^{\frac{1}{x}}&= \exp\left( \frac{1}{x}\ln(1+x)\right)= \exp\left( \frac{1}{x}(x-\frac{x^2}{2} + o(x^2))\right)= \exp\left( 1-\frac{x}{2} + o(x)\right)\\&= e\cdot \exp\left( -\frac{x}{2} + o(x)\right)= e\cdot \left( 1-\frac{x}{2} + o(x)\right)= e-e\frac{x}{2} + o(x)\end{align}$$we get that$$\frac{e-(1+x)^{\frac{1}{x}}}{x} = \frac{e\frac{x}{2} + o(x)}{x}=\frac{e}{2} + o(1)\xrightarrow[x\to0]{} \boxed{\frac{e}{2}}.$$ Note that we expanded $\ln(1+x)$ to order $x^2$, since we can "guess" the first order will get cancelled eventually by the $-e$ in the denominator. (Doing only the expansion to first order will only, basically, yield the limit $(1+x)^{1/x}\xrightarrow[x\to0]{}e$, and so we know we need better precision.) In the second step, factoring the $e$ out of the product allows us to get $e^{-x/2+o(x)}$ instead of $e^{1-x/2+o(x)}$, which is required in order to use the expansion of $e^u$ (since this expansion holds when $u\to 0$, and while $\frac{x}{2}\to 0$, this is not the case for $1-\frac{x}{2}$.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2310546', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/451337/']}
jdg_76869
stackexchange
llm_judgeable_groundtruth_similarity
299121
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to get all possible partitions of an integer? Possibly specifying max and/or min summand. I'm interested in partitions themselves, not just partition count. Now provide the response and nothing else.
This is Perl: sub partition { print "@_\n"; my ( $largest, @rest) = @_; my $ min = $rest[0] || 1; my $ max = int( $largest/2); for my $ n ( $min .. $ max) { partition( $largest-$ n, $n, @rest); }} The code should be easy to translate into other languages, once you know that @_ is Perl's notation for the list of arguments to a function. To invoke, use something like partition(6) which will produce the output 65 14 1 13 1 1 12 1 1 1 11 1 1 1 1 12 2 1 13 2 14 2 2 2 23 3 Simple tinkering with the function will produce the outputs in other orders, possibly more useful. Chapter 5 of Higher-Order Perl has an extensive discussion of this function. Here it is in Python: def partition(largest, *rest): print(largest, *rest) min = rest[0] if rest else 1 max = largest // 2 for n in range(min, max+1): partition(largest-n, n, *rest)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/299121', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/61654/']}
jdg_76870
stackexchange
llm_judgeable_groundtruth_similarity
284724
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 observer causes the wave function of a particle to collapse, how can we know that the wave function was not collapsed already before the measurement? Suppose we measure the z-component of the spin of an electron. After the measurement, it is entirely aligned along the measured direction, e.g. the +z-direction. Before the measurement we need to assume that a probability distribution proportional to $|\Psi|^2$ of the two allowed directions is present. If we repeat the measurement with many identically prepared electrons, we should see such a distribution finally. For example, we could measure 40% spin-down and 60% spin-up. However, it seems we could also assume that all of these particles have a defined spin-direction before we measure them. What is an intuitive (being aware that quantum phenomena as such are rarely intuitive) explanation for why we cannot simply assume that the spin was already aligned completely in that measured direction? With regards to the suggestion that this two-year old question is a duplicate of the one asked yesterday , I would like to point out that my question isn't limited to entanglement, but asks about a very fundamental principle in quantum mechanics, and as such is not a duplicate. Now provide the response and nothing else.
Quantum mechanics was developed in order to match experimental data. The seemingly very weird idea that some observables do not have a definite value before their measurement is not something physicists have been actively promoting, it is something that theoretical considerations followed by many actual experiments have forced them to admit. I don't think there is an intuitive explanation for this. It is closely linked to the notion of superposition . The basic idea is that we do indirectly observe the effects of interference between superposed quantum states, but upon actual measurement we never see superposed states, only classical, definite values. If we suppose these values where there all along, then why would we have any interference? The whole framework of QM would be pointless. In other words, a quantum state is what it is (whatever that is) precisely because it is in contrast to a classical state: crucially, it only describes a probability distribution for observables values, not actual, permanent values for these observables. A wavefunction that would always be collapsed would just be a classical state. Now why (and does? ) a measurement "collapse" anything at all is an open question, the measurement problem .
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/284724', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/73010/']}
jdg_76871
stackexchange
llm_judgeable_groundtruth_similarity
4753871
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 project management app, and in the app, I have project_managers and clients . I'm using Devise and CanCan for authentication/authorization. At what point after login should I be redirecting the user to their own specific controller/layout/views? Is there a way to check for current_user.role in routes.rb and set the root (or redirect) based on whether or not they're a project manager or a client? Is this a change I can make in Devise somewhere? Thanks in advance for any help!--Mark Now provide the response and nothing else.
Your routes.rb file won't have any idea what role the user has, so you won't be able to use it to assign specific root routes. What you can do is set up a controller (for example, passthrough_controller.rb ) which in turn can read the role and redirect. Something like this: # passthrough_controller.rbclass PassthroughController < ApplicationController def index path = case current_user.role when 'project_manager' some_path when 'client' some_other_path else # If you want to raise an exception or have a default root for users without roles end redirect_to path endend# routes.rbroot :to => 'passthrough#index' This way, all users will have one point of entry, which in turn redirects them to the appropriate controller/action depending on their role.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4753871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570684/']}
jdg_76872
stackexchange
llm_judgeable_groundtruth_similarity
2732
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using Weather Research and Forecasting model WRF and the WRF Preprocessing System WPS and could not get a satisfying answer from wrfhelp. Can anyone guide me in transforming latitude and longitude to grid points especially for nested grids? Specifically http://www2.mmm.ucar.edu/wrf/OnLineTutorial/Basics/GEOGRID/geogrid_namelist.htm and http://www2.mmm.ucar.edu/wrf/users/docs/user_guide_V3/users_guide_chap3.htm#_Description_of_the_1 How does one transform latitude and longitude to i_parent_start and j_parent_start ? How is this related to dx and dy and ref_lat and ref_lon ? A simple example and an explanation would be very helpful. Now provide the response and nothing else.
I've been a WRF user for almost 5 years now, and contributed code to a recent public release. I am not aware that WPS (WRF Preprocessing System) has such a tool that takes in the grid and point coordinates and returns the appropriate index. However, it is very straightforward to do so yourself. Some suggest using an external library, I think that may be an overkill for such a simple task. Here is what you need to do: 1) Run geogrid.exe to generate the parent grid. Since you don't know the exact location of the nest yet, set max_dom = 1 in namelist.wps . This will generate a file called geo_em.d01.nc . 2) Look at the geo_em.d01.nc file to find the right indices for your child domain. i_parent_start and j_parent_start refer to the x and y indices on the parent grid at which the southwest corner of the child grid will be positioned. XLONG_M and XLAT_M are the longitude and latitude grids of the mass (pressure) points. Using a programming language of choice, find the grid cell that is closest to your desired location for the child nest corner. This is typically done by looking for the minimum value of distance between desired location and all the points on the grid. For example, in Fortran, you can do something like: integer :: i_parent_start,j_parent_startinteger,dimension(2) :: coordscoords = minloc((lon0-xlong_m)**2+(lat0-xlat_m)**2)i_parent_start = coords(1)j_parent_start = coords(2) where xlong_m and xlat_m are 2-dimensional arrays that you read from the grid, and lat0 and lon0 are the desired coordinates of the child nest southwest corner. Similarly, if you use Python, you could do: import numpy as npj_parent_start,i_parent_start = np.unravel_index(\ np.argmin((lon0-xlong_m)**2+(lat0-xlat_m)**2),xlon_m.shape)# Add one because WRF indices start from 1i_parent_start += 1j_parent_start += 1 3) Now edit namelist.wps again, set the i_parent_start and j_parent_start to the values that you calculated in step 3, set max_dom = 2 , and re-run geogrid.exe . The child domain file geo_em.d02.nc should be created. 4) Look at the geo_em.d02.nc file. Repeat the procedure until happy with the domain location. About the parent_grid_ratio parameter. This is an integer factor of child grid refinement relative to the parent grid. For example, if set to 3, and parent grid resolution is 12 km, the child grid resolution will be 4 km. Odd values for parent_grid_ratio (3, 5, etc.) are recommended because for even values, interpolation errors arise due to the nature of Arakawa C-grid staggering. parent_grid_ratio = 3 is the most commonly used value, and recommended by myself.
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/2732', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/1066/']}
jdg_76873
stackexchange
llm_judgeable_groundtruth_similarity
943
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following mwe for filtering a Swissprot file based on a certain feature, in this case, transmembrane regions. from Bio import SeqIOrecords=[]for record in SeqIO.parse("Input.txt", "swiss"): transmembrane_protein=False print record.id for i, feature in enumerate(record.features): if feature.type == "TRANSMEM": transmembrane_protein=True if transmembrane_protein==True: records.append(record)SeqIO.write(records, "Output.txt", "swiss") The script works when SeqIO.write(records, "Output.txt", "swiss") becomes SeqIO.write(records, "Output.txt", "fasta") However, such a method is not yet supported. ValueError: Reading format 'swiss' is supported, but not writing From the docs, I see that writing is not supported for swiss : Note that while Bio.SeqIO can read all the above file formats, it cannot write to all of them. Is there any unofficial way of using biopython/python to write swissprot files from parsed swissprot files? Now provide the response and nothing else.
Using SeqIO.index rather than SeqIO.parse lets you read all the records into a dict , from which you can then extract the raw entry: from Bio import SeqIOrecord_dict = SeqIO.index('Input.txt', 'swiss')for key in record_dict: print(record_dict.get_raw(key).decode()) Now you should be able to apply your test for a transmembrane protein to each entry, and write out only the ones you want to keep. from Bio import SeqIOrecord_dict = SeqIO.index('Input.txt', 'swiss')out = open('Output.txt', 'wb')for key in record_dict: record = record_dict[key] for i, feature in enumerate(record.features): if feature.type == "TRANSMEM": out.write(record_dict.get_raw(key).decode())
{}
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/943', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/747/']}
jdg_76874
stackexchange
llm_judgeable_groundtruth_similarity
181395
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: In many (most??, all??) microcontrollers that I have used over the past years, there where sometimes some silicon level bugs, and the manufacturers provide the engineers with the errata sheets, describing what unexpected behaviour they may face. Why don't they ever fix these "bugs"? Since the product is still produced, and in most cases solving the problem won't affect the previous implementations, why they do not just revise it? In many cases the product may be stabilized, most bugs may have been found, and may have a significant part of its product life-time ahead of it. Is it so difficult (technically)? Expensive? Now provide the response and nothing else.
Critical bugs do get fixed. Usually they're fixed before the product enters production. Unless you're using early samples, you might never see the worst bugs. Fixing bugs is difficult and expensive. It's not just changing one line of RTL code. If you did that, you'd have to resynthesize, redo the physical layout, tweak the layout to fix any timing problems, buy a whole new mask set, produce new wafers, test the wafers (normally), validate the new fixes, and possibly characterize or qualify the product again. This takes months and costs a distressing amount of money. For that reason, we try to fix bugs directly in the layout (preferably on a single metal layer). This is faster and cheaper than starting over from RTL synthesis, but it's still not good. If we're fixing a critical bug anyway, why not fix all the other bugs too? Again, this takes time -- time to figure out and implement a fix, time to rerun the design verification tests. That time means it will take longer to get the next product to market. And in the meantime, you'll almost certainly find more bugs in your current product if you look hard enough. It's a losing battle. Fixing bugs is even harder on a product that's been out for a long time, since people have to dive into the old design to figure out what's going on. As Null says, customers may have to requalify your product in their system. If your product is still in development, delaying the production release may cause customer schedules to slip, which makes customers very unhappy. Normally, the bugs that get left in only happen in weird configurations, cause very minor problems, have easy workarounds, or all of the above. They're just not bad enough to be worth the trouble. And if you reuse a hardware module on the next product, your existing customers will already have the workaround in their software anyway. Software toolchains are another factor. If a module sticks around long enough, your toolchain might change enough that redoing the old validation tests becomes a major project in itself. And you probably can't just load up the old tools, because you're not paying for the site license anymore. But as long as you don't change the module, you can keep copying and pasting it into new MCUs. Software is also an issue on the customer side. If your bugfix breaks backwards compatibility in any way, all of your customers will have to update their code, which they may not even have the tools for anymore. As someone who works in microcontroller development, I can tell you that we would all love to fix every bug. But trying to do so would delay development unpredictably, annoy customers, cost a ton of money, and at the end of it all, we'd still probably fail.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/181395', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/74739/']}
jdg_76875
stackexchange
llm_judgeable_groundtruth_similarity
42684661
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 new to Vue and webpack in general and I'm having a hard time figuring out how to import things. I created a fresh Vue project through vue init I added bootstrap 4 with yarn add bootstrap@4.0.0-alpha.6 In main.js I try to import bootstrap and jquery: import Vue from 'vue';import jQuery from 'jquery';import bootstrap from 'bootstrap';import App from './App';import router from './router'; But I get: Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript. window.jQuery = window.$ = $; does not work Finally, where and how do I load the Sass such that it's available to the whole app? Now provide the response and nothing else.
I was having the same issue and this is what I ended up with however, I didn't use Bootstrap alpha since the beta has since been released. Install Bootstrap along with its dependencies, jQuery and Popper.js: npm install bootstrap@4.0.0-beta popper.js jquery --save-dev Edit your /build/webpack.dev.conf.js file to add a plugin for jQuery and Popper.js to deal with dependencies (you can read more about that in the Bootstrap docs ): plugins: [ // ... new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'], // In case you imported plugins individually, you must also require them here: Util: "exports-loader?Util!bootstrap/js/dist/util", Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown", // ... }) // ...] Edit /src/main.js to import Bootstrap into the app's entry point: import Vue from 'vue'import App from './App'import router from './router'import 'bootstrap' // ← Edit the App.vue' file's <style> portion to import Bootsrap into your app's root css: <template> <div id="app"> <img src="./assets/logo.png"> <router-view></router-view> </div></template><script>export default { name: 'app'}</script><style>#app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}@import'~bootstrap/dist/css/bootstrap.css'</style> Run your Vue app from the CLI npm start I had to add the @import rule after the #app selector, otherwise the scoped stylingwould be canceled out by the Bootstrap import. I think there is a better way to do this so I will update my answer once I figure it out.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42684661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1751977/']}
jdg_76876
stackexchange
llm_judgeable_groundtruth_similarity
49990
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I understand that there is no order on the field of $p$ -adic numbers $\mathbb{Q}_p$ that makes it into an ordered field (i.e.) compatible with both addition and multiplication. Now, from the responses to a couple of my previous questions, $\mathbb{Q}_p$ is a divisible abelian group under addition (being a field of characteristic $0$ ). $\mathbb{Q}_p$ is torsion-free. It admits an order compatible with the group operation (addition), since every torsion-free abelian group is orderable. My question is, can I write an explicit ordering of $\mathbb{Q}_p$ compatible with the group operation? By "explicit", I mean an ordering in which, given two $p$ -adic numbers, I can decide which is greater. P.S.: I was not sure how to classify this problem, so please feel free to change the tags. Now provide the response and nothing else.
EDIT: I thought it would be appropriate, given the perhaps unexpected descriptive set-theoretic nature of this answer, to give a foreword explaining the focus on the Baire property (BP for short). A subset of a topological space has the BP if it differs from an open set by a meager set (a set contained in the union of countably many nowhere dense sets). In the setting of a Polish space (such as $\mathbb{Z}_p$ or the real numbers), the BP sets contain the Borel sets (and continuous images of Borel sets) and satisfy some nice regularity properties. In this context BP sets should be considered analogous to measurable sets, with meager sets serving as analogs of the null sets. For example, the Polish space itself is not meager, and the Kuratowski-Ulam theorem asserts that a subset of the plane is meager if and only if only a meager set of vertical sections are nonmeager (this is basically a Fubini theorem). One particularly noteworthy fact is that it's consistent with the axioms $\mathtt{ZF+DC}$ that every subset of a Polish space has the BP. Recall that $\mathtt{ZF}$ is the standard axiomatization of set theory without choice, and $\mathtt{DC}$ is the axiom of dependent choice . Intuitively, $\mathtt{DC}$ gives you the freedom to make a countable sequence of choices, where each choice is allowed to refer to properties of your previous choices (so they aren't "independent"). Dependent choice is enough to do almost all of common mathematics: you can perform most of analysis, carry out typical inductive constructions, Borel sets behave reasonably, the first uncountable cardinal is not a countable union of countable sets, etc. Some contexts in which $\mathtt{DC}$ doesn't bestow the full power of $\mathtt{AC}$ include performing wildly nonconstructive acts like building a Vitali set or choosing bases from huge vector spaces. So, I think that $\mathtt{ZF+DC}$ is a reasonable framework in which to carry out your request for an "explicit" linear order of $(\mathbb{Z}_p,+)$ . Once we rule out the existence of such a linear order with the property of Baire, we're therefore forced to concede that no argument producing this order may be carried out in $\mathtt{ZF+DC}$ , dashing our hopes of an explicit construction. By the way, I focus on $(\mathbb{Z}_p, +)$ rather than $(\mathbb{Q}_p,+)$ simply for convenience. It should be clear that any order of the latter induces an order of the former, so if anything the problem is harder for $\mathbb{Z}_p$ . There is no linear order of the additive group $(\mathbb{Z}_2,+)$ of $2$ -adic integers which has the property of Baire (with respect to the usual Polish topology). In particular, it is consistent with $\mathtt{ZF+DC}$ that no such order exists at all, so a large fragment of the axiom of choice is indeed required to build such an order. Analogous arguments will work for all $\mathbb{Z}_p$ , with slightly more obnoxious notation. From here on we will identify elements of $\mathbb{Z}_2$ with infinite binary strings, that is, elements of $2^\omega$ with the product topology. We define an equivalence relation $E_0$ on $2^\omega$ by setting two strings equivalent iff they differ in finitely many coordinates. This $E_0$ has a nice interpretation in $\mathbb{Z}_2$ : $x$ and $y$ are $E_0$ related iff their difference is a (standard) integer. More precisely, $x E_0 y$ iff for some $n$ , $x + 1 + 1 + \cdots + 1 (n \mbox{ times}) = y$ or vice-versa, where $1$ denotes the standard integer $1$ (i.e., the sequence $10000\ldots$ ). (That last part isn't literally true, since the constant $1$ sequence plus $1$ equals the constant $0$ sequence. But it is true off of the eventually constant sequences, which is enough to make the below argument go through (since there are only countably many eventually constant sequences).) We use without proof two standard facts about $E_0$ : If $A \subseteq 2^\omega$ has the Baire property (from now on abbreviated BP) and meets each $E_0$ -class in at most one point, then $A$ is meager (this is essentially the Vitali argument); If $A \subseteq 2^\omega$ has the BP and is $E_0$ -invariant (i.e., $x \in A$ and $x E_0 y$ implies $y \in A$ ), then $A$ is either meager or comeager (this is a form of ergodicity) (*). Now, given a putative order $<$ with the BP, we can partition $2^\omega$ into three $E_0$ -invariant BP pieces: $X_- = \{x \in 2^\omega : \forall y (y E_0 x \implies y < 0)\}$ ; $X_+ = \{x \in 2^\omega : \forall y (y E_0 x \implies y > 0)\}$ ; $X_0 = 2^\omega \backslash (X_- \cup X_+)$ (here $0$ is the identity element of the group: the constant $0$ sequence). So $X_-$ is the union of the $E_0$ -classes which are entirely negative, $X_+$ the union of those entirely positive, and $X_0$ the union of those which are sometimes positive and sometimes negative. (Technically, these pieces might not have the BP, but by Kuratowski-Ulam there's some element in $2^\omega$ we can use in place of $0$ to make the pieces have the BP. For ease of notation, let's assume $0$ works.) We first observe that $X_0$ is meager. Note that the set $\{x : 0 \leq x < 1\}$ (which is meager by Fact 1) hits each $X_0$ class in exactly one point, so $X_0$ is the union of countably many homeomorphic translations (namely, the standard integer shifts) of a meager set, thus is meager. Now let $f: 2^\omega \to 2^\omega$ denote the bitflipping homeomorphism, so $f(01001110\ldots) = 10110001\ldots$ . We note that $x \in A_-$ iff $f(x) \in A_+$ , since $x + f(x) + 1 = 0$ for all $x$ . This means that $A_-$ cannot be comeager, else $A_+ = f[A_-]$ would be a disjoint comeager set. But then by Fact 2, $A_-$ is meager, thus so is $A_+ = f[A_-]$ , and consequently we've written $2^\omega$ as the union of three meager sets. So we've hit a contradiction. (*) By request, here is a reference for Fact 2: Theorem 3.2 of G. Hjorth: Classification and Orbit Equivalence Relations, Mathematical Surveys and Monographs, 75, American Mathematical Society, Providence, RI, 2000. Although actually this theorem is overkill for this special case -- here's a sketch of a more elementary argument that works here. Suppose that $B \subseteq 2^\omega$ is nonmeager; we want to show that $[B]_{E_0} = \{x: \exists y \in B\ (x E_0 y)\}$ is comeager. By localization, there's a basic open set $U$ such that $B \cap U$ is comeager in $U$ . We can find a finite binary string $s$ let's say of length $n$ such that $U$ contains all elements of $2^\omega$ beginning with $s$ . Now look at the $2^n$ homeomorphisms of $2^\omega$ which flip some subset of the first $n$ bits of a string and leave the rest unchanged. These maps send each $x$ to something $E_0$ -related to $x$ , so it follows that $[B]_{E_0}$ is comeager in the union of $U$ 's images under these maps. But the union of these images is all of $2^\omega$ !
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/49990', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12857/']}
jdg_76877
stackexchange
llm_judgeable_groundtruth_similarity
69798302
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: .NET 6 / C# 10 introduced TimeOnly and DateOnly structs, to represent only a time and only a date respectively. The good old DateTime struct always had a Now static property which would give you the current date and time. I was expecting both TimeOnly and DateOnly structs to have similar static properties; like TimeOnly.Now or DateOnly.Today , but they apparently don't. So, what should I do if I want a DateOnly object representing the current date, or a TimeOnly object representing the current time? And I would also like to know WHY they decided not to include properties like that on these two new structs? Now provide the response and nothing else.
You can use .FromDateTime() method, To get current date only: var dateNow = DateOnly.FromDateTime(DateTime.Now); To get current time only: var timeNow = TimeOnly.FromDateTime(DateTime.Now); For more details, you can go through Github issue . There are several good comments which explains, why .Now property is not introduced to DateOnly and TimeOnly Why .Today , .Now and UtcNow properties are not introduced to DateOnly ? From @tarekgh comment , dotnet community is trying to keep DateOnly not relate to time zones Next comment from @tarekgh , explained further complexity if they introduce these properties to the DateOnly . After reading github thread and couple of other documentations, I feel like introducing DateOnly and TimeOnly structs are just to decouple the DateTime . This decoupling of date and time will help us in future to perform individual calculations on Date and Time separately. This will help us to design our model classes precisely and at granular level.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/69798302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7734384/']}
jdg_76878
stackexchange
llm_judgeable_groundtruth_similarity
140943
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 took some pictures of a Microchip EPROM die from the late 80s / early 90s (I can't recall the exact part number). The wire bonding pads are surrounded by a comb-like structure. What is the purpose of this structure? Now provide the response and nothing else.
They are probably large p-MOS and n-MOS transistors that are used for ESD protection on the bonding pads. Here is a reference that shows various bonding pad designs in detail (in general this information is not easy to come by- IC manufacturers seem to treat ESD protection as a kind of trade secret). Image taken from the above pdf: I don't recall Microchip ever making memory EPROMs. Is this part of an EPROM microcontroller? Edit: Just looking at a Microchip PIC16C57, which is probably from a similar era. There are similar patterns on either side of most of the pins (which are I/O) but on only one side of the input-only pins such as T0CKI, /MCLR/Vpp, OSC1. So the structures appear to be drivers on one side and ESD protection circuitry of whatever kind on the other side.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/140943', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/24874/']}
jdg_76879
stackexchange
llm_judgeable_groundtruth_similarity
28357997
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 currently have the current script. #!/bin/bash# script.shfor i in {0..99}; do script-to-run.sh input/ output/ $idone I wish to run it in parallel using xargs. I have tried script.sh | xargs -P8 But doing the above only executed once at the time. No luck with -n8 as well.Adding & at the end of the line to be executed in the script for loop would try to run the script 99 times at once. How do I execute the loop only 8 at the time, up to 100 total. Now provide the response and nothing else.
From the xargs man page: This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial- arguments followed by items read from standard input. Blank lines on the standard input are ignored. Which means that for your example xargs is waiting and collecting all of the output from your script and then running echo <that output> . Not exactly all that useful nor what you wanted. The -n argument is how many items from the input to use with each command that gets run (nothing, by itself, about parallelism here). To do what you want with xargs you would need to do something more like this (untested): printf %s\\n {0..99} | xargs -n 1 -P 8 script-to-run.sh input/ output/ Which breaks down like this. printf %s\\n {0..99} - Print one number per-line from 0 to 99 . Run xargs taking at most one argument per run command line and run up to eight processes at a time
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28357997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2031156/']}
jdg_76880
stackexchange
llm_judgeable_groundtruth_similarity
5337924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since I don't have iPad 2, I need to know what it returns when calling [[UIDevice currentDevice] model]. I thought it returns just "iPad" but it seems I'm wrong. Can somebody let me know? Thanks Now provide the response and nothing else.
Check for an iPad with a camera. BOOL isIPad2 = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]); Note that it is generally better to detect specific features rather than make blanket assumptions based on model/version detection. For instance, if you need a camera, then test for the camera explicitly; if you need to tweak the UI quality based on the amount of RAM available, test for physical RAM ; etc. Also note a comment I wrote that highlights the dangers of using model detection.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5337924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664149/']}
jdg_76881
stackexchange
llm_judgeable_groundtruth_similarity
24746645
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 tried mutliple solutions to this problem but I can't seem to get it. I have time in decimal format, which is in hours. I want to make it much cleaner by changing it into a DD:HH:MM:SS format. Example: 10.89 hours == 10 hours, 53 minutes, 40 seconds EDIT : 10.894945454545455 == 10 hours, 53 minutes, 40 seconds What I've tried: int hours = (int) ((finalBuildTime) % 1);int minutes = (int) ((finalBuildTime * (60*60)) % 60);int seconds = (int) ((finalBuildTime * 3600) % 60);return String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds); Which returned: 0(h) 41(m) 41(s) Any suggestions? Now provide the response and nothing else.
There is no need to do a modular on minutes. Your calculation of minutes should just multiply by 60, not (60*60) double finalBuildTime = 10.89;int hours = (int) finalBuildTime;int minutes = (int) (finalBuildTime * 60) % 60;int seconds = (int) (finalBuildTime * (60*60)) % 60;System.out.println(String.format("%s(h) %s(m) %s(s)", hours, minutes, seconds)); This code gives you the correct output 10(h) 53(m) 24(s) I believe your expected output of 40 seconds is incorrect. It should be 24 seconds. (53*60 + 24)/(60*60) = 0.89
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24746645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2848307/']}
jdg_76882
stackexchange
llm_judgeable_groundtruth_similarity
161145
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: The question is from a problem I am trying to solve in Robert Hogg's introduction to Mathematical Statistics 6th version problem 7.2.9 in page 380. The problem is: We consider a random sample $X_1, X_2,\ldots ,X_n$ from a distribution with pdf $f(x;\theta)=(1/\theta$)exp($-x/\theta$), $0<x<\infty$. Possibly, in a life testing situation, however, we only observe the first r order statistics $Y_1<Y_2<\cdots <Y_r$. (a) Record the joint pdf of these order statistics and denote it by $L(\theta)$ (b) Under these conditions, find the mle, $\hat{\theta}$, by maximizing $L(\theta)$. (c)Find the mgf and pdf of $\hat{\theta}$. (d) With a slight extension of the definition of sufficiency, is $\hat{\theta}$ a sufficient statistic? I can solve (a) and (b) but I am completely stuck by (c) therefore cannot forward to (d) Solve (a): We know joint pdf for $Y_1,Y_2,\ldots,Y_n$ is $g(y_1,y_2,\ldots,y_n)=n!f(y_1)f(y_2)\cdots f(y_n)$ we just integrate out the (r+1) to n terms we will get joint pfd for $Y_1,Y_2,\ldots,Y_r$. $h(y_1,y_2,\ldots,y_r)=n!f(y_1)f(y_2)\cdots f(y_r)\int_{n-1}^{\infty} \int_{n-2}^{\infty}\cdots \int_{r+1}^{\infty} \int_{r}^{\infty}f(y_{r+1})f(y_{r+2})\cdots f(y_{n-1})f(y_n)dy_{r+1}dy_{r+2}\cdots dy_{n-1}dy_{n}$ $=n!f(y_1)f(y_2)\cdots f(y_r) \int_{n-2}^{\infty}\cdots \int_{r+1}^{\infty} \int_{r}^{\infty}f(y_{r+1})f(y_{r+2})\cdots f(y_{n-1})[1-F(y_{n-1})]dy_{r+1}dy_{r+2}\cdots dy_{n-1}$ $=n!f(y_1)f(y_2)\cdots f(y_r)\int_{n-2}^{\infty}\cdots \int_{r+1}^{\infty} \int_{r}^{\infty}f(y_{r+1})f(y_{r+2})\cdots f(y_{n-2})(-1)[1-F(y_{n-1})]dy_{r+1}dy_{r+2}\cdots dy_{n-2}]d[1-F(y_{n-1})]$ $=n!f(y_1)f(y_2)\cdots f(y_r)\int_{n-2}^{\infty}\cdots \int_{r+1}^{\infty} \int_{r}^{\infty}f(y_{r+1})f(y_{r+2})\cdots f(y_{n-2})\frac{[1-F(y_{n-2})]^2}{2}dy_{r+1}dy_{r+2}\cdots dy_{n-2}$ $=n!f(y_1)f(y_2)\cdots f(y_r)\frac{[1-F(y_r)]^{n-r}}{(n-r)!}$ $=n!\frac{1}{\theta}e^{\frac{-y_1}{\theta}}\frac{1}{\theta}e^{\frac{-y_2}{\theta}}\cdots \frac{1}{\theta}e^{\frac{-y_r}{\theta}}[e^{-y_r/\theta}]^{n-r}/(n-r)!$ $=\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}$ (b) This part is not difficult. It just a normal way to calculate mle. $\log L(\theta;y)=\log \frac{n!}{(n-2)!}-r\log(\theta)-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]$Take derivative of the log likelihood function we get:$\partial \frac{L(\theta;y)}{\theta}=\frac{1}{\theta^2}[\sum_{i=1}^{r}y_i+(n-r)y_r]-r\frac{1}{\theta}$ Set the derivative to zero We get: $\hat{\theta}=\frac{[\sum_{i=1}^{r}y_i+(n-r)y_r]}{r}$ (c) To solve (c) I think we need at least to know the distribution of $\sum_{i=1}^{r}y_i$. I search the internet, there is a paper talk about this distribution, https://www.ocf.berkeley.edu/~wwu/articles/orderStatSum.pdf But I think the method might not be correct since for order statistic $F(y_i)$ are different, we cannot use binomial distribution there. There is another paper here http://www.jstor.org/stable/4615746?seq=1#page_scan_tab_contents But I am totally lost at formula (2.2) if someone would like to explain the paper with more detailed calculations, it will be highly appreciated. (d) only after solve (c) Now provide the response and nothing else.
Since$$(y_1,\ldots,y_r)\sim\frac{n!\theta^{-r}}{(n-r)!}e^{-\frac{1}{\theta}[\sum_{i=1}^{r}y_i+(n-r)y_r]}\mathbb{I}_{y_\le y_2\le \ldots \le y_r}$$you have the joint pdf of $(y_1,\ldots,y_r)$. From there, you can deduce the pdf of $$s_r=\sum_{i=1}^{r}y_i+(n-r)y_r\,.$$Indeed, because the Jacobian of the transform is constant,\begin{align*}f_s(y_1,\ldots,y_{r-1},s_r) &\propto f_Y\left(y_1,\ldots,\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}\Big/(n-r+1)\right) \\&\propto \theta^{-r} \exp\{-s_r/\theta\}\mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\end{align*}implies by integration in $y_1,\ldots,y_{r-1}$ that$$f_s(s_r)\propto\theta^{-r} \exp\{-s_r/\theta\}s_r^{r-1}$$Indeed,\begin{align*}f_s(s_r)&=\int\cdots\int f_s(y_1,\ldots,y_{r-1},s_r)\text{d}y_1\cdots\text{d}y_{r-1}\\&= \theta^{-r} \exp\{-s_r/\theta\}\int\cdots\int \mathbb{I}_{y_\le y_2\le \ldots \le\left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)}\text{d}y_1\cdots\text{d}y_{r-1}\end{align*}leads to constraint $y_{r-1}$ by $y_{r-2}\le y_{r-1}$ and by$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-1}y_i\right\}/(n-r+1)=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+1)-\frac{y_{r-1}}{n-r+1}$$which simplifies into$$y_{r-1}\le \left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)$$If one starts integrating in $y_{r-1}$, the most inner integral is\begin{align*}\int_{y_{r-2}}^{\{s_r-\sum_{i=1}^{r-2}y_i\}/(n-r+2)}\text{d}y_{r-1}&=\left\{s_r-\sum_{i=1}^{r-2}y_i\right\}/(n-r+2)-y_{r-2}\\&=\left\{s_r-\sum_{i=1}^{r-3}y_i\right\}/(n-r+2)-\frac{(n-r+1)y_{r-2}}{n-r+2}\end{align*}and from there one can proceed by recursion. Hence$$s_r\sim\mathcal{G}a(r,1/\theta)$$ Here is an R simulation to show the fit: obtained as follows n=10r=5 sim=matrix(rexp(n*1e4),1e4,n)sim=t(apply(sim,1,sort))res=apply(sim[,1:r],1,sum)+(n-r)*sim[,5]hist(res,prob=TRUE)curve(dgamma(x,sh=(n-r),sc=1),add=TRUE)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/161145', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/61705/']}
jdg_76883
stackexchange
llm_judgeable_groundtruth_similarity
35691
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: I inverted the waveform of a given song and was wondering what will happen. The result is that it sounds the exact same way as before. I used Audacity and doublechecked if the wave-form really is inverted. The second thing I tried was: I removed the right channel, duplicated the left one and set the duplicated layer as right channel. This way I made sure that both channels are exactly the same. Then I inverted the second channel only. I thought that this would create some kind of anti-noise, but it didn't. Why is that? Now provide the response and nothing else.
The human ear responds only to the intensity $I$ of the sound it receives (more specifically, to the intensity distribution over the different frequencies) and this goes more or less like the square of the amplitude,$$I\sim A^2.$$Changing the sign of the waveform changes the sign of $A$, which has no effect on $I$.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/35691', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11952/']}
jdg_76884
stackexchange
llm_judgeable_groundtruth_similarity
1147373
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to prove that $$I = \int^{\infty}_{-\infty}u(x,y) \,dy$$ is independent of $x$ and find its value, where $$u(x,y) = \frac{1}{2\pi}\exp\left(+x^2/2-y^2/2\right)K_0\left(\sqrt{(x-y)^2+(-x^2/2+y^2/2)^2}\right)$$ and $K_0$ is the modified Bessel function of the second kind with order zero.Evaluating the integral numerically with Mathematica for different values of $x$ gives the result of $2.38$ , but I want to know if it is possible to show analytically. Increasing $x$ results in an increase of the exponential term on the left, but it also then strongly increases the argument of modified Bessel function, thus reducing its value. To show that integral is independant of $x$ , it is sufficient to show that $\int^{\infty}_{-\infty}\frac{\, d}{\, dx}u(x,y) = 0$ but any differentiation looks more and more ugly. EDIT Mathematica test: x = 100 NIntegrate[ (1/(2 Pi))* Exp[x*x/2 - y*y/2] BesselK[0, Sqrt[(x - y)*(x - y) + (x*x/2 - y*y/2)*(x*x/2 - y*y/2 )]], {y, -Infinity, x, Infinity}, MaxRecursion -> 22] This gives an answer of $0.378936$ independent of the choice of $x$ . In the earlier calculation I missed the factor $\frac{1}{2\pi}$ . Now provide the response and nothing else.
Although I'm about 7 years late, here is an answer anyway for anyone interested: Claim $$I = \frac{e}{2} \sqrt{\pi} \, \text{erfc} (1)$$ and is thus independent of $x$ . Proof. By https://dlmf.nist.gov/10.32#E10 $$K_0 (z) = \frac{1}{2} \int_{0}^{\infty} \exp \left(-t-\frac{z^2}{4t}\right) \, \frac{dt}{t}$$ This allows us to write $$\begin{align}I &= \int_{0}^{\infty} u(x,y) \, dy + \int_{-\infty}^{0} u(x,y) \, dy \\&=\frac{1}{2\pi}\int_0^\infty e^{-v^2/2}\int_0^\infty\frac{e^{xv}e^{-t-v^2[1+(x-v/2)^2]/(4t)}+e^{-xv}e^{-t-v^2[1+(x+v/2)^2]/(4t)}}t\,dt\,dv\\ &=\frac{1}{2\pi}\int_0^\infty\int_0^\infty \frac{\cosh\left(xv\left(\frac{v^2}{4t}+1\right)\right)}{t}\exp\left(-t-\frac{1+2t+x^2}{4t}v^2-\frac{v^4}{16t}\right)\,dv\,dt\end{align}$$ We now enforce the substitution $t = s v^2 \implies dt = v^2 \,ds$ : $$\begin{align}I&=\frac{1}{2\pi} \int_{0}^{\infty} \int_{0}^{\infty}\frac{\cosh\left(x v \left(\frac{1}{4s}+1\right)\right)}{s} \exp\left(-sv^2-\frac{1+2sv^2+x^2}{4s}-\frac{v^2}{16s}\right) \, dv \, ds\\&=\frac{1}{2\pi}\int_{0}^{\infty}\int_{0}^{\infty}\frac{\cosh\left(xv\left(\frac{1}{4s}+1\right)\right)}{s}\exp\left(-\frac{1+x^2}{4s}\right)\exp\left(-v^2 \frac{(1+4s)^2}{16s}\right)\,dv\,ds\end{align}$$ Since $$\int_{0}^{\infty}\cosh(a v)\exp\left(-v^2 b^2\right) \, dv=\frac{\sqrt{\pi}}{2b}\exp\left(\frac{a^2}{4b^2}\right)$$ $$\implies I = \frac{1}{2\pi} \int_{0}^{\infty} \frac{\exp \left(-\frac{1+x^2}{4s}\right)}{s} \cdot \frac{\sqrt{\pi}}{2\left(\frac{1+4s}{4\sqrt{s}}\right)}\exp \left(\frac{4s x^2 \left(\frac{1}{4s}+1\right)^2}{(1+4s)^2}\right)\, ds$$ This results in the integral being independent as we wanted since the $x^2$ terms cancel. $$\implies I = \frac{1}{\sqrt{\pi}} \int_{0}^{\infty} \frac{\exp\left(-\frac{1}{4s}\right)}{\sqrt{s} (1+4s)} \, ds\stackrel{s\,\mapsto\frac{1}{s}}{=}\frac{1}{\sqrt{\pi}} \int_{0}^{\infty} \frac{\exp\left(-\frac{s}{4}\right)}{\sqrt{s} (4+s)} \, ds=\frac{e}{2} \sqrt{\pi} \, \text{erfc} (1)=0.378\cdots$$ $\square$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1147373', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22685/']}
jdg_76885
stackexchange
llm_judgeable_groundtruth_similarity
61744
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I keep reading about situations where a hacker could "easily" brute force a password (most recent example ) but I'm confused about when some has an opportunity to do this kind of thing. If it is a website/web service, aren't attempts like this rate limited? I.e. I can't try my Amazon password 50 million times per second, even if my internet connection were more awesome than it is. What needs to happen for someone to even have the opportunity to brute force their way into a system? And if systems can effectively throttle attempts to dozens or fewer per minute why is there such an emphasis on saying that GPU attacks can generate millions or billions of passwords per second if these are effectively useless? Now provide the response and nothing else.
Mass brute force is usually done after the attackers have somehow seized a list of hashed passwords. This can happen in several situations; most common being: A SQL injection attack which allows attackers to push some more or less constrained SQL expressions to be evaluated by the target database. Depending on the site structure and local constraints for the attack, attackers might not be able to do what they wish with the database, but still be able to dump some parts of it. Data is extracted from a discarded medium, e.g. an old hard disk; possibly an electronically broken hard disk, that the attacker retrieves from a dumpster and repairs. Indelicacy from an employee or intern, who stealthily grabs a copy of the database and stores it on a USB Flash drive. The common trend here is that cracking passwords is used to extend an attack: Attacker got a read-only glimpse of the database, and wants to escalate that into read-write access. The original breach is risky (e.g. attacker had to be physically on the premises) and wants to come back to the server, but from the network and without incurring the risk of an encounter with security guards. Attacker wants to get the password from one server because he knows that most users will reuse the same password on many other servers. The third point is probably the most common motivation for attackers.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/61744', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/49828/']}
jdg_76886
stackexchange
llm_judgeable_groundtruth_similarity
17564804
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 requirement is to start five threads, and wait only in the fastest thread. All five threads went to look for the same data 5 directions, and one is enough to continue the control flow. Actually, I need to wait for the first two threads to return, to verify against each other. But I guess if I know how to wait for the fastest. I can figure out how to wait for the second-fastest. A lot talk about join(timeout) , but you don't know in advance which one to wait (which one to apply join in advance). Now provide the response and nothing else.
Use a queue: each thread when completed puts the result on the queue and then you just need to read the appropriate number of results and ignore the remainder: #!python3.3import queue # For Python 2.x use 'import Queue as queue'import threading, time, randomdef func(id, result_queue): print("Thread", id) time.sleep(random.random() * 5) result_queue.put((id, 'done'))def main(): q = queue.Queue() threads = [ threading.Thread(target=func, args=(i, q)) for i in range(5) ] for th in threads: th.daemon = True th.start() result1 = q.get() result2 = q.get() print("Second result: {}".format(result2))if __name__=='__main__': main() Documentation for Queue.get() (with no arguments it is equivalent to Queue.get(True, None) : Queue.get([block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17564804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1758793/']}
jdg_76887
stackexchange
llm_judgeable_groundtruth_similarity
5963429
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 three tabs.I'd like to know if a tab can have more than one textview.Everytime I try to add a new textview, even if in different positions on the screen, they appear overlapped. The details would be alligned on the left and the data would be alligned on the right. I can't write the way I want in here because I don't how to put tabs. But the idea is something like: on the left a perfect column with Name, Login, Address, etc... and on the right side a perfect column with the name, the login, the address, etc... What I'd like to do is something like, for example: |Personal| -> tab Inside the tab: Information Name: Zoe Shnoeder Login: zoe-shnd Address: Ulisses Street, London, UK Date of birth: 13/11/1990 Contacts Telephone: 2134212 E-mail: zoeshn@hotmail.com And if possible a square around Information and its details and another square around Contacts and its details, like -Contacts--------------------------- | Telephone: 2134212 | | E-mail: zoeshn@hotmail.com | Thanks in advance,Rita Now provide the response and nothing else.
Treat the node as a custom type: [XmlRoot("ObjectSummary")]public class Summary{ public string Name {get;set;} public BoolYN IsValid {get;set;}} Then implement IXmlSerializable on the custom type: public class BoolYN : IXmlSerializable{ public bool Value { get; set } #region IXmlSerializable members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { string str = reader.ReadString(); reader.ReadEndElement(); switch (str) { case "Y": this.Value = true; break; case "N": this.Value = false; break; } } public void WriteXml(System.Xml.XmlWriter writer) { string str = this.Value ? "Y" : "N"; writer.WriteString(str); writer.WriteEndElement(); } #endregion} You can even make that custom class a struct instead, and provide implicit conversions between it and bool to make it even more "transparent".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5963429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/748537/']}
jdg_76888
stackexchange
llm_judgeable_groundtruth_similarity
2348
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the relationship, if any, between Kalman filtering and (repeated, if necessary) least squares polynomial regression? Now provide the response and nothing else.
1. There is a Difference in terms of optimality criteria Kalman filter is a Linear estimator. It is a linear optimal estimator - i.e. infers model parameters of interest from indirect, inaccurate and uncertain observations. But optimal in what sense? If all noise is Gaussian, the Kalman filter minimizes the mean square error of the estimated parameters. This means, that when underlying noise is NOT Gaussian the promise no longer holds. In case of nonlinear dynamics, it is well-known that the problem of state estimation becomes difficult. In this context, no filtering scheme clearly outperforms all other strategies. In such case, Non-linear estimators may be better if they can better model the system with additional information. [See Ref 1-2] Polynomial regression is a form of linear regression in which the relationship between the independent variable x and the dependent variable y is modeled as an nth order polynomial. $$ Y = a_0 + a_1x + a_2x^2 + \epsilon $$ Note that, while polynomial regression fits a nonlinear model to the data, these models are all linear from the point of view of estimation, since the regression function is linear in terms of the unknown parameters $a_0, a_1, a_2$ . If we treat $x, x^2$ as different variables, polynomial regression can also be treated as multiple linear regression . Polynomial regression models are usually fit using the method of least squares. In the least squares method also, we minimize the mean squared error. The least-squares method minimizes the variance of the unbiased estimators of the coefficients, under the conditions of the Gauss–Markov theorem . This theorem, states that ordinary least squares (OLS) or linear least squares is the Best Linear Unbaised Estimator (BLUE) under following conditions: a. when errors have expectation zero i.e. $E(e_i) = 0 $ b. have equal variances i.e. $ Variance(e_i) = \sigma^2 < \infty $ c. and errors are uncorrelated i.e. $ cov(e_i,e_j) = 0 $ NOTE: that here, errors don't have to be Gaussian nor need to beIID. It only needs to be uncorrelated. 2. Kalman Filter is an evolution of estimators from least square In 1970, H. W. Sorenson published an IEEE Spectrum article titled "Least-squares estimation: from Gauss to Kalman. " [See Ref 3.] This is a seminal paper that provides great insight about how Gauss' original idea of least squares to today's modern estimators like Kalman. Gauss' work not only introduced the least square framework but it was actually one of the earliest work that used a probabilistic view. While least squares evolved in the form of various regression methods, there was another critical work that brought filter theory to be used as an estimator. The theory of filtering to be used for stationary time series estimation was constructed by Norbert Wiener during 1940s (during WW-II) and published in 1949 which is now known as Wiener filter. The work was done much earlier, but was classified until well after World War II). The discrete-time equivalent of Wiener's work was derived independently by Kolmogorov and published in 1941. Hence the theory is often called the Wiener-Kolmogorov filtering theory . Traditionally filters are designed for the desired frequency response. However, in case of Wiener filter, it reduces the amount of noise present in a signal by comparison with an estimation of the desired noiseless signal. Weiner filter is actually an estimator. In an important paper, however, Levinson (1947) [See Ref 6] showed that in discrete time, the entire theory could be reduced to least squares and so was mathematically very simple. See Ref 4 Thus, we can see that Weiner's work gave a new approach for estimation problem; an evolution from using least squares to another well-established filter theory.However, the critical limitation is that Wiener filter assumes the inputs are stationary. We can say that Kalman filter is a next step in the evolution which drops the stationary criteria. In Kalman filter, state space model can dynamically be adapted to deal with non-stationary nature of signal or system. The Kalman filters are based on linear dynamic systems in discrete time domain. Hence it is capable of dealing with potentially time varying signal as opposed to Wiener. As the Sorenson's paper draws parallel between Gauss' least squares and Kalman filter as ...therefore, one sees that the basic assumption of Gauss and Kalmanare identical except that later allows the state to change from onetime to next. The difference introduces a non-trivial modification toGauss' problem but one that can be treated within the least squaresframework. 3. They are same as far as causality direction of prediction is concerned; besides implementation efficiency Sometimes it is perceived that Kalman filter is used for prediction of future events based on past data where as regression or least squares does smoothing within end to end points. This is not really true. Readers should note that both the estimators (and almost all estimators you can think of) can do either job. You can apply Kalman filter to apply Kalman smoothing . Similarly, regression based models can also be used for prediction. Given the training vector, $X_t$ and you applied $Y_t$ and discovered the model parameters $α_0 ... a_K$ now for another sample $X_k$ we can extrapolate $Y_K$ based on the model. Hence, both methods can be used in the form of smoothing or fitting (non-causal) as well as for future predictions (causal case). However, the critical difference is the implementation which is significant. In case of polynomial regression - with entire process needs to get repeated and hence, while it may be possible to implement causal estimation but it might be computationally expensive. [While, I am sure there must be some research by now to make things iterative]. On the other hand, Kalman filter is inherently recursive. Hence, using it for prediction for future only using on past data will be very efficient. Here is another good presentation that compares several methods: Ref 5 References Best Introduction to Kalman Filter - Dan Simon Kalman Filtering Embedded Systems Programming JUNE 2001 page 72 Presentation: Lindsay Kleeman Understanding and Applying Kalman Filtering H. W. Sorenson Least-squares estimation: from Gauss to Kalman IEEE Spectrum, July 1970. pp 63-68. Lecture Note MIT Course ware - Inference from Data and Models (12.864) - Wiener and Kalman Filters Presentation Simo Särkkä From Linear Regression to KalmanFilter and Beyond Helsinki University of Technology Levinson, N. (1947). "The Wiener RMS error criterion in filter design and prediction." J. Math. Phys., v. 25, pp. 261–278.
{}
{'log_upvote_score': 7, 'links': ['https://dsp.stackexchange.com/questions/2348', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/154/']}
jdg_76889
stackexchange
llm_judgeable_groundtruth_similarity
32840
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm about to deploy ~25 servers running Debian . The machines will have different roles - web servers, Java appservers, proxies, MySQL boxes. The environment will probably not grow much in the future - maybe 2-5 more servers in next 2 years. I'll probably use fai for system installation, but I'm unsure if it's worth to add also cfengine or puppet centralized configuration management for such small scale. Does configuration management make sense for an environment this size? Now provide the response and nothing else.
I would recommend using a mixture of Debian pre-seeding, where you give the installer a text file that answers all the questions it would ask, and Puppet. THe reason for using the preseeding, rather than FAI is that you don't have to set up an image first and deal with keeping it up to date. You will end up with an install very similar to what you would have if you did them all by hand. When you come to install a new release, you will have to update a config file with the changes, rather than having to rebuild a new image. A configuration management tool is particularly useful where you have several servers performing the same role and you want them to be identical, e.g. webserver cluster. However, they can also be useful for configuring the base install of all servers. You're going to want to install particular packages on all your servers, like ntpd and a MTA. You're going to want to change a config file on all your servers. An additional benefit is that you can keep your manifests in something like subversion and keep a record of what changed on a server and who did it and why. Configuration management can also be a life saver in the case of a server failure and you need to rebuild it quickly. Install the OS (using FAI or preseeding), install puppet and away it goes, built back exactly as it was before. Obviously you'll need to keep backups of data. Configuration management requires dedication to make sure you only make changes using it and will have an upfront cost setting things up, but once you have a working setup you won't regret it. Puppet is the more modern of the two tools you've mentioned. I really recommend it to anyone. The configuration is a declarative language and is easy to build up higher level constructs. There is also a very large community around it and there are always people welcome to help on the mailing list or the IRC channel.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/32840', 'https://serverfault.com', 'https://serverfault.com/users/2413/']}
jdg_76890
stackexchange
llm_judgeable_groundtruth_similarity
299347
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 am reading C# Design Pattern Essentials . I'm currently reading about the iterator pattern. I fully understand how to implement, but I don't understand the importance or see a use case. In the book an example is given where someone needs to get a list of objects. They could have done this by exposing a public property, such as IList<T> or an Array . The book writes The problem with this is that the internal representation in both of these classes has been exposed to outside projects. What is the internal representation? The fact it's an array or IList<T> ? I really don't understand why this is a bad thing for the consumer (the programmer calling this) to know... The book then says this pattern works by exposing its GetEnumerator function, so we can call GetEnumerator() and expose the 'list' this way. I assume this patterns has a place (like all) in certain situations, but I fail to see where and when. Now provide the response and nothing else.
Software is a game of promises and privileges. It is never a good idea to promise more than you can deliver, or more than your collaborator needs. This applies particularly to types. The point of writing an iterable collection is that its user can iterate over it - no more, no less. Exposing the concrete type Array usually creates many additional promises, e.g. that you can sort the collection by a function of your own choosing, not to mention the fact that a normal Array will probably allow the collaborator to change the data that's stored inside it. Even if you think this is a good thing ("If the renderer notices that the new export option is missing, it can just patch it right in! Neat!"), overall this decreases the coherence of the code base, making it harder to reason about - and making code easy to reason about is the foremost goal of software engineering. Now, if your collaborator needs access to a number of thingies so that they are guaranteed not to miss any of them, you implement an Iterable interface and expose only those methods that this interface declares. That way, next year when a massively better and more efficient data structure appears in your standard library, you'll be able to switch out the underlying code and benefit from it without fixing your client code everywhere . There are other benefits to not promising more than is needed, but this one alone is so big that in practice, no others are needed.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/299347', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/119594/']}
jdg_76891
stackexchange
llm_judgeable_groundtruth_similarity
101903
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: Bug introduced in 8 or earlier and fixed in 10.4.0 Bug isn't present in version 5.2 I don't think I quite understand how Except works. I want to define $f(a,b) = (a-b)\ln(a-b)$, with the special case $f(a,a)=0$. Except, the function shouldn't evaluate if either $a$ or $b$ is zero. I tried: ClearAll[f]f[Except[0, a_], Except[0, a_]] := 0;f[Except[0, a_], Except[0, b_]] := (a - b) Log[a - b]; But for some reason DownValues[f] only reports one definition: DownValues[f](* { HoldPattern[ f[Except[0, a_], Except[0, b_]]] :> (a - b) Log[a - b] } *) This is bad because if the user inputs f[x,x] , I get Infinity::indet errors. Question What did I do wrong, and how do I make definitions with Except ? Now provide the response and nothing else.
It seems that f[Except[0, a_], Except[0, a_]] isn't considered doubled argument while this f[a : Except[0], a : Except[0]] is. So the former isn't considered special case and is overwritten by your next definition. I can't explain properly but seems to be expected. ClearAll[f];f[a_, a_] := 0 (*or f[a : Except[0], a : Except[0]] if f[0,0] should give f[0,0]*)f[a : Except[0], b : Except[0]] := {a, b}f[1, 2]f[0, 1]f[0, 0]f[1, 1] {1,2}f[0,1]00
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/101903', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2048/']}
jdg_76892
stackexchange
llm_judgeable_groundtruth_similarity
30805330
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 WPF project and need to create a control that is specific to the domain but will be reused in multiple views. The control must display a decimal value in 3 parts, the integral part and the decimal part split into 2 with different font sizes. I have a dependency property for the Amount and then split the amount in 3 parts in the code behind so I can show them in the specific labels. I also use the decimal amount to decide whether the amount is going up or down and subsequently change the background color of the control. All of this is done in the code behind. I know that some say that code behind is evil and I agree in most cases. However how would you implement this otherwise? Now provide the response and nothing else.
No, it should not be avoided at all costs . Remember, Data is Data, UI is UI . For example, if you have code which does only UI stuff, then there is nothing wrong with having code behind. Anything that works with actual data, including working with the ViewModel should generally be avoided in code-behind, as you would then be creating dependencies, which breaks the MVVM design pattern. So to answer your question more directly, there isn't anything wrong with what you have done. EDIT Let me explain further. Picture the scene, you have a View, with a button that needs to start a Storyboard when it has been clicked. (Of course, you can do this in XAML only, but this is just an example) In this case, there is nothing wrong with adding a click event to the button and starting the storyboard from code-behind. This is UI only code, so it's safe. However, let's say your button needs to change a property in your ViewModel when it is clicked. You should not get hold of the DataContext in the code-behind. You will need to use a Command because you need to keep the View separated from the ViewModel . There's a stigma that if your views have code-behind, then you should be taken out back and shot in the back of the head, execution style. This is untrue. All that said, MVVM is a pattern , not the law.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30805330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4976987/']}
jdg_76893
stackexchange
llm_judgeable_groundtruth_similarity
15197477
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Clicking on an element: $('.my_list').click(function(){ var selected_object = $(this); $('.my_list').each(function(){ var current_object = $(this); if( selected_object == current_object ) alert('FOUND IT !'); });}); I don't know why, but I don't get the alert message "FOUND IT !". Now provide the response and nothing else.
You can use the jQuery.is function: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. if (selected_object.is(current_object)) { ... } An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator: if (selected_object.get(0) == current_object.get(0)) { ...} jsFiddle demo
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15197477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1950209/']}
jdg_76894
stackexchange
llm_judgeable_groundtruth_similarity
1906639
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: What is the greatest common divisor of all numbers that are one less than the twelfth power of a prime with a units digit of one? By Dirichlet's theorem, there exist infinitely many primes with a units digit of $1$. How can we find the greatest common divisor using the fact that our numbers are of the form $p^{12}-1$? Now provide the response and nothing else.
It is not more than $2^4 \times 3^2 \times 5 \times 7 \times 13$. To see this, take the $\gcd(61^{12}-1,71^{12}-1)$. To show that this is indeed the $\gcd$, note that the fact that the prime's unit digit is a one implies that it is not any of $2, 3, 5, 7$ or $13$, so its coprime with those integers. Note that $a^4 \equiv 1 \mod 16$ for all $a$ comprime with $16$. This can be proved by case inspection. So $$p^{12}-1=(p^3)^4 -1 \equiv 0 \mod 16$$ The Euler-Fermat theorem gives the remaining cases: $\varphi(5)=4$, so $p^4\equiv1\mod 5$, so $p^{12}-1\equiv 0 \mod 5$. $\varphi(7)=6$, so $p^6\equiv1\mod 7$, so $p^{12}-1\equiv 0 \mod 7$. $\varphi(9)=6$, so $p^6\equiv1\mod 9$, so $p^{12}-1\equiv 0 \mod 9$. $\varphi(13)=12$, so $p^{12}\equiv1\mod 13$, so $p^{12}-1\equiv 0 \mod 13$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1906639', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/282223/']}
jdg_76895
stackexchange
llm_judgeable_groundtruth_similarity
13266916
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Synchronizing a timer to prevent overlap I have a Threading.Timer in my class. System.Threading.Timer timer; TimerCallback cb = new TimerCallback(ProcessTimerEvent); timer = new Timer(cb, reset, 1000, Convert.ToInt64(this.Interval.TotalSeconds)); and defined a callback for it. private void ProcessTimerEvent(object obj){ if(value) MyFunction();} When run it, re-running callback before myfunction to complete. How to pause Threading.Timer to complete myfunction ? Now provide the response and nothing else.
It is not necessary to stop timer, you could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately. object lockObject = new object();private void ProcessTimerEvent(object state) { if (Monitor.TryEnter(lockObject)) { try { // Work here } finally { Monitor.Exit(lockObject); } } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13266916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970404/']}
jdg_76896
stackexchange
llm_judgeable_groundtruth_similarity
349039
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For a cubic polynomial $f(x)=x^3+x^2+\frac{1}{4}x+c$ over $\mathbb{F}_q$ , where $q$ is a odd prime power, I find that for a lot of $q$ , there does not exist $c\in\mathbb{F}_q$ such that $f$ has three distinct roots in $\mathbb{F}_q$ , one of which is a quadratic residue and the other two are non-residues. I have not found any counter examples, so my question is, does it hold for any $q$ ? If so, what forms of cubic polynomials have such property? Now provide the response and nothing else.
EDIT: Following a clever observation of user44191 in the comments: If $f(x)$ is a monic polynomial, and $c$ a number, then the polynomial $xf(x)^2+c$ has a similar property to your example (the case $f(x)=x+1/2$ ). Indeed, we have $x = \frac{-c}{f(x)^2}$ so If $-c$ is a nonzero square then all rational roots are squares. if $-c$ is a nonsquare then all rational roots are not square, but their ratios are square. If $-c$ is zero then one root is zero and the rest are double (this doesn't really fit the pattern). This produces polynomials of odd degree. For even degree examples, we can do $f(x)^2+cx$ . This gives $x =\frac{ f(x)^2}{-c}$ so we have the same thing except if $-c$ is zero than all roots are double, and there is a special case if $f(0)=0$ . So we have many examples of polynomials of this type. (See the edit history for an earlier argument, special to the case of degree 3 polynomials, if desired. This was inspired by darij grinberg's answer, and that earlier answer inspired user44191's comment, so both of them are partially responsible for this solution.)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/349039', 'https://mathoverflow.net', 'https://mathoverflow.net/users/150240/']}
jdg_76897
stackexchange
llm_judgeable_groundtruth_similarity
14097897
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 received the following error message when I tried to submit the content to my form. How may I fix it? Notice: Undefined index: filename in D:\wamp\www\update.php on line 4 Example Update.php code: <?php $index = 1; $filename = $_POST['filename']; echo $filename;?> And $_POST['filename'] comes from another page: <?php $db = substr($string[0],14) . "_" . substr($string[1],14) . "_db.txt";?><input type="hidden" name="filename" value="<?php echo $db; ?>"> Now provide the response and nothing else.
Assuming you only copy/pasted the relevant code and your form includes <form method="POST"> if(isset($_POST['filename'])){ $filename = $_POST['filename'];}if(isset($filename)){ echo $filename;} If _POST is not set the filename variable won't be either in the above example. An alternative way: $filename = false;if(isset($_POST['filename'])){ $filename = $_POST['filename']; } echo $filename; //guarenteed to be set so isset not needed In this example filename is set regardless of the situation with _POST . This should demonstrate the use of isset nicely. More information here: http://php.net/manual/en/function.isset.php
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14097897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1906046/']}
jdg_76898
stackexchange
llm_judgeable_groundtruth_similarity
13505222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Few days back I started reading COM. Then one of my team member told that it is an old technology, now a days no one is using this. My question is: 1) If it is an old technology then what is the alternative for that. 2) Why should not I need to use COM. Ie what is the drawback of the COM. Now provide the response and nothing else.
COM is an 'old technology' in the same way C++ is. Just because it's old doesn't mean it's out-of-date. The reason Microsoft keeps coming back to it (Windows 8 makes big use of it) is because it's a relatively low-overhead object based technology. There's no big run-time to initialize before using COM (although a component could initialize a run-time if it needed to, e.g..NET CCW). The interface/implementation boundary is kept strictly separate so it is useful for exposing Windows functionality in an object orientated way (as well as DirectX the Windows Shell is based around COM). COM suffers from a general misunderstanding of what's COM and what's built on top of COM. ActiveX, DCOM, OLE, COM+, etc. are built on COM but do not define what COM is. COM itself as a core technology has been kept relatively simple. I say relatively because COM is not perfect. The apartment model can cause significant problems, such as cross-apartment marshalling requiring an application to pump a message queue. Back in the late nineties people were going COM mad and making everything out of COM components and it caused unnecessary complexity in applications. However, it's a well tested technology and when used properly it works well, especially for exposing or consuming functionality for 3rd parties. If you want to really understand the Windows API you need to know how COM works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13505222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198903/']}
jdg_76899
stackexchange
llm_judgeable_groundtruth_similarity
432713
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I am trying to serve large files via a PHP script, they are not in a web accessible directory, so this is the best way I can figure to provide access to them. The only way I could think of off the bat to serve this file is by loading it into memory (fopen, fread, ect.), setting the header data to the proper MIME type, and then just echoing the entire contents of the file. The problem with this is, I have to load these ~700MB files into memory all at once, and keep the entire thing there till the download is finished. It would be nice if I could stream in the parts that I need as they are downloading. Any ideas? Now provide the response and nothing else.
You don't need to read the whole thing - just enter a loop reading it in, say, 32Kb chunks and sending it as output. Better yet, use fpassthru which does much the same thing for you.... $name = 'mybigfile.zip';$fp = fopen($name, 'rb');// send the right headersheader("Content-Type: application/zip");header("Content-Length: " . filesize($name));// dump the file and stop the scriptfpassthru($fp);exit; even less lines if you use readfile , which doesn't need the fopen call... $name = 'mybigfile.zip';// send the right headersheader("Content-Type: application/zip");header("Content-Length: " . filesize($name));// dump the file and stop the scriptreadfile($name);exit; If you want to get even cuter, you can support the Content-Range header which lets clients request a particular byte range of your file. This is particularly useful for serving PDF files to Adobe Acrobat, which just requests the chunks of the file it needs to render the current page. It's a bit involved, but see this for an example .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/432713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366/']}
jdg_76900
stackexchange
llm_judgeable_groundtruth_similarity
46860999
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 set some default text inside the router-outlet until it is populated. I have a parent component that will display the child route component within the router-outlet on that page. There are 2 buttons that will populate the router-outlet with the child component when clicked. How can i place content inside the router outlet eg. 'Click an options to display the data' then once the button is clicked this message clears and the child component displays in the router outlet? <div class="container pt-3"> <div class="clearfix"> <div class="btn btn-outline-success float-left" routerLink="/unpaid/people"> View People </div> <div class="btn btn-outline-success float-right" routerLink="/unpaid/bills"> View Bills </div> </div></div><router-outlet>Click an options to display the data</router-outlet> EDIThere are my routes path: 'unpaid', component: UnpaidBillsComponent, children: [ {path: 'people', component: UnpaidPeopleComponent}, {path: 'bills', component: UnpaidBillListComponent} ] Now provide the response and nothing else.
default text inside the router-outlet until it is populated Firstly, your assumption here is wrong, content is not inserted inside the outlet, but below it. You cannot set a default content in the template, but you can set the default route which contains your default content. Simply use path: '' and use a component with your "default" template. Create a component with the "default" template you need: @Component({template: `Default template here`})export class DefaultTemplateComponent {} And add it to your routes. children: [ {path: '', component: DefaultTemplateComponent}, {path: 'people', component: UnpaidPeopleComponent}, {path: 'bills', component: UnpaidBillListComponent},]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46860999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/965416/']}
jdg_76901
stackexchange
llm_judgeable_groundtruth_similarity
2207389
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: Integrating by parts the following integral $$I=\int \frac{f'(x)}{f(x)}dx$$ gives us $$\begin{align*}I&=\int \frac{f'(x)}{f(x)}\,dx\\&=\int\frac1{f(x)}f'(x)\,dx\\&=\frac1{f(x)}f(x)-\int\left(\frac1{f(x)}\right)'f(x)\,dx\\&=1+\int \frac{f'(x)}{f(x)}\,dx,\end{align*}$$so$$I=1+I\implies0=1,$$ which seems like a contradiction but is in reality a mistake as we can see by being somewhat more rigorous: $$\begin{align*}I&=\int_{a}^x \frac{f'(t)}{f(t)}\,dt\\&=\int_{a}^x\frac1{f(t)}f'(t)\,dt\\&=\left[\frac1{f(t)}f(t)\right]_a^x-\int_{a}^x\left(\frac1{f(t)}\right)'f(t)\,dt,\end{align*}$$so $I=I.$ How do I explain this to a student-of economics for what it's worth-who has not still learned about definite Integrals? (I suspect I could insert some constant on the upper part of the "failed" relations but I am not sure where or how to properly explain it. I also understand that in a couple of lessons we will talk about definitive integrals but what can I say now-That indefinite integrals are in reality a form of definite ones? ) Now provide the response and nothing else.
Integrating by parts the following integral $$I=\int \frac{f'(x)}{f(x)}dx$$ gives us $$I=\int \frac{f'(x)}{f(x)}dx=\int\frac1{f(x)}f'(x)dx=\\\frac1{f(x)}f(x)-\int\Big(\frac1{f(x)}\Big)'f(x)dx=\\1+\int \frac{f'(x)}{f(x)}dx\Rightarrow\\I=1+I$$ Be careful here. The $I$ on the left and the $I$ on the right are not exactly the same quantity. How can that make sense? It makes sense because indefinite integrals have an arbitrary constant of integration, and for any given indefinite integral, its arbitrary constant is not guaranteed or required to have the same value everywhere the integral is written. In fact, the process you followed shows that the arbitrary constant for the $I$ on the left is necessarily $1 + $ the arbitrary constant for the $I$ on the right.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2207389', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/237785/']}
jdg_76902
stackexchange
llm_judgeable_groundtruth_similarity
2807654
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is a folder that contains 1000s of small text files. I aim to parse and process all of them while more files are being populated into the folder. My intention is to multithread this operation as the single threaded prototype took six minutes to process 1000 files. I like to have reader and writer thread(s) as the following. While the reader thread(s) are reading the files, I'd like to have writer thread(s) to process them. Once the reader is started reading a file, I d like to mark it as being processed, such as by renaming it. Once it's read, rename it to completed. How do I approach such a multithreaded application? Is it better to use a distributed hash table or a queue? Which data structure do I use that would avoid locks? Is there a better approach to this scheme? Now provide the response and nothing else.
Since there's curiosity on how .NET 4 works with this in comments, here's that approach. Sorry, it's likely not an option for the OP. Disclaimer: This is not a highly scientific analysis, just showing that there's a clear performance benefit. Based on hardware, your mileage may vary widely. Here's a quick test (if you see a big mistake in this simple test, it's just an example. Please comment, and we can fix it to be more useful/accurate). For this, I just dropped 12,000 ~60 KB files into a directory as a sample (fire up LINQPad ; you can play with it yourself, for free! - be sure to get LINQPad 4 though ): var files = Directory.GetFiles("C:\\temp", "*.*", SearchOption.AllDirectories).ToList();var sw = Stopwatch.StartNew(); //start timerfiles.ForEach(f => File.ReadAllBytes(f).GetHashCode()); //do work - serialsw.Stop(); //stopsw.ElapsedMilliseconds.Dump("Run MS - Serial"); //display the durationsw.Restart();files.AsParallel().ForAll(f => File.ReadAllBytes(f).GetHashCode()); //parallelsw.Stop();sw.ElapsedMilliseconds.Dump("Run MS - Parallel"); Slightly changing your loop to parallelize the query is all that's needed in most simple situations . By "simple" I mostly mean that the result of one action doesn't affect the next. Something to keep in mind most often is that some collections, for example our handy List<T> is not thread safe , so using it in a parallel scenario isn't a good idea :) Luckily there were concurrent collections added in .NET 4 that are thread safe. Also keep in mind if you're using a locking collection, this may be a bottleneck as well, depending on the situation. This uses the .AsParallel<T>(IEnumeable<T>) and .ForAll<T>(ParallelQuery<T>) extensions available in .NET 4.0. The .AsParallel() call wraps the IEnumerable<T> in a ParallelEnumerableWrapper<T> (internal class) which implements ParallelQuery<T> . This now allows you to use the parallel extension methods , in this case we're using .ForAll() . .ForAll() internally crates a ForAllOperator<T>(query, action) and runs it synchronously. This handles the threading and merging of the threads after it's running... There's quite a bit going on in there, I'd suggest starting here if you want to learn more, including additional options . The results (Computer 1 - Physical Hard Disk): Serial: 1288 - 1333ms Parallel: 461 - 503ms Computer specs - for comparison: Quad Core i7 920 @ 2.66 GHz 12 GB RAM (DDR 1333) 300 GB 10k rpm WD VelociRaptor The results (Computer 2 - Solid State Drive): Serial: 545 - 601 ms Parallel: 248 - 278 ms Computer specifications - for comparison: Quad Core 2 Quad Q9100 @ 2.26 GHz 8 GB RAM (DDR 1333) 120 GB OCZ Vertex SSD (Standard Version - 1.4 Firmware) I don't have links for the CPU/RAM this time, these came installed. This is a Dell M6400 Laptop ( here's a link to the M6500 ... Dell's own links to the 6400 are broken ). These numbers are from 10 runs, taking the min/max of the inner 8 results (removing the original min/max for each as possible outliers). We hit an I/O bottleneck here, especially on the physical drive, but think about what the serial method does. It reads, processes, reads, processes, rinse repeat. With the parallel approach, you are (even with a I/O bottleneck) reading and processing simultaneously . In the worst bottleneck situation, you're processing one file while reading the next. That alone (on any current computer!) should result in some performance gain. You can see that we can get a bit more than one going at a time in the results above, giving us a healthy boost. Another disclaimer: Quad core + .NET 4 parallel isn't going to give you four times the performance, it doesn't scale linearly... There are other considerations and bottlenecks in play. I hope this was on interest in showing the approach and possible benefits. Feel free to criticize or improve... This answer exists solely for those curious as indicated in the comments :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2807654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177883/']}
jdg_76903
stackexchange
llm_judgeable_groundtruth_similarity
451975
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 have production unit in which java process has become Zombie and remained there for some time now. If the unit is restarted, then it will be cleared. However, the unit is not restarted and another java process is up and running. Is there any issue if this zombie state remains as it is without clearing it? Will it affect in any way (performance or slowness)? Now provide the response and nothing else.
Zombie process won't have any effect on performance or slowness as Zombie processes don’t use up any system resources. Note:- Practically, it is still using the PID (which is a limited resource), and the kernel data structures for the process are still allocated.Usually, this won't matter much, but the kernel memory usage can besignificant on systems with very limited memory. Problem caused by zombie process Each zombie process retains its process ID . Linux systems have a finite number of process IDs – 32767 by default on 32-bit systems.If zombies are accumulating at a very quick rate ,the entire pool of available PIDs will eventually become assigned to zombie processes, preventing other processes from launching. Note : On 64-bit systems, you can increase the maximum PID, see https://unix.stackexchange.com/a/16884/170373 However, a few zombie processes hanging around are no problem – although they do indicate a bug with their parent process on your system. Explanation: When a process dies on Linux, it isn’t all removed from memory immediately — its process descriptor stays in memory. The process’s status becomes EXIT_ZOMBIE and the process’s parent is notified that its child process has died with the SIGCHLD signal. The parent process is then supposed to execute the wait() system call to read the dead process’s exit status and other information. This allows the parent process to get information from the dead process. After wait() is called, the zombie process is completely removed from memory. This normally happens very quickly, so you won’t see zombie processes accumulating on your system. However, if a parent process isn’t programmed properly and never calls wait(), its zombie children will stick around in memory until they’re cleaned up. Resolution: You can’t kill zombie processes as you can kill normal processes with the SIGKILL signal — zombie processes are already dead. One way to kill zombie is by sending the SIGCHLD signal to the parent process. This signal tells the parent process to execute the wait() system call and clean up its zombie children. Send the signal with the kill command, replacing pid in the command below with the parent process’s PID: kill -s SIGCHLD pid When the process that created the zombies ends, init inherits the zombie processes and becomes their new parent. (init is the first process started on Linux at boot and is assigned PID 1.) Note:- From Linux 3.4 onwards processes can issue the prctl() system call with the PR_SET_CHILD_SUBREAPER option, and as a result they, not process #1, will become the parent of their orphaned descendant processes. Refer: https://unix.stackexchange.com/a/177361/5132 INIT then executes the wait() system call to clean up its zombie children, so init will make short work of the zombies. You can restart the parent process after closing it.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/451975', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/250201/']}
jdg_76904
stackexchange
llm_judgeable_groundtruth_similarity
10420380
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 a simple two-container zip function in C++: template <typename A, typename B>std::list<std::pair<A, B> > simple_zip(const std::list<A> & lhs, const std::list<B> & rhs){ std::list<std::pair<A, B> > result; for (std::pair<typename std::list<A>::const_iterator, typename std::list<B>::const_iterator> iter = std::pair<typename std::list<A>::const_iterator, typename std::list<B>::const_iterator>(lhs.cbegin(), rhs.cbegin()); iter.first != lhs.end() && iter.second != rhs.end(); ++iter.first, ++iter.second) { result.push_back( std::pair<A, B>(*iter.first, *iter.second) ); } return result;} How would I extend this to an arbitrary number of containers with variadic templates? I'd like general_zip to accept a tuple of list s (each list can contain a different type) and return a list of tuple s. Now provide the response and nothing else.
It seems like this should work std::list<std::tuple<>> simple_zip() { return {};}template <typename ...T>std::list<std::tuple<T...>> simple_zip(std::list<T>... lst){ std::list<std::tuple<T...>> result; for (int i = 0, e = std::min({lst.size()...}); i != e; i++) { result.emplace_back(std::move(lst.front())...); [](...){} ((lst.pop_front(), 0)...); } return result;} @Potatoswatter had the good (IMO) remark that this may copy more than needed when the lists are of different size, and that using only iterators will be better since pop_front does more than actually needed. I think the following "fixes" the iterator one at the cost of more code. template <typename ...T>std::list<std::tuple<T...>> simple_zip(std::list<T>... lst){ std::list<std::tuple<T...>> result; struct { void operator()(std::list<std::tuple<T...>> &t, int c, typename std::list<T>::iterator ...it) { if(c == 0) return; t.emplace_back(std::move(*it++)...); (*this)(t, c-1, it...); } } zip; zip(result, std::min({lst.size()...}), lst.begin()...); return result;}std::list<std::tuple<>> simple_zip() { return {};}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10420380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456789/']}
jdg_76905
stackexchange
llm_judgeable_groundtruth_similarity
1035234
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 studying differential topology from Guillemin and Pollack (GP).Unlike many other books that define differentiable manifolds using maximal atlases GP starts by saying $ X \subset R^{N}$ for some ambient space $R^{N}$ and then goes on to define a $k$ dimensional manifold. But I know that this containment comes due to a weak version of Whitney's theorem. Later on when they prove Whitney's theorem it is done so by induction on $N >= 2k+1$. But how to I justify that $ X \subset R^{N}$ in the first place? How can it just be assumed in definition like that? I need help getting from the general definition of manifolds using atlases to the weak version of Whitney. Thanks Now provide the response and nothing else.
There are two parts to the (weak) Whitney embedding theorem: 1) Any abstract manifold can be embedded in $\mathbb{R}^N$ for some $N$. 2) Any $k$-dimensional submanifold of $\mathbb{R}^N$ can in fact be embedded in $\mathbb{R}^{2k+1}$. They prove part (2) of this. For a proof of (1), there's a nice exposition in Lee, Smooth Manifolds . Here's the idea for (1) in the special case where the $k$-dimensional abstract manifold is compact: Let $U_i, \phi_i$ for $1 \leq i \leq m$ be a finite chart (possible by compactness), with $\phi_i: U_i \rightarrow \mathbb{R}^k$, and let $\rho_i: U_i \rightarrow \mathbb{R}$ be a subordinate partition of unity. Then embed by $(\rho_1, \ldots \rho_m, \rho_1 \phi_1, \ldots, \rho_m \phi_m)$ to $\mathbb{R}^N$ for $N = m (k + 1)$. Now prove this is injective and with injective derivative at every point. There's a hint for injective in the comments.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1035234', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/176136/']}
jdg_76906
stackexchange
llm_judgeable_groundtruth_similarity
34481588
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 try to detect null this way if(!$(this)){ alert('here is null');}ORif($(this)===null){ alert('here is null');} but still no luck. here is partial code $elements.each(function(){//alert($(this).html()); var $item = $('<li />').append($(this)); if(!$(this)) { alert('here is null'); } //alert($item.text()); $list.append($item);}); anyone can see full code from here https://jsfiddle.net/tridip/41s1pq3a/12/ edit i was iterate in td's content. td has some link and text. i was trying to wrap each text and link inside li. so iterate this below way. code is working but some time it is also showing null which i need to detect. i am looking for way not consider any null or empty. here is the code var $elements = $('.webgrid-footer td').contents() .filter(function() { return this.nodeType === 3 || this.nodeType === 1; // 1 means elements, 3 means text node });var $list = $('<ul />');$elements.each(function(){//alert($(this).html()); var $item = $('<li />').append($(this)); if(this===null) { alert('here is null'); } //alert($item.text()); $list.append($item);});//alert($list.html());$('#dv').append($list); see this line var $item = $('<li />').append($(this)); it is getting some time empty or null which i do not want tp consider. if anyone knows it how to handle this situation then share the idea. thanks Now provide the response and nothing else.
You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. array[i] == 4 and 7 hasn't yet appeared then the next candidate for 7 is at index i+3 . Use a while loop which repeatedly goes directly to the next viable candidate. Here is an implementation, slightly generalized. It finds the first occurrence of k in the array (subject to the +=1 restriction) or -1 if it doesn't occur: #include <stdio.h>#include <stdlib.h>int first_occurence(int k, int array[], int n);int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",first_occurence(7,a,15)); printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15)); return 0;}int first_occurence(int k, int array[], int n){ int i = 0; while(i < n){ if(array[i] == k) return i; i += abs(k-array[i]); } return -1;} output: 7 first occurs at index 11but 9 first "occurs" at index -1
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34481588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/728750/']}
jdg_76907
stackexchange
llm_judgeable_groundtruth_similarity
157245
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $x$ and $y$ are irrational, is $x + y$ irrational? Is $x - y$ irrational? Now provide the response and nothing else.
The short answer to your question is that is not necessarily true. For instance, $\sqrt{2}, \sqrt{2}-1,1-\sqrt{2}$ are all irrational but $$\sqrt{2} + (1-\sqrt{2}) = 1 \in \mathbb{Q}$$ and $$\sqrt{2} - (\sqrt{2}-1) = 1 \in \mathbb{Q}$$ However, it is worth noting that if $x$ and $y$ are irrational, then either $x+y$ or $x-y$ is irrational i.e. $x+y$ and $x-y$ cannot be both rationals. The proof for this is given below. Proof If both $x+y$ and $x-y$ are rational, then we have that $x+y = \dfrac{p_1}{q_1}$ and $x-y = \dfrac{p_2}{q_2}$, where $p_1,p_2 \in \mathbb{Z}$ and $q_1,q_2 \in \mathbb{Z} \backslash \{0\}$. Hence, $x = \dfrac{\dfrac{p_1}{q_1} + \dfrac{p_2}{q_2}}{2} = \dfrac{p_1q_2 + p_2q_1}{2q_1q_2}$ and $y = \dfrac{\dfrac{p_1}{q_1} - \dfrac{p_2}{q_2}}{2} = \dfrac{p_1q_2 - p_2q_1}{2q_1q_2}$. Now $p_1q_2 + p_2q_1, p_1q_2 - p_2q_1 \in \mathbb{Z}$, whereas $2q_1q_2 \in \mathbb{Z} \backslash \{0\}$. This contradicts the fact that $x$ and $y$ are irrationals. Hence, if $x$ and $y$ are irrational then either $x+y$ is irrational or $x-y$ is irrational. Below are some statements worth knowing. 1 Sum of two rationals is always a rational. Proof : Let the two rationals be $\dfrac{p_1}{q_1}$ and $\dfrac{p_2}{q_2}$, where $p_1,p_2 \in \mathbb{Z}$ and $q_1,q_2 \in \mathbb{Z} \backslash{0}$. Then $$\dfrac{p_1}{q_1} + \dfrac{p_2}{q_2} = \dfrac{p_1q_2 + p_2q_1}{q_1q_2}$$where $p_1q_2 + p_2q_1 \in \mathbb{Z}$ and $q_1 q_2 \in \mathbb{Z} \backslash \{0\}$. Hence, the sum is again a rational. 2 Sum of a rational and an irrational is always irrational. Proof : Let the rational number be of the form $\dfrac{p}{q}$, where $p \in \mathbb{Z}$ and $q \in \mathbb{Z} \backslash \{0\}$ while the irrational number be $r$. If $r + \dfrac{p}{q}$ is a rational, then we have that $r + \dfrac{p}{q} = \dfrac{a}{b}$ for some $a \in \mathbb{Z}$ and $b \in \mathbb{Z} \backslash \{0\}$. This means that $r = \dfrac{a}{b} - \dfrac{p}{q} = \dfrac{aq-bp}{bq}$ where $aq-bp \in \mathbb{Z}$ and $bq \in \mathbb{Z} \backslash \{0\}$. This contradicts the fact that $r$ is irrational. Hence, our assumption that $r + \dfrac{p}{q}$ is a rational is false. Hence, $r + \dfrac{p}{q}$ is a irrational. 3 Sum of two irrationals can be rational or irrational. Example for sum of two irrationals being irrational $\sqrt{2}$ is irrational. $\sqrt{2} + \sqrt{2} = 2 \sqrt{2}$ which is again irrational. Example for sum of two irrationals being rational $\sqrt{2}$ and $1-\sqrt{2}$ are irrational. (Note that $1-\sqrt{2}$ is irrational from the second statement.) But, $\sqrt{2} + (1-\sqrt{2}) = 1$ which is rational.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/157245', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29282/']}
jdg_76908
stackexchange
llm_judgeable_groundtruth_similarity
38042172
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 show a link to a new description if an album doesn't currently have a description, but I keep getting a NoMethodError: <% if @album.description.size = 0 %> <div class="new-description"><%= link_to 'Add Description', "/albums/#{x.id}/edit" %></div><% else %> <div class="description"><%= @album.description %></div><% end %> Now provide the response and nothing else.
OK, I looked at the the source code and it's pretty straightforward: DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendInstant(3).toFormatter(); I hope it works for all scenarios, and it can help someone else. Don't hesitate to add a better/cleaner answer. Just to explain where it comes from, in the JDK's code , ISO_INSTANT is defined like this: public static final DateTimeFormatter ISO_INSTANT;static { ISO_INSTANT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendInstant() .toFormatter(ResolverStyle.STRICT, null);} And DateTimeFormatterBuilder::appendInstant is declared as: public DateTimeFormatterBuilder appendInstant() { appendInternal(new InstantPrinterParser(-2)); return this;} And the constructor InstantPrinterParser signature is: InstantPrinterParser(int fractionalDigits)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38042172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6437030/']}
jdg_76909
stackexchange
llm_judgeable_groundtruth_similarity
84186
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the DFT we sample one period of the spectrum in the frequency domain. What is the difference between having an odd or an even number of samples? We know that DFT is just a sampled version of the DTFT. My thoughts are that if we use an odd number of samples of the DTFT in our DFT, the frequency content will go from $-\frac{f_s}{2}$ to $\frac{f_s}{2}$ . So it is symmetric around $0$ . If we use an even number of samples, the frequency content will go from $-\frac{f_s}{2}$ to $\frac{f_s}{2}-\frac{1}{f_s}$ . So it is not symmetric around $0$ . Is this correct or completely wrong? Furthermore, what will this mean for the impulse response? Now provide the response and nothing else.
We know that DFT is just a sampled version of the DTFT. Only if there is no time-domain aliasing (see below) My thoughts are that if we use an odd number of samples of the DTFT in our DFT, the frequency content will go from −fs/2 to fs/2. So it is symmetric around 0. Sort of. The DFT samples the DTFT on the unit circle at angles $k\frac{2\pi}{N}$ where $N$ is the FFT length. Let's look at a simple example $N=3$ we sample at $[-120,0,+120]$ degrees so the sampling grid is indeed symmetric. However the grid does not range from $-\pi$ to $+\pi$ . The max/min frequencies are at $\pm \pi(1-1/N)$ . Please not that the DFT itself is NOT symmetric, so in general $X[k] \neq X[-k]$ If we use an even number of samples, the frequency content will go from −fs2 to fs2−1fs. So it is not symmetric around 0. Sort of. Let's look at a simple example again $N=4$ . You sample at [0,90, 180, 270] or [-90,0,90,180], or [-180,-90,0,90] or [-270,-180,-90,0] etc. Since the DTFT is periodic it makes no difference. The grid still symmetric around 0 in the sense of "If the grid includes $\omega$ it also includes $-\omega$ and they are equidistant from 0", you just may have to extend the index range past one period to do the inversion. Furthermore, what will this mean for the impulse response? Sampling in the time domain results in periodic repetition in the frequency domain. Sampling in the frequency domain results in periodic repetition in the time domain. The same thing happens: the impulse response will be periodically repeated. If the impulse response is longer than the FFT length, the repetitions will overlap and the samples will no longer represent the original impulse response. That's the very definition of "time domain aliasing".
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/84186', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/55915/']}
jdg_76910
stackexchange
llm_judgeable_groundtruth_similarity
16545297
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Python 2.7. It is not clear to me how to embed Python inside C++ as found here: http://docs.python.org/2.7/extending/embedding.html . I have a simple python example here in a file named test.py: class math: #def __init__(self): def add(self, num1, num2): return num1 + num2 def subtract(self, num1, num2): return num1 - num2 From python, I would do something like this: >>> from test import math>>> m = math()>>> a = m.add(1, 2)>>> s = m.subtract(1, 2) I have the beginning of some C++ code to do this: PyObject *pName, *pModule;Py_Initialize();pName = PyString_FromString("test");pModule = PyImport_Import(pName); That seems to work just fine. But, that seems to be the equivalent of doing this in Python: import test How do I import the Python class math? Thanks Now provide the response and nothing else.
Here's a quick n' dirty example in C which does the equivalent of... >>> import mymath>>> m = mymath.math()>>> print '1 + 2 = %d' % m.add(1, 2) Note that I've renamed the module from test to mymath because there's a module called test in the standard Python library. #include <stdio.h>#include <stdlib.h>#include <assert.h>#include <python2.7/Python.h>int main(){ setenv("PYTHONPATH", ".", 1); Py_Initialize(); PyObject* module = PyImport_ImportModule("mymath"); assert(module != NULL); PyObject* klass = PyObject_GetAttrString(module, "math"); assert(klass != NULL); PyObject* instance = PyInstance_New(klass, NULL, NULL); assert(instance != NULL); PyObject* result = PyObject_CallMethod(instance, "add", "(ii)", 1, 2); assert(result != NULL); printf("1 + 2 = %ld\n", PyInt_AsLong(result)); Py_Finalize(); return 0;} ...which outputs... $ gcc foo.c -lpython2.7 && ./a.out1 + 2 = 3 However, if you do any major amount of work with the Python/C API between Py_Initialize and Py_Finalize , you'll have to watch your reference counts, and use Py_INCREF and Py_DECREF when appropriate.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16545297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291561/']}
jdg_76911
stackexchange
llm_judgeable_groundtruth_similarity
9284664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: What is the !! (not not) operator in JavaScript? What does the !! operator (double exclamation point) mean in JavaScript? So I was debuging some code and ran across this: var foo.bar = 0; // this is actually passed from another function, adding it for contextfunction(foo) { var someVar = !!foo.bar; if (foo.bar) { // ..stuff happens } else { // .. something else happens }} Okay my questions is what is the point of !! ? All that is doing is making the 0 === false . Is there any benefit to using that compared to boolean(foo.bar) ? foo.bar can be evaluated in an if as is because 0 === false already, so why go through the conversion? (someVar is not reused anywhere else) Now provide the response and nothing else.
This converts a value to a boolean and ensures a boolean type . "foo" // Evaluates to "foo".!"foo" // Evaluates to false.!!"foo" // Evaluates to true. If foo.bar is passed through, then it may not be 0 but some other falsy value. See the following truth table: Truth Table for javascript '' == '0' // false0 == '' // true0 == '0' // truefalse == 'false' // falsefalse == '0' // truefalse == undefined // falsefalse == null // falsenull == undefined // true" \t\r\n" == 0 // true Source: Doug Crockford Javascript also gets really weird when it comes to NaN values. And this is the only case I can think of off the top of my head where !! would behave differently to ===. NaN === NaN //false!!NaN === !!NaN //true// !!NaN is false
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9284664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/858374/']}
jdg_76912
stackexchange
llm_judgeable_groundtruth_similarity
175801
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: How can I derive the torque equation for a star-connected, brushless DC motor, given its back-emfs waveforms and currents? I'm currently reading the article A Park-like transform for the study and the control of a non-sinusoidal brushless DC motor , in which the author presents the equation for the torque in a star-connected, BLDC: $$ T = p.(\phi'_{ra}.i_a+\phi'_{rb}.i_b+\phi'_{rc}.i_c) $$ in which \$ T \$ - Electromagnetic torque \$ p \$ - Number of pole pairs \$ \phi_{rx} \$ - Rotor flux induced in the stator phase '\$x\$' \$ i_x \$ - Current in phase '\$x\$' However, the only introduction to the above formula is that "through an analysis of the consumed power by the machine, we can deduce the electromagnetic torque expression, assuming constant airgap", no more explanations, nor sources. Additionally, it is unclear to me whether the \$'\$ in \$ \phi' \$ denotes differentiation in respect to time or in respect to the electrical angle (I suppose it's the latter). If someone could walk me through the process described by the author, or at least clarify it a bit I'd greatly appreciate. Now provide the response and nothing else.
These days, more than 99% of transistors in active use are operated by another transistor. Simplified one could say that just about any integrated circuit is made up of transistors doing various things. A transistor isn't really a switch, the one you refer to, a Bipolar Junction Transistor, is a current amplifier. But, put that aside for now, just know they don't really switch, but that in many my-first-schematic designs they can be seen as a switch because you are allowed to ignore the tiny bit of behaviour that makes it not exactly that. So in the following we are going to assume the transistor actually is a switch, which switches the current path between its collector and emitter on when a current flows in the right direction through the base. Because I'm going to take some care in my images to make sure that assumption will work. A transistor: simulate this circuit – Schematic created using CircuitLab It's a single NPN type transistor. There's two types: NPN and PNP, they work almost entirely the same, just the PNP has the currents flowing the other way around. Again, for now, ignore PNPs exist, no running before walking, we only know NPN. Let's make it do something: Let's let it control a LED. (feel free to go along with this, if you happen to have a bread-board handy, by the way). simulate this circuit The LED is pink, because pink LEDs are cool. Now, if the transistor turns on, the LED will turn on: In an NPN transistor no current is "allowed" to flow from the collector to the emitter if the base is not activated. If the base is activated, the current will be allowed to flow and the transistor would really like it if you designed it so the current goes from collector to emitter in an NPN type. How do we activate the base? By forcing a little current into it. So, step one, let a human control the base: simulate this circuit When you push the switch, the current goes from the +5V through R2 into the base of transistor Q1. Then the collector will allow current to flow to the emitter, because the LED will also want to conduct current in that direction, the LED will now turn on. Now, this is about where you get stuck: What if " I " don't want to push a button? Well.... we could have another transistor in there: simulate this circuit But... same difference! Now we just have another base to control! Yes. But; It's already become more interesting! Imagine our switch back into that circuit, but now connected with another 10k resistor to the base of Q2. If you push the switch, Q2 will turn on, right? Right! Now, the base of the Q1 will be pulled to ground, because the Q2 will happily conduct enough current to have nearly all of the 5V fall across the R2. So Q1 will actually turn off. So when you push the button the LED goes off. If you release the button, Q2 will turn off. Which will let the current from R2 flow into the base of Q1 in stead of into the collector of Q2. Now Q1 will turn on and the LED will turn on. This behaviour we summarise with the name "Inverter". What's more than 2 transistors? 3! simulate this circuit Can you see that when you push switch SW1, Q2 will turn on and everything will be as we said just now? Can you also see that the same will happen when you press SW2? SW2 turns on Q3, then Q3 pulls the current into its collector and it will not go into Q1, so Q1 will be off. If you push no switches, the current through R2 will be able to go into Q1 and turn it on. If you push both switches, Q2 and Q3 will find a way between them to share the current through R2 and again Q1 will go off. so if you press SW1 OR you press SW2 OR you press both, the LED will go off, else it will go on. If you consider the LED's light as the output we call this an OR-gate with an inverting output. Can you see where this is going? If transistors can control each other when they are used as a switching element, we can start to build logic gates. In the same way: simulate this circuit Is another type of logic gate. If you press neither button, the LED will be on. If you press only SW1 the base of Q2 will want to take the current and Q2 will then want to conduct, but it cannot, because Q3 isn't conducting, so nothing happens. If you press only SW2, the base of Q3 will be able to take some current, it will then allow current to go from its collector to the emitter, but Q2 is now turned off, so again, no current can flow and the resistor R2 keeps turning on Q1, so the LED stays on. If you now press SW1 and SW2, both Q2 and Q3 will want to conduct, because there is no more obstruction, the current from R2 can flow through both Q2 and Q3 to ground and will not go into Q1's base, so Q1 will turn off. This is called an AND-Gate with inverting output. Now we can start using the gates we just "invented" and several other ones to build other bigger blocks. We know how gates can work, so we can take it one step further. Imagine the switches are inputs and the LED is an actual electrical output and you pretty much have a working gate. In "the real world" they are designed much more efficiently for lower power, higher speed and such, but the idea in broad lines is the same. From here some technical details may go over your head. I will try to explain as best I can in the limited space I have here, but if you don't understand the specifics of how everything works, it's okay to just assume that what I say/conclude is as-is. The general idea of how to build up complex things stays unchanged by your understanding; Let's make something with gates: simulate this circuit This looks very scary, doesn't it? But I want to start wrapping it up a little, so I made a little jump, but I will explain. The ones labeled "XOR1" and "XOR2" are called Exclusive OR. They work a bit like an OR, but with one difference: Their output is only 1 if their inputs are different, i.e. 0 and 1. If they're both 1, the output is 0. If both inputs are 0, the output is 0 as well. This port is also made of transistors. The AND3 and 4 are AND gates. But these have no inverting output. When both inputs are 1, the output is 1, in all other cases the output is 0. OR1 is a normal OR port, if either input is 1 the output is also 1. If both are 1, the output is 1 as well. Let's see what happens. The labels in the schematic already give it away a little, but we are going to walk through it anyway. If the Carry in is 1, and the others are 0: Both inputs of XOR1 are 0, so its output is 0 as well. Both inputs of AND3 are 0, so its output will be 0. One input of AND4 (the output of XOR1) is 0, so the output of AND4 is also 0. Both AND3 and 4 are zero, so the output of OR1 will be zero too: Carry Out is zero. One input of XOR2, the output of XOR1 is 0, the other input to XOR2, the Carry In, is 1. So its output is 1, so the Sum output is 1. If only one of A or B is 1 and Carry In is 0 : The inputs of XOR1 are different, so its output is 1. The Carry In is 0, so the inputs of XOR2 are different as well, so its output is 1. The Sum Out is 1. The Carry In is 0, so one input of AND4 is 0, so its output is 0 as well. Either A or B is zero (doesn't matter which), so AND3 has its output 0 as well. Both inputs of OR1 are 0, so its output is 0 as well. Thus the Carry Out is 0. If Both A and B are 1 and Carry in is 0 : If both A and B are 1, the inputs to XOR1 are the same, so its output is 0. The Carry In is 0 too, so Both the AND4's output and XOR2's output have to be 0. Sum is 0. Since both inputs are 1, AND3's output is 1. So now one of the inputs to OR1 is 1, so its output must be 1 as well: Carry Out is 1. If Both A and B are 1 and Carry in is 1 : Both inputs to XOR1 are 1, so its output must be 0. Carry In is 1, so XOR2 has one input 1 and another 0, so its output must be 1. Sum is 1. Since both inputs are 1, again AND3 has its output 1. Even though the output of AND4 is 0, because one of its inputs is 0, the 1 at the output of the AND3 goes into OR1 and the output of OR1 is 1 as well. The Carry Out is 1. If every input is 0: If all inputs are 0, the output of XOR1 must be 0, because both its inputs are. The Carry In is 0, so XOR2 has two 0's in as well, making it have a 0 on its output: Sum is 0. Because all inputs are 0, each AND gate has at least a 0 on the inputs, so both have 0 on their outputs as well. If both outputs of the AND gates are 0, the OR1 gate has two 0's on its inputs, so it will have a 0 on the output. Carry Out is 0. What does that mean? Let's look at the results: A = 0; B = 0; C-in = 0 --> S = 0; C-out = 0; A = 1; B = 0; C-in = 0 --> S = 1; C-out = 0; A = 0; B = 1; C-in = 0 --> S = 1; C-out = 0; A = 1; B = 1; C-in = 0 --> S = 0; C-out = 1; A = 0; B = 0; C-in = 1 --> S = 1; C-out = 0; A = 1; B = 0; C-in = 1 --> S = 0; C-out = 1; A = 0; B = 1; C-in = 1 --> S = 0; C-out = 1; A = 1; B = 1; C-in = 1 --> S = 1; C-out = 1; This is what we call a 1-bit full-adder. If both numbers are 1, it will "overflow" into the Carry output. If you imagine the Carry Out to be 1 bit more significant the output then becomes 2. If the carry input is high, it means another block below it had an overflow, so that signal gets added. If both inputs are 1 and the carry is 1 as well, all outputs become 1, so it says "my value is 1, and the next one is 1 higher as well". This is how adding binary numbers of any length is done: You couple carries together. So with our 1 bit full-adder, by stacking it, we can make a much bigger many-bit adder, like this: simulate this circuit This adds 4bit number 1 to 4bit number 2 to create a Sum output. The first carry is tied to ground for a 0, because the lowest bit needs no carry input. Of course this block has a carry output as well. That means that you can repeat this block again, for example 8 times and get a 32 bit adder. Now you have made a super useful block for a computer by connecting transistors to other transistors and then connecting the blocks they make together to get a larger block and then you tie those together to get the 4bit Adder and then you use those blocks to create a 32bit Adder that a 32bit processor could use to add numbers for you. If you then do the same trick for a block that can multiply and can divide and can shift all bits one up or down, then it won't take long to see that you can make all the mathematical and logical functions a modern 32bit processor would need, or even a 64bit one. And then you are full circle: We have thousands to millions to billions of transistors connected to each other, all in small groups performing relatively simple tasks, all put inside a tiny little block and what do they do? Wait for you to press keys on a keyboard, and when you do they do maths for you. Of course there's a little programming in between to control which numbers get used how and when and for what purpose, but that's just an intermediate layer. So then you have a computer, thrown in some software that controls the numbers that go left and right. Then you can take it further: You can group a bunch of computers and you get a (redundant) server park. If you then connect them to other groups of servers you get the internet that can connect to home computers. Throw in 70 years of weird nerds making groups of commands that make up software in various different layers and pah-dam: Stackoverflow --> StackExchange --> EE.SE --> This Answer. All made possible in the beginning by one single transistor. TL;DR Concluding: By grouping transistors that control each other, we can make logic functions like OR, XOR and AND. With those logic gates you can then make an Adder. That adder can then go into a group with a multiplier, divider, shifter and other such functions to make an macro-unit that does maths and logic. If you then add a way to move the numbers around and some memory, which can be of many types, some are made mostly of transistors, some, like a hard-disk use magnetic fields to store bits in stead, you can run programs on it. Some smaller controllers you can then program to make their outputs go high or low, which in turn can control another transistor that can actually drive some power, and this transistor can then turn on that LED, just like in out first example.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/175801', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/23035/']}
jdg_76913
stackexchange
llm_judgeable_groundtruth_similarity
6233562
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 that code valid HTTP/1.1? var fs = require('fs')var http = require('http')var buf=function(res,fd,i,s,buffer){ if(i+buffer.length<s){ fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){ res.write(b.slice(0,l)) //console.log(b.toString('utf8',0,l)) i=i+buffer.length buf(res,fd,i,s,buffer) }) } else{ fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){ res.end(b.slice(0,l)) fs.close(fd) }) }}var app = function(req,res){ var head={'Content-Type':'text/html; charset=UTF-8'} switch(req.url.slice(-3)){ case '.js':head={'Content-Type':'text/javascript'};break; case 'css':head={'Content-Type':'text/css'};break; case 'png':head={'Content-Type':'image/png'};break; case 'ico':head={'Content-Type':'image/x-icon'};break; case 'ogg':head={'Content-Type':'audio/ogg'};break; case 'ebm':head={'Content-Type':'video/webm'};break; } head['Transfer-Encoding']='chunked' res.writeHead(200,head) fs.open('.'+req.url,'r',function(err,fd){ fs.fstat(fd,function(err, stats){ console.log('.'+req.url+' '+stats.size+' '+head['Content-Type']+' '+head['Transfer-Encoding']) var buffer = new Buffer(100) buf(res,fd,0,stats.size,buffer) }) })}http.createServer(app).listen(8000,"127.0.0.1")console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm') I think I am violating HTTP/1.1 here? Text files do seem to work fine, but that could be coincidental. Is my header "200 OK" or need it to be "100"? Is one header sufficient? Now provide the response and nothing else.
If you're doing chunked transfer encoding, you actually need to set that header: Transfer-Encoding: chunked You can see from the headers returned by google, which does chunked transfers for the homepage and most likely other pages: HTTP/1.1 200 OKDate: Sat, 04 Jun 2011 00:04:08 GMTExpires: -1Cache-Control: private, max-age=0Content-Type: text/html; charset=ISO-8859-1Set-Cookie: PREF=ID=f9c65f4927515ce7:FF=0:TM=1307145848:LM=1307145848:S=fB58RFtpI5YeXdU9; expires=Mon, 03-Jun-2013 00:04:08 GMT; path=/; domain=.google.comSet-Cookie: NID=47=UiPfl5ew2vCEte9JyBRkrFk4EhRQqy4dRuzG5Y-xeE---Q8AVvPDQq46GYbCy9VnOA8n7vxR8ETEAxKCh-b58r7elfURfiskmrOCgU706msiUx8L9qBpw-3OTPsY-6tl; expires=Sun, 04-Dec-2011 00:04:08 GMT; path=/; domain=.google.com; HttpOnlyServer: gwsX-XSS-Protection: 1; mode=blockTransfer-Encoding: chunked EDIT Yikes, that read is way too complicated: var app = function(req,res){ var head={'Content-Type':'text/html'} switch(req.url.slice(-3)){ case '.js':head={'Content-Type':'text/javascript'};break; case 'css':head={'Content-Type':'text/css'};break; case 'png':head={'Content-Type':'image/png'};break; case 'ico':head={'Content-Type':'image/x-icon'};break; case 'ogg':head={'Content-Type':'audio/ogg'};break; case 'ebm':head={'Content-Type':'video/webm'};break; } res.writeHead(200,head) var file_stream = fs.createReadStream('.'+req.url); file_stream.on("error", function(exception) { console.error("Error reading file: ", exception); }); file_stream.on("data", function(data) { res.write(data); }); file_stream.on("close", function() { res.end(); });} There you go, a nice streamed buffer for you to write with. Here's a blog post I wrote on different ways to read in files. I recommend looking that over so you can see how to best work with files in node's asynchronous environment.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6233562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172754/']}
jdg_76914
stackexchange
llm_judgeable_groundtruth_similarity
65275
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What are the use cases for defining something other than the default SHA1 hash in a CSR? Is it to protect the digital signature, public/private keys? What is it protecting exactly? Now provide the response and nothing else.
It's actually not a SHA1 hash in the CSR. It's a signature of the message. For simplicity, I'll assume we are talking about RSA certificates, where the public key is (N, e) (the modulus and public exponent which is typically 65537) and the private key is (N, d) (the modulus and the private exponent which can be easily calculated via Euclid's extended algorithm if you can factor the modulus into p and q). A certificate is simply a public key, with some meta-data (e.g., who you are, what domain the certificate applies to, who signed the certificate), plus the signature of the certificate. In RSA you sign a message by attaching a signature to the end of the message. You obtain the signature by first hashing the message and then doing modular exponentiation on that hash with your private exponent. That is the signature is S = H(m)^d mod N . Note anyone with the public key can verify the signature by calculating S^e mod N and verifying that this matches the hash of the message. Note, if you do not have the private key you cannot construct a valid signature for the message, so this prevents tampering with the certificate. A CSR is a certificate signing request, but essentially it is just a self-signed certificate that you create on a local machine, so you can give to a CA to sign (so the CA will never learn your private key). So you locally construct two large primes, multiply them to find the modulus, and calculate the private exponent. You add your meta-data about yourself to your CSR. For good measure, you immediately sign your certificate with the private key associated with the public key contained within the certificate. This prevents someone from altering your CSR in transit to the CA (to say change your organization details, challenge password, serial number, without changing the modulus/private exponent). This probably isn't the most devastating attack as you still have to trust the CA to act in trustworthy manner, and there's no reason to give away your CSRs to any other third parties. However, its straightforward to sign it, takes no additional effort, so it is commonly done.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/65275', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/53029/']}
jdg_76915
stackexchange
llm_judgeable_groundtruth_similarity
1810386
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $X$ be distributed uniformly on $[0,2]$ and $f(X) = \beta X$, $0 < \beta <1$. Also, let $f(0) = 0$ and $f(X) < X$ for $X>0$. Note that $c,\beta$ are constants. Then:$$E[X \vert f(X) \leq c] = \frac{c}{2\beta}$$ My question is how to derive this using the definitions here (and elsewhere). Specifically,$$E[X\vert Y = y] = \int_{-\infty}^\infty x f_{X\vert Y}(x\vert y) dx$$with $$f_{X\vert Y}(x\vert y) = \frac{f_{X,Y}(x,y)}{f_Y(y)}$$where I believe $f_{X,Y}(x,y)$ is the joint distribution of $X$ and $Y$, $f_Y(y)$ is the marginal distribution of $Y$. My attempt at calculating the expectation was as follows:$$E[X \vert f(X) \leq c] = E[X \vert \beta X \leq c] = E[X \vert X \leq \frac{c}{\beta}]$$Then, some steps I am unsure about,$$E[X \vert X \leq \frac{c}{\beta}] = \int_{0}^{c/\beta}x f_X dx = \int_{0}^{c/\beta}x \frac{1}{2} dx = \frac{c^2}{4b^2}$$which is not correct... I do get the correct answer from $\int_{0}^{c/\beta} f_X dx$ though, but isn't $E[X] = \int_{-\infty}^\infty x f_X dx$? (see equation $(2)$ at this stackexchange answer So I guess I am asking two question: 1) How do to evaluate the conditional expecation using the formulas provided at the beginning. (This is my main question) 2) What is the mistake in my approach? Thank you very much. Now provide the response and nothing else.
Since $7$ is prime and there is no $7$-note signature that sums to $12$ with all $7$ steps identical, we don't have to worry about periodicity; we can just divide by $7$ in the end. Thus, we just have to count the number of ways of distributing $12-7=5$ balls into $7$ bins with capacity $3-1=2$. There are $\binom75=21$ ways to have $5$ steps of $2$, $\binom7{1,3,3}=140$ ways to have $3$ steps of $2$ and $1$ step of $3$, and $\binom7{2,1,4}=105$ ways to have $1$ step of $2$ and $2$ steps of $3$, for a total of $21+140+105=266$ scales in $266/7=38$ cyclically inequivalent types. In the present case, inclusion-exclusion would be a bit of an overkill, but since you said you'd like a method that generalises to any number of notes with any number of maximum steps, let's generalise: For $k$ notes with a maximum of $m$ steps that sum to $12$, we want to distribute $12-k$ balls into $k$ bins with capacity $m-1$. As explained at Balls In Bins With Limited Capacity , inclusion-exclusion yields a count of $$\sum_{t=0}^{12-k}(-1)^t\binom{12-k}t\binom{12-k+k-tm-1}{12-k-1}=\sum_{t=0}^{12-k}(-1)^t\binom{12-k}t\binom{11-tm}{11-k}\;,$$ where, contrary to convention, binomial coefficients with negative upper index are taken to be zero. For the present case of $k=7$, $m=3$, this again yields $$\sum_{t=0}^7(-1)^t\binom7t\binom{11-3t}6=\binom{11}6-\binom71\binom86=266$$ signatures. If $k$ isn't prime, or if it divides $12$, then you have to do a bit more to deal with periodicity; otherwise, you can just divide the above result by $k$.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1810386', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/344247/']}
jdg_76916
stackexchange
llm_judgeable_groundtruth_similarity
508581
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am having some issues installing PowerShell on my 32-bit Kali Linux PC. I followed this guide and started with: apt update && apt -y install curl gnupg apt-transport-https Next, I downloaded and added the public repository GPG key so APT will trust the packages and alert the user to any issues with package signatures. curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - With the GPG key added, I added the Microsoft package repository to its own package list file under /etc/apt/sources.list.d/ and updated the list of available packages. echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-stretch-prod stretch main" \ > /etc/apt/sources.list.d/powershell.listapt update No errors so far indicated in the update process, Microsoft sources are in my source.list, and everything should be good to go. When I execute: apt -y install powershell I get: root@kali:/opt# apt -y install powershellReading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package powershell Now provide the response and nothing else.
You have successfully added the repository for Powershell to your sources.list . However, you report to be using a 32-bit architecture system. Your output of apt-cache confirms that your Repositories do not contain the Powershell package. Taking a look at the Powershell GitHub , it appears that Microsoft does not provide a Linux package for Powershell for 32-bit Linux systems. All of the source and binary packages available for Linux here are for 64-bit systems. As user Bob points out in his comment, Powershell for Linux depends on .Net Core . If you are familiar with building from source, you could potentially build a 32-bit package, but that is a different kind of question. This may not actually work as Powershell maybe has hard requirements for 64-bit instructions and optimizations.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/508581', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/277198/']}
jdg_76917
stackexchange
llm_judgeable_groundtruth_similarity
4325144
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 reading about Empty Base Optimization(EBO). While reading, the following questions popped up in my mind: What is the point of using Empty class as base class when it contributes nothing to the derived classes (neither functionality-wise, nor data-wise) ? In this article , I read this: //S is empty class struct T : S { int x; }; [...] Notice that we didn’t lose any data orcode accuracy: when you create astandalone object of type S, theobject’s size is still 1 (or more) asbefore; only when S is used as baseclass of another class does its memoryfootprint shrink to zero. To realizethe impact of this saving, imagine avector that contains 125,000objects. The EBO alone saves half amegabyte of memory! Does it mean that if we don't use "S" as base class of "T", we would necessarily consume double of megabyte of memory? I think, the article compares two different scenarios which I don't think is correct. I would like to know a real scenario when EBO can proven to be useful.(means, in the same scenario, we would necessarily be at loss IF we don't use EBO!). Please note that if your answer contains explanations like this : The whole point is that an empty class has non-zero size, but when derived or deriving it can have zero size, then I'm NOT asking that, as I know that already. My question is, why would anyone derive his class from an empty class in the first place? Even if he doesn't derive and simply writes his class (without any empty base), is he at loss in ANY way? Now provide the response and nothing else.
EBO is important in the context of policy based design , where you generally inherit privately from multiple policy classes. If we take the example of a thread safety policy, one could imagine the pseudo-code : class MTSafePolicy{public: void lock() { mutex_.lock(); } void unlock() { mutex_.unlock(); }private: Mutex mutex_;};class MTUnsafePolicy{public: void lock() { /* no-op */ } void unlock() { /* no-op */ }}; Given a policy based-design class such as : template<class ThreadSafetyPolicy>class Test : ThreadSafetyPolicy{ /* ... */}; Using the class with a MTUnsafePolicy simply add no size overhead the class Test : it's a perfect example of don't pay for what you don't use .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4325144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415784/']}
jdg_76918
stackexchange
llm_judgeable_groundtruth_similarity
30038540
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 replace a @VERSION@ token in a java source file with a version before building (Gradle is my build system of choice). In my current script ant.replace(file: 'src/main/java/randers/notenoughvocab/main/Reference.java', token: '@VERSION@', value: version) it replaces the occurrences of @VERSION@ in the actual source file, so after a build all occurrences of the pattern have been replaced by the version and if I change the version the the gradle build file it will no longer find any patterns in there and the version will not update. I have also seen a task here , but I do not get what values need to be applied for my specific project. The project layout for my project, if that is needed: Now provide the response and nothing else.
You only need to replace @VERSION@ tokens before releasing your software to the public. Here I defined a task compileForRelease that accomplishes it: import org.apache.tools.ant.filters.ReplaceTokenstask sourcesForRelease(type: Copy) { from 'src/main/java' into 'build/adjustedSrc' filter(ReplaceTokens, tokens: [VERSION: '2.3.1'])}task compileForRelease(type: JavaCompile, dependsOn: sourcesForRelease) { source = sourcesForRelease.destinationDir classpath = sourceSets.main.compileClasspath destinationDir = file('build/adjustedClasses')} I don't recommend messing with standard tasks defined by the Java plugin because that would add unnecessary overhead to each and every build.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30038540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4464702/']}
jdg_76919
stackexchange
llm_judgeable_groundtruth_similarity
40668616
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After browsing around Google, I've came across this page about h264 encoding and discovered about qp. https://trac.ffmpeg.org/wiki/Encode/H.264 My questions are: What are the differences with crf and qp? Is it better to use qp over crf overall, or is it only if for using qp 0 for best lossless? Does qp have a known sensible setting if it's preferred? So far, I know crf has the default value of 23 while 18 is a sensible preferred increase in quality, although I don't understand why 18 wouldn't be default if better sensible lossless. Lastly, would changing either of them cause incompatibility with non-ffmpeg players or just qp? I'm converting from webm to mp4 by the way. I was going to test crf 23 and 18 and pick which is best but I can't seem to find any concrete information on this comparison or about qp. Now provide the response and nothing else.
When you set the quantization parameter QP directly it remains constant throughout the encoding and each frame will be compressed based on the set value. Constant rate factor CRF allows the QP to go up for frames with a lot of motion or down for still frames resulting in a consistent perceived quality while keeping the compression efficient. This article explains it very well. The CRF default is just a default, you need to pick a value adapted for your type of video. FFmpeg has filters like PSNR and SSIM which allow you to compare the results.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40668616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6318164/']}
jdg_76920
stackexchange
llm_judgeable_groundtruth_similarity
10078283
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 read that sizeof operator in C is interpreted at compile time and since at compile time compiler knows the array size and its type,sizeof is abled to compute the number of bytes occupied by array.But how is sizeof working for the following code : #include<stdio.h> #include<string.h> int main() { int n; scanf("%d",&n); int a[n]; int s=sizeof(a); printf("%d",s); return 0; } Here array size is not known at compile time,then how is it working properly ? Now provide the response and nothing else.
sizeof is always computed at compile time in C89. Since C99 and variable length arrays, it is computed at run time when a variable length array is part of the expression in the sizeof operand. Same for the evaluation of the sizeof operand: it is not evaluated in C89 but in C99 if the operand is of variable length array type it is evaluated. For example: int n = 5;sizeof (int [n++]); // n is now 6
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10078283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/751223/']}
jdg_76921
stackexchange
llm_judgeable_groundtruth_similarity
390064
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am a teacher and I use Linux which is great! But students are curious about this "new" operating system they do not know and in GUI they tweak program settings which affects hidden files inside /home/user : [profesor@240-kateder ~]$ ls -a. .dbeaver4 .gtkrc-2.0 .sane.. .dbeaver-drivers .icons .swt.bash_history .dropbox .kde4 .themes.bash_logout .eclipse .local .thumbnails.bash_profile .esd_auth .lyx .ViberPC.bashrc .FlatCAM .masterpdfeditor .w3m.cache .FreeCAD .mozilla .Xauthority.config .gimp-2.8 .pki .xinitrc.convertall .gnupg .qucs .xournal This is unwanted because over time program interfaces will change so dramatically that programs will be missing toolbars, buttons, main menus, status menus... and students end up with completely different GUI, so they are calling me about the issue and we spend too much time. Now to optimize this I have to make sure that program settings (hidden files inside /home/user ) aren't changed, so I tried to change them like sudo chmod -R 555 ~/.* but this didn't work out well for all of the programs, because some of the programs want to manipulate their settings at boot and they therefore fail to start withouth sudo . And student's don't have sudo privileges. But sudo chmod -R 555 ~/.* worked for .bash_profile , .bash_logout , .bashrc , .bash_history , .xinitrc so I was thinking if I would: prevent user from deleting .bash_profile , .bash_logout , .bashrc , .bash_history , .xinitrc copy all hidden setting files into a folder /opt/restore_settings program .bash_profile to clean up all settings in users home directory on login using rm -r ~/.* (I assume this wouldn't delete files from point 1., if I protect them) and then restore settings from the /opt/restore_settings . I wan't to know your opinion about this idea, or if there is any better way to do it. And I need a way to prevent users from deleting files from point 1. Otherwise this can't work. Now provide the response and nothing else.
Totally different approach: Create a group students , give each student his own account with group membership in students . Have a script that restores a given home directory from a template to a known good state, possibly deleting all extra dot files. Tell students about this script. If you have a number of computers, centralize this approach (user management on a single central server), and use a central file server for student home directories, so each student gets the same home directory on any machine. Together with proper (basic chmod ) permissions everywhere, this will ensure that each student can only wreak havoc in his or her own home directoy, and can restore it when it breaks, possibly loosing their own customizations in this process, so they'll be more cautious next time. BTW, that's a very standard setup for many users on a cluster of machines.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/390064', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9135/']}
jdg_76922
stackexchange
llm_judgeable_groundtruth_similarity
12059509
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 create a single executable from my Python project. A user should be able to download and run it without needing Python installed. If I were just distributing a package, I could use pip, wheel, and PyPI to build and distribute it, but this requires that the user has Python and knows how to install packages. What can I use to build a self-contained executable from a Python project? Now provide the response and nothing else.
There are several different ways of doing this. The first -- and likely most common -- way is to use "freeze" style programs. These programs work by bundling together Python and your program, essentially combining them into a single executable: PyInstaller: Website || Repo || PyPi Supports Python 3.7 - 3.10 on Windows, Mac, and Linux. cx_Freeze: Website || Repo || PyPi Supports Python 3.6 - 3.10 on Windows, Mac, and Linux. py2exe: Website || Repo || PyPi Supports Python 3.7 - 3.10 on Windows only. py2app: Website || Repo || PyPi Supports Python 3.6 - 3.10 on Macs only. The main thing to keep in mind is that these types of programs will generally only produce an exe for the operating system you run it in. So for example, running Pyinstaller in Windows will produce a Windows exe, but running Pyinstaller in Linux will produce a Linux exe. If you want to produce an exe for multiple operating systems, you will have to look into using virtual machines or something like Wine . Of course, that's not the only way of doing things: pynsist: Website || Repo || PyPi Pynsist will create a Windows installer for your program which will directly install Python on the user's computer instead of bundling it with your code and create shortcuts that link to your Python script. The pynsist tool itself requires Python 3.5+ to run, but supports bundling any version of Python with your program. Pynsist will create Windows installers only, but can be run from Windows, Mac, and Linux. See their FAQ for more details. Nuitka: Website || Repo (Github mirror) || PyPi Nuitka will literally compile your Python code and produce an exe (as opposed to the other projects, which simply include Python) to try and speed up your code. As a side effect, you'll also get a handy exe you can distribute. Note that you need to have a C++ compiler available on your system. Supports Python 2.6 - 2.7 and Python 3.3 - 3.10 on Windows, Mac, and Linux. cython: Website || Repo || PyPi Cython is similar to Nuitka in that it is a Python compiler. However, instead of directly compiling your code, it'll compile it to C. You can then take that C code and turn your code into an exe . You'll need to have a C compiler available on your system. Supports Python 2.7 and Python 3.3 - 3.11 on Windows, Mac, and Linux. My personal preference is to use PyInstaller since it was the easiest for me to get up and running, was designed to work nicely with various popular libraries such as numpy or pygame, and has great compatibility with various OSes and Python versions. However, I've also successfully built various exes using cx_Freeze without too much difficulty, so you should also consider trying that program out. I haven't yet had a chance to to try pynist, Nuitka, or Cython extensively, but they seem like pretty interesting and innovative solutions. If you run into trouble using the first group of programs, it might be worthwhile to try one of these three. Since they work fundamentally differently then the Pyinstaller/cx_freeze-style programs, they might succeed in those odd edge cases where the first group fails. In particular, I think pynist is a good way of sidestepping the entire issue of distributing your code altogether: Macs and Linux already have native support for Python, and just installing Python on Windows might genuinely be the cleanest solution. (The downside is now that you need to worry about targeting multiple versions of Python + installing libraries). Nuitka and Cython (in my limited experience) seem to work fairly well. Again, I haven't tested them extensively myself, and so my main observation is that they seem to take much longer to produce an exe then the "freeze" style programs do. All this being said, converting your Python program into an executable isn't necessarily the only way of distributing your code. To learn more about what other options are available, see the following links: https://packaging.python.org/overview/#packaging-python-applications https://docs.python-guide.org/shipping/packaging/#for-linux-distributions
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12059509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972706/']}
jdg_76923
stackexchange
llm_judgeable_groundtruth_similarity
47556819
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 two projects with similar Cloud Functions setup, both directly using Typescript setup (no Webpack) similar to this example or this one One of them uses Firestore, other one doesn't. The one that does not use Firestore compiles and deploys with no error. However the one with Firestore functions gives me this error on tsc compile: ../node_modules/@types/googlemaps/index.d.ts(33,29): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(37,19): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(54,28): error TS2304: Cannot find name 'Node'.../node_modules/@types/googlemaps/index.d.ts(787,30): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(798,36): error TS2304: Cannot find name 'Node'.../node_modules/@types/googlemaps/index.d.ts(811,26): error TS2304: Cannot find name 'Node'.../node_modules/@types/googlemaps/index.d.ts(1135,20): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1136,22): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1137,18): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1138,22): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1139,23): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1140,23): error TS2304: Cannot find name 'Element'.../node_modules/@types/googlemaps/index.d.ts(1141,29): error TS2304: Cannot find name 'Element'.... and goes on. These are package.json dependencies: "dependencies": { "@google-cloud/storage": "^1.5.0", "axios": "^0.17.1", "child-process-promise": "^2.2.1", "firebase-admin": "~5.5.1", "firebase-functions": "^0.7.3" }, "devDependencies": { "typescript": "^2.6.2" }, and content of the tsconfig : { "compilerOptions": { "lib": ["es6", "es2015.promise"], "module": "commonjs", "noImplicitAny": false, "outDir": "build", "sourceMap": true, "target": "es6" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ]} What am I missing? Is it related to Typescript version? (2.6) Do I need to import a @types ? Adding dev-dependency @types/node did not help. Now provide the response and nothing else.
At first I thought problem was exclusion of node_modules folder in tsconfig file and removed "exclude": [ "node_modules" ] part. It did not help. Then since all errors seems to be related to DOM element names or "Node", it should be about a missing types definition of some general package, hence did another search on that matter and run into this answer of a similar question: Typescript build getting errors from node_modules folder Changing tsconfig like this (adding reference to lib.es6.d.ts ) make my problem go away: "include": [ "src/**/*.ts" ], "files": [ "node_modules/typescript/lib/lib.es6.d.ts" ], "exclude": [ "node_modules" ]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47556819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1539073/']}
jdg_76924
stackexchange
llm_judgeable_groundtruth_similarity
269285
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am in need of a chip that is capable of both receiving GPS NMEA sentences and reading raw RSSI/signal strength values in the L1 GPS band (1575.42 MHz). I've read through the datasheets of the GPS modules available on Sparkfun and Adafruit, done some other searches through TI and SiLabs products, but haven't found any that provide a raw RSSI value (in dBm or similar). My application requires that I can display the raw RSSI value of received GPS signals in dBm, not just the SNR value that is available in standard NMEA sentences. Can anyone either suggest a method which would let me get the RSSI reading for a GPS signal, or point me to a method to calculate it from values provided in basic NMEA sentences? The basic scenario is that I am helping test some simulation hardware, and need to provide a simple way to tell if the current signal on the receiver side is from an actual satellite or from a simulator. I know it seems like a Rube-Goldberg machine, but given the limitations on our test setup and the requirements that we have, the best way to do this is believed to be to examine the raw signal strength (or something analogous), since when the simulator is on the raw signal power is dramatically higher. Now provide the response and nothing else.
RSSI at what point? Are you talking narrow band (consumer GPS systems) or wider bandwidth (multi-constellation & RTK industrial systems) receivers)? Before the input correlators there is no meaningful signal to measure and if there was there would be no way of telling the signals from the different SVs apart since they are all on exactly the same frequency.You could measure the total in band power hitting the antenna but you have no way of telling how much power is from which SV, you couldn't even tell if it's GPS or something else. Some GPS receivers will give you some of this information. e.g. in a ublox system the UBX-MON-HW message will give you the AGC level and noise level at the correlators. They also give an indication of suspected jamming level which will indicate how much non-GPS energy there is in the band. Multiply the SNR value by the noise and you get an approximation of the signal strength level post correlation. You could in theory then subtract the correlator gain and AGC gain to get the raw signal power. Just how reliable the end result is after applying all of these fiddle factors I have no idea. SNR is certainly not linear with signal level but I've never tried factoring in AGC levels to see if that helps. Either way it's only ever going to be an estimate. A non-gps software radio isn't going to be able to tell you the difference between GPS and any other in band noise and isn't going to give you per SV values for the reasons already given. And I have no idea why you would want to do this, in 10 years of designing GPS receivers (actually designing them, not using off the shelf modules) I never had to look at that sort of number once.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/269285', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/129894/']}
jdg_76925
stackexchange
llm_judgeable_groundtruth_similarity
313954
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I convert a number from one base, $b_1 \neq 10$ to another base $b_2 \neq 10$ without going through base $10$ i.e. $b_1\rightarrow 10 \rightarrow b_2$? Now provide the response and nothing else.
Short answer: You can do it, but you have to do arithmetic in base $b_1$. If you're using a computer, it's easy. If you are using pencil-and-paper, it may be easier to convert through base 10. The algorithm to convert a number $x$ to base $b$ is: Set $n = 0$ Divide $x$ by $b$, yielding a quotient $q$ and a remainder $r$ Digit $r_n$ of the answer is $r$ If $q = 0$, halt; the answer is $r_{n}r_{n-1}\ldots r_0$. Set $x = q$, $n = n+1$ and return to step 2 Let's say you want to convert 1e6 (base 17) to base 7. We set $x = $ 1e6 and $n=0$. We divide $x$ by 7, yielding a quotient of 48 and a remainder of 1, so $r_0 = 1$ and return to step 2. Now we divide 48 by 7, yielding a quotient of a and a remainder of 6, so $r_1 = 6$ and we return to step 2. Now we divide a by 7 yielding a quotient of 1 and a remainder of 3, so $r_2 = 3$ and we return to step 2. Now we divide 1 by 7 yielding a quotient of 0 and a remainder of 1, so $r_3 = 1$ and since $q=0$ we halt. The answer is $1361_7$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/313954', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_76926
stackexchange
llm_judgeable_groundtruth_similarity
20915916
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 integrating one of my github repos (full code here if it helps) with Cocopods, and I get this error when I run pod spec lint . -> DropDownMenu (0.0.1) - ERROR | [iOS] The `source_files` pattern did not match any file. This is the relevant code of my .podspec which I believe is causing the problem. Looking at examples here , here , and here , I have tried the following s.source_files = 'Classes/*.{h,m}'s.source_files = 'Classes/DropDownMenu.{h,m}'s.source_files = 'Classes's.source_files = 'Classes/**/*.{h,m}' Is my s.source_files field incorrect? Or did I do something wrong with the .podspec ? What can I do to fix this? My problem is similar to this question , however the solution does not work for me (my code is updated on Github). Now provide the response and nothing else.
The problem is that your podspec is referencing a commit that did not yet have the Classes folder, i.e. this commit doesn't have a classes folder yet https://github.com/kevinrandrup/DropDownMenu/tree/09c9b3d515b78550557eabc0a8542f9f6f2623cf You can fix this issue by referencing the latest commit, i.e. changing your podspec source to: s.source = { :git => "https://github.com/kevinrandrup/DropDownMenu.git", :commit => "0d6761feefccff1f7d8b7c7788ceb8e9cd1314ea" }s.source_files = 'Classes/*.{h,m}'
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20915916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1916845/']}
jdg_76927
stackexchange
llm_judgeable_groundtruth_similarity
1448455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know of any API key generator script/class for PHP? The class should have method generate, that would generate a key and isValid() method, to check if the key is valid. Now provide the response and nothing else.
There are multiple ways to generate API keys. I've used following 3 methods depending on the applications, Base62(random). Generate a large secure random number and Base-62 encode it. The key looks like "w5vt2bjzf8ryp63t". This is good for self-provisioned system. You don't have to worry about collision and inappropriate keys. You have to check database to know if the key is valid. Base62(MD5-HMAC(key, Normalize(referer))). This works great if the API is only allowed from one site. Just check the HMAC of the normalized referer and you know if the key is valid, no database access. You need to keep the HMAC key secret to do this. Human assigned friendly names like "example.com". This works great if API users are required to own a domain or they are your corporate partners. Please keep in mind that there is no security in API keys. It's just a name assigned to your API application. More and more people are using terms like "App ID" or "Dev ID" to reflect what it really is. You have to assign another secret key if you want secure your protocol, like consumer_key/consumer_secret in OAuth.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1448455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132257/']}
jdg_76928
stackexchange
llm_judgeable_groundtruth_similarity
6736895
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the following code in R on windows: library(RCurl)postForm("https://www.google.com/accounts/ClientLogin/", "email" = "me@gmail.com", "Passwd" = "abcd", "service" = "finance", "source" = "Test-1") but go the following error: Error in postForm()SL certificate problem, verify that the CA cert is OK. Details:error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed How do I setup RCurl to allow use of HTTPs? Now provide the response and nothing else.
You need to install a SSL library. For windows you can get one here: Download "OpenSSL for Windows" version 0.9.8k Unzip to a temporary folder, and copy the files "libeay32.dll" and"ssleay32.dll" from the "bin" sub-folder to R\library\RCurl\lib\i386. Also you might copy it into the same directory as the R.exe. Then check if you have access to the https protocol: library(RCurl)curlVersion()$protocol ## [1] "tftp" "ftp" "telnet" "dict" "ldap" "http" "file" "https" ## [9] "ftps" "scp" "sftp" Then install a new set of credential files: ca-bundle.crt can be found at : http://curl.haxx.se/ca/cacert.pem rename / copy to ca-bundle.crt Test with this: getURL("https://www.google.com/accounts/ClientLogin/?service=finance&email=me@gmail.com&Passwd=abcd&source=Test-1", cainfo = "path to R/library/RCurl/CurlSSL/ca-bundle.crt")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6736895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345660/']}
jdg_76929
stackexchange
llm_judgeable_groundtruth_similarity
1199227
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to prove that if $$ H \subseteq G, $$ where G is a finite group, and $H$ is closed under multiplication, then $H$ is a subgroup of $G$. We have that $G$ is a finite group. Then, there exist elements $$ a^s = a^r,$$ both in $H$ (because $H$ is closed under multiplication). Then "there must be" that $$ a^{r-s} = e.$$ I don't get this last statement. I also don't understand why the proof can not be like this next one: $G$ is a finite group. Then, for every $$ a \in G $$ there exists its inverse. Then, as $H$ is closed under multiplication, $$ aa^{-1}=e .$$ Then $$ e \in H. $$ Associativity is valid in $G$. In particular it is valid for the elements in $H$. Therefore, $H$ is a subroup of $G$. Now provide the response and nothing else.
The fact that $H$ is closed under multiplication does not guarantee that $a^{-1}\in H$. What can be said is that if $H$ is closed under multiplication, then $a^n\in H$ for every $n\in\Bbb Z^+$. If $G$ is finite, then closure under multiplication is enough to ensure that $a^{-1}\in H$ for every $a\in H$, since $a^n=e$ for some positive $n$, and so $a^{n-1}=a^{-1}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1199227', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/84063/']}
jdg_76930
stackexchange
llm_judgeable_groundtruth_similarity
37667611
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: S3 FAQ mentions that "Amazon S3 buckets in all Regions provide read-after-write consistency for PUTS of new objects and eventual consistency for overwrite PUTS and DELETES." However, I don't know how long it takes to get eventual consistency. I tried to search for this but couldn't find an answer in S3 documentation. Situation: We have a website consists of 7 steps. When user clicks on save in each step, we want to save a json document (contains information of all 7 steps) to Amazon S3. Currently we plan to: Create a single S3 bucket to store all json documents. When user saves step 1 we create a new item in S3. When user saves step 2-7 we override the existing item. After user saves a step and refresh the page, he should be able to see the information he just saved. i.e. We want to make sure that we always read after write. The full json document (all 7 steps completed) is around 20 KB. After users clicked on save button we can freeze the page for some time and they cannot make other changes until save is finished. Question: How long does it take for AWS S3 to save and load an item? (We can freeze our website when document is being saved to S3) Is there a function to calculate save/load time based on item size? Is the save/load time gonna be different if I choose another S3 region? If so which is the best region for Seattle? Now provide the response and nothing else.
I wanted to add to @error2007s answers. How long does it take for AWS S3 to save and load an item? (We can freeze our website when document is being saved to S3) It's not only that you will not find the exact time anywhere - there's actually no such thing exact time . That's just what "eventual consistency" is all about: consistency will be achieved eventually . You can't know when. If somebody gave you an upper bound for how long a system would take to achieve consistency, then you wouldn't call it "eventually consistent" anymore. It would be "consistent within X amount of time". The problem now becomes, "How do I deal with eventual consistency?" (instead of trying to "beat it") To really find the answer to that question, you need to first understand what kind of consistency you truly need, and how exactly the eventual consistency of S3 could affect your workflow. Based on your description, I understand that you would write a total of 7 times to S3, once for each step you have. For the first write, as you correctly cited the FAQs, you get strong consistency for any reads after that. For all the subsequent writes (which are really "replacing" the original object), you might observe eventual consistency - that is, if you try to read the overwritten object, you might get the most recent version, or you might get an older version. This is what is referred to as "eventual consistency" on S3 in this scenario. A few alternatives for you to consider: don't write to S3 on every single step; instead, keep the data for each step on the client side, and then only write 1 single object to S3 after the 7th step. This way, there's only 1 write, no "overwrites", so no "eventual consistency". This might or might not be possible for your specific scenario, you need to evaluate that. alternatively, write to S3 objects with different names for each step. E.g., something like: after step 1, save that to bruno-preferences-step-1.json ; then, after step 2, save the results to bruno-preferences-step-2.json ; and so on, then save the final preferences file to bruno-preferences.json , or maybe even bruno-preferences-step-7.json , giving yourself the flexibility to add more steps in the future. Note that the idea here to avoid overwrites, which could cause eventual consistency issues. Using this approach, you only write new objects, you never overwrite them. finally, you might want to consider Amazon DynamoDB . It's a NoSQL database, you can securely connect to it directly from the browser or from your server. It provides you with replication, automatic scaling, load distribution (just like S3). And you also have the option to tell DynamoDB that you want to perform strongly consistent reads (the default is eventually consistent reads; you have to change a parameter to get strongly consistent reads). DynamoDB is typically used for "small" records, 20kB is definitely within the range -- the maximum size of a record would be 400kB as of today. You might want to check this out: DynamoDB FAQs: What is the consistency model of Amazon DynamoDB?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37667611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5704534/']}
jdg_76931
stackexchange
llm_judgeable_groundtruth_similarity
27434595
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 finish my paint program for my Daughter and am having issues with the panel keeping drawings rendered on the panel when the application is minimized. I would also like for the program to automatically save to a file what she drew on the panel when she clicks on the "CLEAR" and/or "CLOSE" button. Now provide the response and nothing else.
Firstly, do you want to support creating new book instances, or only updating existing ones? If you only ever wanted to create new book instances you could do something like this... class PageSerializer(serializers.Serializer): text = serializers.CharField(max_length=500)class BookSerializer(serializers.Serializer): page = PageSerializer(many=True) title = serializers.CharField(max_length=50) def create(self, validated_data): # Create the book instance book = Book.objects.create(title=validated_data['title']) # Create or update each page instance for item in validated_data['pages']: page = Page(id=item['page_id'], text=item['text'], book=book) page.save() return book Note that I haven't included the book_id here. When we're creating book instances we won't be including a book id. When we're updating book instances we'll typically include the book id as part of the URL, rather than in the request data. If you want to support both create and update of book instances then you need to think about how you want to handle pages that are not included in the request, but are currently associated with the book instance. You might choose to silently ignore those pages and leave them as they are, you might want to raise a validation error, or you might want to delete them. Let's assume that you want to delete any pages not included in the request. def create(self, validated_data): # As before. ...def update(self, instance, validated_data): # Update the book instance instance.title = validated_data['title'] instance.save() # Delete any pages not included in the request page_ids = [item['page_id'] for item in validated_data['pages']] for page in instance.books: if page.id not in page_ids: page.delete() # Create or update page instances that are in the request for item in validated_data['pages']: page = Page(id=item['page_id'], text=item['text'], book=instance) page.save() return instance It's also possible that you might want to only support book updates, and not support creation, in which case, only include the update() method. There are also various ways you could reduce the number of queries eg. using bulk create/deletion, but the above would do the job in a fairly straightforward way. As you can see there are subtleties in the types of behavior you might want when dealing with nested data, so think carefully about exactly what behavior you're expecting in various cases. Also note that I've been using Serializer in the above example rather than ModelSerializer . In this case it's simpler just to include all the fields in the serializer class explicitly, rather than relying on the automatic set of fields that ModelSerializer generates by default.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27434595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4352039/']}
jdg_76932
stackexchange
llm_judgeable_groundtruth_similarity
154800
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Imagine I wish to upload my sensitive personal information (photos, document scans, list of passwords, email backups, credit card information, etc.) on Google Drive (or any other cloud service). I want to make sure this entire bunch of data is as safe as possible (against hackers that would in some way get their hands on this data, and against Google and its employees, and also in the future, i.e. if I delete this data from Google I want to be sure they won't be able to 'open' it even if they keep its backup forever). So in this case instead of uploading all this data right away to the cloud, I will instead make one folder containing all the data I want to upload, and then I will compress this entire folder using 7-Zip and of course password-protect it using 7-Zip. I will do this not once, but a few times, i.e. once I have the 7-Zip password-protected archive ready, I will compress it once again using 7-Zip and use a completely different password. I will do this five times. So in the end my data is compressed five times and it has been password-protected using 7-Zip by five completely different unrelated passwords. So in order to get to my data I have to extract it five times and provide five different passwords. What I will then do is that, I will take this five-times-password-protected archive, and I will compress it once again using 7-Zip and yet a different sixth password, but in addition to that this time I will also choose to split the archive into smaller chunks. Let's say in the end I end up with 10 split archives, where each of them is a 200 MB archive except the 10th one being only a 5 MB archive. The assumption is, all those six passwords are at least 32-character passwords and they are completely unrelated and they all contain lower/upper case, numbers, and symbols. Now I take those nine 200 MB archives and put them in one container and encrypt the container using VeraCrypt (assuming the three level cascade encryption) and then upload this container to my Google Drive. I keep the 10th archive (the 5 MB one) on a completely different service (say on Dropbox -- and that Dropbox account is in no way connected/linked to my Google account at all) (also encrypted by VeraCrypt). - Have I created a security theater ? Or have I really made it impossible for anyone to access and extract my data? After all they have to pass one level of encryption by VeraCrypt and even after that the archives are six times password protected and one of the archives (the tenth one) is stored somewhere else! - If someone gets access to my Google Drive and downloads all those nine archives, is there any way for them to extract the archive without having the last (the tenth) 5 MB archive? Can the data in any way be accessed with one of the split-archives missing? - Even if someone gets their hand on all those 10 archives together and manages to bypass the VeraCrypt encryption in any way, will it be still feasible to break the six remaining passwords? Now provide the response and nothing else.
First of all, that multi-encryption scheme is ridiculous. The algorithm used by 7-Zip is AES-256 which is considered secure. But if someone would find a flaw in it which would make it breakable, then they would likely be able to break all your encryption layers with equal effort. So either you trust the encryption algorithm used by 7-Zip, then one application would be good enough. Or you don't trust it, then you would do another encryption pass with a different algorithm. Layering the same algorithm multiple times often doesn't have as much effect as one would think, as the meet-in-the-middle attack on Triple-DES demonstrated. Regarding splitting up an encrypted file: It is often possible to rescue some data from a 7-Zip archive if parts of the archive are missing. 7-Zip uses AES in CBC mode to emulate stream-cipher behavior (every 128-bit block is combined with the previous 128 bit block). That means if someone is missing a part of the message, they can't decrypt anything which follows (unless they have a known plaintext somewhere), but everything which comes before it. That means if you want to prevent an attacker from decrypting the archive by withholding a part of it, you need to withhold the first chunk, not the last one.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/154800', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/142930/']}
jdg_76933
stackexchange
llm_judgeable_groundtruth_similarity
10950831
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 javascript that gets the value of the cursor position and it works well. Am assigning that value to asp.net label's innerHtml property. When there s a treeview_selectednodechange event happening i want to access this innerHtml property in my program. How can this be achieved? this is the javascript am using:- function ShowSelection() { var txt1 = document.getElementById("MainContent_txtQuery"); var currentRange = document.selection.createRange(); var workRange = currentRange.duplicate(); txt1.select(); var allRange = document.selection.createRange(); var len = 0; while (workRange.compareEndPoints("StartToStart", allRange) > 0) { workRange.moveStart("character", -1); len++; } currentRange.select(); document.getElementById("MainContent_lblPos").innerHTML = len; } And the place where i want to access it is:- string[] selectedNode = treeViewTables.SelectedNode.Text.Split('<', '>'); string pos = lblPos.Text; if (selectedNode[2].Equals("Table(s)") || selectedNode[2].Equals("Parameter(s)")) { return; } string parentNode = treeViewTables.SelectedNode.Parent.Text; if (parentNode.Contains("Table(s)")) { txtQuery.Text = txtQuery.Text + " " + selectedNode[2]; txtQuery.Text = RemoveSpaces(txtQuery.Text); } else if (parentNode.Contains("Parameter")) { //if (txtQuery.Text != "") if (lblPos.Text == string.Empty) { if (txtQuery.Text.Length == 0) { txtQuery.Text = selectedNode[2]; } else if (txtQuery.Text[txtQuery.Text.Length - 1] != ',') { txtQuery.Text = txtQuery.Text + " " + "'" + selectedNode[2] + "'"; txtQuery.Text = RemoveSpaces(txtQuery.Text); } else { txtQuery.Text = txtQuery.Text + " " + selectedNode[2]; txtQuery.Text = RemoveSpaces(txtQuery.Text); } } } else { txtQuery.Text = txtQuery.Text + " " + selectedNode[2] + ","; txtQuery.Text = RemoveSpaces(txtQuery.Text); } TreeNode nodeSelected = treeViewTables.Nodes[0]; nodeSelected.Select(); please help. Thank You Now provide the response and nothing else.
You can use subtle and ugly tricks in order to create that kind of templates. Here's what I would do: Creation of a templated list Macro to define the list I would first create a macro - let's call it say define_list(type) - that would create all the functions for a list of a given type. I would then create a global structure containing function pointers to all the list's functions and then have a pointer to that global structure in each instance of the list (note how similar it is to a virtual method table ). This kind of thing: #define define_list(type) \\ struct _list_##type; \ \ typedef struct \ { \ int (*is_empty)(const struct _list_##type*); \ size_t (*size)(const struct _list_##type*); \ const type (*front)(const struct _list_##type*); \ void (*push_front)(struct _list_##type*, type); \ } _list_functions_##type; \ \ typedef struct _list_elem_##type \ { \ type _data; \ struct _list_elem_##type* _next; \ } list_elem_##type; \ \ typedef struct _list_##type \ { \ size_t _size; \ list_elem_##type* _first; \ list_elem_##type* _last; \ _list_functions_##type* _functions; \ } List_##type; \ \ List_##type* new_list_##type(); \ bool list_is_empty_##type(const List_##type* list); \ size_t list_size_##type(const List_##type* list); \ const type list_front_##type(const List_##type* list); \ void list_push_front_##type(List_##type* list, type elem); \ \ bool list_is_empty_##type(const List_##type* list) \ { \ return list->_size == 0; \ } \ \ size_t list_size_##type(const List_##type* list) \ { \ return list->_size; \ } \ \ const type list_front_##type(const List_##type* list) \ { \ return list->_first->_data; \ } \ \ void list_push_front_##type(List_##type* list, type elem) \ { \ ... \ } \ \ _list_functions_##type _list_funcs_##type = { \ &list_is_empty_##type, \ &list_size_##type, \ &list_front_##type, \ &list_push_front_##type, \ }; \ \ List_##type* new_list_##type() \ { \ List_##type* res = (List_##type*) malloc(sizeof(List_##type)); \ res->_size = 0; \ res->_first = NULL; \ res->_functions = &_list_funcs_##type; \ return res; \ }#define List(type) \ List_##type#define new_list(type) \ new_list_##type() Generic interface Here are some macros that simply call the list's functions via the stored function pointers: #define is_empty(collection) \ collection->_functions->is_empty(collection)#define size(collection) \ collection->_functions->size(collection)#define front(collection) \ collection->_functions->front(collection)#define push_front(collection, elem) \ collection->_functions->push_front(collection, elem) Note that if you use the same structure to design other collections than lists, you'll be able to use the last functions for any collections that stores the good pointers. Example of use And to conclude, a small example of how to use our new list template: /* Define the data structures you need */define_list(int)define_list(float)int main(){ List(int)* a = new_list(int); List(float)* b = new_list(float); push_front(a, 5); push_front(b, 5.2);} You can use that amount of tricks if you really want to have some kind of templates in C, but that's rather ugly (just use C++, it'll be simpler). The only overhead will be one more pointer per instance of data structure, and thus one more indirection whenever you call a function (no cast is done, you don't have to store void* pointers, yeah \o/). Hope you won't ever use that :p Limitations There are of course some limitations since we are using mere text replacement macros, and not real templates. Define once You can only define each type once per compile unit, otherwise, your program will fail to compile. This can be a major drawback for example if you write a library and some of your headers contain some define_ instructions. Multi-word types If you want to create a List whose template type is made of several words ( signed char , unsigned long , const bar , struct foo ...) or whose template type is a pointer ( char* , void* ...), you will have to typedef that type first. define_list(int) /* OK */define_list(char*) /* Error: pointer */define_list(unsigned long) /* Error: several words */typedef char* char_ptr;typedef unsigned long ulong;define_list(char_ptr) /* OK */define_list(ulong) /* OK */ You will have to resort to the same trick if you want to create nested lists.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10950831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/956668/']}
jdg_76934
stackexchange
llm_judgeable_groundtruth_similarity
17597434
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 3 values displayed consecutively on the screen and I need to add 2-3 vertical separator lines between all of them.The issue is everytime I add a view/ divider between them they shift to the left or right way too much and some values cut off/ disappear. I was wondering if there is a way to go abotu it, below is my xml code for the same: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:foo="http://schemas.android.com/apk/res/com.justin.abc" android:layout_width="20dp" android:layout_height="match_parent" android:orientation="horizontal" android:paddingBottom="8dp" android:paddingLeft="20dp" android:paddingTop="8dp" > <LinearLayout android:id="@+id/layout1" android:layout_width="2dp" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <com.justin.abc.utils.FontView android:id="@+id/symbol" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="3dp" android:textColor="@color/white" android:textSize="12sp" foo:customFont="Roboto-Bold.ttf" /> <com.justin.abc.utils.FontView android:id="@+id/arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" foo:customFont="Roboto-Bold.ttf" /> </LinearLayout> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/value1_back" style="@style/abc.TextView.ListsTextView.Header" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="3dp"/> <com.justin.abc.utils.FontView android:id="@+id/change" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" foo:customFont="Roboto-Bold.ttf" /> </FrameLayout> </LinearLayout> <LinearLayout android:id="@+id/layout2" android:layout_width="0dp" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <com.justin.abc.utils.FontView android:id="@+id/symbol2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="3dp" android:textColor="@color/white" android:textSize="12sp" foo:customFont="Roboto-Bold.ttf" /> <com.justin.abc.utils.FontView android:id="@+id/dashboard_markets_arrow2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" foo:customFont="Roboto-Bold.ttf" /> </LinearLayout> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/value2_back" style="@style/abc.TextView.ListsTextView.Header" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="3dp"/> <com.justin.abc.utils.FontView android:id="@+id/change2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" foo:customFont="Roboto-Bold.ttf" /> </FrameLayout> </LinearLayout> <LinearLayout android:id="@+id/layout3" android:layout_width="0dp" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <com.justin.abc.utils.FontView android:id="@+id/dashboard_markets_symbol3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="3dp" android:textColor="@color/white" android:textSize="12sp" foo:customFont="Roboto-Bold.ttf" /> <com.justin.abc.utils.FontView android:id="@+id/dashboard_markets_arrow3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" foo:customFont="Roboto-Bold.ttf" /> </LinearLayout> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/value3_back" style="@style/abc.TextView.ListsTextView.Header" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="3dp"/> <com.justin.abc.utils.FontView android:id="@+id/change3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" foo:customFont="Roboto-Bold.ttf" /> </FrameLayout> </LinearLayout></LinearLayout> Do I need to add a layer or something in the background for it to support the same or do I need to change this structure? Thanks!Justin even after adding android:gravity="center" I still see the same results Now provide the response and nothing else.
Assuming you are trying to get values from a page that is rendered using javascript templates (for instance something like handlebars ), then this is what you will get with any of the standard solutions (i.e. beautifulsoup or requests ). This is because the browser uses javascript to alter what it received and create new DOM elements. urllib will do the requesting part like a browser but not the template rendering part. A good description of the issues can be found here . This article discusses three main solutions: parse the ajax JSON directly use an offline Javascript interpreter to process the request SpiderMonkey , crowbar use a browser automation tool splinter This answer provides a few more suggestions for option 3, such as selenium or watir. I've used selenium for automated web testing and its pretty handy. EDIT From your comments it looks like it is a handlebars driven site. I'd recommend selenium and beautiful soup. This answer gives a good code example which may be useful: from bs4 import BeautifulSoupfrom selenium import webdriverdriver = webdriver.Firefox()driver.get('http://eve-central.com/home/quicklook.html?typeid=34')html = driver.page_sourcesoup = BeautifulSoup(html)# check out the docs for the kinds of things you can do with 'find_all'# this (untested) snippet should find tags with a specific class ID# see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-classfor tag in soup.find_all("a", class_="my_class"): print tag.text Basically selenium gets the rendered HTML from your browser and then you can parse it using BeautifulSoup from the page_source property. Good luck :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17597434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_76935
stackexchange
llm_judgeable_groundtruth_similarity
478801
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How to allow only certain users to login to an SSH server from a particular network interface? e.g. eth0 is "outside", eth1 is "inside". user1 is trusted to login from anywhere user2 is only allowed to login from "inside" Can't use AllowUsers user1@eth0 because AllowUsers takes a hostname not an interface name. Other answers on this site suggest something like: Match address 1.2.3.4/16 # eth0's network AllowUsers user1Match address 2.3.4.5/16 # eth1's network AllowUsers user1,user2Match address 0.0.0.0/0 # Match's equivalent of a closing brace? However if eth0 is using a DHCP server to get its address, then it doesn't know in advance that 1.2.3.4 is the right address to put in sshd_config. (OpenSSH on Ubuntu 12.04 if that makes a difference) Now provide the response and nothing else.
I don't know how to do this in a Match block, and your comment above suggests it's not possible (as does, as you note, the man page). But if you're sure that you want to do the user restriction by interface - which your questions says you do - you could run two sshd s, each having a different sshd_config which directs it to listen on one interface only, controlled by the ListenAddress directive. The sshd listening on the internal interface could in its config have AllowUsers user1 user2 , while that listening on the external interface could have AllowUsers user1 . I'd probably do it by group membership and have AllowGroups internal / AllowGroups internal external instead, but that's just me. Edit : imo, the right way to do this is to run /usr/sbin/sshd -f /etc/ssh/sshd_config_inside and /usr/sbin/sshd -f /etc/ssh/sshd_config_outside . Arranging how this works at boot time, and ensuring that your service startup/shutdown files do the right thing, is indeed important, but it is also a perfectly normal thing for a sysadmin to need to do, and to do. It is definitely not necessary to have two binaries, or even the same binary by two different names, to do this.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/478801', 'https://serverfault.com', 'https://serverfault.com/users/86816/']}
jdg_76936
stackexchange
llm_judgeable_groundtruth_similarity
48133381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the Pair val coordinates = Pair(2, 3) , is it possible to name each value so I can do something like coordinates.x to return 2 ? Or is coordinates.first the only way to access that first value? Now provide the response and nothing else.
This is not supported. You should write a wrapper (data) class for that purposes or you could use Kotlin destructuring declarations: val (x, y) = coordinatesprintln("$x;$y") See more here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48133381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1839500/']}
jdg_76937
stackexchange
llm_judgeable_groundtruth_similarity
4155730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My problem is that I want to create xml tree and get a simple string object (or even char*).And I can't save xml to file. So in the input I have xmlDocPtr with complete xml tree and want to get string containing xml but without using files. Thx for attention. Now provide the response and nothing else.
Use xmlDocDumpMemory or any of its cousins. Usage: void xml_to_string(xmlDocPtr doc, std::string &out){ xmlChar *s; int size; xmlDocDumpMemory(doc, &s, &size); if (s == NULL) throw std::bad_alloc(); try { out = (char *)s; } catch (...) { xmlFree(s); throw; } xmlFree(s);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4155730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/504663/']}
jdg_76938
stackexchange
llm_judgeable_groundtruth_similarity
300167
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 reading about the debuggerstepperboundary attribute and a site says it is is useful in a context switch. What exactly is a context switch? I'm assuming it is a switch from one thread to another, or in execution or security context? However, these are not particularly educated guesses so I'm asking here. Now provide the response and nothing else.
A context switch (also sometimes referred to as a process switch or a task switch) is the switching of the CPU (central processing unit) from one process or thread to another. Context switching can be described in slightly more detail as the kernel (i.e., the core of the operating system) performing the following activities with regard to processes (including threads) on the CPU: (1) suspending the progression of one process and storing the CPU's state (i.e., the context) for that process somewhere in memory, (2) retrieving the context of the next process from memory and restoring it in the CPU's registers and (3) returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process. A context switch is sometimes described as the kernel suspending execution of one process on the CPU and resuming execution of some other process that had previously been suspended. Although this wording can help clarify the concept, it can be confusing in itself because a process is, by definition, an executing instance of a program. Thus the wording suspending progression of a process might be preferable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/300167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32484/']}
jdg_76939
stackexchange
llm_judgeable_groundtruth_similarity
34271551
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For some reason, my second character array (var2) merges with the first one (var1).Here is my code: #include <stdlib.h>#include <stdio.h>#include <string.h>int main() { char var1[5] = "Hello"; char var2[5] = "World"; printf("This program can write:\t%s\t%s\n", var1, var2); getch(); return 0;} after compiling it, I got the following print: This program can write: Hello WorldHello When I changed the code to printf("This program can write:\t%s\n", var2); I got the following print: This program can write: WorldHello So It's clear that that var1 is merging with var2. Is this some kind of compiler bug. If so, how can I fix it? I tried reinstalling MINGW, but I'm still getting the same results. Thanks a lot Now provide the response and nothing else.
Strings are actually one-dimensional array of characters terminated by a null character '\0' . Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char var1[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; You can more simply do : #include <stdlib.h>#include <stdio.h>#include <string.h>int main() { char var1[] = "Hello"; char var2[] = "World"; printf("This program can write:\t%s\t%s\n", var1, var2); getchar(); return 0;} The C compiler automatically places the '\0' at the end of the string when it initializes the array (if the array is long enough to contain the '\0' , otherwise the '\0' will be dropped rather than overwrite another variable).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34271551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5673752/']}
jdg_76940