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 | 4497841 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
An O(n) algorithm to detect if a line intersects a convex polygon consists in checking if any edge of the polygon intersects the line, and look if the number of intersections is odd or even. Is there an asymptotically faster algorithm, e.g. an O(log n) one?
Now provide the response and nothing else.
| lhf's answer is close to correct. Here is a version that should fix the problem with his. Let the polygon have vertices v0, v1, ..., vn in counterclockwise order. Let the points x0 and x1 be on the line. Note two things: First, finding the intersection of two lines (and determining its existence) can be done in constant time. Second, determining if a point is to the left or the right of a line can be done in constant time. We will follow the same basic idea of lhf to get an O(log n) algorithm. The base cases are when the polygon has 2 or 3 vertices. These can both be handled in constant time. Determine if the line (v0,v(n/2)) intersects the line (x0,x1). Case 1: They do not intersect. In this case the line we are interested in is either to the left or the right of the line splitting the polygon, and so we can recurse into that half of the polygon. Specifically, if x0 is to the left of (v0,v(n/2)) then all the vertices in the right "half", {v0, v1, ... v(n/2)} are on the same side of (x0,x1) and so we know that there is no intersection in that "half" of the polygon. Case 2: They do intersect. This case is a little trickier, but we can still narrow down the intersection to one "half" of the polygon in constant time. There are 3 subcases: Case 2.1: The intersection is between the points v0 and v(n/2) We are done. The line intersects the polygon. Case 2.2: The intersection is closer to v0 (that is, outside the polygon on v0's side) Determine if the line (x0,x1) intersects with the line (v0,v1). If it does not then we are done, the line does not intersect the polygon. If it does, find the intersection, p. If p is to the right of the line (v0, v(n/2)) then recurse into the right "half" of the polygon, {v0, v1, ..., v(n/2)}, otherwise recurse to the left "half" {v0, v(n/2), ... vn}. The basic idea in this case is that all points in the polygon are to one side of the line (v0, v1). If (x0, x1) is diverging away from (v0, v1) on one side of its intersection with (v0, v(n/2)). We know that on that side there can be no intersection with the polygon. Case 2.3: The intersection is closer to v(n/2) This case is handled similarly to Case 2.2 but using the appropriate neighbor of v(n/2). We are done. For each level, this requires two line intersections, a left-right check, and determining where a point is on a line. Each recursion divides the number of vertices by 2 (technically divides them by at least 4/3). And so we get a runtime of O(log n). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4497841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/549721/']} | jdg_72141 |
stackexchange | llm_judgeable_groundtruth_similarity | 23197594 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following dataset: df<-structure(list(IDFAM = c("2010 7599 2996 1", "2010 7599 3071 1", "2010 7599 3071 1", "2010 7599 3660 1", "2010 7599 4736 1", "2010 7599 6235 1", "2010 7599 6299 1", "2010 7599 9903 1", "2010 7599 11013 1", "2010 7599 11778 1", "2010 7599 11778 1", "2010 7599 12248 1", "2010 7599 13127 1", "2010 7599 14261 1", "2010 7599 16280 1", "2010 7599 16280 1", "2010 7599 16280 1", "2010 7599 16280 1", "2010 7599 16280 1", "2010 7599 17382 1"), AGED = c(45L, 47L, 24L, 46L, 46L, 44L, 43L, 43L, 43L, 16L, 43L, 46L, 44L, 47L, 43L, 16L, 20L, 18L, 18L, 43L)), .Names = c("IDFAM", "AGED"), row.names = c("5614", "5748", "5753", "6864", "8894", "11761", "11884", "18738", "20896", "22351", "22353", "23267", "24939", "27072", "30946", "30947", "30949", "30950", "30952", "33034"), class = "data.frame") I would like to assign an ID to each observation having the same IDFAM value ranging from 1 to n, where n is the number of observations with the same value of IDFAM . This would result in the following table: IDFAM AGED ID2010 7599 2996 1 45 12010 7599 3071 1 47 12010 7599 3071 1 24 22010 7599 3660 1 46 12010 7599 4736 1 46 12010 7599 6235 1 44 12010 7599 6299 1 43 12010 7599 9903 1 43 12010 7599 11013 1 43 12010 7599 11778 1 16 12010 7599 11778 1 43 22010 7599 12248 1 46 12010 7599 13127 1 44 12010 7599 14261 1 47 12010 7599 16280 1 43 12010 7599 16280 1 16 22010 7599 16280 1 20 32010 7599 16280 1 18 42010 7599 16280 1 18 52010 7599 17382 1 43 1 How can I do this ? Thanks.
Now provide the response and nothing else.
| There are several ways. In base R, use ave : with(df, ave(rep(1, nrow(df)), IDFAM, FUN = seq_along))# [1] 1 1 2 1 1 1 1 1 1 1 2 1 1 1 1 2 3 4 5 1 With the "data.table" package, use sequence(.N) : library(data.table)DT <- as.data.table(df)DT[, ID := sequence(.N), by = IDFAM] With the "dplyr" package, try: df %>% group_by(IDFAM) %>% mutate(count = sequence(n())) or (as recommended by Hadley in the comments): df %>% group_by(IDFAM) %>% mutate(count = row_number(IDFAM)) Update Since this seems to be something that is asked for relatively frequently, this feature has been added as a function ( getanID ) in my "splitstackshape" package. It is based on the "data.table" approach above. library(splitstackshape)getanID(df, id.vars = "IDFAM")# IDFAM AGED .id# 1: 2010 7599 2996 1 45 1# 2: 2010 7599 3071 1 47 1# 3: 2010 7599 3071 1 24 2# 4: 2010 7599 3660 1 46 1# 5: 2010 7599 4736 1 46 1# 6: 2010 7599 6235 1 44 1# 7: 2010 7599 6299 1 43 1# 8: 2010 7599 9903 1 43 1# 9: 2010 7599 11013 1 43 1# 10: 2010 7599 11778 1 16 1# 11: 2010 7599 11778 1 43 2# 12: 2010 7599 12248 1 46 1# 13: 2010 7599 13127 1 44 1# 14: 2010 7599 14261 1 47 1# 15: 2010 7599 16280 1 43 1# 16: 2010 7599 16280 1 16 2# 17: 2010 7599 16280 1 20 3# 18: 2010 7599 16280 1 18 4# 19: 2010 7599 16280 1 18 5# 20: 2010 7599 17382 1 43 1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23197594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2568648/']} | jdg_72142 |
stackexchange | llm_judgeable_groundtruth_similarity | 707888 |
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 $U \subseteq \mathbb{R}^n$ be open in the usual topology. Is its boundary, $\partial U$, necessarily a topological manifold?
Now provide the response and nothing else.
| No, consider $U = \{ (x,y) \in \mathbb{R}^2 : xy \neq 0 \}$. Then $\partial U = \{ (x,y) : x = 0 \vee y = 0 \}$, and the point $(0,0)$ doesn't have a neighborhood homeomorphic to $\mathbb{R}$. You can modify this example to get a connected and bounded $U$: consider$$U = \{ (x,y) : x^2 + y^2 < 2 \} \setminus \left( [-1,1]\times0 \cup 0 \times [-1,1]\right)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/707888', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104117/']} | jdg_72143 |
stackexchange | llm_judgeable_groundtruth_similarity | 1444723 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove or Disprove: If every nontrivial subgroup of a group $G$ is cyclic, then $G$ is cyclic. This is a question from page $181$, Chapter $3.4$ Elements of Modern Algebra ($8^{th}$ Edition) by Linda Gilbert. My intuition tells me that the given statement is false, however, I cannot seem to find a rigorous argument (or counterexample) to disprove the statement. Can anyone please point me in the right direction? I know that if a group $G$ is cyclic, then every subgroup is cyclic. This is not an if and only if statement - hence my intuition telling me the above mentioned statement is false.
Now provide the response and nothing else.
| The question is easily settled even without an explicit counterexample. There exist non cyclic finite abelian groups, so a non cyclic finite abelian group of minimal cardinality provides the counterexample. Indeed its proper subgroups must be cyclic, by minimality. Of course, the counterexample can be shown: the Klein group $\mathbb{Z}/2\mathbb{Z}\oplus\mathbb{Z}/2\mathbb{Z}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1444723', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137485/']} | jdg_72144 |
stackexchange | llm_judgeable_groundtruth_similarity | 10661026 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ive been trying to get resque to work with heroku. i can successfully get it to work in development mode, however when i try pushing to heroku i get Errno::ECONNREFUSED (Connection refused - Unable to connect to Redis on 127.0.0.1:6379): i then read and followed http://blog.redistogo.com/2010/07/26/resque-with-redis-to-go/ i put the configurations listed in the site but got the following error SocketError (getaddrinfo: nodename nor servname provided, or not known): i put in my initializers/resque.rb Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }ENV["redis://redistogo:[email protected]:9254/"] ||= "redis://heroku_username:heroku_password@host:9254/"uri = URI.parse(ENV["redis://redistogo:[email protected]:9254/"])Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) however it throws the error mentioned above. on my dev mode now, i get the error as well. i tried using my heroku username (im using the add on from heroku), putting my password to heroku, and changing the port to 9254. however i keep getting the socket error now. what am i doing wrong? help would be much appreciated. thank you UPDATE. @kevin i tried uri = URI.parse(ENV["my_url_string"] || "redis://localhost:9254/" )REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) in a initializer/redis.rb as well but i get the following error Errno::ECONNREFUSED (Connection refused - Unable to connect to Redis on 127.0.0.1:6379): are the numbers in the error, ie 127.0.0.1:6379 significant? ive checked my redis gui app and also from heroku config that my port number is 9254 REDISTOGO_URL => redis://redistogo:[email protected]:9254/ did you have any other configuration settings? thanks for helping! FINAL UPDATE. i fixed it. i can't believe it! my complete solution is uri = URI.parse(ENV["REDISTOGO_URL"])REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)Resque.redis = REDIS verbatim. it works without explicitly setting the url because i guess heroku tries to set it up for me already
Now provide the response and nothing else.
| For my setup I have /config/initializers/redis.rb with these lines: uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/" )REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) My REDISTOGO_URL is defined in my heroku configuration. You should be able to validate that by typing: heroku config --app my_app You'll see in the output the value for REDISTOGO_URL You should copy your REDISTOGO_URL directly from Redis To Go. You find it in by going to the instance in heroku and clicking on Add Ons -> Redis To Go. Here are a couple pointers: Verify you have your REDIS_TO_GO URL in your heroku config from the command line like I've demonstrated above. Verify the REDIS_TO_GO URL is identical to the one assigned to that instance in the Add Ons -> Redis To Go config. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10661026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743615/']} | jdg_72145 |
stackexchange | llm_judgeable_groundtruth_similarity | 61332 |
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 essence of my question is this: Let $Y \in \mathbb{R}^n$ be a multivariate normal random variable with mean $\mu$ and covariance matrix $\Sigma$. Let $Z := \log(Y)$, i.e. $Z_i = \log(Y_i), i \in \{1,\ldots,n\}$. How do I compare the AIC of a model fit to observed realizations of $Y$ versus a model fit to observed realizations of $Z$? My initial and slightly longer question: Let $Y \sim \mathcal{N}(\mu,\Sigma)$ be a multivariate normal random variable. If I want to compare a model fit to $Y$ versus a model fit to $\log(Y)$, I could look at their log-likelihoods. However, since these models aren't nested, I can't compare the log-likelihoods (and stuff like AIC, etc.) directly, but I have to transform them. I know that if $X_1,\ldots,X_n$ are random variables with joint pdf $g(x_1,\ldots,x_n)$ and if $Y_i = t_i(X_1,\ldots,X_n)$ for one-to-one transformations $t_i$ and $i \in \{1,\ldots,n\}$, then the pdf of $Y_1,\ldots,Y_n$ is given by $$f(y_1,\ldots,y_n)=g(t_1^{-1}(y),\ldots,t_n^{-1}(y))\det(J)$$ where $J$ is the Jacobian associated with the transformation. Do I simply have to use the transformation rule to compare $$l(Y) = \log(\prod_{i=1}^{n}\phi(y_i;\mu,\Sigma))$$ to $$l(\log(Y))=\log(\prod_{i=1}^{n}\phi(\log(y_i);\mu,\Sigma))$$ or is there something else I can do? [edit] Forgot to place logarithms in the last two expressions.
Now provide the response and nothing else.
| You cannot compare the AIC or BIC when fitting to two different data sets i.e. $Y$ and $Z$. You only can compare two models based on AIC or BIC just when fitting to the same data set. Have a look at Model Selection and Multi-model Inference: A Practical Information-theoretic Approach (Burnham and Anderson, 2004). They mentioned my answer on page 81 (section 2.11.3 Transformations of the Response Variable): Investigators should be sure that all hypotheses are modeled using the same response variable (e.g., if the whole set of models were based on log(y), no problem would be created; it is the mixing of response variables that is incorrect). And by the way, for using the AIC or BIC criteria, your models do not need to be necessarily nested (same ref, page 88, section 2.12.4 Nonnested Models), and actually that's one of the advantages of using BIC. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/61332', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5795/']} | jdg_72146 |
stackexchange | llm_judgeable_groundtruth_similarity | 13373882 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ack foo * returns a listing of lines: bar.txt28: this is foo stuffdump.txt12: results of foogobs.txt1137: more lines with foo and ack -c -l returns 3 My question is, how can I show both? I'd like the list of lines as in the first example and a count of the number of lines that matched as in the second example.
Now provide the response and nothing else.
| You can use ack -hc ( -h being shorthand for --no-filename ) to get a total count. According to the ack documentation/man page : -c, --count Suppress normal output; instead print a count of matching lines for each input file. If -l is in effect, it will only show the number of lines for each file that has lines matching. Without -l , some line counts may be zeroes. If combined with -h ( --no-filename ) ack outputs only one total count. Here's what worked for me (expanding on @Jordan's answer) -- ack 'pattern' && ack -hc 'pattern' or, better (IMO): ack 'pattern'; ack -hc 'pattern' As far as I understand, using && , the second command depends on the first one returning to run; using ; instead will just run them both, one after the other, regardless. In this case, I think the ; is more appropriate. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13373882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1103236/']} | jdg_72147 |
stackexchange | llm_judgeable_groundtruth_similarity | 13645666 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to create an Objective-C class that can have an arbitrary number of dynamic properties at runtime? I want to be able to call mySpecialClass.anyProperty and intercept this inside my class to be able to provide my own custom implementation that can then return an NSString (for instance) at runtime with raising an exception. Obviously this all has to compile. Ideal would be if I could refer to my properties using something similar to the new literal syntax, e.g. mySpecialClass["anyProperty"] . I guess in a way I want to create something like a dynamic NSDictionary with no CFDictionary backing store, that executes 2 custom methods on property getting and setting respectively, with the property name passed in to these accessor methods so they can decide what to do.
Now provide the response and nothing else.
| There are at least two ways to do this. Subscripting Use objectForKeyedSubscript: and setObject:forKeyedSubscript: @property (nonatomic,strong) NSMutableDictionary *properties; - (id)objectForKeyedSubscript:(id)key { return [[self properties] valueForKey:[NSString stringWithFormat:@"%@",key]]; } - (void)setObject:(id)object forKeyedSubscript:(id <NSCopying>)key { [[self properties] setValue:object forKey:[NSString stringWithFormat:@"%@",key]]; } Person *p = [Person new]; p[@"name"] = @"Jon"; NSLog(@"%@",p[@"name"]); resolveInstanceMethod: This is the objc_sendMsg executed by the runtime for all methods: If you look at the bottom, you have the opportunity to resolveInstanceMethod: , which lets you redirect the method call to one of your choosing. To answer your question, you need to write a generic getter and setter that looks-up a value on a dictionary ivar: // generic getterstatic id propertyIMP(id self, SEL _cmd) { return [[self properties] valueForKey:NSStringFromSelector(_cmd)];}// generic setterstatic void setPropertyIMP(id self, SEL _cmd, id aValue) { id value = [aValue copy]; NSMutableString *key = [NSStringFromSelector(_cmd) mutableCopy]; // delete "set" and ":" and lowercase first letter [key deleteCharactersInRange:NSMakeRange(0, 3)]; [key deleteCharactersInRange:NSMakeRange([key length] - 1, 1)]; NSString *firstChar = [key substringToIndex:1]; [key replaceCharactersInRange:NSMakeRange(0, 1) withString:[firstChar lowercaseString]]; [[self properties] setValue:value forKey:key];} And then implement resolveInstanceMethod: to add the requested method to the class. + (BOOL)resolveInstanceMethod:(SEL)aSEL { if ([NSStringFromSelector(aSEL) hasPrefix:@"set"]) { class_addMethod([self class], aSEL, (IMP)setPropertyIMP, "v@:@"); } else { class_addMethod([self class], aSEL,(IMP)propertyIMP, "@@:"); } return YES;} You could also do it returning a NSMethodSignature for the method, which is then wrapped in a NSInvocation and passed to forwardInvocation: , but adding the method is faster. Here is a gist that runs in CodeRunner. It doesn't handle myClass["anyProperty"] calls. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13645666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/399772/']} | jdg_72148 |
stackexchange | llm_judgeable_groundtruth_similarity | 44663903 |
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 Pandas dataframe that looks like the below: codes1 [71020]2 [77085]3 [36415]4 [99213, 99287]5 [99233, 99233, 99233] I'm trying to split the lists in df['codes'] into columns, like the below: code_1 code_2 code_3 1 710202 770853 364154 99213 992875 99233 99233 99233 where columns that don't have a value (because the list was not that long) are filled with blanks or NaNs or something. I've seen answers like this one and others similar to it, and while they work on lists of equal length, they all throw errors when I try to use the methods on lists of unequal length. Is there a good way do to this?
Now provide the response and nothing else.
| Try: pd.DataFrame(df.codes.values.tolist()).add_prefix('code_') code_0 code_1 code_20 71020 NaN NaN1 77085 NaN NaN2 36415 NaN NaN3 99213 99287.0 NaN4 99233 99233.0 99233.0 Include the index pd.DataFrame(df.codes.values.tolist(), df.index).add_prefix('code_') code_0 code_1 code_21 71020 NaN NaN2 77085 NaN NaN3 36415 NaN NaN4 99213 99287.0 NaN5 99233 99233.0 99233.0 We can nail down all the formatting with this: f = lambda x: 'code_{}'.format(x + 1)pd.DataFrame( df.codes.values.tolist(), df.index, dtype=object).fillna('').rename(columns=f) code_1 code_2 code_31 71020 2 77085 3 36415 4 99213 99287 5 99233 99233 99233 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44663903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2446029/']} | jdg_72149 |
stackexchange | llm_judgeable_groundtruth_similarity | 17751 |
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I know there are certain consonants in the IPA that have vowel-like properties, and can therefor be used as vowels, such as [n], [m], and [l]. Examples include [pnt], or [ʒlf]. So, in the loosest possible sense, can a vowel ever be treated as a consonant? I realize that this is kind of a weird question, and the obvious answer is probably not , but surely, some language might have certain words that sometimes have a vowel in place of a consonant. Thanks!
Now provide the response and nothing else.
| A vowel has two closely related but inequivalent definitions. One of them looks what's happening in the mouth etc. Vowel is a sound in which the tongue doesn't touch anything and there's no build of pressure anywhere. That's why the sound may last uniformly and that's why it has the potential to be the peak of a syllable. The sound that allows a syllable to exist is the other definition of a vowel. The consonants you mention – for example, in Czech, most famously, "L" and "R" – may form syllables, so they satisfy the syllabic definition of a vowel (my last name is "Motl" with an "L" and has two syllables; similarly "prcek" with "R"). However, they don't satisfy the tongue-and-pressure-based definition of a vowel so "L" and "R" are still considered consonants (although they are "syllabic nuclei"). On the other hand, vowels (by their sound) may fail to be the bulk of a syllable and they may be treated as consonants. These sounds are called "semivowels" and in English, "y" (in "yes") and "w" (in "west") are examples of such semivowels. By the essence of their sound, "y" and "w" are vowels. After all, "y" is a relative of "i" and "w" is the "double u". But because they're not the most important or long-lasting part of English syllables, they behave as consonants. | {} | {'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/17751', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/13328/']} | jdg_72150 |
stackexchange | llm_judgeable_groundtruth_similarity | 18900593 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hello I'm trying to create a section on the right of the navbar. I used the div class navbar-right which should float the div to the right, but I am getting a new line instead. See below for code & thanks! <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php">xxx</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.php">Home</a></li> <li><a href="about.php">About</a></li> <li><a href="contact.php">Contact</a></li> </ul> </div> <div class="navbar-right"> <p> <b> '.$username.' </b> | Access Level: '.$level.' | <a href=logout.php>Logout</a> </p> </div> </div> </div>
Now provide the response and nothing else.
| In order to be placed at the top level of nav-bar, the contents must be placed inside of a div with the class: navbar-header So instead of declaring the logout link inside of the div: <div class="navbar-right"> Use the following classes instead: <div class="navbar-header pull-right"> Since you'll want the Brand to pull-left , you can place two navbar-header divs right next to each other at the very top and have one pull to each direction. Like this: <div class="navbar-header pull-left"> <a class="navbar-brand" href="index.php">xxx</a></div><div class="navbar-header pull-right"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <p class="navbar-text"> <b> '.$username.' </b> <a href="logout.php" class="navbar-link">Logout</a> </p> </div> jsFiddle Expanded Collapsed Update : As per Ram's comment, in order to not have the pull down menu not overlap on a small screen, you'll have to clear the left float like this: .navbar-collapse.in,.navbar-collapse.collapsing { clear: left;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18900593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1235078/']} | jdg_72151 |
stackexchange | llm_judgeable_groundtruth_similarity | 124183 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a text file that contains five columns of data in which columns 1 and 2 correspond to projected distance along dimension 1 and 2 from the center of the dark halo and then columns 3, 4 and 5 are values of the neutral hydrogen column density in projections 0 "z", 1 "x" and 2 "y" respectively. I would like to transform this .txt table into actual 2d maps in which the color strength of each pixel would correspond to the magnitude of the function in that pixel. This means that I would have three planes xy, yz and xz in which each pixel is filled with a color. My values for columns 3,4 and 5 are mostly zero with few of them on the order of $10^{14}$ to $10^{21}$. I am interested in having three contour levels (less than $10^{17}$, between $10^{17}$ and $10^{20.3}$ and larger than $10^{20.3}$). Let's say if the function value is smaller than $10^{17}$, the color should be LightRed, if the function value is between $10^{17}$ and $10^{20.3}$, the color should be Red, and if the function value is larger than $10^{20.3}$, the color should be DarkRed. In other words, my 2d map is in fact a set of 3 contour plots that are produced out of .txt table. (Here is the link of a portion of my data: MyData ) Is there anyway to translate this into the maps by a color bar and apply it to the maps? Based on the examples shown in ListContourPlot , I could not find something similar to my case. But, here is what I have for the three maps (thanks to Conor Consett for solving the original problem of importing a .txt file into mathematica notebook) including the modifications I made in the original code (considering ALL data and not the abridged version uploaded here): datam10q = Import["/Users/U of A/Desktop/covering_fractions/m10q.txt", "Table"]xy10q = datam10q[[All, {1, 2, 3}]];yz10q = datam10q[[All, {1, 2, 4}]];xz10q = datam10q[[All, {1, 2, 5}]];{ListContourPlot[xy10q, Contours -> {{10^14, Thick}, {10^15.5, Thick}, {10^17, Thick}, {10^20.3, Thick}}, ContourShading -> {Yellow, Orange, Red, Brown, Black}, ContourStyle -> None, InterpolationOrder -> 5, BoundaryStyle -> Black, PerformanceGoal -> "Quality"], ListContourPlot[yz10q, Contours -> {{10^14, Thick}, {10^15.5, Thick}, {10^17, Thick}, {10^20.3, Thick}}, ContourShading -> {Yellow, Orange, Red, Brown, Black}, ContourStyle -> None, InterpolationOrder -> 5, BoundaryStyle -> Black, PerformanceGoal -> "Quality"], ListContourPlot[xz10q, Contours -> {{10^14, Thick}, {10^15.5, Thick}, {10^17, Thick}, {10^20.3, Thick}}, ContourShading -> {Yellow, Orange, Red, Brown, Black}, ContourStyle -> None, InterpolationOrder -> 5, BoundaryStyle -> Black, PerformanceGoal -> "Quality"]}
Now provide the response and nothing else.
| I would approach this by experimenting with a tiny version of the problem. Here is a 5 column .txt file I made: http://pastebin.com/wCPxdvQB Download it and Import it into your session with: data = Import["/Users/johncosnett/Downloads/xy123data.txt", "Table"]xy = data[[All, {1, 2, 3}]];yz = data[[All, {1, 2, 4}]];xz = data[[All, {1, 2, 5}]];{ListContourPlot[xy, PlotTheme -> {"Monochrome", Red}], ListContourPlot[yz, PlotTheme -> {"Monochrome", Red}], ListContourPlot[xy, PlotTheme -> {"Monochrome", Red}]} | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/124183', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/24828/']} | jdg_72152 |
stackexchange | llm_judgeable_groundtruth_similarity | 58247 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a disease that is autosomal recessive. If one was heterozygous for this trait, could the recessive gene still be expressed? I know sickle cell anemia has a heterozygous advantage so it must be possible but what are the conditions for this to happen and also to what degree? EDIT: This isn't asking how a gene is recessive or dominant in a molecular level.
Now provide the response and nothing else.
| Short answer The concepts dominance, additivity, epistasis, recessivity and others are all specific to a given phenotype. Here you are getting confused because you are considering two different phenotypes at once. Slightly longer answer By definition, if an allele is recessive, then in the heterozygote state, the phenotype of interest is just like the homozygous dominant. An important point in the above sentence is "the phenotype of interest". A given locus may show a pattern of simple dominance-recessivity for a given phenotype but may show a completely different pattern for another phenotypic trait. Let's consider your example of sickle cell anemia. For the phenotype which is the disease, sickle cell anemia has a simple dominance-recessivity relationship. However, for the phenotypic trait which is fitness (yes, in quantitative genetics, fitness is often modelled as a simple phenotypic trait), sickle-cell anemia shows (environment dependent) heterozygote advantage. Also, the fitnesses of the two homozygotes differ greatly. Note that, in reality, very few loci show cases of perfect recessivity dominance. EDIT You are considering two (or even three) phenotypes. First Phenotype: Fitness Fitness shows overdominance (with highly unequal fitness for both homozygotes). Second phenotype: Disease Double mutant are sick, the others aren't. Perfect dominance-recessivity (although if I am not mistaken heterozygotes individuals have some restriction when it comes to scuba diving if I am not mistaken) Third phenotype: Shape of hemoglobin If the heterozygote hemoglobin is shaped just like the healthy homozygote, then there is dominance-recessivity. If the shape differs (which might be causing malaria resistance, I don't know), then there is some partial dominance going on. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/58247', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/31455/']} | jdg_72153 |
stackexchange | llm_judgeable_groundtruth_similarity | 35608686 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to get the HLS URL for YouTube live streams like this one https://www.youtube.com/embed/WVZpCdHq3Qg I've tried the typical get_video_info methods but they don't seem to work with live streams.
Now provide the response and nothing else.
| You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk First, get the formats of the video: ➜ ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk[youtube] _Gtc-GtLlTk: Downloading webpage[youtube] _Gtc-GtLlTk: Downloading video info webpage[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk[download] Downloading playlist: Southwest Florida Eagle Cam[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)[download] Downloading video 1 of 2[youtube] _Gtc-GtLlTk: Downloading webpage[youtube] _Gtc-GtLlTk: Downloading video info webpage[youtube] _Gtc-GtLlTk: Extracting video information[youtube] _Gtc-GtLlTk: Downloading formats manifest[youtube] _Gtc-GtLlTk: Downloading DASH manifest[info] Available formats for _Gtc-GtLlTk:format code extension resolution note140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only137 mp4 1920x1080 DASH video 4347k , avc1.640028, 30fps, video only151 mp4 72p HLS , h264, aac @ 24k132 mp4 240p HLS , h264, aac @ 48k92 mp4 240p HLS , h264, aac @ 48k93 mp4 360p HLS , h264, aac @128k94 mp4 480p HLS , h264, aac @128k95 mp4 720p HLS , h264, aac @256k96 mp4 1080p HLS , h264, aac @256k (best)[download] Downloading video 2 of 2[youtube] aflWCT1tYL0: Downloading webpage[youtube] aflWCT1tYL0: Downloading video info webpage[youtube] aflWCT1tYL0: Extracting video information[youtube] aflWCT1tYL0: Downloading formats manifest[youtube] aflWCT1tYL0: Downloading DASH manifest[info] Available formats for aflWCT1tYL0:format code extension resolution note140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only151 mp4 72p HLS , h264, aac @ 24k132 mp4 240p HLS , h264, aac @ 48k92 mp4 240p HLS , h264, aac @ 48k93 mp4 360p HLS , h264, aac @128k94 mp4 480p HLS , h264, aac @128k95 mp4 720p HLS , h264, aac @256k (best)[download] Finished downloading playlist: Southwest Florida Eagle Cam In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL: ➜ ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTkhttps://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8 These are your HLS m3u8 playlists, one for each camera associated with the live stream. Without youtube-dl, your flow might look like this: Take your video id and make a GET request to the get_video_info endpoint: HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en In the response, the hlsvp value will be the link to the m3u8 HLS playlist: https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35608686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704836/']} | jdg_72154 |
stackexchange | llm_judgeable_groundtruth_similarity | 4945802 |
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 model like this: class MyModel(models.Model): REGULAR = 1 PREMIUM = 2 STATUS_CHOICES = ((REGULAR, "regular"), (PREMIUM, "premium")) name = models.CharField(max_length=30) status = models.IntegerField(choices = STATUS_CHOICES, default = REGULAR)class MyForm(forms.ModelForm): class Meta: model = models.MyModel In a view I initialize one field and try to make it non-editable: myform = MyForm(initial = {'status': requested_status})myform.fields['status'].editable = False But the user can still change that field. What's the real way to accomplish what I'm after?
Now provide the response and nothing else.
| Step 1: Disable the frontend widget Use the HTML readonly attribute: http://www.w3schools.com/tags/att_input_readonly.asp Or disabled attribute: http://www.w3.org/TR/html401/interact/forms.html#adef-disabled You can inject arbitrary HTML key value pairs via the widget attrs property: myform.fields['status'].widget.attrs['readonly'] = True # text inputmyform.fields['status'].widget.attrs['disabled'] = True # radio / checkbox Step 2: Ensure the field is effectively disabled on backend Override your clean method for your field so that regardless of POST input (somebody can fake a POST, edit the raw HTML, etc.) you get the field value that already exists. def clean_status(self): # when field is cleaned, we always return the existing model field. return self.instance.status | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4945802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/526169/']} | jdg_72155 |
stackexchange | llm_judgeable_groundtruth_similarity | 6780613 |
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've got a multithreaded python program, which is currently suffering from deadlock. I was going to log lock acquiring by subclassing threading.Lock objects: import tracebackclass DebugLock(threading.Lock): def acquire(self): print >>sys.stderr, "acquired", self #traceback.print_tb threading.Lock.acquire(self) def release(self): print >>sys.stderr, "released", self #traceback.print_tb threading.Lock.release(self) When I try to run the program, I get the following error: class DebugLock(threading.Lock):TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances So, my question is twofold: Is it possible to subclass Lock objects to do what I'm doing? If not, what is the best way to debug deadlock in python? Note: I'm not writing any Python extension. There's a similar question: How to debug deadlock with python? However, it deals with compiling C++ code and using GDB, which I can't do since my code is pure python.
Now provide the response and nothing else.
| You could just use the "has a lock" versus "is a lock" approach, like so: import threading, traceback, sysclass DebugLock(object): def __init__(self): self._lock = threading.Lock() def acquire(self): print("acquired", self) #traceback.print_tb self._lock.acquire() def release(self): print("released", self) #traceback.print_tb self._lock.release() def __enter__(self): self.acquire() def __exit__(self, type, value, traceback): self.release() where I've thrown in the appropriate context guards since you likely want to use the with syntax with your locks (who wouldn't?). Usage shown below: >>> lock = DebugLock() >>> with lock: ... print("I'm atomic!") ... acquired <__main__.DebugLock object at 0x7f8590e50190> I'm atomic! released <__main__.DebugLock object at 0x7f8590e50190> >>> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6780613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788337/']} | jdg_72156 |
stackexchange | llm_judgeable_groundtruth_similarity | 105249 |
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 am trying to understand how TLS works. Assuming the I have a java client that uses TLSv1 to communicate to the server which supports TLSv1.2, can the client talk to the server successfully? When a server supports TLSv1.2, does this mean it is capable of accepting connections which are TLSv1, TLSv1.1 and TLSv1.2 or does it just accept TLSv1.2?
Now provide the response and nothing else.
| A server generally isn't configured to only support one version. The server can be configured to accept all versions, even lower stuff like SSLv3. During the initial connection between the client and server, they will negotiate and determine the highest protocol version they both support. That being said, if a server only accepts 1.2 and the client only knows 1.0, they will not be able to negotiate a connection. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/105249', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/91675/']} | jdg_72157 |
stackexchange | llm_judgeable_groundtruth_similarity | 16680134 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi i have a project made in windows who uses windows 1252 charset and i need to convert all my .php file to utf-8 charset because my database is all utf-8 encoded.Is there a way to do that using linux commands or a software?
Now provide the response and nothing else.
| In your project's root directory, use find(1) to list all *.php files and combine that with recode(1) to convert those files in place: find . -type f -name '*.php' -exec recode windows1252..utf8 \{} \; As an alternative to recode(1), you could also use iconv(1) to do the conversion (for usage with above find command: iconv -f windows-1252 -t utf-8 -o \{} \{} ). You need to have either recode or iconv installed for the above to work. Both should be easily installable via a package manager on most modern systems. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16680134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1208060/']} | jdg_72158 |
stackexchange | llm_judgeable_groundtruth_similarity | 40636 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that Symbolic Model Checking is state space traversal based on representations of states sets and transition relations as formulas like in CTL using models like Kripke Model. I know the theory. But I'm finding it hard to understand the actual application. Where exactly is it used? What exactly does it do and how does it work? Can someone explain with a real example and relate theory to practice?
Now provide the response and nothing else.
| Symbolic Model Checking is Model Checking that works on symbolic states. That is, they encode the states into symbolic representations, typically Ordered Binary Decision Diagrams (OBDDs). The question is what do they do and how do they work. You first have your source code for some application. You then transform your source code into some state-transition graph like a Kripke Structure. The states are filled with atomic propositions which describe what is true in that particular state. In Symbolic Model Checking the atomic propositions are encoded as OBDDs to save on space and improve performance. The Model Checker then starts at some initial state, and explores the states, looking for errors in the state-transition graph. If it finds an error it will often generate a test case demonstrating the error. It uses the symbolic OBDDs to somewhat optimally navigate the state space. Wish I could explain more there but still learning. But that's basically it. You have a program converted into a formal model (state-transition graph), and then you use symbolic optimizations to navigate the state space to look for errors (by comparing it against an LTL/CTL specification). And if an error is found, the Model Checker gives you some stuff to help document and solve it. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/40636', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/29940/']} | jdg_72159 |
stackexchange | llm_judgeable_groundtruth_similarity | 5493776 |
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 small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server: TemplateSyntaxError at / 'current_tags' is not a valid tag library: Template library current_tags not found, tried django.templatetags.current_tags The problem is with a line in an html file: {% load current_tags %} This exact same code works on his system with no errors. What could that be?
Now provide the response and nothing else.
| I would suggest the following: (Most likely) You haven't installed one of the dependencies of your tag library. Check the imports inside the current_tags.py module. Make sure the application that includes the tag library is registered in settings.py under INSTALLED_APPS . Make sure that you can successfully import the tag library. python manage.py shell>>> from app.templatetags import current_tags This boils down what the following link recommends, which is that the error itself tends to mislead you about where it's looking for a template from. It silently ignores errors on import, which means current_tags.py itself might have a syntax error or another reason why it raises ImportError. If everything else fails, check this link: http://www.b-list.org/weblog/2007/dec/04/magic-tags/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5493776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110028/']} | jdg_72160 |
stackexchange | llm_judgeable_groundtruth_similarity | 9731215 |
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 pushed a couple of commits to the remote repository and found they are creating problems. How can I go back to the previous version? That is, removing the two latest commits?
Now provide the response and nothing else.
| Since you have already pushed the commits to a remote repository, the best way is probably to revert the two commits so that you do not create any problems for anyone who has already pulled from the remote repository. Examples use the following commit history: e512d38 Adding taunts to management.bd89039 Adding kill switch in case I'm fired.da8af4d Adding performance optimizations to master loop.db0c012 Fixing bug in the doohickey If you just want to revert the commits without modifying the history, you can do the following: git revert e512d38git revert bd89039 Alternatively, if you don’t want others to see that you added the kill switch and then removed it, you can roll back the repository using the following (however, this will cause problems for others who have already pulled your changes from the remote): git reset --hard da8af4dgit push origin -f localBranch:remoteBranch where localBranch is the name of the local branch and remoteBranch is the name of the remote branch. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9731215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052665/']} | jdg_72161 |
stackexchange | llm_judgeable_groundtruth_similarity | 6205433 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Edit Downvoter, how is this a bad question? I have provided runnable example code of the issue. If it works for you please let me know or point out what is unclear. Hello, in the code below which has a single JComboBox in a JFrame , I am not notified when the mouse enters the JComboBox or is clicked or focus gained. However, the PopupMenuEvent works properly. What am I doing wrong? (My goal is to be alerted when the text component of the JComboBox is clicked) public class TestJComboBox extends javax.swing.JFrame{ public TestJComboBox() { initComponents(); } // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jComboBox1 = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { formMouseClicked(evt); } }); jComboBox1.setEditable(true); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jComboBox1.setName("jComboBox1"); // NOI18N jComboBox1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jComboBox1MouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jComboBox1MouseEntered(evt); } }); jComboBox1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { jComboBox1PopupMenuWillBecomeVisible(evt); } }); jComboBox1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jComboBox1FocusGained(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(70, 70, 70) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(104, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(90, 90, 90) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(164, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jComboBox1FocusGained(java.awt.event.FocusEvent evt) { System.out.println("JComboBox Focus gained"); } private void formMouseClicked(java.awt.event.MouseEvent evt) { System.out.println("Form clicked"); jComboBox1.setFocusable(false); jComboBox1.setFocusable(true); } private void jComboBox1MouseClicked(java.awt.event.MouseEvent evt) { System.out.println("JComboBox Click"); } private void jComboBox1PopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { System.out.println("JComboBox Visible menu"); } private void jComboBox1MouseEntered(java.awt.event.MouseEvent evt) { System.out.println("Entered JComboBox"); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TestJComboBox().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JComboBox jComboBox1; // End of variables declaration} Thanks!
Now provide the response and nothing else.
| Possibly the downvoter took offense at your use of Netbeans GUI editor. I don't like it myself, but you're welcome to use it if you find that you can actually maintain a complex gui with it. I personally hate it due to various extremely annoying bugs that only show themselves when you're trying to edit the form and it quietly loses your layout and component settings. But that's beside the point. Anyway, you need to add your ActionListener like this: jComboBox1.getEditor().getEditorComponent().addMouseListener(...); JComboBox is really a composite component with a JTextField, JButton, and JList buried inside it, so you were adding the ActionListener to the wrapping component, when the mouse events are really going to the inner JTextField. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6205433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215887/']} | jdg_72162 |
stackexchange | llm_judgeable_groundtruth_similarity | 30591046 |
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 creating Windows Service that sends batches of emails every 5 minutes. I want to send batches of 10-100 emails every 5 minutes. This is extreme edge case. Batches are sent every 5 minutes and normally consist of up to 10 emails. I'm using SmtpClient from System.Net.Mail namespace. What is proper lifetime of SmtpClient object?Should I create one every time batch is send?Or should I create one on Service start and never dispose of it?
Now provide the response and nothing else.
| You should always utilise using using (var smtpClient = new SmtpClient()){ smtpClient.SendMail(message);} In most cases you should always dispose of anything that implements IDisposable as soon as you are finished with it, however you should always check the Docs to be sure. The SmtpClient class in .NET 4.0 implements IDisposable so be sure to use it! To quote MSDN: The SmtpClient class has no Finalize method, so an application mustcall Dispose to explicitly free up resources. If you find yourself doing async related tasks then you can make a new instance for each email to prevent blocking yourself.You can use the following. var smtpClient = new SmtpClient();smtpClient.SendCompleted += (s, e) => { client.Dispose(); message.Dispose(); };client.SendAsync(message, null); At Request - Best option for Bulk Send Emails As noted above you can reuse the same client. If you keep it all on the same thread I recommend you just use one client MSDN States: The SmtpClient class implementation pools SMTP connections so that itcan avoid the overhead of re-establishing a connection for everymessage to the same server. An application may re-use the sameSmtpClient object to send many different emails to the same SMTPserver and to many different SMTP servers. However it goes on to say: ...As a result, there is no way to determine when an application isfinished using the SmtpClient object and it should be cleaned up. So assuming you dispose of your Client when complete it is fine. There is discussion of a number of SMTP related topics linked below as I recently found myself asking the same question More from Stackoverflow: What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0 How to dispose objects having asynchronous methods called? Related Reading: MSDN SmtpClient Implementing Finalize and Dispose to clean up managed resources | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30591046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465408/']} | jdg_72163 |
stackexchange | llm_judgeable_groundtruth_similarity | 48269545 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to javascript and I am trying to remove multiple values from an array of objects. Right now I can remove one object like this if(obj.findObjectByKey(response, 'cat_id', 171) == true) { var catId = response.map(item => item.cat_id).indexOf(171);} In the code above I will remove the item with a id of "171" but now I have an array with multiple values that I would like to remove. So how can I modify the code above to let me pass in an array of items that I want to remove from the list eg ['171', '172', '173, '174'];
Now provide the response and nothing else.
| If you can use ES6, try using JavaScript's filter and includes for this. const nums = [1, 2, 3, 4, 5, 6];const remove = [1, 2, 4, 6];function removeFromArray(original, remove) { return original.filter(value => !remove.includes(value));}console.log(removeFromArray(nums, remove)); This will work just as well with strings. const nums = ["1", "2", "3", "4", "5", "6"];const remove = ["1", "2", "4", "6"];function removeFromArray(original, remove) { return original.filter(value => !remove.includes(value));}console.log(removeFromArray(nums, remove)); This solution also has the added benefit of being immutable. Meaning that you are returning new data rather than morphing the old. Which is considered good practice. https://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48269545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5900705/']} | jdg_72164 |
stackexchange | llm_judgeable_groundtruth_similarity | 188536 |
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 a script that will pipe its output to |tee scriptnameYYMMDD.txt . After each cycle of the for loop in which the output is generated, I'll be reversing the file contents with tac scriptnameYYYYMMDD.txt > /var/www/html/logs/scriptname.txt so that the log output is visible in a browser window with the newest lines at the top. I'll have several scripts doing this in parallel. I'm trying to minimize the disk activity, so output from |tee scriptnameYYYYMMDD.txt to a RAMdisk would be best. mktemp creates a file in the /tmp folder, but that doesn't appear to be off-disk.
Now provide the response and nothing else.
| You can mount a tmpfs partititon and write the file there: mount -t tmpfs -o size=500m tmpfs /mountpoint This partition now is limited to 500 MB. If your temporary file grows larger than 500 MB an error will occur: no space left on device . But, it doesn't matter when you specify a larger amount of space than your systems RAM has. tmpfs uses swap space too, so you cannot force a system crash, as opposed to ramfs . You can now write your file into /mountpoint : command | tee /mountpoint/scriptnameYYYYMMDD.txt | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/188536', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/38537/']} | jdg_72165 |
stackexchange | llm_judgeable_groundtruth_similarity | 6393 |
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 understand left/right cosets in group theory. Here is the example in my text: Let $G = \lbrace 1, a, b, c, d ,e \rbrace$ Lets define the group operation $.$ by the following table, where the entry at row $x$ and column $y$ gives $x.y$ ex. $d.e = b$ 1 a b c d e 1 1 a b c d e a a b 1 d e c b b 1 a e c d c c e d 1 b a d d c e a 1 b e e d c b a 1 This is no problem I understand this. But then we get the left and right cosets. Let $G$ be a group and let $H \leq G$. A left coset of $H$ in $G$ ($G / H$) is a set of the form $gH = \lbrace gh : h \in H \rbrace$ for some $g \in G$. A right coset of $H$ in $G$ ($H$ \ $G$) is a set of the form $Hg = \lbrace hg : h \in H \rbrace$ for some $g \in G$. Here are some examples that I am trying to figure out how they are generated. I guess i just do not understand the theory fully. I would like a little help explaining and possible a few more examples. $\lbrace 1, a, b, c, d, e \rbrace / \lbrace 1, a, b \rbrace = \lbrace \lbrace1, a, b\rbrace , \lbrace c, d, e \rbrace\rbrace$ $\lbrace 1, a, b \rbrace$ \ $\lbrace 1, a, b, c, d, e\rbrace = \lbrace \lbrace 1, a, b \rbrace, \lbrace c, d, e \rbrace \rbrace$ $\lbrace 1, a, b, c, d, e \rbrace / \lbrace 1, c \rbrace = \lbrace \lbrace 1, c \rbrace, \lbrace a, d \rbrace, \lbrace b, e \rbrace \rbrace$ A few more examples which i want to figure out are: $\lbrace 1, a, b, c, d, e \rbrace / \lbrace 1, e \rbrace = ?$ $\lbrace 1, d \rbrace$ \ $\lbrace 1, a, b, c, d, e \rbrace = ?$ Thanks!
Now provide the response and nothing else.
| If your table is correct, it should be the symmetric group in three letters, with a and b the 3-cycles, and c , d , and e the transpositions. Now. Your first equations is, alas, nonsense. The set that contains $1$, $a$, $b$, $c$, $d$, and $e$ is certainly not equal to the set whose elements are the sets $\{1,a,b\}$ and $\{c,d,e\}$. You are writing nonsense. The rest are a bit better because you are looking at cosets. Fixed in problem. $G$ has six different subgroups: the trivial subgroup $\{1\}$; the whole subgroup $G$; one subgroup of order three, $H=\{1,a,b\}$, and three subgroups of order two: $K_1=\{1,c\}$, $K_2=\{1,d\}$, and $K_3=\{1,e\}$. What are the left cosets of $H$ in $G$? They are the sets $1H$, $aH$, $bH$, $cH$, $dH$, and $eH$. As it happens, $1H=aH=bH = H$, and $cH=dH=eH=\{c,d,e\}$. You can verify it exlicitly; for instance, $$aH = \{ ah : h \in H\} = \{a1, aa, ab\} = \{a, b, 1\} = H$$and$$cH = \{ ch: h \in H\} = \{c1, ca, cb\} = \{c, e, d\}.$$ The right costs of $H$ are the same as the left cosets. Now, what are the left cosets of $K_3=\{1,e\}$ in $G$? They are the sets $1K_3$, $aK_3$, $bK_3$, $cK_3$, $dK_3$, and $eK_3$. They are:$$\begin{array}{rcl}1K_3 & = & \{1k : k \in K_3\} = \{11, 1e\} = \{1,e\} = K_3\\aK_3 & = & \{ak : k \in K_3\} = \{a1, ae\} = \{a, c\}.\\bK_3 & = & \{bk : k \in K_3\} = \{b1, be\} = \{b, d\}.\\cK_3 & = & \{ck : k \in K_3\} = \{c1, ce\} = \{c, a\} = aK_3.\\dK_3 & = & \{dk : k \in K_3\} = \{d1, de\} = \{d, b\} = bK_3.\\eK_3 & = & \{ek : k \in K_3\} = \{ei, ee\} = \{e, 1\} = K_3.\end{array}$$So there are three distinct left cosets, and they are $\{1,e\}$, $\{a,c\}$, and $\{b,d\}$. What are the right cosets of $\{1,d\}$ in $G$? They are $K_21$, $K_2a$, $K_2b$, $K_2c$, $K_2d$, and $K_2e$. Let us be a bit smarter this time, rather than computing them directly: we know that any two distinct cosets are disjoint, and that the right coset of $x$ contains $x$. So $K_21$ contains both $1$ and $d$, hence must be equal to the right coset of $d$, $K_2d$; that is, $K_21=K_2d = \{1,d\}$. The right coset of $a$ contains $a$ and contains $da = c$, hence must be equal to the right coset of $c$, $K_2c$; indeed it is, as $dc = a$; so $K_2a=K_2c=\{a,c\}$. And the right coset of $b$, $K_2b$, contains $b$ and $db=e$, hence must equal the right coset of $e$, $K_2e$, which it does (since $de=b$ and $1e=1$). So $K_2b=K_2e=\{b,e\}$. So the three right cosets of $K_2$ in $G$ are $\{1,d\}$, $\{a,c\}$, and $\{b,e\}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/6393', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43/']} | jdg_72166 |
stackexchange | llm_judgeable_groundtruth_similarity | 41631727 |
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 puzzled me the last 15 minutes: if ('ab' =~ /^a|b$/) { print 't' } else { print 'f' }print "\n"; I have expected that 'a' or 'b' following the beginning and followed by the end, should match only one character. So the test should fail for two characters 'ab'. But it succeeds. Why?
Now provide the response and nothing else.
| If you group the alternation, then you will get the expected behavior: /^(a|b)$/ Your regex will find a a at the start of the string (with ^a branch) or b at the end (with the b$ branch). When you use ^(a|b)$ , the anchors are applied to the whole group and thus it will match a string that is equal to a or b . Also, if you do not really need to capture the value, you may either use a non-capturing group , /^(?:a|b)$/ , or a n modifier , /^(a|b)$/n . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41631727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/402322/']} | jdg_72167 |
stackexchange | llm_judgeable_groundtruth_similarity | 7274711 |
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 run tests in Xcode 4 using OCUnit without launching the simulator. Please, don't try and convince me I am doing unit testing wrong or anything like that. I like to do TDD the traditional way: write the API for the class in the tests, then make the class pass the tests. I will write separate tests that are end-to-end that run in the simulator. If there's no way to do this, then please can someone tell me how to have the test harness not instantiate the whole app? My app is event driven, and it sends a bunch of events through when it starts up that mess with my tests.
Now provide the response and nothing else.
| Please can someone tell me how to have the test harness not instantiate the whole app? My app is event driven, and it sends a bunch of events through when it starts up that mess with my tests. I use Xcode 4's built-in testing. App instantiation may seem like a pain, but as I write on Xcode Unit Testing: The Good, the Bad, the Ugly , it makes it possible to write tests without distinguishing between logic tests and application tests. Specifically, it lets me write unit tests for view controllers. Here's what I do to avoid my full startup sequence: Edit the scheme Select the Test action In "Test" select the Arguments tab Disable "Use the Run action's options" Add an environment variable, setting runningTests to YES Edit your app delegate Add the following to -application:didFinishLaunchingWithOptions: as soon as it makes sense to: #if DEBUG if (getenv("runningTests")) return YES;#endif Do the same for -applicationDidBecomeActive: but simply return . Update: I have changed my approach. See How to Easily Switch Your App Delegate for Testing . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7274711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/924001/']} | jdg_72168 |
stackexchange | llm_judgeable_groundtruth_similarity | 25345843 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to set members of an array that are below a threshold to nan. This is part of a QA/QC process and the incoming data may already have slots that are nan. So as an example my threshold might be -1000 and hence I would want to set -3000 to nan in the following array x = np.array([np.nan,1.,2.,-3000.,np.nan,5.]) This following: x[x < -1000.] = np.nan produces the correct behavior, but also a RuntimeWarning, but the overhead of disabling the warning warnings.filterwarnings("ignore")...warnints.resetwarnings() is kind of heavy an potentially a bit unsafe. Trying to index twice with fancy indexing as follows doesn't produce any effect: nonan = np.where(~np.isnan(x))[0]x[nonan][x[nonan] < -1000.] = np.nan I assume this is because a copy is made due to the integer index or the use of indexing twice. Does anyone have a relatively simple solution? It would be fine to use a masked array in the process, but the final product has to be an ndarray and I can't introduce new dependencies. Thanks.
Now provide the response and nothing else.
| Any comparison (other than != ) of a NaN to a non-NaN value will always return False: >>> x < -1000array([False, False, False, True, False, False], dtype=bool) So you can simply ignore the fact that there are NaNs already in your array and do: >>> x[x < -1000] = np.nan>>> xarray([ nan, 1., 2., nan, nan, 5.]) EDIT I don't see any warning when I ran the above, but if you really need to stay away from the NaNs, you can do something like: mask = ~np.isnan(x)mask[mask] &= x[mask] < -1000x[mask] = np.nan | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25345843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/513904/']} | jdg_72169 |
stackexchange | llm_judgeable_groundtruth_similarity | 188998 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to plot a Graphics3D object using a fisheye view like, for example, the equidistant fisheye described here , where the distance R of a point from the centre of the image is proportional to the angles θ between the points in the real 3-dim scene: R = f×θ. For illustration, let's take the Graphics3D object produced by the following Mathematica code paraboloid[a_, u_, nu_] := {a Sqrt[u] Cos[nu], a Sqrt[u] Sin[nu], u}a = 10;h = 20;gr1 = ParametricPlot3D[paraboloid[a, u, nu], {nu, 0, Pi}, {u, 0, h}];gr2 = Graphics3D[Table[ Rotate[Cuboid[## - {1, 1, 0}, ## + {1, 1, 2}], nu, {0, 0, 1}, ##]& [paraboloid[a, u, nu]], {nu, 0, Pi, Pi/20}, {u, 2, h, 2}]];Show[gr1, gr2, ViewPoint -> {0, -0.5, 0}] which produces some sort of paraboloid amphitheatre in usual perspective as follows How can I view the same scene using a fisheye view instead of the usual perspective? For reference, here is an example of fisheye perspective from MathWorld
Now provide the response and nothing else.
| I follow the approach suggested by Alex, which was taken from the Mathematica documentation of ImageForwardTransformation . But the required explanation and changes to produce an actual fisheye view are too extensive to be included in a comment, so I write them here. As mentioned in my comment to Alex's answer, the key is to use as the radial coordinate of the ImageForwardTransformation the angles between the objects in the scene, as seen from the observer. This would produce the ideal and most common fisheye view, which is the equidistant, or equiangle, fisheye . But other fisheye formulas can be used by simply replacing the angle with a function of angles. The key is then to obtain angles to the centre of the view for the pixels in a Mathematica image. Mathematica uses standard perspective for which is easy to show (see figure below) that the angles are given by theta = ArcTan[R/d] . But to obtain proper angles from the image pixel units one has to consider the definition of ViewPoint and the bounding box of the Graphics3D object: ViewPoint -> {x,y,z} gives the position of the view point relative to the center of the three‐dimensional box that contains the objects. The view point is given in a special scaled coordinate system in which the longest side of the bounding box has length 1 . The centre of the bounding box is taken to have coordinates {0,0,0} . Other key steps for the fisheye view are (i) to place the ViewPoint orthogonal to the bounding box (two ViewPoint coordinates have to be zero), (ii) as close as possible (but at a finite distance) to the nearest side of the box and (iii) with ViewAngle -> All . This will produce an extremely distorted view, for a field of view close to 180 degrees, which can then be remapped into a fisheye view. The image has to be rasterized at high pixels resolution, to account for the fact that the central part of the distorted image will appear much smaller than the outer parts, due to the large field of view. This, of course, results in a very inefficient procedure. An alternative would be to obtain different views, as Szabolcs suggested in his comments. But this would significantly complicate the procedure. Following the above steps here is the proposed solution. I take for illustration the amphitheatre proposed in my original question. paraboloid[a_, u_, nu_] := {a Sqrt[u] Cos[nu], a Sqrt[u] Sin[nu], u}a = 5;h = 20;gr1 = ParametricPlot3D[paraboloid[a, u, nu], {nu, 0, Pi}, {u, 0, h}];gr2 = Graphics3D[ Table[Rotate[Cuboid[## - {1, 1, 0}, ## + {1, 1, 2}], nu, {0, 0, 1}, ##] &[paraboloid[a, u, nu]], {nu, 0, Pi, Pi/10}, {u, 2, h, 2}]]; Which appears as follow with default viewing parameters Show[gr1, gr2] and I show it from a very close distance to the bounding box side and using the full field of view dist = 0.3;gr = Show[gr1, gr2, ViewPoint -> {0, -dist, 0}, ViewAngle -> All];img = Rasterize[gr, RasterSize -> 1000] This produces the original very distorted (non fisheye) perspective, covering, in this case, a field of view of 169 degrees This image can be remapped into an equidistant fisheye view, using ImageForwardTransformation as suggested by Alex, but with a proper fisheye transformation, as follow f[point_, center_, edgeTan_] := With[ {r = Norm[point - center], ang = ArcTan @@ (point - center), radius = Max[center]}, rnew = radius*ArcTan[edgeTan*r/radius]/ArcTan[edgeTan]; center + rnew*{Cos[ang], Sin[ang]}]rat = BoxRatios /. AbsoluteOptions[gr, BoxRatios];ratios = rat/Max @@ rat;center = ImageDimensions[img]/2;edgeTan = (0.5 Max @@ ratios[[{1, 3}]])/(dist - 0.5 ratios[[2]]); (* Tan of edge *)ImageForwardTransformation[img, f[#, center, edgeTan] &, DataRange -> Full]fov = 2 ArcTan[edgeTan]/Degree (* Image field of view for information *) This produces the desired equidistant fisheye view, where I show in black the region outside the field of view of the original Mathematica projection | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/188998', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/41148/']} | jdg_72170 |
stackexchange | llm_judgeable_groundtruth_similarity | 6871851 |
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 GridView.AutoGenerateColumn=true . i have created button on footer on rowdatabound when i click on button row command event is not fired Here is my code: dt = ESalesUnityContainer.Container.Resolve<IAgentService>().GetAgentMaterialPercentage();grdMaterialPercentage.DataSource = dt;grdMaterialPercentage.DataBind();protected void grdMaterialPercentage_RowDataBound(object sender, GridViewRowEventArgs e){ if (grdMaterialPercentage.AutoGenerateColumns == true) { if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Visible = false; } if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].Visible = false; if (DataBinder.Eval(e.Row.DataItem, "AgentName").ToString() != string.Empty) { int i = 0; foreach (TableCell c in e.Row.Cells) { if (i >= 3) { TextBox tb = new TextBox(); tb.Text = c.Text; tb.Style.Add("Width", "25px"); tb.Style.Add("Height", "15px"); c.Controls.Clear(); c.Controls.Add(tb); } i++; } } else { e.Row.Visible = false; } } if (e.Row.RowType == DataControlRowType.Footer) { e.Row.Cells[0].Visible = false; int j = 0; foreach (TableCell c in e.Row.Cells) { if (j >= 3) { DataRow dr = dt.Rows[dt.Rows.Count - 1]; LinkButton btn = new LinkButton(); btn.ID = j.ToString(); btn.CommandName ="fghfh"+j.ToString(); btn.Text = "Save" + dr[j - 1].ToString(); btn.CssClass = "button"; btn.Style.Add("align", "center"); btn.CommandArgument = dr[j - 1].ToString(); // btn.OnClientClick = "return ValidateTotalPercentage(this)"; c.Controls.Clear(); c.Controls.Add(btn); } j++; } } }}
Now provide the response and nothing else.
| There are lots of problems with your code. Let's take it apart, shall we: _TCHAR* whatTheHeck(_TCHAR* name) // We're inside a local scope{ _TCHAR Buffer[BUFSIZE]; // "Buffer" has automatic storage _TCHAR* what = new _TCHAR[BUFSIZE]; // "what" points to newly allocated dyn. memory what = _tcscat(Buffer, TEXT("\\")); // Oh no, we overwrite "what" - leak! // Now what == Buffer. what = _tcscat(what, name); // Equivalent to "_tcscat(Buffer, name)" return Buffer; // WTPF? We're returning a local automatic! } As you can see, you are both causing a memory leak with a gratuitious and reckless new , and you are also returning the address of a local object past its lifetime! I would strongly recommmend reading the documentation for strcat and understanding "source" and "destination", not using strcat , but a safer version like strncat , not using strncat , but instead std::string . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6871851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/866708/']} | jdg_72171 |
stackexchange | llm_judgeable_groundtruth_similarity | 18968387 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Has anyone one come up with a good config script to install Oracle Java 1.7 in to an Elastic Beanstalk instance using the config files stored in .ebextensions . I am using a tomcat7 version of elastic beanstalk and I was able to install openJDK with yum using the following: packages: yum: java-1.7.0-openjdk: [] java-1.7.0-openjdk-devel: []commands: use_java7: command: alternatives --set java /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java How ever I would like to use Oracle Java 1.7 not OpenJDK and yum does not have that in it's repo natively.
Now provide the response and nothing else.
| try this configuration file files: "/home/ec2-user/install-oracle-jdk.sh": mode: "000755" owner: ec2-user group: ec2-user content: | #!/usr/bin/env bash wget -O jdk-7u25-linux-x64.rpm --no-cookies --no-check-certificate --header 'Cookie:gpw_e24=http://www.oracle.com; oraclelicense=accept-securebackup-cookie' 'http://download.oracle.com/otn-pub/java/jdk/7u51-b13/jdk-7u51-linux-x64.rpm' rpm -Uvh /home/ec2-user/jdk-7u25-linux-x64.rpm alternatives --install /usr/bin/java java /usr/java/default/bin/java 3 alternatives --set java /usr/java/default/bin/javacommands: execute-install-oracle-jdk-script: command: ./install-oracle-jdk.sh cwd: /home/ec2-user | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18968387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/368651/']} | jdg_72172 |
stackexchange | llm_judgeable_groundtruth_similarity | 166367 |
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:
Given the inverse square law force of gravity shouldn't two particles that are infinitely close to each other be infinitely attracted to one another? For example, suppose the hands of some super deity grabbed hold of two neutrinos and put them infinitely close to one another or suppose that some physicists in a high energy particle physics laboratory shot two neutrinos together at super high speeds. Why should any forces be able to pull the neutrinos apart again after they collide? Why don't we find any tiny super dense lumps of matter around us that are the results of high energy collisions and that we are unable to pull apart?
Now provide the response and nothing else.
| There is no established quantum theory of gravity. Hence, at the microscopic level of particle, we don't know what is going on gravitationally between particle, but it isn't going to be the "inverse square law" we know, just like electromagnetism between two charged particles is, on quantum scales, not just an "inverse square law", but a rich variety of interactions that can be thought of as being mediated by virtual photons, and that gives the inverse square law of electrostatics only in the macroscopic and non-relativistic limit of the simplest of these interactions. Essentially, particles don't clump together as you imagine because they are, on the smallest scales, not particles at all. They are quantum states that are smeared out over an area like an electron orbital in an atom , and they do not behave as our classical intuition leads us to believe. In essence, because we don't have a good description of gravity at these scales, and because quantum objects are not little dots of mass in space, your question might as well be countered with: "Why should they?" | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/166367', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/73720/']} | jdg_72173 |
stackexchange | llm_judgeable_groundtruth_similarity | 152513 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
According to Jairo comment on the first version of this question I revise the question as follows;Let $g$ be a real analytic Riemannan metric on $S^{2}$. Is it true to say that: There are at most a finite number of disjoint simple closed geodesics on $S^{2}$. If the answer is yes put $m$= the sup of the number of such disjoint closed geodesics. What is a geometric interpretation for this geometric invariant $m$? For a given $n\in \mathbb{N}$, is there a real analytic Riemannian metric on $S^{2} $ for which $m=n$
Now provide the response and nothing else.
| As it was shown by Igor, there is no univeral bound on number of such geodesics.Let me show that the number can not be infinite. Assume it is possible to get infinite number of such geodesics, say $\gamma_n$, $n\in\mathbb N$.Note that the geodesics $\gamma_i$ for $i\le n$ cut $\mathbb S^2$ into surfaces with geodesic boundaries. By Gauss--Bonnet formula most of these surfaces are cylinders. By passing to a subsequence, we can assume that for each $n$, the geodesics $\gamma_i$ for $i\le n$ cut $\mathbb S^2$ into two discs and cylinders between $\gamma_i$ and $\gamma_{i+1}$. Denote by $\gamma_\infty$ the limit of $\gamma_n$ as $n\to\infty$. Note that this limit is defined and the limit geodesic $\gamma_\infty$ is stable. Given a point $p$ near $\gamma_\infty$ denote by $\ell(p)$ the length of mimimal geodesic loop based at $p$ which goes sufficiently close to $\gamma_\infty$.Note that $\ell$ is an analytic function and its derivatives vanish on $\gamma_\infty$.It follows that $\ell\equiv 0$; i.e. $\gamma_\infty$ lies in a one parameter family of closed geodesics which sweep a neighborhood of $\gamma_\infty$. Pass to the analytical extension of this one parameter family, lets denote it by $\xi_\tau$.Note that the geodesics in the family stay simple and disjoint locally.Globally, it only may happen that $\xi_0=\xi_c$ for some parameter $c\ne0$.Moreover, since the surface is compact it actually happens.In this case the surface is a total space of a circle bundle, a contradiction. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/152513', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36688/']} | jdg_72174 |
stackexchange | llm_judgeable_groundtruth_similarity | 7080269 |
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 make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload <script type="text/javascript">function con() { var answer = confirm("do you want to check our other products") if (answer){ alert("bye"); } else{ window.location = "http://www.example.com"; }}</script></head><body onunload="con();"><h1 style="text-align:center">main page</h1></body></html> But it confirm after page already closed? How to do it properly? It would be even better if someone shows how to do it with jQuery?
Now provide the response and nothing else.
| onunload (or onbeforeunload ) cannot redirect the user to another page. This is for security reasons. If you want to show a prompt before the user leaves the page, use onbeforeunload : window.onbeforeunload = function(){ return 'Are you sure you want to leave?';}; Or with jQuery: $(window).bind('beforeunload', function(){ return 'Are you sure you want to leave?';}); This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go. You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload ): window.onunload = function() { alert('Bye.');} Or with jQuery: $(window).unload(function(){ alert('Bye.');}); | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7080269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896925/']} | jdg_72175 |
stackexchange | llm_judgeable_groundtruth_similarity | 45248 |
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:
For one dimensional quantum mechanics $$[\hat{x},\hat{p}]=i\hbar. $$ Does this fix univocally the form of the $\hat{p}$ operator? My bet is no because $\hat{p}$ actually depends if we are on coordinate or momentum representation, but I don't know if that statement constitutes a proof. Moreover if we choose $\hat{x}\psi=x\psi$ is the answer of the following question yes? For the second one $$(\hat{x}\hat{p}-\hat{p}\hat{x})\psi=x\hat{p}\psi-\hat{p}x\psi=i\hbar\psi, $$ but I don't see how can I say that $\hat{p}$ must be proportional to $\frac{\partial}{\partial x}$. I don't know if trying to see that $\hat{p}$ must satisfy the Leibniz rule and thus it should be proportional to the $x$ derivative could help. Or using the fact that $\hat{x}$ and $\hat{p}$ must be hermitian Any hint will be appreciated.
Now provide the response and nothing else.
| No. You can add an arbitrary constant shift (or an arbitrary operator commuting with $x$) without affecting the CCR. For 1-dimensional QM, the general solution of the CCR with $\hat x$ represented as multiplication by $x$ on wave functions with argument $x$ is $\hat p=\hat p_0-A(\hat x)~~$, where $\hat p_0$ is the canonical momentum operator , and $A(x)$ is an arbitrary function of $x$. Proof. The difference $\hat A:=\hat p_0-\hat p~$ commutes with $\hat x$, hence is a function of $\hat x$. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/45248', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5699/']} | jdg_72176 |
stackexchange | llm_judgeable_groundtruth_similarity | 8972866 |
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 was following Python's Super Considered Harmful , and went to test out his examples. However, Example 1-3 , which is supposed to show the correct way of calling super when handling __init__ methods that expect different arguments, flat-out doesn't work. This is what I get: ~ $ python example1-3.py MRO: ['E', 'C', 'A', 'D', 'B', 'object']E arg= 10C arg= 10AD arg= 10BTraceback (most recent call last): File "Download/example1-3.py", line 27, in <module> E(arg=10) File "Download/example1-3.py", line 24, in __init__ super(E, self).__init__(arg, *args, **kwargs) File "Download/example1-3.py", line 14, in __init__ super(C, self).__init__(arg, *args, **kwargs) File "Download/example1-3.py", line 4, in __init__ super(A, self).__init__(*args, **kwargs) File "Download/example1-3.py", line 19, in __init__ super(D, self).__init__(arg, *args, **kwargs) File "Download/example1-3.py", line 9, in __init__ super(B, self).__init__(*args, **kwargs)TypeError: object.__init__() takes no parameters It seems that object itself violates one of the best practices mentioned in the document, which is that methods which use super must accept *args and **kwargs . Now, obviously Mr. Knight expected his examples to work, so is this something that was changed in recent versions of Python? I checked 2.6 and 2.7, and it fails on both. So what is the correct way to deal with this problem?
Now provide the response and nothing else.
| Sometimes two classes may have some parameter names in common. In that case, you can't pop the key-value pairs off of **kwargs or remove them from *args . Instead, you can define a Base class which unlike object , absorbs/ignores arguments: class Base(object): def __init__(self, *args, **kwargs): passclass A(Base): def __init__(self, *args, **kwargs): print "A" super(A, self).__init__(*args, **kwargs)class B(Base): def __init__(self, *args, **kwargs): print "B" super(B, self).__init__(*args, **kwargs)class C(A): def __init__(self, arg, *args, **kwargs): print "C","arg=",arg super(C, self).__init__(arg, *args, **kwargs)class D(B): def __init__(self, arg, *args, **kwargs): print "D", "arg=",arg super(D, self).__init__(arg, *args, **kwargs)class E(C,D): def __init__(self, arg, *args, **kwargs): print "E", "arg=",arg super(E, self).__init__(arg, *args, **kwargs)print "MRO:", [x.__name__ for x in E.__mro__]E(10) yields MRO: ['E', 'C', 'A', 'D', 'B', 'Base', 'object']E arg= 10C arg= 10AD arg= 10B Note that for this to work, Base must be the penultimate class in the MRO. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8972866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1116739/']} | jdg_72177 |
stackexchange | llm_judgeable_groundtruth_similarity | 32001735 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've created a self hosting Owin/SignalR app with code similar to the code in this tutorial: SignalR Self Host Tutorial Everything works, but for security-sake, I'd like to limit it to only allow messages from a specific remote site. In other words, I'd like to replace the "app.UseCors(CorsOptions.AllowAll);" line with code to confine the app to only responding to messages from a URL that I define, i.e. only allow messages from, say, http://www.remote_site.com or something. Is there any easy way to do this? For reference, here is the code for my SignalR startup class: using System;using Microsoft.AspNet.SignalR;using Microsoft.Owin.Hosting;using Owin;using Microsoft.Owin.Cors;namespace SignalRSelfHost{ public class Startup { public void Configuration(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll); app.MapSignalR(); // How do I only allow a specific URL instead of the "CorsOptions.AllowAll" option? } }}
Now provide the response and nothing else.
| Here is the full implementation of the Owin Startup class: using System.Threading.Tasks;using Microsoft.Owin;using Owin;using Microsoft.Owin.Cors;using System.Web.Cors;[assembly: OwinStartup(typeof(SignalRSelfHost.Startup))]namespace SignalRSelfHost{ public class Startup { public void Configuration(IAppBuilder app) { var policy = new CorsPolicy() { AllowAnyHeader = true, AllowAnyMethod = true, SupportsCredentials = true }; policy.Origins.Add("domain"); //be sure to include the port://example: "http://localhost:8081" app.UseCors(new CorsOptions { PolicyProvider = new CorsPolicyProvider { PolicyResolver = context => Task.FromResult(policy) } }); app.MapSignalR(); } }} Also, if you want to server to accept a list of domains, you simply add them to the Origins . Hope this helps! Good luck! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32001735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2860297/']} | jdg_72178 |
stackexchange | llm_judgeable_groundtruth_similarity | 31367005 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Xcode's Variables View, on the right of the Debug area, when an app is running and paused at a breakpoint you can right-click a variable and select "Edit Value". For a swift String it's greyed out, and I can imagine why that might be the case. But even for a simple int, it brings up an edit box to enter an new value, but after hitting the value stays at the old value. This is true even for a var which is changed during the code. Update: as shown in Jim's answer below, you should be able to set the value using the lldb expression command, but, although Xcode will tell you it has changed, it fails to actually change the value. Is this broken, or is there something specific you need to do for it to work? Thanks. Update: It's a compile bug - see Jim's comment . Here's a workaround... println("Before lldb change, foo is \(foo)") //make compiler think foo may change, so I can change it myself at the console if count("abcd") == 0 { foo = 0 } println("After lldb change, code now thinks foo is \(foo)")
Now provide the response and nothing else.
| Most Swift entities, for sure strings but even "simple" types like Int's, are actually not simple types. The values you see in the Variables View are constructed by data formatters in lldb that are set up to present a useful view of the Values without running any code (for performance reasons.) They know how grub around & fetch the contents of Swift types, but we didn't teach them how to edit values, only present them. If you want to change a value, you need to run some code in your program to do that, which you can do using the expression command in the lldb console. So for instance if you have an Int variable called foo , you can do: (lldb) expr foo = 12 That will compile & execute that code fragment, and of course the Swift compiler does know how to alter these Swift values, so the resultant code will correctly set the value. Note, it does appear that the swift compiler will sometimes copy a value to a register and use it from the register w/o indicating that fact in the debug info. If that happens, lldb will report the value it set in the location the debug information pointed to, but the code will actually use the temporary value. I've filed a bug with the swift compiler demonstrating one instance of this. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31367005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297981/']} | jdg_72179 |
stackexchange | llm_judgeable_groundtruth_similarity | 59068 |
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'm learning (or at least trying to learn) about electrochemistry, but a major obstacle to that, is that different books I refer use different terms for the same symbols. So in a last ditch attempt to clear stuff up, I've resorted to Chem.SE. So here's what I intend to do; I'll list out everything I think I've understood, as well as pose a couple of questions regarding some of them. I'd really appreciate it if someone would take the time to go through what I've listed out, checking them for errors and then clearing those queries which I've got. So here I go Symbols used: Resistance ($R$) , Resistivity or specific resistance ($\rho$), Conductance ($C$), Conductivity or specific conductance ($\kappa$), Area of cross-section of the electrode ($A$), distance between the electrodes ($L$), and the REALLY confusing bit, Molar conductance according to some books and Molar conductivity according to others and one book uses both terms, both represented by $\mathrm{Λ_{m}}$ Now,$$R = \rho \frac{L}{A}\\R = \frac1C\\$$Therefore$$\frac1\rho = \frac1R\cdot\frac{L}A = C\cdot\frac{L}A = \kappa$$ Now if I've got this right, then, Conductance is the degree to which the solution conducts electricity. Conductivity is the conductance per unit volume of the solution; it may also be considered as the concentration of ions per unit volume of solution. Molar Conductivity is the conductance of the entire solution having 1 mole of electrolyte dissolved in it. Q1. So what's Molar Conductance ? Q2. Is there a difference between Molar Conductivity and Molar Conductance ? Also, according to Ostwald's Dilution Law , greater the dilution, greater the dissociation of the electrolyte in solution. Regarding dilution of an electrolyte solution, this is what I've understood As dilution increases, Conductivity (ion concentration per unit volume) DECREASES. As dilution increases, Molar conductivity (Conductance of 1 mole of electrolyte in the total solution) should INCREASE in accordance with Ostwald's Law Q3. How does dilution affect Molar Conductance ? Q4. How is Conductance affected upon dilution? I suppose if the above statements are proof-read and the queries answered, I might get fairly good idea about this.... Also if you feel there is are any additional points worth mentioning, by all means go ahead and put it in the answer. And finally, if anyone could recommend a decent site that deals with the above-mentioned terms and concepts in a fairly lucid manner, it'd be appreciated.
Now provide the response and nothing else.
| I can understand your frustration. The use of terminology is often inconsistent and confused (much to my chagrin). I think you've got the general idea, the conductance ( $G$ ) can be defined as follows: $$G = \frac{1}{R}$$ i.e. the ease with which a current can flow. As you said, $$R = \rho \frac{l}{A}$$ one can now identify, $$G = \kappa\frac{A}{l}$$ where the conductivity $$\kappa = \frac{1}{\rho}$$ Molar "any quantity" always has the dimensions (it is helpful to think in terms of dimensions) $\text{"quantity" } \mathrm{mol^{-1}}$ so, it follows molar conductivity $$ \Lambda_m = \frac{\kappa}{c}$$ where $c$ is the molar concentration. It is useful to define molar conductivity because, as you already know, conductivity changes with concentration. Now, to address the effect of change of concentration on molar conductivity, we need to consider the case of weak and strong electrolytes separately. For a strong electrolyte, we can assume ~ 100% disassociation into constituent ions. A typical example is an $\ce{MX}$ salt like $\ce{KCl}$ $$\ce{MX} \rightleftharpoons \ce{M^+} + \ce{X^-}$$ The equilibrium constant for this reaction is $$ K = \frac{[\ce{M^+}][\ce{X^-}]}{[\ce{MX}]}$$ and thus, with decreasing molar concentration of the electrolyte, equilibrium shifts towards the disassociated ions. At sufficiently low concentrations, the following relations are obeyed: $$\Lambda _{m}=\Lambda _{m}^{0}-K{\sqrt {c}}$$ where $ \Lambda _{m}^{0}$ is known as the limiting molar conductivity, $K$ is an empirical constant and $c$ is the electrolyte concentration (Limiting here means "at the limit of the infinite dilution"). In effect, the observed conductivity of a strong electrolyte becomes directly proportional to concentration, at sufficiently low concentrations As the concentration is increased however, the conductivity no longer rises in proportion. Moreover, the conductivity of a solution of a salt is equal to the sum of conductivity contributions from the cation and anion. $$ \Lambda_{m}^{0}= \nu_{+}\lambda_{+}^{0}+\nu _{-}\lambda _{-}^{0}$$ where: $ \nu _{+}$ and $\nu _{-}$ are the number of moles of cations and anions, respectively, which are created from the dissociation of $\pu{1 mol}$ of the dissolved electrolyte, and $\lambda _{+}^{0}$ , $\lambda _{-}^{0}$ are the limiting molar conductivity of each individual ion. The situation becomes slightly more complex for weak electrolytes, which never fully disassociate into their constituent ions. We no longer have a limit of dilution below which the relationship between conductivity and concentration becomes linear. We always have a mixture of ions and complete molecules in equilibrium. Hence, the solution becomes ever more fully dissociated at weaker concentrations. For low concentrations of "well behaved" weak electrolytes, the degree of dissociation of the weak electrolyte becomes proportional to the inverse square root of the concentration. A typical example would be a monoprotic weak acid like acetic acid (again, from your graph): $$\ce{AB} \rightleftharpoons \ce{A^+} + \ce{B^-} $$ Let $\alpha$ be the fraction of dissociated electrolyte, then $ \alpha c_0$ is the concentration of each ionic species. And $(1 - \alpha)$ , and $(1 - \alpha)c_0 $ gives the fraction, and concentration of undissociated electrolyte. The dissociation constant is: $$K = \frac{\alpha^2 c_0}{1-\alpha}$$ for weak electrolytes, $\alpha$ is tiny, so the denominator is nearly equal to one so, $$ K \approxeq \alpha^2 c_0$$ and $$ \alpha = \sqrt{\frac{K}{c_0}}$$ (like I said earlier) for conductivities, one can now write the following relation $$\frac{1}{\Lambda_m} = \frac{1}{\Lambda_m^0} + \frac{\Lambda_mc}{K (\Lambda_m^0)^2}$$ This fits the curve seen in your graph. Caveat, all these arguments hold for dilute solutions. Things get out of hand at high concentrations, and one has to account for some additional phenomenon (for example, acetic acid will form hydrogen bonded dimers). Anyway, long story short, conductivity increases with increasing dilution (though differently for strong and weak electrolytes). From the definitions I outlined at the very start, guessing how conductance changes is trivial. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/59068', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/33991/']} | jdg_72180 |
stackexchange | llm_judgeable_groundtruth_similarity | 1511540 |
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 compare the growth rates of functions to review my understanding of basic Algorithms. The text asks to compare: $$N\log \log N$$ and $$N\log^2{N}$$ Are they not the same function?
Now provide the response and nothing else.
| Asking to compare $N\log(\log(N))$ with $N\log^2(N)$ would be useless if $\log^2(N)$ meant $\log(\log(N))$, therefore it most likely means $\log(N)^2$, i.e. $\log(N)\times\log(N)$, although I would avoid using that notation at all as being ambiguous. The first function grows slower. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1511540', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/284114/']} | jdg_72181 |
stackexchange | llm_judgeable_groundtruth_similarity | 60654 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering why dogs shouldn't eat chocolate. Can't dogs just excrete the indigestible component in their droppings? It's common knowledge that dogs shouldn't eat chocolate. What I don't know is why chocolate would kill them, from a specifically biological perspective.
Now provide the response and nothing else.
| The reason is simple: Chocolate contains cocoa which contains Theobromine . The darker the chocolate is (meaning the more cocoa it contains) the more theobromine it contains. This is a bitter alkaloid which is toxic to dogs (and also cats), but can be tolerated by humans. The reason for this is the much slower metabolization of theobromine in the animals (there are reports for poisonings of dogs, cats, birds, rabbits and even bear cubs) so that the toxic effect can happen. Depending on the size of the dog, something between 50 and 400g of milk chocolate can be fatal. As mentioned by @anongoodnurse the cocoa content in milk chocolate is the lowest and much higher the darker the chocolate gets. The poisoning comes from the Theobromine itself, which has different mechanisms of action: First it is an unselective antagonist of the adenosine receptor , which is a subclass of G-protein coupled receptors on the cell surface which usually bind adenosine as a ligand. This influences cellular signalling. Then it is a competitive nonselective phosphodiesterase inhibitor , which prevents the breakdown of cyclic AMP in the cell. cAMP is an important second messenger in the cell playing an important role in the mediation of signals from the outside of the cells via receptors to a reaction of a cell to changing conditions. The levels of cAMP are tightly controlled and the half-life of the molecule is generally short. Elevated levels lead to an activation of the protein kinase A , an inhibition TNF-alpha and leukotriene synthesis and reduces inflammation and innate immunity. For references see here . The LD 50 for theobromine is very different among species (table from here ), with LD 50 as the lethal dose killing 50% of the individuals and TD lo the lowest published toxic dose: The LD 50 also differs between different breeds of dogs, so there are online calculators available to make an estimation, if there is a problem or not. You can find them for example here and here . The selective toxicity makes it even an interesting poison for pest control of coyotes, see reference 4 for some details. References: Chocolate - Veterinary Manual Chocolate intoxication The Poisonous Chemistry of Chocolate Evaluation of cocoa- and coffee-derived methylxanthines as toxicantsfor the control of pest coyotes. | {} | {'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/60654', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/33104/']} | jdg_72182 |
stackexchange | llm_judgeable_groundtruth_similarity | 24007898 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to PHP, and I am not quite sure: what is the difference between the file() , file_get_contents() , and fopen() functions, and when should I use one over the other?
Now provide the response and nothing else.
| The first two, file and file_get_contents are very similar. They both read an entire file, but file reads the file into an array, while file_get_contents reads it into a string. The array returned by file will be separated by newline, but each element will still have the terminating newline attached, so you will still need to watch out for that. The fopen function does something entirely different—it opens a file descriptor, which functions as a stream to read or write the file. It is a much lower-level function, a simple wrapper around the C fopen function, and simply calling fopen won't do anything but open a stream. Once you've open a handle to the file, you can use other functions like fread and fwrite to manipulate the data the handle refers to, and once you're done, you will need to close the stream by using fclose . These give you much finer control over the file you are reading, and if you need raw binary data, you may need to use them, but usually you can stick with the higher-level functions. So, to recap: file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string. fopen — Opens a file handle that can be manipulated with other library functions, but does no reading or writing itself. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24007898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3701753/']} | jdg_72183 |
stackexchange | llm_judgeable_groundtruth_similarity | 93542 |
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:
Enumeration, enumeration, and even more enumeration is the generic pentesting mantra, but enumeration is worthless if you can't read the results. I came across the Windows RPC service, where metasploit returns results such as msf auxiliary(endpoint_mapper) > run[*] Connecting to the endpoint mapper service...[*] 12345778-1234-abcd-ef00-0123456789ac v1.0 TCP (49179) 192.168.41.221[*] 2f5f6521-cb55-1059-b446-00df0bce31db v1.0 PIPE (\pipe\tapsrv) \\XXXXX [Unimodem LRPC Endpoint][*] 2f5f6521-cb55-1059-b446-00df0bce31db v1.0 LRPC (tapsrvlpc) [Unimodem LRPC Endpoint][*] 2f5f6521-cb55-1059-b446-00df0bce31db v1.0 LRPC (unimdmsvc) [Unimodem LRPC Endpoint][*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (LRPC-d08ef1fa6d632a075d)[*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (LRPC-d08ef1fa6d632a075d)[*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (LRPC-d08ef1fa6d632a075d)[*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (LRPC-d08ef1fa6d632a075d)[*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (OLEEE86D47927814F3C96D95E0A7601)[*] 906b0ce0-c70b-1067-b317-00dd010662da v1.0 LRPC (LRPC-bec9533644f8432732)[*] 367abb81-9844-35f1-ad32-98f038001003 v2.0 TCP (49164) 192.168.41.221[*] 12345678-1234-abcd-ef00-0123456789ab v1.0 LRPC (LRPC-9d7905a8727cb4e919) [IPSec Policy agent endpoint][*] 50abc2a4-574d-40b3-9d66-ee4fd5fba076 v5.0 TCP (49155) 192.168.41.221... or msf auxiliary(management) > run[*] UUID e1af8308-5d1f-11c9-91a4-08002b14a0fa v3.0[*] Remote Management Interface Error: DCERPC FAULT => nca_s_fault_ndr[*] listening: 00000000[*] killed: 00000005[*] name: 00010000000000000100000000000000d3060000[*] UUID 0b0a6584-9e0f-11cf-a3cf-00805f68cb1b v1.1[*] Remote Management Interface Error: DCERPC FAULT => nca_s_fault_ndr[*] listening: 00000000[*] killed: 00000005[*] name: 00010000000000000100000000000000d3060000... or msf auxiliary(tcp_dcerpc_auditor) > run192.168.41.221 - UUID 99fcfec4-5260-101b-bbcb-00aa0021347a 0.0 OPEN VIA 135 ACCESS GRANTED 00000000000000000000000000000000000000000000000076070000192.168.41.221 - UUID afa8bd80-7d8a-11c9-bef4-08002b102989 1.0 OPEN VIA 135 ACCESS GRANTED 000002000c0000000c00000004000200080002000c0002001000020014000200180002001c0002002000020024000200280002002c000200300002000883afe11f5dc91191a408002b14a0fa0300000084650a0b0f9ecf11a3cf00805f68cb1b0100010026b5551d37c1c546ab79638f2a68e86901000000e6730ce6f988cf119af10020af6e72f402000000c4fefc9960521b10bbcb00aa0021347a00000000609ee7b9523dce11aaa100006901293f000002001e242f412ac1ce11abff0020af6e7a17000002003601000000000000c0000000000000460000000072eef3c67eced111b71e00c04fc3111a01000000b84a9f4d1c7dcf11861e0020af6e7c5700000000a001000000000000c000000000000046000000007f0bfe64f59e5345a7db9a19757775540100000000000000 However, I have no idea what to do with this information. Sample #1 seems to be kind of useful, but anyway: How would this information help an attacker to plan his next move? What is metasploit telling me here?
Now provide the response and nothing else.
| Based on the MSRPC DCE-RPC IFIDs from the first command output you posted, the target appears potentially vulnerable to MS00-070 , CVE-2000-0544 , CVE-2001-0662 , CVE-2002-1561 , CVE-2003-0533 , CVE-2003-0818 , CVE-2004-0894 , CVE-2005-1984 (Nessus 19406 and 19407 as well as CANVAS ms05_043 and CORE IMPACT MSRPC SPOOLSS Buffer Overflow ), CVE-2005-2119 , CVE-2006-0034/1184 (Nessus 21334 and CORE IMPACT MSDTC Allocation ), or CVE-2007-1748 . You can get cursory information about some of the IFIDs identified by using the epdump tool or deep information about each IFID by going through the Windows network services internals documentation here: 12345778-1234-abcd-ef00-0123456789ac -- References: samr , samr interface , SAM access 2f5f6521-cb55-1059-b446-00df0bce31db -- References: Unimodem LRPC Endpoint 906b0ce0-c70b-1067-b317-00dd010662da -- References: MS-DTC , IXnRemote operations , Distributed Transaction Coordinator 367abb81-9844-35f1-ad32-98f038001003 -- References: SVCCTL RPC , Services Control Manager 12345678-1234-abcd-ef00-0123456789ab -- References: winipsec and spoolss , IPSec services and Spooler service , winipsec operations , winspool operations 50abc2a4-574d-40b3-9d66-ee4fd5fba076 -- References: DnsServer , DnsServer operations e1af8308-5d1f-11c9-91a4-08002b14a0fa -- References: epmp , RPC endpoint mapper , Portmapper , Portmapper RPC service , epmp operations 0b0a6584-9e0f-11cf-a3cf-00805f68cb1b -- References: localepmp , localepmp operations 99fcfec4-5260-101b-bbcb-00aa0021347a -- References: IObjectExporter , IOXIDResolver , IOIXResolver operations afa8bd80-7d8a-11c9-bef4-08002b102989 -- This is the RMI, or remote management interface that allows all of this enumeration to occur without authentication. Generally fixed in XP SP2 but the machine you are targeting behaves more like Windows 2000 or Server 2003. If you want a pretty GUI that enumerates all of the IFIDs and explains what they are, check out this older tool from securityfriday.com called RpcScan . The download link therein didn't work, so after a bit of sleuthing, I was able to find the tool at a disreputable location -- here -- but I was able to verify the GPG signature contained in the zip file by using '--verify' on the .sig file, using '--search-keys' for the resulting keyid, editing the key to add trust, and finally verifying the signature with the associated executable. You may want to run it in a blow-away guest VM just in case. Additionally, that first IFID shows that the SAMR is running on 192.168.41.221 via TCP port 49179 because of dynamic allocation . This can be queried using a tool such as walksam from the rpctools utilities bundle. Read more about rpctools here -- https://web.archive.org/web/20070510223113/http://www.bindview.com/Services/RAZOR/Utilities/Windows/rpctools1.0-readme.cfm And download the zip file here -- https://web.archive.org/web/20070510223113/http://www.bindview.com/Resources/RAZOR/Files/rpctools-1.0.zip Query the server using the following technique: C:\> walksam -p ncacn_ip_tcp -e 49179 192.168.41.221 Also run walksam (against all SMB hosts) without the flags to get more general user information as it walks through the SAM database. TrustedSec also released a tool to perform RID cycling, which is one of the techniques performed by walksam. You can check out rid_enum.py in more depth on its GitHub page. There are plenty of tools that relate to pivot points from the information you gathered via those metasploit-framework auxiliary modules. Some can be found here -- http://winhackingexposed.com/tools.html -- and are discussed in that book's sections on RPC and SMB Enumeration in Chapter 4. I'd also recommend Chris McNab's work as I gathered much of the information for this answer from his wise books. The best modern equivalent for this MSRPC toolchain is the CoreSec impacket tools. There is an rpcdump.py, but you may get better use out of their ifmap.py and opmap.py tools. These will lead you towards the other tools, such as samrdump.py, lookupsid.py, and potentially even services.py or secretsdump.py. These are all speaking purely from an MSRPC DCE-RPC perspective, there may be many other pathways into this Windows machine or surrounding environment. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/93542', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/42981/']} | jdg_72184 |
stackexchange | llm_judgeable_groundtruth_similarity | 177867 |
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'm trying to prove that if $N$ is a normal subgroup of $G$, with $N$ and $G/N$ solvable, then $G$ is solvable. Proving that $G/N$ is abelian would of course suffice, but I'm not sure if that's a necessary condition or not. I suppose it's possible that I could find some normal subgroup $K$ in $G$ such that $N\subseteq K\subseteq G$ with both $G/K$ and $K/N$ abelian, but I can't see how to go about constructing it. I've tried a couple things with the isomorphism theorems, and looking at properties preserved under homomorphisms and such, but nothing's panned out. Can anyone help me here, I'm a bit stuck, thanks.
Now provide the response and nothing else.
| If $~1=U_0\le U_1\le \cdots \le U_n=G/N~$ and $~1=V_0\le V_1\le \cdots \le V_m=N$ are subnormal series with abelian factor groups, then consider the series induced by "superimposing" the former over latter: $$1=V_0\le V_1\le \cdots\le V_m=N=U_0'\le U_1'\le \cdots \le U_n'=G$$ where $U_i'$ are the unique subgroups of $G$ such that $U_i'/N=U_i$ (given by the lattice theorem). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/177867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26920/']} | jdg_72185 |
stackexchange | llm_judgeable_groundtruth_similarity | 5983099 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a map using Google Maps API that highlights all Minnesota counties. Basically, I created the county polygons using a set of longitudes/latitudes coordinates. Here's a screenshot of the generated map:- One of the user requirements is to be able to have a similar map as an image so that they can embed it in their PowerPoint/keynote slides. I couldn't find any useful Google Maps API that allows me to save my custom map the way it is (if you know a way, let me know), so I figure I should just draw it with Graphics2D in Java. After reading about the formulas to convert the longitude/latitude to X/Y coordinate, I end up with the following code:- private static final int EARTH_RADIUS = 6371;private static final double FOCAL_LENGTH = 500;...BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);Graphics2D g = bi.createGraphics();for (Coordinate coordinate : coordinates) { double latitude = Double.valueOf(coordinate.getLatitude()); double longitude = Double.valueOf(coordinate.getLongitude()); latitude = latitude * Math.PI / 180; longitude = longitude * Math.PI / 180; double x = EARTH_RADIUS * Math.sin(latitude) * Math.cos(longitude); double y = EARTH_RADIUS * Math.sin(latitude) * Math.sin(longitude); double z = EARTH_RADIUS * Math.cos(latitude); double projectedX = x * FOCAL_LENGTH / (FOCAL_LENGTH + z); double projectedY = y * FOCAL_LENGTH / (FOCAL_LENGTH + z); // scale the map bigger int magnifiedX = (int) Math.round(projectedX * 5); int magnifiedY = (int) Math.round(projectedY * 5); ... g.drawPolygon(...); ...} The generated map is similar the one generated by Google Maps API using the same set of longitudes/latitudes. However, it seems a little bit tilted and it looks a little off, and I'm not sure how to fix this. How do I make the shape of the counties to look just like the one generated by Google Maps API above? Thanks much. FINAL SOLUTION I finally found the solution thanks to @QuantumMechanic and @Anon. The Mercator projection really does the trick here. I'm using Java Map Projection Library to perform the calculation for Mercator projection. private static final int IMAGE_WIDTH = 1000;private static final int IMAGE_HEIGHT = 1000;private static final int IMAGE_PADDING = 50;...private List<Point2D.Double> convertToXY(List<Coordinate> coordinates) { List<Point2D.Double> xys = new ArrayList<Point2D.Double>(); MercatorProjection projection = new MercatorProjection(); for (Coordinate coordinate : coordinates) { double latitude = Double.valueOf(coordinate.getLatitude()); double longitude = Double.valueOf(coordinate.getLongitude()); // convert to radian latitude = latitude * Math.PI / 180; longitude = longitude * Math.PI / 180; Point2D.Double d = projection.project(longitude, latitude, new Point2D.Double()); // shift by 10 to remove negative Xs and Ys // scaling by 6000 to make the map bigger int magnifiedX = (int) Math.round((10 + d.x) * 6000); int magnifiedY = (int) Math.round((10 + d.y) * 6000); minX = (minX == -1) ? magnifiedX : Math.min(minX, magnifiedX); minY = (minY == -1) ? magnifiedY : Math.min(minY, magnifiedY); xys.add(new Point2D.Double(magnifiedX, magnifiedY)); } return xys;}... By using the generated XY coordinate, the map seems inverted, and that's because I believe the graphics2D's 0,0 starts at top left. So, I need to invert the Y by subtracting the value from the image height, something like this:- ...Polygon polygon = new Polygon();for (Point2D.Double point : xys) { int adjustedX = (int) (IMAGE_PADDING + (point.getX() - minX)); // need to invert the Y since 0,0 starts at top left int adjustedY = (int) (IMAGE_HEIGHT - IMAGE_PADDING - (point.getY() - minY)); polygon.addPoint(adjustedX, adjustedY);}... Here's the generated map:- IT IS PERFECT! UPDATE 01-25-2013 Here's the code to create the image map based on the width and height (in pixel). In this case, I'm not relying on the Java Map Project Library, instead, I extracted out the pertinent formula and embed it in my code. This gives you a greater control of the map generation, compared to the above code example that relies on an arbitrary scaling value (the example above uses 6000). public class MapService { // CHANGE THIS: the output path of the image to be created private static final String IMAGE_FILE_PATH = "/some/user/path/map.png"; // CHANGE THIS: image width in pixel private static final int IMAGE_WIDTH_IN_PX = 300; // CHANGE THIS: image height in pixel private static final int IMAGE_HEIGHT_IN_PX = 500; // CHANGE THIS: minimum padding in pixel private static final int MINIMUM_IMAGE_PADDING_IN_PX = 50; // formula for quarter PI private final static double QUARTERPI = Math.PI / 4.0; // some service that provides the county boundaries data in longitude and latitude private CountyService countyService; public void run() throws Exception { // configuring the buffered image and graphics to draw the map BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH_IN_PX, IMAGE_HEIGHT_IN_PX, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufferedImage.createGraphics(); Map<RenderingHints.Key, Object> map = new HashMap<RenderingHints.Key, Object>(); map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); map.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); RenderingHints renderHints = new RenderingHints(map); g.setRenderingHints(renderHints); // min and max coordinates, used in the computation below Point2D.Double minXY = new Point2D.Double(-1, -1); Point2D.Double maxXY = new Point2D.Double(-1, -1); // a list of counties where each county contains a list of coordinates that form the county boundary Collection<Collection<Point2D.Double>> countyBoundaries = new ArrayList<Collection<Point2D.Double>>(); // for every county, convert the longitude/latitude to X/Y using Mercator projection formula for (County county : countyService.getAllCounties()) { Collection<Point2D.Double> lonLat = new ArrayList<Point2D.Double>(); for (CountyBoundary countyBoundary : county.getCountyBoundaries()) { // convert to radian double longitude = countyBoundary.getLongitude() * Math.PI / 180; double latitude = countyBoundary.getLatitude() * Math.PI / 180; Point2D.Double xy = new Point2D.Double(); xy.x = longitude; xy.y = Math.log(Math.tan(QUARTERPI + 0.5 * latitude)); // The reason we need to determine the min X and Y values is because in order to draw the map, // we need to offset the position so that there will be no negative X and Y values minXY.x = (minXY.x == -1) ? xy.x : Math.min(minXY.x, xy.x); minXY.y = (minXY.y == -1) ? xy.y : Math.min(minXY.y, xy.y); lonLat.add(xy); } countyBoundaries.add(lonLat); } // readjust coordinate to ensure there are no negative values for (Collection<Point2D.Double> points : countyBoundaries) { for (Point2D.Double point : points) { point.x = point.x - minXY.x; point.y = point.y - minXY.y; // now, we need to keep track the max X and Y values maxXY.x = (maxXY.x == -1) ? point.x : Math.max(maxXY.x, point.x); maxXY.y = (maxXY.y == -1) ? point.y : Math.max(maxXY.y, point.y); } } int paddingBothSides = MINIMUM_IMAGE_PADDING_IN_PX * 2; // the actual drawing space for the map on the image int mapWidth = IMAGE_WIDTH_IN_PX - paddingBothSides; int mapHeight = IMAGE_HEIGHT_IN_PX - paddingBothSides; // determine the width and height ratio because we need to magnify the map to fit into the given image dimension double mapWidthRatio = mapWidth / maxXY.x; double mapHeightRatio = mapHeight / maxXY.y; // using different ratios for width and height will cause the map to be stretched. So, we have to determine // the global ratio that will perfectly fit into the given image dimension double globalRatio = Math.min(mapWidthRatio, mapHeightRatio); // now we need to readjust the padding to ensure the map is always drawn on the center of the given image dimension double heightPadding = (IMAGE_HEIGHT_IN_PX - (globalRatio * maxXY.y)) / 2; double widthPadding = (IMAGE_WIDTH_IN_PX - (globalRatio * maxXY.x)) / 2; // for each country, draw the boundary using polygon for (Collection<Point2D.Double> points : countyBoundaries) { Polygon polygon = new Polygon(); for (Point2D.Double point : points) { int adjustedX = (int) (widthPadding + (point.getX() * globalRatio)); // need to invert the Y since 0,0 starts at top left int adjustedY = (int) (IMAGE_HEIGHT_IN_PX - heightPadding - (point.getY() * globalRatio)); polygon.addPoint(adjustedX, adjustedY); } g.drawPolygon(polygon); } // create the image file ImageIO.write(bufferedImage, "PNG", new File(IMAGE_FILE_PATH)); }} RESULT: Image width = 600px, Image height = 600px, Image padding = 50px RESULT: Image width = 300px, Image height = 500px, Image padding = 50px
Now provide the response and nothing else.
| The big issue with plotting maps is that the spherical surface of the Earth cannot be conveniently converted into a flat representation. There are a bunch of different projections that attempt to resolve this. Mercator is one of the simplest: it assumes that lines of equal latitude are parallel horizontals, while lines of equal longitude are parallel verticals. This is valid for latitude (1 degree of latitude approximately equals 111 km no matter where you are), but not valid for longitude (the surface distance of a degree of longitude is proportional to the cosine of the latitutude ). However, as long as you're below about 45 degrees (which most of Minnesota is), a Mercator projection works very well, and creates the forms that most people will recognize from their grade school maps. And it's very simple: just treat the points as absolute coordinates, and scale to whatever space you're drawing them in. No trig necessary. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5983099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341508/']} | jdg_72186 |
stackexchange | llm_judgeable_groundtruth_similarity | 8801047 |
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 fill the color in white area for Paint based application so please give me suggestion for how to do this work..
Now provide the response and nothing else.
| I found the Solution with Flood fill algoritham private void FloodFill(Bitmap bmp, Point pt, int targetColor, int replacementColor){Queue<Point> q = new LinkedList<Point>();q.add(pt);while (q.size() > 0) { Point n = q.poll(); if (bmp.getPixel(n.x, n.y) != targetColor) continue; Point w = n, e = new Point(n.x + 1, n.y); while ((w.x > 0) && (bmp.getPixel(w.x, w.y) == targetColor)) { bmp.setPixel(w.x, w.y, replacementColor); if ((w.y > 0) && (bmp.getPixel(w.x, w.y - 1) == targetColor)) q.add(new Point(w.x, w.y - 1)); if ((w.y < bmp.getHeight() - 1) && (bmp.getPixel(w.x, w.y + 1) == targetColor)) q.add(new Point(w.x, w.y + 1)); w.x--; } while ((e.x < bmp.getWidth() - 1) && (bmp.getPixel(e.x, e.y) == targetColor)) { bmp.setPixel(e.x, e.y, replacementColor); if ((e.y > 0) && (bmp.getPixel(e.x, e.y - 1) == targetColor)) q.add(new Point(e.x, e.y - 1)); if ((e.y < bmp.getHeight() - 1) && (bmp.getPixel(e.x, e.y + 1) == targetColor)) q.add(new Point(e.x, e.y + 1)); e.x++; }}} flood fill in android: See this FloodFill | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8801047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/644182/']} | jdg_72187 |
stackexchange | llm_judgeable_groundtruth_similarity | 452865 |
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:
Given that zsh can clobber all files given the command: >* I'm thinking that setting the option noclobber would be a good idea. I can always use >| file if I want to use the default clobber behaviour in both bash and zsh. (zsh also allows the alternative syntax >!file ). I'm guessing noclobber is unset by default because of POSIX compatibility, but just to be sure: Are there any downsides to setting noclobber ? Is there anyway to set noclobber only for the interactive shell?
Now provide the response and nothing else.
| The reason noclobber is not set by default is tradition. As a matter of user interface design, it's a good idea to make “create this new file” the easy action and to put an extra hurdle the more dangerous action “either create a new file or overwrite an existing file”. Thus noclobber is a good idea ( > to create a new file, >| to potentially overwrite an existing file) and it would likely have been the default if the shell had been designed a few decades later. I strongly recommend to use the following in your interactive shell startup file ( .bashrc or .zshrc ): set -o noclobberalias cp='cp -i'alias mv='mv -i' In each case (redirection, copying, moving), the goal is to add an extra hurdle when the operation may have the side effect of erasing some existing data, even though erasing existing data is not the primary goal of the operation. I don't put rm -i in this list because erasing data is the primary goal of rm . Do note that noclobber and -i are safety nets . If they trigger, you've done something wrong . So don't use them as an excuse to not check what you're overwriting! The point is that you should have checked that the output file doesn't exist. If you're told file exists: foo or overwrite 'foo'? , it means you made a mistake and you should feel bad and be more careful. In particular, don't get into the habit of saying y if prompted to overwrite (arguably, the aliases should be alias cp='yes n | cp -i' mv='yes n | mv -i' , but pressing Ctrl + C makes the output look better): if you did mean to overwrite, cancel the command, move or remove the output file, and run the command again. It's also important not to get into the habit of triggering those safeties because if you do, one day you'll be on a machine which doesn't have your configuration, and you'll lose data because the protections you were counting on aren't there. noclobber will only be set for interactive shells, since .bashrc or .zshrc is only read by interactive shells. Of course you shouldn't change shell options in a way that would affect scripts, since it could break those scripts. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/452865', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/143394/']} | jdg_72188 |
stackexchange | llm_judgeable_groundtruth_similarity | 17671383 |
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 upgraded my IE from version 10 to 11 and found that my ActiveX custom event couldn't work. The reason is that IE11 does not support attachEvent any more, and seems I have to use addEventListener . For example previously I used obj.attachEvent("onSelected", method1); and now, it is obj.addEventListener("onSelected",method1,false); After changing the code, the method1 cannot be triggered. I have no idea how to bind custom event, which is implemented in ActiveX plugin, to JS method and make it work on IE11?
Now provide the response and nothing else.
| The only way I found so far for IE 11 is using the for...event script blocks: <script for="myActiveX" event="onSelected(param1, param2)"> method1(param1, param2);</script><object id="myActiveX" ...></object> Both elements can also be created dynamically with JavaScript. You only must make sure you set the for attribute with the setAttribute method: var handler = document.createElement("script");handler.setAttribute("for", "myActiveX");handler.event = "onSelected(param1, param2)"; handler.appendChild(document.createTextNode("method1(param1, param2);"));document.body.appendChild(handler);var activeX = document.createElement("object");activeX.id = "myActiveX"; activeX.codebase = "foobar.cab";activeX.classid = "CLSID:123456789-1234-1234-1234-123456789012";document.body.appendChild(activeX); Older IE versions (IE 8 and older) don't like the above code. For these older browsers you must pass the codebase parameter and for parameter with the createElement method: var handler = document.createElement('<script for="myActiveX">');...var activeX = document.createElement('<object classid="CLSID:123456789-1234-1234-1234-123456789012">'); Newer browsers will throw an exception when encountering this code so to support all IE versions you must catch this exception and then use the other method. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17671383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/644010/']} | jdg_72189 |
stackexchange | llm_judgeable_groundtruth_similarity | 32841300 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using command line xcodebuild tool to export ad-hoc distribution ipa file out of my archive like this: xcodebuild -exportArchive -archivePath /path/Archive.xcarchive -exportPath /path -exportOptionsPlist /path/options.plist However, this command fails with error exportArchive: exportOptionsPlist error for key 'method': expected one of {}, but found ad-hoc No mater what 'method' I provide in my export options plist, it always fails with this error. It also fails if I remove the 'method' option from the plist file.
Now provide the response and nothing else.
| I suspected xcodebuild tool initially, but it turned out the archive file was invaid. When I opened the archive file in Xcode and tried to export an ipa file manually, I noticed that "Upload to App Store" and "Validate" buttons were disabled. After clicking the "Export" button, it gave me two options: "Save Built Products" and "Export as an Xcode Archive", but there was no Export ad-hoc distribution and the other regular options. It turned out there were few library files along my .app file in the archive. Xcode considers this a generic archive and not an app archive. Check the Build Phases in your project settings for copying header and library files. For more details, see https://developer.apple. com/library/ios/technotes/tn2215/_index.html | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32841300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22764/']} | jdg_72190 |
stackexchange | llm_judgeable_groundtruth_similarity | 1230 |
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:
Seth Roberts claims that the field of climate modelling hasn't produced models that have effectively predicted future climate events. According to him the models are only validated on past data. Is this charge valid or did climate models make important predictions about the temperature on earth a decade ago that came true? If so, what were the greatest successes of the models?
Now provide the response and nothing else.
| Firstly, 'climate events' is something of a contradiction in terms, since climate is a statistical average of weather this Seth Roberts has probably confused weather events with climate events. Secondly, climate is clearly far more predictable than the weather, because everyone who books a ski or sun holiday, and manages to find the snow or the sun as expected when they arrive there, successfully predicts the climate. This happens often enough that people build businesses around the concept. In addition, Global Climate Models have successfully predicted: That the globe would warm, and abouthow fast, and about how much. That the troposphere would warm andthe stratosphere would cool. That nighttime temperatures wouldincrease more than daytimetemperatures. That winter temperatures wouldincrease more than summertemperatures. Polar amplification (greatertemperature increase - compared to former local averages - as you movetoward the poles). That the Arctic would warm fasterthan the Antarctic. The magnitude (0.3 K) and duration(two years) of the cooling from theMt. Pinatubo eruption. They made a retrodiction for LastGlacial Maximum sea surfacetemperatures which was inconsistentwith the paleo evidence, and betterpaleo evidence showed the modelswere right. They predicted a trend significantlydifferent and differently signedfrom UAH satellite temperatures, andthen a bug was found in thesatellite data, i.e. the models wereright. The amount of water vapor feedback due to ENSO. The response of southern ocean winds to the ozone hole. The expansion of the Hadley cells. The poleward movement of storm tracks. The rising of the tropopause and the effective radiating altitude. The clear sky super greenhouse effect from increased water vapor in the tropics. The near constancy of relative humidity on global average. That coastal upwelling of ocean water would increase. Source: http://bartonpaullevenson.com/ModelsReliable.html | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/1230', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/196/']} | jdg_72191 |
stackexchange | llm_judgeable_groundtruth_similarity | 14774486 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use timeago plugin to make dates look nicer. The problem is that these dates are fetched via AngularJS from the REST dynamically. So, when I attach this jQuery plugin to my page, it just doesn't process it. So, how to better do such things? I would be happy to run without jQuery at all if possible.
Now provide the response and nothing else.
| I would use momentjs - http://momentjs.com/ - it has no dependencies. Then you can just create a filter called 'timeAgo' or 'fromNow'. You should probably call it fromNow because that's what momentjs calls it: angular.module('myApp').filter('fromNow', function() { return function(date) { return moment(date).fromNow(); }}); Then you would just use simple data binding in your view: <p>Pizza arrives {{pizzaArrivalDate | fromNow}}</p> If you really wanted to use the jQuery plugin, you would probably have to write a directive. But that way of doing it is bad because it links your data to a DOM element. The way I put above seperates data from DOM which is the angular way. And it's pretty :-D | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14774486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135829/']} | jdg_72192 |
stackexchange | llm_judgeable_groundtruth_similarity | 1305601 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a simple form created using Ajax.BeginForm : <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id }, new AjaxOptions { UpdateTargetId = "DescriptionDiv", HttpMethod = "post" },new {id ='AjaxForm' })) {%>Description:<%= Html.TextBox("Description", Model.Description) %><br /><input type="submit" value="save" /><% }%> The controller is wired up and returns a partial view that updates the DescriptionDiv . And it all works neatly. Now I would like to be able to submit this form without having the submit button (via a clik on a link or on an image or whatever). Unfortunately this little jQuery snippet does not do the job: $('form#AjaxForm').submit(); It does submit the form, but does (I suppose not surprisingly) a regular post-back and not an Ajax one. For the sake of simplicity the above jQuery is wired up like this: <a href="#" onclick="$('form#AjaxForm').submit(); return false;">submit</a> The form's onsubmit is using the Sys.Mvc.AsyncForm.handleSubmit() but the jQuery submit seems to be bypassing this. PS. I am looking for a solution in this particular approach. I know how to achieve the same using a normal form and posting it using AJAX+jQuery. I am interested in this particular solution though.
Now provide the response and nothing else.
| I'm going to assume that your lack of quotes around the selector is just a transcription error, but you should check it anyway. Also, I don't see where you are actually giving the form an id. Usually you do this with the htmlAttributes parameter. I don't see you using the signature that has it. Again, though, if the form is submitting at all, this could be a transcription error. If the selector and the id aren't the problem I'm suspicious that it might be because the click handler is added via markup when you use the Ajax BeginForm extension. You might try using $('form').trigger('submit') or in the worst case, have the click handler on the anchor create a hidden submit button in the form and click it. Or even create your own ajax submission using pure jQuery (which is probably what I would do). Lastly, you should realize that by replacing the submit button, you're going to totally break this for people who don't have javascript enabled. The way around this is to also have a button hidden using a noscript tag and handle both AJAX and non-AJAX posts on the server. BTW, it's consider standard practice, Microsoft not withstanding, to add the handlers via javascript not via markup. This keeps your javascript organized in one place so you can more easily see what's going on on the form. Here's an example of how I would use the trigger mechanism. $(function() { $('form#ajaxForm').find('a.submit-link').click( function() { $('form#ajaxForm').trigger('submit'); }).show(); }<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id }, new AjaxOptions { UpdateTargetId = "DescriptionDiv", HttpMethod = "post" }, new { id = "ajaxForm" } )) {%> Description: <%= Html.TextBox("Description", Model.Description) %><br /> <a href="#" class="submit-link" style="display: none;">Save</a> <noscript> <input type="submit" value="Save" /> </noscript><% } %> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1305601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59009/']} | jdg_72193 |
stackexchange | llm_judgeable_groundtruth_similarity | 18696122 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have some input data: data = np.random.normal(loc=100,scale=10,size=(500,1,32))hist = np.ones((32,20)) # initialise histfor z in range(32): hist[z],edges = np.histogram(data[:,0,z],bins=np.arange(80,122,2)) I can plot it using imshow() : plt.imshow(hist,cmap='Reds') getting: However, the x-axis values do not match the input data (i.e. mean of 100, range from 80 to 122). Therefore, I'd like to change the x-axis to show the values in edges . I have tried: ax = plt.gca()ax.set_xlabel([80,122]) # range of values in edges...# this shifts the plot so that nothing is visible and ax.set_xticklabels(edges)...# this labels the axis but does not centre around the mean: Any ideas on how I can change the axis values to reflect the input data I am using?
Now provide the response and nothing else.
| I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data. Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort. fig, ax = plt.subplots(figsize=(6,6))ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18696122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1461850/']} | jdg_72194 |
stackexchange | llm_judgeable_groundtruth_similarity | 1214980 |
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 will convert 1 hex character to its integer value, but needs to construct a (sub) string. Convert.ToInt32(serializedString.Substring(0,1), 16); Does .NET have a built-in way to convert a single hex character to its byte (or int, doesn't matter) value that doesn't involve creating a new string?
Now provide the response and nothing else.
| int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index])); Or even faster (subtraction vs. array search), but no checking for bad input: int HexToInt(char hexChar){ hexChar = char.ToUpper(hexChar); // may not be necessary return (int)hexChar < (int)'A' ? ((int)hexChar - (int)'0') : 10 + ((int)hexChar - (int)'A');} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1214980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126769/']} | jdg_72195 |
stackexchange | llm_judgeable_groundtruth_similarity | 8835108 |
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 laptop on which I have no root privilege. onto the machine I have a library installed using configure --prefix=$HOME/.usr . after that, I got these files in ~/.usr/lib : libXX.so.16.0.0libXX.so.16libXX.solibXX.lalibXX.a when I compile a program that invokes one of function provided by the library with this command : gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX xxx.out was generated without warning, but when I run it error like this was thrown: ./xxx.out: error while loading shared libraries: libXX.so.16: cannot open shared object file: No such file or directory , though libXX.so.16 resides there. my clue-less assumption is that ~/.usr/lib wasn't searched when xxx.out is invoked.but what can I do to specify path of .so , in order that xxx.out can look there for .so file? An addition is when I feed -static to gcc, another error happens like this: undefined reference to `function_proviced_by_the_very_librar' It seems .so does not matter even though -L and -l are given to gcc.what should I do to build a usable exe with that library? For other people who has the same question as I did I found a useful article at tldp about this. It introduces static/shared/dynamic loaded library, as well as some example code to use them.
Now provide the response and nothing else.
| There are two ways to achieve that: Use -rpath linker option: gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file: export LD_LIBRARY_PATH=/home/user/.usr/lib This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org , unpack the binaries and shared libraries into your home directory, and launch them without recompiling. For a quick test, you can also do (in bash at least): LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out which has the advantage of not changing your library path for everything else. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8835108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327815/']} | jdg_72196 |
stackexchange | llm_judgeable_groundtruth_similarity | 28978759 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way in handlebars to check the length of a value? Something like this: {{#if value.length > 20}...do something{{else}}...do something else{{/if}}
Now provide the response and nothing else.
| Create Handlebars helper like below:- Handlebars.registerHelper('checklength', function (v1, v2, options) {'use strict'; if (v1.length>v2) { return options.fn(this); } return options.inverse(this);}); and use this like:- {{#checklength jobTitle 20}} //jobtitle is property and 20 is length <p>Up to 20</p> {{else}} <p>Less then 20</p> {{/checklength}} Demo | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28978759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2656987/']} | jdg_72197 |
stackexchange | llm_judgeable_groundtruth_similarity | 742428 |
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 get that $11$ is a small number and that I could maybe do this by inspection, but I was wondering if there was a more intelligent approach?
Now provide the response and nothing else.
| It means "weakly" decreasing, so they may not get smaller, but they don't get larger. Let's look at $3-1/n$.\begin{align}& \sup\left\{3 - \frac1 1, 3-\frac12,3-\frac13,3-\frac14,3-\frac15,\ldots\right\} \\[8pt]& \sup\left\{ 3-\frac12,3-\frac13,3-\frac14,3-\frac15,\ldots\right\} \\[8pt]& \sup\left\{3-\frac13,3-\frac14,3-\frac15,\ldots\right\} \\[8pt]& \sup\left\{3-\frac14,3-\frac15,\ldots\right\} \\[8pt]& {}\qquad \vdots\end{align} The sequence of suprema gets (weakly) smaller. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/742428', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_72198 |
stackexchange | llm_judgeable_groundtruth_similarity | 13551 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
First: I don't think this is a duplicate question. There are related question on mergers of black holes that orbit around each other etc., so please read on. I'm having a hard time picturing what might happen in the following scenario: Assume two black holes of the same size on an almost frontal collision course with a very high relative speed of x km/h (replace x with whatever would be necessary to enable the scenarios described below). If their event horizons don't "touch" I'd assume their courses will change considerably but it would be a normal flyby - right ? But what happens if their event horizons "touch", if their event horizons "overlap" just a few meters ? On the one hand both objects have a massive kinetic energy with opposite directional vectors. And on the other hand nothing can escape below the gravitational radius. Where does all the kinetic energy go ? Would the two black holes extremely deform, like creating a long string before they collapse into spherical form? And what if in a similar scenario one of the two objects is a neutron star. Would the neutron star be ripped apart when it scrapes the black hole on high-speed flyby ?
Now provide the response and nothing else.
| I think it's a fun question, and I can answer some of it. If their event horizons don't "touch" I'd assume their courses will change considerably but it would be a normal flyby - right? While the relativistic speeds and time dilation might change things a bit, a flyby is still a flyby. They would either fly past each other, the dense objects would change direction as a result, but the combined kinetic energy and momentum would remain constant. Second option is they enter into orbit around each other. Pretty much the same with any two massive objects passing near each other. But what happens if their event horizons "touch", if their event horizons "overlap" just a few meters? With classic (non Kerr) black holes, if the event horizons touch the black holes have no option but to merge. The event horizon is directly proportional to the radius, so when the two event horizons touch it, as that happens, no longer two black holes but one black hole. The mass of the two objects combined has an event horizon that circles both of them. For Kerr black holes this question is more complicated and I'm not sure but I think it's the same. Once the event horizons touch it's no longer two separate black holes but one bigger one. On the one hand both objects have a massive kinetic energy with opposite directional vectors. And on the other hand nothing can escape below the gravitational radius. When you're talking about event horizons, gravity always wins. Kinetic energy cannot exceed the speed of light, so it loses. Where does all the kinetic energy go ? Would the two black holes extremely deform, like creating a long string before they collapse into spherical form? A long string doesn't make any sense. A temporarily non-round event horizon as the holes merge seems possible, but think of a merger of two stretched balls, not a string. Each black hole is centered around it's "singularity", those shapes might warp some as the holes collide or spiral into each other. As an FYI, direct collisions would be rare. Spiraling into each other is much more common. The kinetic energy gets absorbed inside the black hole. It can't, by definition of the black hole, escape. Total momentum is likely preserved. And what if in a similar scenario one of the two objects is a neutron star. Would the neutron star be ripped apart when it scrapes the black hole on high-speed flyby ? A few points to consider regarding a black hole. Anything that falls within a black hole's photon-sphere is unlikely to ever escape, so one of the magical distances to consider is 1.5 times the radius of the black hole where all orbits are destined to fall into the black hole. If the black hole and neutron star are of similar size and the neutron star passes close to the event horizon and relativistic speed, then there's an interesting scenario where some of the neutron star (at close to the speed of light) would be outside the photon-sphere and have the momentum to escape and some of it would not. Neutron stars are bound together very tightly, but the tidal forces would be very strong and it's possible that some of the neutron star material could get torn off in this hypothetical scenario. Would the entire neutron star be torn apart? Maybe. It's hard to say. The math in that hypothetical is way above my pay-grade. If the neutron star is much smaller than the black hole, then it's likely inside the photon-sphere and it will spiral into the black hole, perhaps breaking apart in the process into an accretion disk, perhaps not, but it will get absorbed into the black hole if it's entirely within the photon-sphere, even at nearly the speed of light. The problem with this hypothetical is that it's pretty much impossible. Objects the size of stars don't accelerate at nearly the speed of light relative to other near by stellar mass objects. What actually happens is described in the first answer to your question, the two dense objects would either have sufficient relative velocity to fly past each other or they would get caught into a mutual orbit that would likely lead to a merger. In the actual universe, a close to the event horizon fly-by between a neutron star and a black hole would result in a merger of the two. In theory, with enough kinetic energy the neutron star could fly close to and still fly past the black hole, but that much relative velocity probably never happens. People smarter than me should feel free to correct anything I got wrong, but I thought this one was a fun one to answer. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/13551', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/10676/']} | jdg_72199 |
stackexchange | llm_judgeable_groundtruth_similarity | 404558 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As we say goodbye to the old year and welcome the new one, we have a tradition of sharing moderation stats for the past 12 months . As most of you here are aware, sites on the Stack Exchange network are moderated somewhat differently to other sites on the web: We designed the Stack Exchange network engine to be mostly self-regulating, in that we amortize the overall moderation cost of the system across thousands of teeny-tiny slices of effort contributed by regular, everyday users. -- A Theory of Moderation That doesn't eliminate the need for having moderators altogether, but it does mean that the bulk of moderation work is carried out by regular folks. Every bit of time and effort y'all contribute to the site gives you access to more privileges you can use to help in this effort, all of which produce a cumulative effect that makes a big difference. So as we welcome 2021, and in keeping with tradition, let us look back at what we accomplished as a community... by looking at some exciting stats . Below is a breakdown of moderation actions performed on Stack Overflow over the past 12 months: Action Moderators Community¹ Users suspended² 1,196 1,512 Users destroyed³ 4,653 0 Users deleted 5,434 0 Users contacted 4,865 0 User suspensions lifted early 34 0 User review-bans lifted early 179 0 User banned from review 22,340 2,258 Tasks reviewed⁴: Triage queue 610 741,283 Tasks reviewed⁴: Suggested Edit queue 1,726 817,980 Tasks reviewed⁴: Reopen Vote queue 3,256 220,473 Tasks reviewed⁴: Low Quality Posts queue 53 285,613 Tasks reviewed⁴: Late Answer queue 5 284,066 Tasks reviewed⁴: Helper queue 8 11,072 Tasks reviewed⁴: First Post queue 1,084 849,618 Tasks reviewed⁴: Close Votes queue 56,427 225,745 Tags merged 285 0 Tag synonyms proposed 178 209 Tag synonyms created 273 86 Tag highlight language set 59 0 Revisions redacted 438 0 Questions unprotected 12 89 Questions reopened 2,544 12,197 Questions protected 57 4,288 Questions migrated 435 1,267 Questions merged 109 0 Questions flagged⁵ 2,146 415,492 Questions closed 96,631 424,627 Question flags handled⁵ 73,556 343,268 Posts unlocked 155 1,789 Posts undeleted 4,966 75,194 Posts locked 1,707 10,691 Posts deleted⁶ 155,196 1,449,456 Posts bumped 0 33,260 Escalations to the Community Manager team 748 0 Comments undeleted 1,083 0 Comments flagged 373 446,811 Comments deleted⁷ 756,159 1,009,253 Comment flags handled 269,372 177,751 Bounties canceled 157 2 Answers flagged 4,313 345,227 Answer flags handled 268,537 80,891 All comments on a post moved to chat 1,884 0 Footnotes ¹ "Community" here refers both to the membership of Stack Overflow without diamonds next to their names , and to the automated systems otherwise known as user #-1 . ² The system will suspend users under three circumstances: when a user is recreated after being previously suspended, when a user is recreated after being destroyed for spam or abuse, and when a network-wide suspension is in effect on an account. ³ A "destroyed" user is deleted along with all that they had posted: questions, answers, comments. Generally used as an expedient way of getting rid of spam. ⁴ This counts every review that was submitted (not skipped) - so the 2 suggested edits reviews needed to approve an edit would count as 2, the goal being to indicate the frequency of moderation actions. This also applies to flags, etc. ⁵ Includes close flags (but not close or reopen votes). ⁶ This ignores numerous deletions that happen automatically in response to some other action. ⁷ This includes comments deleted by their own authors (which also account for some number of handled comment flags). Further reading: Wanna see how these numbers have changed over time? We posted a similar report here last year: 2019: a year in moderation You can also check out this report on other sites Or peruse detailed information on the number of questions closed and reopened across all sites A big thank you to Shog9 for writing the queries and script to facilitate fetching and posting this data to all the sites in the network, and to Brian for the subsequent work making the whole thing more user friendly. Wishing everyone a happy 2021!
Now provide the response and nothing else.
| Wanna see how these numbers have changed over time? Yes. And now my first question is: why is there such a huge difference in Comments deleted by Moderators? Action Mod2020 Mod2019 Change Comm2020 Comm2019 Change Users suspended² 1,196 1,340 -11% 1,514 1,615 -6% Users destroyed³ 4,653 4,305 8% 0 0 Users deleted 5,434 4,155 31% 0 0 Users contacted 4,866 4,475 9% 0 0 User suspensions lifted early 34 45 -24% 0 0 User review-bans lifted early 179 64 180% 0 0 User banned from review 22,340 3,023 639% 2,258 4,004 -44% Tasks reviewed⁴: Triage queue 610 34 1,694% 741,283 1,239,611 -40% Tasks reviewed⁴: Suggested Edit queue 1,726 2,940 -41% 817,980 1,141,695 -28% Tasks reviewed⁴: Reopen Vote queue 3,256 223 1,360% 220,473 185,719 19% Tasks reviewed⁴: Low Quality Posts queue 53 219 -76% 285,613 343,007 -17% Tasks reviewed⁴: Late Answer queue 5 25 -80% 284,066 282,584 1% Tasks reviewed⁴: Helper queue 8 9 -11% 11,072 31,119 -64% Tasks reviewed⁴: First Post queue 1,084 89 1,118% 849,618 804,290 6% Tasks reviewed⁴: Close Votes queue 56,427 3,126 1,705% 225,745 318,431 -29% Tags merged 285 534 -47% 0 0 Tag synonyms proposed 178 423 -58% 209 107 95% Tag synonyms created 273 534 -49% 86 77 12% Tag highlight language set 59 28 111% 0 0 Revisions redacted 438 490 -11% 0 0 Questions unprotected 12 8 50% 89 75 19% Questions reopened 2,544 1,235 106% 12,197 9,112 34% Questions protected 57 141 -60% 4,288 6,039 -29% Questions migrated 435 418 4% 1,267 758 67% Questions merged 109 94 16% 0 0 Questions flagged⁵ 2,146 1,758 22% 415,492 472,085 -12% Questions closed 96,631 33,862 185% 424,627 306,210 39% Question flags handled⁵ 73,556 45,195 63% 343,268 430,080 -20% Posts unlocked 155 147 5% 1,789 574 212% Posts undeleted 4,966 3,325 49% 75,194 70,345 7% Posts locked 1,707 432 295% 10,691 8,517 26% Posts deleted⁶ 155,196 142,938 9% 1,449,456 1,251,256 16% Posts bumped 0 0 33,260 34,352 -3% Escalations to the Community Manager team 748 1387 -46% 0 0 Comments undeleted 1,083 1,770 -39% 0 0 Comments flagged 373 611 -39% 446,811 471,440 -5% Comments deleted⁷ 756,159 6,075,670 -88% 1,009,253 981,980 3% Comment flags handled 269,372 244,261 10% 177,751 227,661 -22% Bounties canceled 157 227 -31% 2 0 Answers flagged 4,313 3,707 16% 345,227 366,618 -6% Answer flags handled 268,537 265,031 1% 80,891 105,362 -23% All comments on a post moved to chat 1,884 1,568 20% 0 0 | {} | {'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/404558', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/1328704/']} | jdg_72200 |
stackexchange | llm_judgeable_groundtruth_similarity | 504402 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let x be a positive real number. I want to prove that $\forall$ x, $\exists$ n $\in$ N such that x < $2^n$ . To me it seems that as x increases, I can just pick larger and larger values for n to satisfy this property. Since n goes to infinity, I should be able to do this process forever. Any idea how to prove this?
Now provide the response and nothing else.
| Let $X$ be a topological space, $\langle x_n:n\in\Bbb N\rangle$ a sequence of points of $X$, and $x\in X$. Definition $1$. $\langle x_n:n\in\Bbb N\rangle$ converges to $x$ if and only if for each open nbhd $U$ of $x$ there is an $m\in\Bbb N$ such that $x_n\in U$ whenever $n\ge m_U$. We sometimes express this informally by saying that every open nbhd of $x$ contains a tail of the sequence, meaning all of the terms from some point on. This is a generalization of the familiar definition of convergence of sequences of real numbers: Definition $2$. $\langle x_n:n\in\Bbb N\rangle\to x$ if and only if for each $\epsilon>0$ there is an $m_\epsilon\in\Bbb N$ such that $x_n\in(x-\epsilon,x+\epsilon)$ whenever $n\ge m_\epsilon$. The sets $(x-\epsilon,x+\epsilon)$ for positive $\epsilon$ aren’t the only open nbhds of $x$ in the usual topology on $\Bbb R$, but it turns out that if $U$ is an open nbhd of $x$ in the usual topology on $\Bbb R$, then there is an $\epsilon>0$ such that $(x-\epsilon,x+\epsilon)\subseteq U$, and we can use this fact to show that a sequence of real numbers converges by one definition if and only if it converges by the other. Thus, you know lots of examples of non-convergent sequences in $\Bbb R$ with its usual topology; $x_n=(-1)^n$ and $x_n=n$ give you two of them. Here’s another fairly simple example. Let $X=\Bbb R$, and let $$\tau=\{U\subseteq X:X\setminus U\text{ is a countable set}\}\cup\{\varnothing\}\;.$$ Check that $\langle X,\tau\rangle$ is a topological space. (This topology $\tau$ is called the co-countable topology on $X$.) Let $\langle x_n:n\in\Bbb N\rangle$ be any sequence of distinct points of $X$, and let $x$ be any point of $X$; I claim that $\langle x_n:n\in\Bbb N\rangle$ does not converge to $x$. To see this, let $S=\{x_n:n\in\Bbb N\}\setminus\{x\}$, and let $U=X\setminus S$. Then $X\setminus U=S$, which is countable, so $U\in\tau$, i.e., $U$ is an open set in this space. Moreover, $x\notin S$, so $x\in U$, and $U$ is therefore an open nbhd of $x$. Clearly no $x_n$ belongs to the set $U$, so there cannot possibly be an $m_U\in\Bbb N$ such that $x_n\in U$ whenever $n\ge m_U$, and therefore $\langle x_n:n\in\Bbb N\rangle$ does not converge to $x$. (In fact it turns out that this is another space in which the only convergent sequences are the ones that are constant from some point on; you might try to prove that.) In your specific problem the topology of $X$ is the discrete topology, meaning that every subset of $X$ is an open set, and you’re given that the sequence $\langle a_n:n\in\Bbb N\rangle$ converges to $b$ in $X$. Since every subset of $X$ is open, $\{b\}$ is an open nbhd of $b$; and since $\langle a_n:n\in\Bbb N\rangle$ converges to $b$, there must be some $m\in\Bbb N$ such that $a_n\in\{b\}$ whenever $n\ge m$. If $a_n\in\{b\}$, what is $a_n$? | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/504402', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_72201 |
stackexchange | llm_judgeable_groundtruth_similarity | 2329566 |
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:
We know that $A$ is $n\times n$ and has $n$ different eigenvalues. Also it is known that $AB = BA$. Prove that $B$ is diagonalizable.
Now provide the response and nothing else.
| Suppose $\lambda$ is an eigenvalue for $A$, and $v$ an associated eigenvector. Then$$A(Bv) = (AB)v = (BA)v = B(Av) = \lambda (Bv)$$Since the eigenspace of $A$ associated with $v$ is one-dimensional, $Bv$ must be a scalar multiple of $v$, and so $Bv=\mu v$ for some $\mu\in\mathbb R$. In particular, $v$ is an eigenvector for $B$. Thus, since $A$ has $n$ linearly independent eigenvectors, so does $B$. Hence, $B$ is diagonalizable. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2329566', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415400/']} | jdg_72202 |
stackexchange | llm_judgeable_groundtruth_similarity | 6282468 |
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 2 symmetric matrices (mathematical meaning of matrices), one with distances between locations (the locations are coded with 4 digit numbers:2030, 2059, 2095...) that looks like this: 2030 2059 2095 ... 2030 NA 59328 68464 2059 59328 NA 37196 2095 68464 37196 NA ... and another with the correlations between locations : 2030 2059 2095... 2030 1.0000000 0.4651804 0.6185849 2059 0.4651804 1.0000000 0.4428746 2095 0.6185849 0.4428746 1.0000000 ... I need to combine these 2 matrices in a plot of correlations vs. distances but have no idea how to do it in R and considering I have more than 80 locations I don't want to do it manually! Does anyone know of a way to do it? Thanks!
Now provide the response and nothing else.
| The easiest custom approach I've seen and used as far is to create a <h:inputHidden> field with a <f:validator> wherein you reference all involved components as <f:attribute> . If you declare it before the to-be-validated components, then you can obtain the submitted values inside the validator by UIInput#getSubmittedValue() . E.g. <h:form> <h:inputHidden id="foo" value="true"> <f:validator validatorId="fooValidator" /> <f:attribute name="input1" value="#{input1}" /> <f:attribute name="input2" value="#{input2}" /> <f:attribute name="input3" value="#{input3}" /> </h:inputHidden> <h:inputText binding="#{input1}" value="#{bean.input1}" /> <h:inputText binding="#{input2}" value="#{bean.input2}" /> <h:inputText binding="#{input3}" value="#{bean.input3}" /> <h:commandButton value="submit" action="#{bean.submit}" /> <h:message for="foo" /></h:form> (please note the value="true" on the hidden input; the actual value actually doesn't matter, but keep in mind that the validator won't necessarily be fired when it's null or empty, depending on the JSF version and configuration) with @FacesValidator(value="fooValidator")public class FooValidator implements Validator { @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput input1 = (UIInput) component.getAttributes().get("input1"); UIInput input2 = (UIInput) component.getAttributes().get("input2"); UIInput input3 = (UIInput) component.getAttributes().get("input3"); // ... Object value1 = input1.getSubmittedValue(); Object value2 = input2.getSubmittedValue(); Object value3 = input3.getSubmittedValue(); // ... }} If you declare the <h:inputHidden> after the to-be-validated components, then the values of the involved components are already converted and validated and you should obtain them by UIInput#getValue() or maybe UIInput#getLocalValue() (in case the UIInput isn't isValid() ) instead. See also: Validator for multiple fields (JSF 1.2 targeted) Alternatively, you can use 3rd party tags/components for that. RichFaces for example has a <rich:graphValidator> tag for this, Seam3 has a <s:validateForm> for this, and OmniFaces has several standard <o:validateXxx> components for this which are all showcased here . OmniFaces uses a component based approach whereby the job is done in UIComponent#processValidators() . It also allows customizing it in such way so that the above can be achieved as below: <h:form> <o:validateMultiple id="foo" components="input1 input2 input3" validator="#{fooValidator}" /> <h:inputText id="input1" value="#{bean.input1}" /> <h:inputText id="input2" value="#{bean.input2}" /> <h:inputText id="input3" value="#{bean.input3}" /> <h:commandButton value="submit" action="#{bean.submit}" /> <h:message for="foo" /></h:form> with @ManagedBean@RequestScopedpublic class FooValidator implements MultiFieldValidator { @Override public boolean validateValues(FacesContext context, List<UIInput> components, List<Object> values) { // ... }} The only difference is that it returns a boolean and that the message should be specified as message attribute in <o:validateMultiple> . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6282468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/747311/']} | jdg_72203 |
stackexchange | llm_judgeable_groundtruth_similarity | 24430220 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Following is my user schema in user.js model - var userSchema = new mongoose.Schema({ local: { name: { type: String }, email : { type: String, require: true, unique: true }, password: { type: String, require:true }, }, facebook: { id : { type: String }, token : { type: String }, email : { type: String }, name : { type: String } }});var User = mongoose.model('User',userSchema);module.exports = User; This is how I am using it in my controller - var user = require('./../models/user.js'); This is how I am saving it in the db - user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){ if(err) res.send(err); else { console.log(result); req.session.user = result; res.send({"code":200,"message":"Record inserted successfully"}); }}); Error - {"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1 dup key: { : null }"} I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ? FYI - req.body.email and req.body.password are fetching values. I also checked this post but no help STACK LINK If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the local.email
Now provide the response and nothing else.
| The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address. The relevant documentation for this: If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error. unique indexes Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. In other words, a sparse index is ok with multiple documents all having null values. sparse indexes From comments: Your error says that the key is named mydb.users.$email_1 which makes me suspect that you have an index on both users.email and users.local.email (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes() if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>) . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24430220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1594368/']} | jdg_72204 |
stackexchange | llm_judgeable_groundtruth_similarity | 9839179 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to connect to a site via HTTPS in Python 3.2. I tried conn = http.client.HTTPSConnection(urlStr, 8443) conn.putrequest('GET', '/') response = conn.getresponse() print(response.read()) but I get http.client.ResponseNotReady: Request-started Anyone know what the problem is?
Now provide the response and nothing else.
| First of all, if you just want to download something and don't want any special HTTP requests, you should use urllib.request instead of http.client . import urllib.requestr = urllib.request.urlopen('https://paypal.com/')print(r.read()) If you really want to use http.client, you must call endheaders after you send the request headers: import http.clientconn = http.client.HTTPSConnection('paypal.com', 443)conn.putrequest('GET', '/')conn.endheaders() # <---r = conn.getresponse()print(r.read()) As a shortcut to putrequest / endheaders , you can also use the request method, like this: import http.clientconn = http.client.HTTPSConnection('paypal.com', 443)conn.request('GET', '/') # <---r = conn.getresponse()print(r.read()) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9839179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1190650/']} | jdg_72205 |
stackexchange | llm_judgeable_groundtruth_similarity | 40727801 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my detail view controller (DetailViewController.m), a notification to change an image in a UITableViewCell type is fired. I have two types of UITableViewCells. That said, when acceptButton or declineButton is tapped, I ONLY want the image to change in 1 specific cell (specifically, an image in the tapped cell that opens the detail view - not in all cells of that type). How might I go about doing this? Here's my code so far: DetailViewController.m - (IBAction)acceptButton:(id)sender { if (!checked1) { [self.acceptCheck setImage:[UIImage imageNamed:@"checkedgreen.png"] forState:UIControlStateNormal]; checked1 = YES; [[NSNotificationCenter defaultCenter] postNotificationName:@"ImageChangeNotification" object:nil]; AcceptedViewController *detailViewController = [[AcceptedViewController alloc] initWithNibName:@"AcceptedViewController" bundle:nil]; [self presentViewController:detailViewController animated:YES completion:nil]; } else if (checked1) { [self.acceptCheck setImage:[UIImage imageNamed:@"uncheckedgray.png"] forState:UIControlStateNormal]; checked1 = NO; } }- (IBAction)declineButton:(id)sender { if (!checked2) { [self.declineCheck setImage:[UIImage imageNamed:@"declinered.png"] forState:UIControlStateNormal]; checked2 = YES; [[NSNotificationCenter defaultCenter] postNotificationName:@"Declined" object:nil]; DeniedViewController *detailViewController = [[DeniedViewController alloc] initWithNibName:@"DeniedViewController" bundle:nil]; [self presentViewController:detailViewController animated:YES completion:nil]; } else if (checked2) { [self.declineCheck setImage:[UIImage imageNamed:@"declinegray.png"] forState:UIControlStateNormal]; checked2 = NO; }} TableViewCellB.m - (void)awakeFromNib { [super awakeFromNib]; // Initialization code [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeImage) name:@"ImageChangeNotification" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(declineImage) name:@"Declined" object:nil]; }-(void)changeImage{ [self.displayedBar setImage:[UIImage imageNamed:@"greenbar.png"]]; self.Title.text = @"Accepted!";}-(void)declineImage{ [self.displayedBar setImage:[UIImage imageNamed:@"redbar.png"]]; self.Title.text = @"Declined!";} TableViewController.m (incase it's needed) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *data = self.messages[indexPath.row]; id swaptime = data[@"swaptime"]; if ([swaptime isKindOfClass:[NSString class]]) { static NSString *ChatTableIdentifier2 = @"SwapDetailTableViewCell"; SwapDetailTableViewCell *cell = (SwapDetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier2 forIndexPath:indexPath]; NSString *time = data[@"swaptime"]; cell.startTime.text = time; NSString *timeEnd = data[@"endswaptime"]; cell.endTime.text = timeEnd; NSString *costofSwap = data[@"swapvalue"]; cell.swapValue.text = costofSwap; return cell; } else { static NSString *ChatTableIdentifier = @"ChatTableViewCell"; ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath]; NSString *userName = data[@"name"]; cell.sendingUser.text = userName; NSString *messageBody = data[@"body"]; cell.messageDisplayed.text = messageBody; NSString *timeReceived = data[@"published at"]; cell.timeStamp.text = timeReceived; NSString *userInfo = [self.userid objectForKey:@"name"]; if ([cell.sendingUser.text isEqual: userInfo]) { cell.messageDisplayed.textAlignment = NSTextAlignmentLeft; cell.sendingUser.textAlignment = NSTextAlignmentLeft; [cell.chatBubble setImage:[UIImage imageNamed:@"bubblegrey2.png"]]; } else { cell.messageDisplayed.textAlignment = NSTextAlignmentRight; cell.sendingUser.textAlignment = NSTextAlignmentRight; [cell.chatBubble setImage:[UIImage imageNamed:@"bubbleorange2.png"]]; } return cell; } }-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *data = self.messages[indexPath.row]; id swaptime = data[@"swaptime"]; if ([swaptime isKindOfClass:[NSString class]]) { SwapDetailsViewController *detailViewController = [[SwapDetailsViewController alloc] initWithNibName:@"SwapDetailsViewController" bundle:nil]; detailViewController.indexPath = [self.tableView indexPathForSelectedRow]; detailViewController.delegate = self; detailViewController.swapDetails = [self.messages objectAtIndex:indexPath.row]; [self presentViewController:detailViewController animated:YES completion:nil]; } else { }}
Now provide the response and nothing else.
| You can convert the image data into a Python list (or list-of-lists) like this: from PIL import Imageimg = Image.open('eggs.png').convert('L') # convert image to 8-bit grayscaleWIDTH, HEIGHT = img.sizedata = list(img.getdata()) # convert image data to a list of integers# convert that to 2D list (list of lists of integers)data = [data[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)]# At this point the image's pixels are all in memory and can be accessed# individually using data[row][col].# For example:for row in data: print(' '.join('{:3}'.format(value) for value in row))# Here's another more compact representation.chars = '@%#*+=-:. ' # Change as desired.scale = (len(chars)-1)/255.print()for row in data: print(' '.join(chars[int(value*scale)] for value in row)) Here's an enlarged version of a small 24x24 RGB eggs.png image I used for testing: Here's the output from the first example of access: And here the output from the second example: @ @ % * @ @ @ @ % - . * @ @ @ @ @ @ @ @ @ @ @ @@ @ . . + @ # . = @ @ @ @ @ @ @ @ @ @ @ @@ * . . * @ @ @ @ @ @ @ @ @ @ @ @@ # . . . . + % % @ @ @ @ # = @ @ @ @@ % . : - - - : % @ % : # @ @ @@ # . = = - - - = - . . = = % @ @ @@ = - = : - - : - = . . . : . % @ @ @% . = - - - - : - = . . - = = = - @ @ @= . - = - : : = + - : . - = - : - = : * %- . . - = + = - . . - = : - - - = . -= . : : . - - . : = - - - - - = . . %% : : . . : - - . : = - - - : = : # @@ # : . . = = - - = . = + - - = - . . @ @@ @ # . - = : - : = - . - = = : . . # @@ @ % : = - - - : = - : - . . . - @@ @ * : = : - - - = . . - . . . + @@ # . = - : - = : : : . - % @ @ @* . . . : = = - : . . - . - @ @ @ @ @* . . . : . . . - = . = @ @ @ @ @ @@ : - - . . . . # @ @ @ @ @ @ @ @@ @ = # @ @ * . . . - @ @ @ @ @ @ @ @ @@ @ @ @ @ @ @ . . . # @ @ @ @ @ @ @ @ @ @ @@ @ @ @ @ @ @ - . % @ @ @ @ @ @ @ @ @ @ @ @@ @ @ @ @ @ @ # . : % @ @ @ @ @ @ @ @ @ @ @ @ @ Access to the pixel data should now be faster than using the object img.load() returns (and the values will be integers in the range of 0..255). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40727801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2246306/']} | jdg_72206 |
stackexchange | llm_judgeable_groundtruth_similarity | 36447910 |
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 possible to lint entire folder using tslint? Using eslint it is possible to do eslint ./src to validate whole folder. When i try to do the same for tslint - i am getting an error Error: EISDIR: illegal operation on a directory . In their examples on the site - they show how to validate single file, which is not the case usually. Is that possible to validate my project without extra things like gulp-tslint , just from the command line?
Now provide the response and nothing else.
| You can use a glob to lint multiple files. Normally, if you just pass a glob as is, your shell will expand it and pass the resulting files to TSLint. So for example, in bash 4+ with the globstar option enabled, you could do the following to lint all .ts and .tsx files: tslint src/**/*.ts{,x} You're probably better off though using a command that will work consistently across platforms and shells though. For this, you can pass the glob in quotes. When in quotes, the glob will get passed as is to TSLint which will handle it with node-glob . You could then run the following command to get the same results as above: tslint 'src/**/*.ts?(x)' | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36447910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/714495/']} | jdg_72207 |
stackexchange | llm_judgeable_groundtruth_similarity | 41105795 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way to update a ListBox on a UserForm outside of the Userform_Initialize sub? Why? I am building a blackjack game and using listboxes to tell the user what cards they have/ the dealer has. I was hoping to use a simple sub ( ShowCards ) to add items to the listboxes but I've run into problems: The Play button calls the PlayBlackjack sub which sits in a normal module Option ExplicitDim cards As New CollectionSub ShowGame() UFDisplay.ShowEnd SubSub PlayBlackjack() 'fill the cards collection with 5 shuffled decks PrepareCards Dim i As Integer Dim userHand As New Collection Dim dealerHand As New Collection 'deal cards (removing the dealt cards from the cards collection) For i = 1 To 2 DealCard cards, userHand DealCard cards, dealerHand Next i ShowCards userHand, UFDisplay.UserHandList <-- ERROR HERE (Type mismatch) 'more code to followEnd SubPrivate Sub ShowCards(hand As Collection, list As ListBox) Dim i As Integer For i = 1 To hand.Count list.AddItem hand(i).CardName Next iEnd Sub Let me know if you think you need any more of the code. hand is a collection of card classes where .CardName returns something like 3 of Hearts Everything I read seems to tell me that the userform is static after being initialized so I would need to refresh it in some way after adding the new items. I tried Userform.Repaint with no luck. So if there really is no other way, should I declare userHand and dealerHand as global variables, update them and call Useform_Initialize to take the updated values and show them to the user? Given the nature of the game being that multiple more cards could be dealt for both players it doesn't seem sensible to be re-initializing the userform multiple times each game. All suggestions welcome. If you think I should have done it completely differently I'd still be keen to hear (but not so interested in worksheet solutions) Update #1 For clarity, ShowGame is called by a button on the workshet, then PlayBlackjack is called from the Play button on the Userform (nothing else in the userform code)
Now provide the response and nothing else.
| This question refers to this github tidyverse/ggplot2 solved issue: https://github.com/tidyverse/ggplot2/issues/3252 And it is implemented in ggplot2 (development version): https://github.com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md Themes have gained two new parameters, plot.title.position and plot.caption.position, that can be used to customize how plot title/subtitle and plot caption are positioned relative to the overall plot (@clauswilke, #3252). To follow your example as a reprex: # First install the development version from GitHub:#install.packages("devtools") #If required#devtools::install_github("tidyverse/ggplot2")library(ggplot2)packageVersion("ggplot2")#> [1] '3.2.1.9000'df <- data.frame(type=factor(c("Brooklyn","Manhatten and\n Queens")), value=c(15,30))ggplot(df, aes(x=type, y=value)) + geom_bar(stat='identity') + coord_flip() + labs(title = "This is a nice title", subtitle = "A subtitle", caption = "We even have a caption. A very long one indeed.") + theme(plot.caption = element_text(hjust = 0, face= "italic"), #Default is hjust=1 plot.title.position = "plot", #NEW parameter. Apply for subtitle too. plot.caption.position = "plot") #NEW parameter Created on 2019-09-04 by the reprex package (v0.3.0) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41105795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2859347/']} | jdg_72208 |
stackexchange | llm_judgeable_groundtruth_similarity | 10982167 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
XDocument xDocument = XDocument.Load("...");IEnumerable<XElement> elements = xDocument .Element("lfm") .Element("events") .Elements("event");try{ foreach (XElement elm in elements) { comm.Parameters.AddWithValue("extID", elm.Element("id").Value ?? ""); comm.Parameters.AddWithValue("Title", elm.Element("title").Value ?? ""); comm.Parameters.AddWithValue("HeadlineArtist", elm.Element("artists").Element("headliner").Value ?? ""); but I want the value of the element "image" with the attribute "size=large", I have been looking all night, and this is the closest I have come: comm.Parameters.AddWithValue("LargeImage", elm.Descendants("image") .FirstOrDefault(i => (string)i.Attribute("size") == "large").Value); Sample of the part of XML response: <lfm status="ok"> <events xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" location="Chicago, United States" page="1" perPage="1" totalPages="341" total="341" festivalsonly="0" tag=""> <event xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"> <id>3264699</id> <title>Iron And Wine</title> <artists> <artist>Iron And Wine</artist> <artist>Dr. John</artist> <headliner>Iron And Wine</headliner> </artists> <venue> <id>8915382</id> <name>Ravinia Festival</name> <location> <city>Highland Park</city> <country>United States</country> <street>200 Ravinia Park Rd</street> <postalcode>60035</postalcode> <geo:point> <geo:lat>42.15831</geo:lat> <geo:long>-87.778409</geo:long> </geo:point> </location> <url>http://www.last.fm/venue/8915382+Ravinia+Festival</url> <website>http://www.ravinia.org/</website> <phonenumber>847.266.5100</phonenumber> <image size="small">http://userserve-ak.last.fm/serve/34/63026487.jpg</image> <image size="medium">http://userserve-ak.last.fm/serve/64/63026487.jpg</image> <image size="large">http://userserve-ak.last.fm/serve/126/63026487.jpg</image> <image size="extralarge">http://userserve-ak.last.fm/serve/252/63026487.jpg</image>
Now provide the response and nothing else.
| Try XElement result = elm.Descendants("image") .FirstOrDefault(el => el.Attribute("size") != null && el.Attribute("size").Value == "large");if (result != null) { process result.Value ...} Starting with C#6.0 (VS 2015), you can write: XElement result = elm.Descendants("image") .FirstOrDefault(el => el.Attribute("size")?.Value == "large");if (result != null) { process result.Value ...} A non-obvious alternative (as @RandRandom pointed out) is to cast the Attribute to string : XElement result = elm.Descendants("image") .FirstOrDefault(el => (string)el.Attribute("size") == "large");if (result != null) { process result.Value ...} This works, because because of XAttribute Explicit Conversion (XAttribute to String) . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10982167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813523/']} | jdg_72209 |
stackexchange | llm_judgeable_groundtruth_similarity | 26188946 |
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 figure out where WooCommerce creates it's messages for when there is a success, error or notice in WooCommerce. I want to edit those messages to fit the scenario more neatly and also edit the HTML. Where are these messages located and how do I edit them?
Now provide the response and nothing else.
| Many of them are directly in the plugin files - unfortunately. Some messages are tied to filter hooks that allow you to edit them without messing with plugin files but that's not always the case. The message you wanted to change was "Product Name was successfully added to your cart". This one is set in the function wc_add_to_cart_message in wc-cart-functions.php and this function allows you to change it using a filter: wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ) ); So in your functions.php file you could add something like: add_filter('wc_add_to_cart_message', 'handler_function_name', 10, 2);function handler_function_name($message, $product_id) { return "Thank you for adding product" . $product_id;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26188946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/972101/']} | jdg_72210 |
stackexchange | llm_judgeable_groundtruth_similarity | 1764472 |
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:
Where would you start if you were told to plot: $$||x-1|-1|$$ I looked at just $f(x) = |x-1|$ and noticed that the two equations are: $\pm (x-1)$ for $x \geq 1$ and $x < 1$. Extrapolating then: $\pm(\pm(x-1)-1)$, but how would I know which regions which equation would work for?
Now provide the response and nothing else.
| If you know the graph of $f(x)$, then the graph of $|f(x)|$ is just the result of “folding” $f$ about to the $x$ axis. Hence, plotting $f(x) = \bigl\lvert \lvert x - 1 \rvert - 1 \bigr\rvert$ goes like this. Plot $y = x - 1$ and fold the portion of it that lies below the $x$ axis over the $x$ axis. The result is the graph of $\lvert x - 1 \rvert$. Then shift this graph downward by $1$ and do the same folding again. Then you will get $\bigl\lvert \lvert x - 1 \rvert - 1 \bigr\rvert$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1764472', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/254304/']} | jdg_72211 |
stackexchange | llm_judgeable_groundtruth_similarity | 10998521 |
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 submitted a pull request with this code: my_sum = sum([x for x in range(10)]) One of the reviewers suggested this instead: my_sum = sum(x for x in range(10)) (the difference is just that the square braces are missing). I was surprised that the second form seems to be identical. But when I tried to use it in other contexts where the first one works, it fails: y = x for x in range(10) ^ SyntaxError !!! Are the two forms identical? Is there any important reason for why the square braces aren't necessary in the function? Or is this just something that I have to know?
Now provide the response and nothing else.
| This is a generator expression. To get it to work in the standalone case, use braces: y = (x for x in range(10)) and y becomes a generator. You can iterate over generators, so it works where an iterable is expected, such as the sum function. Usage examples and pitfalls: >>> y = (x for x in range(10))>>> y<generator object <genexpr> at 0x0000000001E15A20>>>> sum(y)45 Be careful when keeping generators around, you can only go through them once. So after the above, if you try to use sum again, this will happen: >>> sum(y)0 So if you pass a generator where actually a list or a set or something similar is expected, you have to be careful. If the function or class stores the argument and tries to iterate over it multiple times, you will run into problems. For example consider this: def foo(numbers): s = sum(numbers) p = reduce(lambda x,y: x*y, numbers, 1) print "The sum is:", s, "and the product:", p it will fail if you hand it a generator: >>> foo(x for x in range(1, 10))The sum is: 45 and the product: 1 You can easily get a list from the values a generator produces: >>> y = (x for x in range(10))>>> list(y)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] You can use this to fix the previous example: >>> foo(list(x for x in range(1, 10)))The sum is: 45 and the product: 362880 However keep in mind that if you build a list from a generator, you will need to store every value. This might use a lot more memory in situations where you have lots of items. Why use a generator in your situation? The much lower memory consumption is the reason why sum(generator expression) is better than sum(list) : The generator version only has to store a single value, while the list-variant has to store N values. Therefore you should always use a generator where you don't risk side-effects. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10998521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/894284/']} | jdg_72212 |
stackexchange | llm_judgeable_groundtruth_similarity | 11070826 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've found a simple solution somewhere on the internet to an identity class without built-in C++ RTTI . template <typename T>class Identity {public: static int64_t id() { static int64_t dummy; return reinterpret_cast<int64_t>(&dummy); }}; When we need some class ID, we just use: Identity<OurClass>::id(); I'm wondering, are there any collisions? Can it return the same ID for the different classes, or the different ID for the same classes? I have tried this code with g++ with different optimization values, everything seems ok.
Now provide the response and nothing else.
| First off: there is such an integral type that is made specifically to contain pointers: intptr_t and in C++11 uintptr_t Second, even though in practice on gcc they are equal, the size of a pointer to an object and the size of a function pointer (or pointer to member) might well be different. Therefore it would be better using a specific object rather than the method itself (for Standard conformance). Third, it only gives you identity, while RTTI is much richer, as it knows about all the subclasses a given object can be cast to, and even allows cross-casts or casts across virtual inheritance. Still, the corrected version can be useful I guess: struct Foo { static intptr_t Id() { static boost::none_t const Dummy = {}; return reinterpret_cast<intptr_t>(&Dummy); }}; And in hierarchies, having a virtual function returning that ID. For completeness, I'll mention that Clang and LLVM have their own way of dealing with object identification without RTTI. You may want to read about their way of implementing isa , cast and dyn_cast here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11070826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1284025/']} | jdg_72213 |
stackexchange | llm_judgeable_groundtruth_similarity | 5735257 |
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 recently seen code like this: val maybeInt = catching(classOf[NFE]) opt arg.toInt What is this opt ? An Option? Why isn't it using getOrElse to extract the value? In the above code, will maybeInt be None if a NumberFormatException gets thrown?
Now provide the response and nothing else.
| catching looks like it's some sort of method call, doesn't it? It is, but it actually returns an instance of a class Catch ; it doesn't directly take an argument. This class has two methods that are particularly useful for dealing with exceptions (and several more for catching multiple exceptions). The first is def opt [U >: T] (body: ⇒ U) : Option[U] which is being used here--you give it something that may throw an exception, and it will return Some(result) if everything went okay, and None if the targeted exception was caught: scala> type NFE = NumberFormatExceptiondefined type alias NFEscala> import scala.util.control.Exception._import scala.util.control.Exception._scala> catching(classOf[NFE]).opt( "fish".toInt )res0: Option[Int] = Nonescala> catching(classOf[NFE]).opt( "42".toInt ) res1: Option[Int] = Some(42) You can then deal with this with map or filter or getOrElse or whatever else you use to deal with options. The other useful method is either , which returns an instance of Left(exception) if an exception was thrown, and a Right(result) if it was not: scala> catching(classOf[NFE]).either( "fish".toInt )res2: Either[Throwable,Int] = Left(java.lang.NumberFormatException: For input string: "fish")scala> catching(classOf[NFE]).either( "42".toInt )res3: Either[Throwable,Int] = Right(42) You can then use fold or map to an option or whatever else you like doing with eithers. Note that you can define a single catcher and use it multiple times (so you don't need to create the catcher object every time you, for example, parse an integer): scala> val catcher = catching(classOf[NFE])catcher: util.control.Exception.Catch[Nothing] = Catch(java.lang.NumberFormatException)scala> catcher.opt("42".toInt)res4: Option[Int] = Some(42)scala> catcher.opt("fish".toInt)res5: Option[Int] = None Edit: as Daniel points out in the comments, this still creates a temporary Catch[Option] ; given the method signatures, there isn't an easy way to just have it trap exceptions and generate options without creating any extra objects. This reminds me why I write my own methods to do exactly that: def optNFE[T](t: => T) = try { Some(t) } catch {case nfe: NFE => None}optNFE( "fish".toInt ) // gives NoneoptNFE( "42".toInt ) // gives Some(42) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5735257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31610/']} | jdg_72214 |
stackexchange | llm_judgeable_groundtruth_similarity | 256870 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I just started reading "The calculi of lambda conversion" by Church. Church defines functions like: id x = x, and says the domain and range are understood to be as permissible as possible. Permitting even itself, id id = id In my experience, I've always been told to specify a domain and range with the functions I've defined. And they are usually relatively limited, in contrast to id. This is the first time I've seen functions with a domain and range this large. Are there uses for functions with wide domains and ranges in mathematical contexts other then logic or lambda calculus?
Now provide the response and nothing else.
| The question you are trying to ask is "What is a denotational semantics for the untyped lambda calculus?" This is a difficult problem because, as Bjorn Kjos-Hanssen said in his answer, if you try and make variables range over elements of some set $D$ you find that you must have $D \times D \cong D$ and $D^D \cong D$. Unfortunately this implies that $D$ is the singleton set and all lambda terms must represent the same function. Dana Scott solved the problem of giving a denotational semantics to the untyped calculus with the invention of domain theory . | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/256870', 'https://mathoverflow.net', 'https://mathoverflow.net/users/47532/']} | jdg_72215 |
stackexchange | llm_judgeable_groundtruth_similarity | 1288336 |
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,\mathcal F)$ be a measure space, then for each $x \in X$ does there always exists a smallest measurable set containing $x$? If $X$ is countable or $\mathcal F$ finite, then this is true, as then the set$$ \bigcap_{\substack{E \in \mathcal F \\ x \in E}} E$$could be rewritten as an at most countable intersection (i.e. selecting just a countable subset of the measurable sets containing $x$). But what in the general case? If I look for example at the Borel-$\sigma$-algebra over $\mathbb R$, then each singleton set $\{x\}$ is measurable, and trivially the smallest set containing $x$, so there comes no example to my mind where such a set is not uniquely specified?
Now provide the response and nothing else.
| The answer is no, and here is one example: Let $X=\mathbb{R}$, and define a set $E \subseteq \mathbb{R}$ to be measurable if either $0 \notin E$ and $E$ is countable, or $0 \in E$ and the complement $E^c$ is countable. Then it is easy to see that there is no smallest measurable set containing $x=0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1288336', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33817/']} | jdg_72216 |
stackexchange | llm_judgeable_groundtruth_similarity | 152580 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I check if an object is of a given type, or if it inherits from a given type? How do I check if the object o is of type str ? Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)? , How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.
Now provide the response and nothing else.
| Use isinstance to check if o is an instance of str or any subclass of str : if isinstance(o, str): To check if the type of o is exactly str , excluding subclasses of str : if type(o) is str: Another alternative to the above: if issubclass(type(o), str): See Built-in Functions in the Python Library Reference for relevant information. Checking for strings in Python 2 For Python 2, this is a better way to check if o is a string: if isinstance(o, basestring): because this will also catch Unicode strings. unicode is not a subclass of str ; whereas, both str and unicode are subclasses of basestring . In Python 3, basestring no longer exists since there's a strict separation of strings ( str ) and binary data ( bytes ). Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode) : if isinstance(o, (str, unicode)): | {} | {'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/152580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14102/']} | jdg_72217 |
stackexchange | llm_judgeable_groundtruth_similarity | 51771206 |
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 been using Random (java.util.Random) to shuffle a deck of 52 cards. There are 52! (8.0658175e+67) possibilities. Yet, I've found out that the seed for java.util.Random is a long , which is much smaller at 2^64 (1.8446744e+19). From here, I'm suspicious whether java.util.Random is really that random ; is it actually capable of generating all 52! possibilities? If not, how can I reliably generate a better random sequence that can produce all 52! possibilities?
Now provide the response and nothing else.
| Selecting a random permutation requires simultaneously more and less randomness than what your question implies. Let me explain. The bad news: need more randomness. The fundamental flaw in your approach is that it's trying to choose between ~2 226 possibilities using 64 bits of entropy (the random seed). To fairly choose between ~2 226 possibilities you're going to have to find a way to generate 226 bits of entropy instead of 64. There are several ways to generate random bits: dedicated hardware , CPU instructions , OS interfaces , online services . There is already an implicit assumption in your question that you can somehow generate 64 bits, so just do whatever you were going to do, only four times, and donate the excess bits to charity. :) The good news: need less randomness. Once you have those 226 random bits, the rest can be done deterministically and so the properties of java.util.Random can be made irrelevant . Here is how. Let's say we generate all 52! permutations (bear with me) and sort them lexicographically. To choose one of the permutations all we need is a single random integer between 0 and 52!-1 . That integer is our 226 bits of entropy. We'll use it as an index into our sorted list of permutations. If the random index is uniformly distributed, not only are you guaranteed that all permutations can be chosen, they will be chosen equiprobably (which is a stronger guarantee than what the question is asking). Now, you don't actually need to generate all those permutations. You can produce one directly, given its randomly chosen position in our hypothetical sorted list. This can be done in O(n 2 ) time using the Lehmer [1] code (also see numbering permutations and factoriadic number system ). The n here is the size of your deck, i.e. 52. There is a C implementation in this StackOverflow answer . There are several integer variables there that would overflow for n=52, but luckily in Java you can use java.math.BigInteger . The rest of the computations can be transcribed almost as-is: public static int[] shuffle(int n, BigInteger random_index) { int[] perm = new int[n]; BigInteger[] fact = new BigInteger[n]; fact[0] = BigInteger.ONE; for (int k = 1; k < n; ++k) { fact[k] = fact[k - 1].multiply(BigInteger.valueOf(k)); } // compute factorial code for (int k = 0; k < n; ++k) { BigInteger[] divmod = random_index.divideAndRemainder(fact[n - 1 - k]); perm[k] = divmod[0].intValue(); random_index = divmod[1]; } // readjust values to obtain the permutation // start from the end and check if preceding values are lower for (int k = n - 1; k > 0; --k) { for (int j = k - 1; j >= 0; --j) { if (perm[j] <= perm[k]) { perm[k]++; } } } return perm;}public static void main (String[] args) { System.out.printf("%s\n", Arrays.toString( shuffle(52, new BigInteger( "7890123456789012345678901234567890123456789012345678901234567890"))));} [1] Not to be confused with Lehrer . :) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51771206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7138492/']} | jdg_72218 |
stackexchange | llm_judgeable_groundtruth_similarity | 169960 |
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'm developing an app that will be used to open and close valves in an industrial environment, and was thinking of something simple like this:- public static void ValveController{ public static void OpenValve(string valveName) { // Implementation to open the valve } public static void CloseValve(string valveName) { // Implementation to close the valve }} (The implementation would write a few bytes of data to the serial port to control the valve - an "address" derived from the valve name, and either a "1" or "0" to open or close the valve). Another dev asked whether we should instead create a separate class for each physical valve, of which there are dozens. I agree it would be nicer to write code like PlasmaValve.Open() rather than ValveController.OpenValve("plasma") , but is this overkill? Also, I was wondering how best to tackle the design with a couple of hypothetical future requirements in mind:- We are asked to support a new type of valve requiring different values to open and close it (not 0 and 1). We are asked to support a valve that can be set to any position from 0-100, rather than simply "open" or "closed". Normally I would use inheritance for this kind of thing, but I've recently started to get my head around "composition over inheritance" and wonder if there is a slicker solution to be had using composition?
Now provide the response and nothing else.
| If each instance of the valve object would run the same code as this ValveController, then it seems like multiple instances of a single class would be the right way to go. In this case just configure which valve it controls(and how) in the valve object's constructor. However if each valve control needs different code to run, and the current ValveController is running a giant switch statement that does different things depending on the type of valve, then you have reimplemented polymorphism poorly. In that case rewrite it to multiple classes with a common base(if that makes sense) and let the single responsibility principle be your design guide. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/169960', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/68815/']} | jdg_72219 |
stackexchange | llm_judgeable_groundtruth_similarity | 899138 |
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 Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ? I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ? The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.
Now provide the response and nothing else.
| Basically, you create a Function interface: public interface Func<In, Out> { public Out apply(In in);} and then pass in an anonymous subclass to your method. Your method could either apply the function to each element in-place: public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) { ListIterator<T> itr = list.listIterator(); while (itr.hasNext()) { T output = f.apply(itr.next()); itr.set(output); }}// ...List<String> myList = ...;applyToListInPlace(myList, new Func<String, String>() { public String apply(String in) { return in.toLowerCase(); }}); or create a new List (basically creating a mapping from the input list to the output list): public static <In, Out> List<Out> map(List<In> in, Func<In, Out> f) { List<Out> out = new ArrayList<Out>(in.size()); for (In inObj : in) { out.add(f.apply(inObj)); } return out;}// ...List<String> myList = ...;List<String> lowerCased = map(myList, new Func<String, String>() { public String apply(String in) { return in.toLowerCase(); }}); Which one is preferable depends on your use case. If your list is extremely large, the in-place solution may be the only viable one; if you wish to apply many different functions to the same original list to make many derivative lists, you will want the map version. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/899138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78351/']} | jdg_72220 |
stackexchange | llm_judgeable_groundtruth_similarity | 13671053 |
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 coded a very simple "Word Count" program that reads a file and counts each word's occurrence in the file. Here is a part of the code: class Alaki{ private static List<string> input = new List<string>(); private static void exec(int threadcount) { ParallelOptions options = new ParallelOptions(); options.MaxDegreeOfParallelism = threadcount; Parallel.ForEach(Partitioner.Create(0, input.Count),options, (range) => { var dic = new Dictionary<string, List<int>>(); for (int i = range.Item1; i < range.Item2; i++) { //make some delay! //for (int x = 0; x < 400000; x++) ; var tokens = input[i].Split(); foreach (var token in tokens) { if (!dic.ContainsKey(token)) dic[token] = new List<int>(); dic[token].Add(1); } } }); } public static void Main(String[] args) { StreamReader reader=new StreamReader((@"c:\txt-set\agg.txt")); while(true) { var line=reader.ReadLine(); if(line==null) break; input.Add(line); } DateTime t0 = DateTime.Now; exec(Environment.ProcessorCount); Console.WriteLine("Parallel: " + (DateTime.Now - t0)); t0 = DateTime.Now; exec(1); Console.WriteLine("Serial: " + (DateTime.Now - t0)); }} It is simple and straight forward. I use a dictionary to count each word's occurrence. The style is roughly based on the MapReduce programming model. As you can see, each task is using its own private dictionary. So, there is NO shared variables; just a bunch of tasks that count words by themselves. Here is the output when the code is run on a quad-core i7 CPU: Parallel: 00:00:01.6220927 Serial: 00:00:02.0471171 The speedup is about 1.25 which means a tragedy! But when I add some delay when processing each line, I can reach speedup values about 4. In the original parallel execution with no delay, CPU's utilization hardly reaches to 30% and therefore the speedup is not promising. But, when we add some delay, CPU's utilization reaches to 97%. Firstly, I thought the cause is the IO-bound nature of the program (but I think inserting into a dictionary is to some extent CPU intensive) and it seems logical because all of the threads are reading data from a shared memory bus. However, The surprising point is when I run 4 instances of serial programs (with no delays) simultaneously, CPU's utilization reaches to about raises and all of the four instances finish in about 2.3 seconds! This means that when the code is being run in a multiprocessing configuration, it reaches to a speedup value about 3.5 but when it is being run in multithreading config, the speedup is about 1.25. What is your idea?Is there anything wrong about my code? Because I think there is no shared data at all and I think the code shall not experience any contentions.Is there a flaw in .NET's run-time? Thanks in advance.
Now provide the response and nothing else.
| Parallel.For doesn't divide the input into n pieces (where n is the MaxDegreeOfParallelism ); instead it creates many small batches and makes sure that at most n are being processed concurrently. (This is so that if one batch takes a very long time to process, Parallel.For can still be running work on other threads. See Parallelism in .NET - Part 5, Partioning of Work for more details.) Due to this design, your code is creating and throwing away dozens of Dictionary objects, hundreds of List objects, and thousands of String objects. This is putting enormous pressure on the garbage collector. Running PerfMonitor on my computer reports that 43% of the total run time is spent in GC. If you rewrite your code to use fewer temporary objects, you should see the desired 4x speedup. Some excerpts from the PerfMonitor report follow: Over 10% of the total CPU time was spent in the garbage collector.Most well tuned applications are in the 0-10% range. This is typicallycaused by an allocation pattern that allows objects to live just longenough to require an expensive Gen 2 collection. This program had a peak GC heap allocation rate of over 10 MB/sec.This is quite high. It is not uncommon that this is simply aperformance bug. Edit: As per your comment, I will attempt to explain the timings you reported. On my computer, with PerfMonitor, I measured between 43% and 52% of time spent in GC. For simplicity, let's assume that 50% of the CPU time is work, and 50% is GC. Thus, if we make the work 4× faster (through multi-threading) but keep the amount of GC the same (this will happen because the number of batches being processed happened to be the same in the parallel and serial configurations), the best improvement we could get is 62.5% of the original time, or 1.6×. However, we only see a 1.25× speedup because GC isn't multithreaded by default (in workstation GC). As per Fundamentals of Garbage Collection , all managed threads are paused during a Gen 0 or Gen 1 collection. (Concurrent and background GC, in .NET 4 and .NET 4.5, can collect Gen 2 on a background thread.) Your program experiences only a 1.25× speedup (and you see 30% CPU usage overall) because the threads spend most of their time being paused for GC (because the memory allocation pattern of this test program is very poor). If you enable server GC , it will perform garbage collection on multiple threads. If I do this, the program runs 2× faster (with almost 100% CPU usage). When you run four instances of the program simultaneously, each has its own managed heap, and the garbage collection for the four processes can execute in parallel. This is why you see 100% CPU usage (each process is using 100% of one CPU). The slightly longer overall time (2.3s for all vs 2.05s for one) is possibly due to inaccuracies in measurement, contention for the disk, time taken to load the file, having to initialise the threadpool, overhead of context switching, or some other environment factor. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13671053', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/860027/']} | jdg_72221 |
stackexchange | llm_judgeable_groundtruth_similarity | 56804 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know the Galois group is $S_3$. And obviously we can swap the imaginary cube roots. I just can't figure out a convincing, "constructive" argument to show that I can swap the "real" cube root with one of the imaginary cube roots. I know that if you have a 3-cycle and a 2-cycle operating on three elements, you get $S_3$. I have a general idea that based on the order of the group there's supposed to be at least a 3-cycle. But this doesn't feel very "constructive" to me. I wonder if I've made myself understood in terms of what kind of argument I'd like to see?
Now provide the response and nothing else.
| A brute-force way to see it is easy enough. The roots of $X^3 - 2$ are $\sqrt[3]{2},\; \omega\sqrt[3]{2},\; \omega^2\sqrt[3]{2}$, so the splitting field of your polynomial is $K = \mathbb{Q}(\sqrt[3]{2},\omega)$. You are asking why it's legitimate to send $\sqrt[3]{2}$ to $\omega\sqrt[3]{2}$. Well, let's try it. Let $\sigma: K \to K$ be a map that sends $\sqrt[3]{2}$ to $\omega\sqrt[3]{2}$. How are we going to extend this to an element of the Galois group? We need $\sigma$ to be an automorphism that fixes $\mathbb{Q}$. Our field $K$ is a $\mathbb{Q}$-vector space generated by six basis elements: $1,\; \sqrt[3]{2},\; \sqrt[3]{4},\; \omega,\; \omega\sqrt[3]{2},\; \omega\sqrt[3]{4}$. If we can define how $\sigma$ acts on those, we can extend linearly to the whole space: that is, we can extend $\sigma$ such that $\sigma(a+b) = \sigma(a) + \sigma(b)$ for all $a$ and $b$. We also know that, if we define $\sigma$ sensibly, we should get that $\sigma(ab) = \sigma(a) \sigma(b)$. By "sensibly" here, I mean that $\sigma$ should send each element of $K$ to one of its conjugates - that is, it should send $x$ to any $y$ that satisfies the same minimal polynomial as $x$. We also know that it's enough to make sure $\sigma$ is multiplicative on the basis, and in fact we only need to define it on $\sqrt[3]{2}$ and $\omega$, since the rest will then follow automatically by multiplicativity. So we have a few options from what we've deduced so far. $\sigma$ can send $\sqrt[3]{2}$ to any of $\sqrt[3]{2},\; \omega\sqrt[3]{2},\; \omega^2\sqrt[3]{2}$, and it can send $\omega$ to either of $\omega$ and $\omega^2$. So let's say $\sigma(\sqrt[3]{2}) = \omega\sqrt[3]{2}$ (as we wanted) and $\sigma(\omega) = \omega$ (no good reason for this choice, but we had to make one). Where do all the other basis elements go? Can you convince yourself now that $\sigma$ is an element of the Galois group? (What would have happened if we'd chosen $\sigma(\omega) = \omega^2$?) | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/56804', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10838/']} | jdg_72222 |
stackexchange | llm_judgeable_groundtruth_similarity | 18947892 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've run into the following code in the es-discuss mailing list: Array.apply(null, { length: 5 }).map(Number.call, Number); This produces [0, 1, 2, 3, 4] Why is this the result of the code? What's happening here?
Now provide the response and nothing else.
| Understanding this "hack" requires understanding several things: Why we don't just do Array(5).map(...) How Function.prototype.apply handles arguments How Array handles multiple arguments How the Number function handles arguments What Function.prototype.call does They're rather advanced topics in javascript, so this will be more-than-rather long. We'll start from the top. Buckle up! 1. Why not just Array(5).map ? What's an array, really? A regular object, containing integer keys, which map to values. It has other special features, for instance the magical length variable, but at it's core, it's a regular key => value map, just like any other object. Let's play with arrays a little, shall we? var arr = ['a', 'b', 'c'];arr.hasOwnProperty(0); //truearr[0]; //'a'Object.keys(arr); //['0', '1', '2']arr.length; //3, implies arr[3] === undefined//we expand the array by 1 itemarr.length = 4;arr[3]; //undefinedarr.hasOwnProperty(3); //falseObject.keys(arr); //['0', '1', '2'] We get to the inherent difference between the number of items in the array, arr.length , and the number of key=>value mappings the array has, which can be different than arr.length . Expanding the array via arr.length does not create any new key=>value mappings, so it's not that the array has undefined values, it does not have these keys . And what happens when you try to access a non-existent property? You get undefined . Now we can lift our heads a little, and see why functions like arr.map don't walk over these properties. If arr[3] was merely undefined, and the key existed, all these array functions would just go over it like any other value: //just to remind youarr; //['a', 'b', 'c', undefined];arr.length; //4arr[4] = 'e';arr; //['a', 'b', 'c', undefined, 'e'];arr.length; //5Object.keys(arr); //['0', '1', '2', '4']arr.map(function (item) { return item.toUpperCase() });//["A", "B", "C", undefined, "E"] I intentionally used a method call to further prove the point that the key itself was never there: Calling undefined.toUpperCase would have raised an error, but it didn't. To prove that : arr[5] = undefined;arr; //["a", "b", "c", undefined, "e", undefined]arr.hasOwnProperty(5); //truearr.map(function (item) { return item.toUpperCase() });//TypeError: Cannot call method 'toUpperCase' of undefined And now we get to my point: How Array(N) does things. Section 15.4.2.2 describes the process. There's a bunch of mumbo jumbo we don't care about, but if you manage to read between the lines (or you can just trust me on this one, but don't), it basically boils down to this: function Array(len) { var ret = []; ret.length = len; return ret;} (operates under the assumption (which is checked in the actual spec) that len is a valid uint32, and not just any number of value) So now you can see why doing Array(5).map(...) wouldn't work - we don't define len items on the array, we don't create the key => value mappings, we simply alter the length property. Now that we have that out of the way, let's look at the second magical thing: 2. How Function.prototype.apply works What apply does is basically take an array, and unroll it as a function call's arguments. That means that the following are pretty much the same: function foo (a, b, c) { return a + b + c;}foo(0, 1, 2); //3foo.apply(null, [0, 1, 2]); //3 Now, we can ease the process of seeing how apply works by simply logging the arguments special variable: function log () { console.log(arguments);}log.apply(null, ['mary', 'had', 'a', 'little', 'lamb']); //["mary", "had", "a", "little", "lamb"]//arguments is a pseudo-array itself, so we can use it as well(function () { log.apply(null, arguments);})('mary', 'had', 'a', 'little', 'lamb'); //["mary", "had", "a", "little", "lamb"]//a NodeList, like the one returned from DOM methods, is also a pseudo-arraylog.apply(null, document.getElementsByTagName('script')); //[script, script, script, script, script, script, script, script, script, script, script, script, script, script, script, script, script, script, script, script]//carefully look at the following twolog.apply(null, Array(5));//[undefined, undefined, undefined, undefined, undefined]//note that the above are not undefined keys - but the value undefined itself!log.apply(null, {length : 5});//[undefined, undefined, undefined, undefined, undefined] It's easy to prove my claim in the second-to-last example: function ahaExclamationMark () { console.log(arguments.length); console.log(arguments.hasOwnProperty(0));}ahaExclamationMark.apply(null, Array(2)); //2, true (yes, pun intended). The key => value mapping may not have existed in the array we passed over to apply , but it certainly exists in the arguments variable. It's the same reason the last example works: The keys do not exist on the object we pass, but they do exist in arguments . Why is that? Let's look at Section 15.3.4.3 , where Function.prototype.apply is defined. Mostly things we don't care about, but here's the interesting portion: Let len be the result of calling the [[Get]] internal method of argArray with argument "length". Which basically means: argArray.length . The spec then proceeds to do a simple for loop over length items, making a list of corresponding values ( list is some internal voodoo, but it's basically an array). In terms of very, very loose code: Function.prototype.apply = function (thisArg, argArray) { var len = argArray.length, argList = []; for (var i = 0; i < len; i += 1) { argList[i] = argArray[i]; } //yeah... superMagicalFunctionInvocation(this, thisArg, argList);}; So all we need to mimic an argArray in this case is an object with a length property. And now we can see why the values are undefined, but the keys aren't, on arguments : We create the key=>value mappings. Phew, so this might not have been shorter than the previous part. But there'll be cake when we finish, so be patient! However, after the following section (which'll be short, I promise) we can begin dissecting the expression. In case you forgot, the question was how does the following work: Array.apply(null, { length: 5 }).map(Number.call, Number); 3. How Array handles multiple arguments So! We saw what happens when you pass a length argument to Array , but in the expression, we pass several things as arguments (an array of 5 undefined , to be exact). Section 15.4.2.1 tells us what to do. The last paragraph is all that matters to us, and it's worded really oddly, but it kind of boils down to: function Array () { var ret = []; ret.length = arguments.length; for (var i = 0; i < arguments.length; i += 1) { ret[i] = arguments[i]; } return ret;}Array(0, 1, 2); //[0, 1, 2]Array.apply(null, [0, 1, 2]); //[0, 1, 2]Array.apply(null, Array(2)); //[undefined, undefined]Array.apply(null, {length:2}); //[undefined, undefined] Tada! We get an array of several undefined values, and we return an array of these undefined values. The first part of the expression Finally, we can decipher the following: Array.apply(null, { length: 5 }) We saw that it returns an array containing 5 undefined values, with keys all in existence. Now, to the second part of the expression: [undefined, undefined, undefined, undefined, undefined].map(Number.call, Number) This will be the easier, non-convoluted part, as it doesn't so much rely on obscure hacks. 4. How Number treats input Doing Number(something) ( section 15.7.1 ) converts something to a number, and that is all. How it does that is a bit convoluted, especially in the cases of strings, but the operation is defined in section 9.3 in case you're interested. 5. Games of Function.prototype.call call is apply 's brother, defined in section 15.3.4.4 . Instead of taking an array of arguments, it just takes the arguments it received, and passes them forward. Things get interesting when you chain more than one call together, crank the weird up to 11: function log () { console.log(this, arguments);}log.call.call(log, {a:4}, {a:5});//{a:4}, [{a:5}]//^---^ ^-----^// this arguments This is quite wtf worthy until you grasp what's going on. log.call is just a function, equivalent to any other function's call method, and as such, has a call method on itself as well: log.call === log.call.call; //truelog.call === Function.call; //true And what does call do? It accepts a thisArg and a bunch of arguments, and calls its parent function. We can define it via apply (again, very loose code, won't work): Function.prototype.call = function (thisArg) { var args = arguments.slice(1); //I wish that'd work return this.apply(thisArg, args);}; Let's track how this goes down: log.call.call(log, {a:4}, {a:5}); this = log.call thisArg = log args = [{a:4}, {a:5}] log.call.apply(log, [{a:4}, {a:5}]) log.call({a:4}, {a:5}) this = log thisArg = {a:4} args = [{a:5}] log.apply({a:4}, [{a:5}]) The later part, or the .map of it all It's not over yet. Let's see what happens when you supply a function to most array methods: function log () { console.log(this, arguments);}var arr = ['a', 'b', 'c'];arr.forEach(log);//window, ['a', 0, ['a', 'b', 'c']]//window, ['b', 1, ['a', 'b', 'c']]//window, ['c', 2, ['a', 'b', 'c']]//^----^ ^-----------------------^// this arguments If we don't provide a this argument ourselves, it defaults to window . Take note of the order in which the arguments are provided to our callback, and let's weird it up all the way to 11 again: arr.forEach(log.call, log);//'a', [0, ['a', 'b', 'c']]//'b', [1, ['a', 'b', 'c']]//'b', [2, ['a', 'b', 'c']]// ^ ^ Whoa whoa whoa...let's back up a bit. What's going on here? We can see in section 15.4.4.18 , where forEach is defined, the following pretty much happens: var callback = log.call, thisArg = log;for (var i = 0; i < arr.length; i += 1) { callback.call(thisArg, arr[i], i, arr);} So, we get this: log.call.call(log, arr[i], i, arr);//After one `.call`, it cascades to:log.call(arr[i], i, arr);//Further cascading to:log(i, arr); Now we can see how .map(Number.call, Number) works: Number.call.call(Number, arr[i], i, arr);Number.call(arr[i], i, arr);Number(i, arr); Which returns the transformation of i , the current index, to a number. In conclusion, The expression Array.apply(null, { length: 5 }).map(Number.call, Number); Works in two parts: var arr = Array.apply(null, { length: 5 }); //1arr.map(Number.call, Number); //2 The first part creates an array of 5 undefined items. The second goes over that array and takes its indices, resulting in an array of element indices: [0, 1, 2, 3, 4] | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18947892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348195/']} | jdg_72223 |
stackexchange | llm_judgeable_groundtruth_similarity | 3804080 |
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:
My reasoning:From the assumption it follows that for all numbers in form $n = 2^m - 5k$ , where $n,m,k$ are some natural numbers $T(n)$ is true. When $n=5$ then $(5 = 2^m - 5k) \equiv 5(k+1) = 2^m$ , therefore $n$ can't equal $5$ . Hence we can't conclude (from given assumptions) that $T(n)$ is true for all $n$ in natural numbers. Neither we can say that $T(n)$ is not true for all natural numbers. So my answer would be that we can't tell. Am I wrong?
Now provide the response and nothing else.
| For the edited version of the question: no, you can't conclude that $T(n)$ is true for every $n$ . Perhaps the easiest way to show this is to notice that if $T(n)$ is the proposition " $n$ is not a multiple of $5$ " then it satisfies all three requirements, but is not true for all natural numbers. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3804080', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/678235/']} | jdg_72224 |
stackexchange | llm_judgeable_groundtruth_similarity | 2924517 |
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'm aware of counter examples to Playfair's axiom-"Given a line L and a point P not on that line, there is one and only one line passing through point P which is parallel to L." These are violated in spherical geometry where all lines intersect so there are no parallel lines and in hyperbolic geometry where there are multiple parallel lines through a point. I'm unaware of any exceptions WITHIN the plane. Euclid avoids using the parallel postulate for almost the first 30 propositions in The Elements. Others have made attempts to prove the parallel postulate only for it not to be accepted despite the counterexamples of spherical and hyperbolic geometry not having yet been discovered. What was the basis of that objection without the new geometries? Apparently proofs were rejected despite constructive examples we have today. How were they able to do that? More specifically, without using what we know from spherical geometry and hyperbolic geometry, where does the following "theorem" fail? SKIP TO THE PROOF THAT TWO LINES PERPENDICULAR TO A THIRD ARE PARALLEL TO EACH OTHER TO GET TO THE HEART OF THE PROOF Given a line L and a point C not on the line, construct a second line M through C and perpendicular to L. Also Construct a line through C perpendicular to M called N. 1) Start with line L and point C not on L.2) Select an arbitrary point on L, Q1. Construct a circle through C centered at Q1. 3) Select another, different, arbitrary point on L,Q2. Construct a circle through C centered at Q2. 4) Draw a line, M, through C and the other intersection of these two circles, R. 5) Pick a point, P, on the same side of L as C and on the opposite of M as C. 6) Construct a circle centered at P passing through C. Call the other place this circle intersects M, M1. 7) Construct a line through M1 and P, calling the farthest point of intersection on CircleP from M1, P1.8) Draw a line,N, through P1 and C. 9) Claim, N is parallel to L and perpendicular to M. Proof??: Proof N is perpendicular to M and M is perpendicular to L. The segment connecting Q1 and Q2 and the upper radii containing C of either circle creates a triangle congruent to the triangle fromed by the same segment, Q1Q2, and the lower radii, containing R, of either circle. These triangles being congruent, it follows that L is an angle bisector of angle CQ1R. By SAS, it follows that L is the bisector of segment RC. It also follows that the angle made by L and M is a right angle because the angles are congruent and sum to a straight line. So M is perpendicular to L. The line M1 through P to P1 is a diameter of the circle centered at P. By Thales' Theorem, the line from P1 to C , called N, is perpendicular to M. Proof?? two lines perpendicular to a third are parallel to each other Given lines L,M, and N with M intersecting L and N at right angles, intersecting N at point C with point C not on L: Construct a circle centered at point C to an arbitrary point,X1, on L. Draw a line through C and X1. Determine the midpoint of line CX1. Draw a line from the intersection of L and M through that midpoint. Construct a circle centered at the midpoint and passing through the intersection of M and L. This circle creates a new intersection R, as far from the midpoint as the intersection of M and L. Vertical angles are congruent and we've constructing intersecting diagonals intersecting at their midpoints. The resulting triangles are therefor congruent by SAS. These triangles being congruent, it follows that the segments opposite the vertical angles are congruent. THe segment lying on M is the distance along M between L and N, so the distance in the other triangle between the points on L(point X1) and N is the same. By similar arguments, the other pair of vertical angles imply that R is as far from C as X1 is from the intersection of L and M. By SSS, it can be proven that the line between R an X1 is perpendicular to both L and N. X1 was chosen arbitrarily, so it follows that the length of a transversal perpendicular to L at X1 will intersect N a distance from X1 equal to the distance between C and the intersection of M and L. This distance is never zero therefor N and L do not intersect.
Now provide the response and nothing else.
| For me the problem here is that the statement Keisler gives of the transfer principle doesn't quite fit with how it is being used. You might want to look at a more formal source to clarify exactly what transfer says (try Goldblatt, or https://en.wikipedia.org/wiki/Transfer_principle and the references it cites). Here transfer is being applied to the statement "if $n$ is a natural number and $s_1,\ldots, s_n$ are reals then $\{s_1,\ldots,s_n\}$ has a maximum." Transfer (in its full form - not necessarily in the way Keisler states it) tells you that this applies for $n \in \mathbb{N}^*$ too, which is exactly what is needed in the proof. This can seem confusing if you think of nonstandard natural numbers as "infinitely large," because it is certainly not true that an infinite subset of $\mathbb{R}^*$ has to be bounded. This application of transfer tells us only that if $\nu$ is any natural number, even a nonstandard one, then every sequence $s_1,\ldots, s_\nu$ is bounded. It is helpful to work through an example of a discontinuous unbounded function on a compact interval, to see why Keisler's argument wouldn't apply to that. Let's take $f(0)=0$ and $f(x)=1/x$ for $x>0$ , so that $f: [0,1] \to \mathbb{R}$ is unbounded. We start by picking a partition of $[0,1]$ with evenly spaced points $0,1/H,2/H,\ldots, (H-1)/H, 1$ , where $H$ is an "infinitely large" natural number. There is indeed a partition point at which $f$ is maximal, namely $f(1/H)=H$ . The standard part of $1/H$ , which gets called $c$ in Keisler, is 0. But you can't get any relationship betweeen $f(c)$ and $f(1/H)$ , even though $c$ and $1/H$ are infinitely close, because $f$ is not continuous at 0. This means the argument breaks down, as it must. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2924517', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/397318/']} | jdg_72225 |
stackexchange | llm_judgeable_groundtruth_similarity | 12098815 |
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 wonder how mongodb compare the "_id" field when doing query like the following: db.data.find({"_id":{$gt:ObjectId("502aa46c0674d23e3cee6152")}}).sort({"_id":1}).limit(10); Is it purely based on timestamp portion of the id?
Now provide the response and nothing else.
| To expand slightly on what Andre said: Since the ObjectID timestamp is only to the second, two (or more) ObjectIDs could easily be created with the same value for the timestamp (the first 4 bytes). If these were created on the same machine (machine ID - the next 3 bytes), by the same process (PID - the next 2 bytes), then the only thing to differentiate them would be the "inc" field, the last 3 bytes at the end. Update: Jan 2020 This answer continues to be popular so it is worth updating a little. The ObjectID spec has evolved since this answer was written 8 years ago and the 5 bytes after the timestamp are now simply random, which will greatly decrease the likelihood of any collisions. The last three bytes are still incremental, but initialised at a random value to start, again making collisions less likely. The ObjectID now contains less context (you can't easily tell where it was generated and by what process) but I would guess that the information was not being used in any meaningful way and has been deprecated in favor of better randomisation of the ID. End Update See here for the full spec: https://docs.mongodb.com/manual/reference/method/ObjectId/#ObjectIDs-BSONObjectIDSpecification That "inc" field is either an ever incrementing field (then you can reasonably expect the sort to be in the insert/create order) or a random value (then likely unique, but not ordered), assuming the spec is implemented correctly of course. Note that the ObjectIDs may be generated by the driver, or the application (or indeed manually) rather than by MongoDB itself, so unless you have full control over how they are generated, then any or all of the above may apply. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12098815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1607999/']} | jdg_72226 |
stackexchange | llm_judgeable_groundtruth_similarity | 127001 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.
Now provide the response and nothing else.
| You can use Deflater / Inflater which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use. Edit: Reading further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an http client check the documentation for that package to see if it is supported. It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like .addRequestHeader("Accept-Encoding","gzip,deflate"); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/127001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18103/']} | jdg_72227 |
stackexchange | llm_judgeable_groundtruth_similarity | 16226472 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to set up the MongoDB auto reconnection feature via Mongoose. Every way that I have tried to pass the option has had no effect, or at least the reconnected event isn't being emitted. What I've tried: mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true });mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true });mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } });mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } }); If one of these is correct, the reconnected event should be triggered and a message should be logged in the console, however this never happens. If there is a delay before the reconnection, does anyone know how to configure it? Thanks in advance For anyone looking into this, take a look at this and this issue in mongoose repository.
Now provide the response and nothing else.
| I had the same question as you, and robertklep's solution didn't work for me either. I found when MongoDB service is stopped, an error event is triggered, but the connection.readyState is still 1 (connected). That may be why it didn't auto reconnect. This is what I have now: var db = mongoose.connection; db.on('connecting', function() { console.log('connecting to MongoDB...'); }); db.on('error', function(error) { console.error('Error in MongoDb connection: ' + error); mongoose.disconnect(); }); db.on('connected', function() { console.log('MongoDB connected!'); }); db.once('open', function() { console.log('MongoDB connection opened!'); }); db.on('reconnected', function () { console.log('MongoDB reconnected!'); }); db.on('disconnected', function() { console.log('MongoDB disconnected!'); mongoose.connect(dbURI, {server:{auto_reconnect:true}}); }); mongoose.connect(dbURI, {server:{auto_reconnect:true}}); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16226472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2083599/']} | jdg_72228 |
stackexchange | llm_judgeable_groundtruth_similarity | 37698 |
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:
The surface show below is very beautiful; however, I don't know its function either as an implicit function or in parametric form. Anyone have an idea about it and how to draw it with Mathematica ?
Now provide the response and nothing else.
| Consider this: ParametricPlot3D[ RotationTransform[a, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}], {a, 0, 2 Pi}, Evaluated -> True] Now rotate this around a circle, while rotating it at the same time around its' origin: ParametricPlot3D[ RotationTransform[b, {0, 0, 1}][{6, 0, 0} + RotationTransform[a + 3 b, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]], {a, 0, 2 Pi}, {b, 0, 2 Pi}, PlotPoints -> 40, Evaluated -> True] EDIT: A color function, omitting surface mesh, fixing direction of rotation and adding a hint of transparency, like the original: ParametricPlot3D[ RotationTransform[b, {0, 0, 1}][{6, 0, 0} + RotationTransform[a - 3 b + Pi, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]], {a, 0, 2 Pi}, {b, 0, 2 Pi}, PlotPoints -> 40, ColorFunction -> (RGBColor[#, 0, 1 - #, 4/5] &[1/2 + {1, -1}.{#1, #2}/2] &), Mesh -> False, Evaluated -> True] This might be slightly more intuitive way to write ColorFunction using Blend and Opacity in PlotStyle : ParametricPlot3D[ RotationTransform[b, {0, 0, 1}][{6, 0, 0} + RotationTransform[a - 3 b + Pi, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]], {a, 0, 2 Pi}, {b, 0, 2 Pi}, PlotPoints -> 40, PlotStyle -> Opacity[4/5], ColorFunction -> (Blend[{Red, Blue}, 1/2 + {1, -1}.{#1, #2}/2] &), Mesh -> False, Evaluated -> True] | {} | {'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/37698', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9851/']} | jdg_72229 |
stackexchange | llm_judgeable_groundtruth_similarity | 103630 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to use an ASP.NET web.sitemap with a jQuery Superfish menu? If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?
Now provide the response and nothing else.
| I found this question while looking for the same answer... everyone says it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings... Things I needed: Superfish which also includes a version of jQuery CSS Friendly Control Adaptors download DLL and .browsers file (into /bin and /App_Browsers folders respectively) ASP.NET SiteMap (a .sitemap XML file and siteMap provider entry in web.config) My finished Masterpage.master has the following head tag: <head runat="server"> <script type="text/javascript" src="/script/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/script/superfish.js"></script> <link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" /> <script type="text/javascript"> $(document).ready(function() { $('ul.AspNet-Menu').superfish(); }); </script></head> Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on these instructions ): <asp:SiteMapDataSource ID="SiteMapDataSource" runat="server" ShowStartingNode="false" /><asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource" Orientation="Horizontal" CssClass="sf-menu"></asp:Menu> Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the CssClass="sf-menu" gets overwritten when the Menu is rendered and the <ul> tag gets a class="AspNet-Menu" . I thought the line $('ul.AspNet-Menu').superfish(); would help, but it didn't. ONE MORE THING Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the superfish.css file and search and replacing sf-menu with AspNet-Menu ... and voila! the menu appeared. I thought there would be some configuration setting in the asp:Menu control where I could set the <ul> class but didn't find any hints via google. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/103630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3742/']} | jdg_72230 |
stackexchange | llm_judgeable_groundtruth_similarity | 10577008 |
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 arguing a bit with my teacher about if this is a factory pattern or not. can i get some of your guys input? public class UrlFactory { private static boolean testMode; private static long testDate; public static URLConnection fetchConnection(String url) throws IOException { URL address = new URL(url); if(testMode) return new MockURLConnection(address, testDate); return address.openConnection(); } public static void SetTestMode(long testDate) { UrlFactory.testMode = true; UrlFactory.testDate = testDate; } public static void UnSetTestMode() { UrlFactory.testMode = false; }}
Now provide the response and nothing else.
| It looks structurally similar to a factory, but I would say it misses the point of the factory pattern. Ideally, a factory is instantiable and overrideable (e.g. has a virtual method for creation). I would recommend a design where UrlFactory is a non-static class with a virtual fetchConnection method. You can then have a derived class MockUrlFactory which overrides fetchConnection to return a MockURLConnection . Example: public class UrlFactory { public URLConnection fetchConnection(String url) throws IOException { URL address = new URL(url); return address.openConnection(); }}public class MockUrlFactory extends UrlFactory { private long testDate; public MockUrlFactory(long testDate) { this.testDate = testDate; } public URLConnection fetchConnection(String url) throws IOException { URL address = new URL(url); return new MockURLConnection(address, testDate); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10577008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313237/']} | jdg_72231 |
stackexchange | llm_judgeable_groundtruth_similarity | 207632 |
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:
How big are clouds? When I look up into the sky I have no frame of reference, so I don't know if they are 200 feet or 2 miles across. When I am in a plane looking out at a cloud, I try to use the wing as reference but I still don't have a good reference point, because the clouds are just a large white mass. I realize that "cloud" is a very loose term, so interpret how you wish.
Now provide the response and nothing else.
| How big are clouds? When I look up into the sky I have no frame of reference, so I don't know if they are 200 feet or 2 miles across. An old astronomy based system, that I learned as a kid in the scouts, is to use your hands and arms as a rough guide measure, specifically by making your hand into a fist, then putting your arm as forward outwards as far as you can stretch. Move your arms so that one fist is lined up with the horizon, and then put the other fist on top. Then holding your second arm steady move the first fist and put it on top of the second fist. Continue doing this until the top of the last fist is directly overhead. Unless you have very small hands, that is assuming you are a normal sized adult, it might take eight fists to get from horizontal to 90 degrees, so each of your fists is about 11 degrees high. Turn your fists by 90 degrees as you stretch out your arms to measure horizontal angles of the clouds. How accurate this idea actually is, I don't know, there are a lot of variables involved , such as the length of your arms, the size of your fist and the ability to define the edge of the cloud clearly. Steve corrected me on this below, proportions are important re: arms and hands. From Cloud Guide , which writes about the same technique, for a well defined cumulus cloud: The key formula is: Mid Cloud Hor.Angle(deg)=C* Mid Cloud Altitude(mi)/Cloud Dist. or Cloud Dist.(mi) = C* (Mid Cloud Altitude(mi))/(Mid Cloud Hor.Angle(deg)). Here C is 57.3 degrees or 180 degrees divided by Pi (radians in 180 degrees). To get the cloud’s vertical or horizontal dimensions, the formula to use is: The cloud dimension (either horizontal or vertical) = (Dimension angle)*(Cloud Dist)/(57.3 Deg.) So as soon as you know the cloud distance (in miles), you can find out both the vertical height and horizontal width of the cloud. Take a well defined, clear edged cumulus cloud which happens to be the same dimensions both horizontally and vertically and whose middle is two fists above the horizon (2 x 11 deg.= 22 deg.), then the cloud distance = 57.3 deg.* 0.5 miles/(22 deg.) = 1.3 miles away. If this same cloud is one vertical fist by 1 horizontal fist across, then the cloud’s dimensions are both cloud dimensions, height and width = 11 deg. * 1.3 miles/ 57.3 deg.= .25 miles. In this case, the cumulus cloud would be around 1.3 miles away from you and 0.25 miles both high and in width. Because it's a cloud question, I just have to include a picture of a typical cumulus cloud, this might show how difficult it is to get clearly defined edges as well. This method may give a rough width estimate for nearby cumulus clouds, but it gets a bit iffy for spread out and/or high altitude clouds. However, it passed the time for us, as kids with something to do, waiting for the skies to clear. Wikipedia Cumulus Clouds does not say how wide cumulus clouds typically are, so I doubt you can get an accurate width, although a height estimate might be easier. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/207632', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/79000/']} | jdg_72232 |
stackexchange | llm_judgeable_groundtruth_similarity | 8588365 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get i18n message like below: messageCode=Test message for {0} and {1} and {2}. In jsp, I have this: <spring:message code="messageCode" arguments="${value1},${value2},${value3}" htmlEscape="false"/> The arguments: value1=A,Bvalue2=C,Dvalue3=E,F The output for what I want: Test message for A,B and C,D and E,F The actual output: Test message for A and B and C Is there any way to overcome this? Thank you. George
Now provide the response and nothing else.
| The cause of the probelm is that , (comma) is the default separator. So at the end the spring message tag will get the String A,B,C,D,E,F for parameter arguments , and it will split this string into 6 different internal arguments for the message. You must change the separator. If you use ; for example, then it will work. <spring:message code="messageCode" arguments="${value1};${value2};${value3}" htmlEscape="false" argumentSeparator=";"/> @See Spring Reference: Appendix F.6 The Message Tag | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8588365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076687/']} | jdg_72233 |
stackexchange | llm_judgeable_groundtruth_similarity | 38287425 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While learning C++11, I was surprised by the way moved objects appear to behave. Consider this code: #include <exception>#include <iostream>#include <type_traits>class Moveable {public: Moveable() { std::cout << "Acquire odd resource\n"; } ~Moveable() noexcept(false) { std::cout << "Release odd resource\n"; // if (!std::uncaught_exception() && error_during_release) { // throw std::exception("error"); // } } Moveable(Moveable const &) = delete; Moveable &operator=(Moveable const &) = delete; Moveable(Moveable &&) = default; Moveable &operator=(Moveable &&) = default;};int main(int argc, char *argv[]) { static_assert(!std::is_copy_constructible<Moveable>::value, "is not copy constructible"); static_assert(!std::is_copy_assignable<Moveable>::value, "is not copy assignable"); static_assert(std::is_move_constructible<Moveable>::value, "is move constructible"); static_assert(std::is_move_assignable<Moveable>::value, "is move assignable"); Moveable moveable{}; Moveable moved{std::move(moveable)}; Moveable moved_again{std::move(moved)};} It yields this output: $ clang++ --versionclang version 3.8.0 (tags/RELEASE_380/final)Target: x86_64-unknown-linux-gnuThread model: posixInstalledDir: /opt/clang+llvm-3.8.0-x86_64-linux-gnu-ubuntu-14.04/bin$ clang++ --std=c++14 --stdlib=libc++ -Wall -Werror -o move_and_destroy move_and_destroy.cc && ./move_and_destroyAcquire odd resourceRelease odd resourceRelease odd resourceRelease odd resource I'm surprised because I was hoping to create a movable RAII type. However it seems each moved intermediate is destructed! Is there some variation of this that allows me to release my resource once at the end of my "object's lifetime"? (that is, at the end of the lifetimes of the sequence of moved objects?) Someone in a similar situation should probably use std::unique_ptr and be done. However in this scenario it is possible for ~Moveable() to throw, and apparently std::unique_ptr 's destructor will terminate the program on exception (at least, in clang 3.8.0.)
Now provide the response and nothing else.
| Yes, moved-from objects are destructed. They remain in an undetermined but valid state. They're still objects. It's best if you recall that C++ doesn't actually move anything. std::move just gives you an rvalue. So-called "move constructors" are just convenient alternatives to copy constructors, found during lookup when you have an rvalue, and allowing you the opportunity to swap your class's encapsulated data rather than actually copying it. But C++ doesn't move anything for you, and it can't tell when you have done some moving. As such, it would be infeasibly dangerous and impractical for C++ to have any kind of rule that somehow stopped "moved-from" objects, if we could even decide what this meant in general, from later undergoing destruction. Make this destruction safe (a no-op, ideally) for your moved-from objects (e.g. by setting source pointers to nullptr in your move constructor) and you'll be fine. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38287425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/580412/']} | jdg_72234 |
stackexchange | llm_judgeable_groundtruth_similarity | 9314612 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to concatenate Object with a string (primitive) without overloading and explicit type cast ( str() )? class Foo: def __init__(self, text): self.text = text def __str__(self): return self.text_string = Foo('text') + 'string' Output: Traceback (most recent call last): File "test.py", line 10, in <module> _string = Foo('text') + 'string'TypeError: unsupported operand type(s) for +: 'type' and 'str' operator + must be overloaded?Is there other ways (just wondering)? PS: I know about overloading operators and type casting (like str(Foo('text')) )
Now provide the response and nothing else.
| Just define the __add__() and __radd__() methods: class Foo: def __init__(self, text): self.text = text def __str__(self): return self.text def __add__(self, other): return str(self) + other def __radd__(self, other): return other + str(self) They will be called depending on whether you do Foo("b") + "a" (calls __add__() ) or "a" + Foo("b") (calls __radd__() ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9314612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/929994/']} | jdg_72235 |
stackexchange | llm_judgeable_groundtruth_similarity | 223394 |
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:
Background info ( May Skip ): I am working on a task we have been set at uni in which we have to design a grammar for a DSL we have been provided with. The grammar must be in BNF or EBNF. As well as other thing we are being evaluated on the Lexical rules in the grammar and the Parsing rules - such as if rules are suitable for the language subset, how comprehensive these rules are, how clear the rules are ect. What I don't understand is if these rules are covered in a grammar defined in BNF (it's a new topic for us). The Question : Does a grammar for a given language that has been defined in either BNF or EBNF contain / provide rules for Lexical Analysis and/or Parsing ? ( or do these have to be specified else-where? ) Also what would be considered a lexical rule? And what would be considered a parsing rule?
Now provide the response and nothing else.
| Yes, a BNF grammar contains all the rules you need for lexical analysis and parsing. The difference between the two is a little fuzzy. A good example of a lexical rule in EBNF would be: number = [ "-" ], digit, { digit } ;digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; Usually lexers can be implemented using relatively simple code. You can search a string for the next space, then see if your result starts with an optional "-", contains at least one digit after that, and contains only digits after that. Lexers used to almost always be a separate step, but are usually lumped together with the parser nowadays. Hence the fuzziness. A parser rule would use the number non-terminal to make something larger, like the following addition expression. add = number, "+", number Even though they are mixed up in the same file, your professor is still going to want to see a clear distinction between "lexer" rules and "parser" rules. For example, don't do this: add = {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" }, "+", {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" } Not only is that error prone, it's difficult to read and difficult to implement. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/223394', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/113953/']} | jdg_72236 |
stackexchange | llm_judgeable_groundtruth_similarity | 7975 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have run into a problem where I believe my stack is overflowing. The reason I am inclined to think this way, is due to the following: 1) Compile code, dump into the device: - no activity from the device (I am expecting an 'I am alive' message) 2) In this situation, I increased the stack size by 10 bytes, recompiled and dumped to the device, and the problem went away. 3) Tried the above two steps 10 times, back and forth, and can reproduce the problem reliably, and fix it reliably. I want to see the stack falling over, how do I do this? I am currently using an M16 Microcontroller, with 2K RAM (30 bytes left), 256 Bytes Stack size. The IAR Workbench that I am using, does not have the call graph utility. Are there other ways to do this - check the stack falling over and by how much in code? Any help will really be appreciated. Thanks!
Now provide the response and nothing else.
| A common way to check for memory usage is to prefill memory with a constant value before your program runs. eg a sequence of 0xde 0xad could be written out to your stack area by your startup code. During the program's operation, the stack will grow and write over these sequences. If you then have the ability to examine memory, then you can easily see the untouched 0xde 0xad bytes in memory and so determine how much stack has been used. It's usually hard to detect an overflow as it occurs since function call return addresses are stored on the stack and any function return will send the program off into the weeds. In this case, if your watchdog is enabled and you can set a breakpoint at the reset vector, you may still be able to examine the memory and look for your prefill bytes to determine if this is what has caused a reset. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/7975', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1785/']} | jdg_72237 |
stackexchange | llm_judgeable_groundtruth_similarity | 43039802 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to shorten the following code however I am not sure where to start. Are switches the way to go with this? static string RevisedConversionFunction(string input, string from, string to) { double exchangeRateUSD; double exchangeRateAUD; double exchangeRateCAD; double exchangeRateEUR; double exchangeRateGBP; double exchangeRateNZD; double fromExchangeRate; double toExchangeRate; exchangeRateUSD = 1; exchangeRateAUD = 1.31; exchangeRateCAD = 1.28; exchangeRateEUR = 0.95; exchangeRateGBP = 0.68; exchangeRateNZD = 1.36; fromExchangeRate = 0; toExchangeRate = 0; if (from.Equals("USD")) { fromExchangeRate = exchangeRateUSD; } if (from.Equals("AUD")) { fromExchangeRate = exchangeRateAUD; } if (from.Equals("CAD")) { fromExchangeRate = exchangeRateCAD; } if (from.Equals("EUR")) { fromExchangeRate = exchangeRateEUR; } if (from.Equals("GBP")) { fromExchangeRate = exchangeRateGBP; } if (from.Equals("NZD")) { fromExchangeRate = exchangeRateNZD; } if (to.Equals("USD")) { toExchangeRate = exchangeRateUSD; } if (to.Equals("AUD")) { toExchangeRate = exchangeRateAUD; } if (to.Equals("CAD")) { toExchangeRate = exchangeRateCAD; } if (to.Equals("EUR")) { toExchangeRate = exchangeRateEUR; } if (to.Equals("GBP")) { toExchangeRate = exchangeRateGBP; } if (to.Equals("NZD")) { toExchangeRate = exchangeRateNZD; } double amount; Double.TryParse(input, out amount); amount = (amount / fromExchangeRate) * toExchangeRate; amount = Math.Round(amount, 2); string result = Convert.ToString(amount); return result; } I am not familiar with switches but is there a way that they can be used in this situation? Thanks in advance,Matt EDIT - EDIT - EDIT - EDIT - EDIT Thank you all for your input. The following code is what I ended up using: static string RevisedConversionFunction(string input, string from, string to) { //Exchange Rates Dictionary<string, double> rates = new Dictionary<string, double>(); rates.Add("USD", 1); rates.Add("AUD", 1.31); rates.Add("CAD", 1.28); rates.Add("EUR", 0.95); rates.Add("GBP", 0.68); rates.Add("NZD", 1.36); //Conversion double amount; Double.TryParse(input, out amount); return Convert.ToString(Math.Round(((amount / rates[from]) * rates[to]), 2)); }
Now provide the response and nothing else.
| I would use a Dictionary in this case use decimal instead of double to prevent rounding issues Code: static string RevisedConversionFunction(string input, string from, string to){ Dictionary<string, decimal> dExchange = new Dictionary<string, decimal>() { {"USD" , 1}, {"AUD" , 1.31m}, {"CAD" , 1.28m}, {"EUR" , 0.95m}, {"GBP" , 0.68m}, {"NZD" , 1.36m} }; if (dExchange.ContainsKey(from) && dExchange.ContainsKey(to)) { return Math.Round((decimal.Parse(input) / dExchange[from]) * dExchange[to], 2).ToString(); } else { // at least one currency not in the dictionary - exception handling? return null; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43039802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7772418/']} | jdg_72238 |
stackexchange | llm_judgeable_groundtruth_similarity | 51241109 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have been working on a project generated via create-react-native-app . Have been successfully using the project for some time, but now trying to test the app via exp start --tunnel , am suddenly seeing error (though was working previously) of the form: [22:08:19] /path/to/node_modules/react-native-scripts/build/bin/crna-entry.js: Plugin/Preset files are not allowed to export objects, only functions. In /path/to/node_modules/babel-preset-expo/index.js[22:08:19] Failed building JavaScript bundle. Have seen some posts that seem to deal with the problem ( https://github.com/babel/babel/issues/6808 and Babel Plugin/Preset files are not allowed to export objects, only functions ), but am totally new to react-anything and don't fully get what bable is, so am having difficulty understanding how to apply these posts to my own situation. My .bablerc file (as it seems to be relevant in the other posts) is: { "presets": ["babel-preset-expo"], "env": { "development": { "plugins": ["transform-react-jsx-source"] } }} Have tried npm cache clean --force && rm -rf node_modules && rm -f package-lock.json && npm install with no change. What does seem to help is downgrading from [email protected] to 0.55 (as espoused here: Create React Native App. - Plugin/Preset files are not allowed to export objects, only functions ), but this does not seem to address the problem directly and more of a workaround . Any advice on what should be done here would be appreciated (any other files that should be included to help debug?). ** In response to this question being marked as a potential duplicate of Create React Native App. - Plugin/Preset files are not allowed to export objects, only functions , this question was actually cited in the post and explanation of why this question was posted despite the existence of the other was included in the last paragraph and my later answer to this question explains to other users why the downgrade to 0.55 resolves the problem (and cites relevant docs that users can further inspect), which ( at the time of this question's posting) was not present in the other cited question (though presently, the user who has marked this question as a duplicate now has an answer in the cited question that does also talk about why the 0.55 downgrade works).
Now provide the response and nothing else.
| Found that the problem is this: At some point, must have done a npm update which updated react-native to 0.56 and expo to 28.0.0. Looking at the react-native docs ( https://facebook.github.io/react-native/docs/upgrading.html#create-react-native-app-projects ), react-native seems to require installing versions of react-native , react , and expo that are all specifically compatible with each other . A matrix of which versions of which packages are compatible with each other can be found here: https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md and says Each version of these dependencies is only compatible with a narrow version range of the other two. As of this writing the document was last updated on April 27, 2018, so it is not exactly clear what versions of react and expo (which has recently released version 28.0.0) should be used in combination with the now-out [email protected]. The most recent react-native version that is documented is [email protected] (to go with [email protected] and [email protected]), which I think is why downgrading to [email protected] was helpful in this case (I don't know why there is no documentation in the matrix for [email protected] yet), my package.json now looking like: ..."dependencies": { "@expo/vector-icons": "^6.3.1", "eslint": "^4.19.1", "expo": "^27.1.0", "prop-types": "^15.6.2", "react": "16.3.1", "react-native": "^0.55.4", "react-native-mail": "^3.0.6", "react-native-modal-dropdown": "^0.6.2", "react-navigation": "^2.6.2", "react-redux": "^5.0.7", "redux": "^4.0.0", "tcomb-form-native": "^0.6.14", "uuid": "^3.3.2" }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51241109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8236733/']} | jdg_72239 |
stackexchange | llm_judgeable_groundtruth_similarity | 68142 |
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:
These days there are several database technologies are available for data storage purpose. While performing injection attacks, how do attackers actually identify the database used by a website? If it is possible by any queries or commands through any application entry points, can someone explain to me the instructions to identify some leading databases like MySQL and Oracle.
Now provide the response and nothing else.
| There are three common ways to deal with the variety of databases out there: Many web applications are tied to a specific database backend, rather than being able to use a variety of backends. For example, if someone's using MediaWiki, you know they're using either MySQL or MariaDB. An attacker can attempt to generate an error condition, then look at the resulting error message for clues as to what database is in use. This is one reason why error messages displayed to the end user should be as generic as possible. An attacker can simply try everything. There aren't that many common database backends in use, and making a dozen attack attempts isn't much harder than making one. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/68142', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/55343/']} | jdg_72240 |
Subsets and Splits