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
879036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We just installed Redmine Charts ( http://github.com/mszczytowski/redmine_charts/tree/master ) and the associated OpenFlashChart plugin but when we start the Ruby server, we get the error below. Our steps were to: Download the tar file for charts Untar into $REDMINE_ROOT/plugins dir $REDMINE_ROOT/script/plugin install http://svn.pullmonkey.com/plugins/trunk/open_flash_chart/ Try to start server => Booting WEBrick.../usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:276:in load_missing_constant': uninitialized constant Redmine::I18n (NameError)from /usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:468:in const_missing'from /usr/local/apps/redmine-0.8/vendor/plugins/mszczytowski-redmine_charts-e3c5010466d7585d987bc1018e94daee90906a5d/lib/redmine_charts/line_data_converter.rb:4from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require'from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require'from /usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in require'from /usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:355:in new_constants_in'from /usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in require'from /usr/lib64/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:102:in require_or_load' ... 27 levels...from /usr/lib64/ruby/gems/1.8/gems/rails-2.1.2/lib/commands/server.rb:39from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require'from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in require'from script/server:3 Now provide the response and nothing else.
As luke noted, the code to create and bind the context is specific to each windowing platform. Here are some functions to get you started in terms of initializing OpenGL on specific platforms: Windows (a tutorial is here ) wglCreateContext(hDC) Mac OS X -- OS X has essentially three options: Carbon, Cocoa, and the underlying Core Graphics Layer The entire guide for Mac OS X OpenGL development Carbon : aglCreateContext Cocoa : Create (or subclass) an NSOpenGLView. They create their own context, and you can read their method documentation to find how to make it current. CoreGraphicsLayer : CGLCreateContext Linux glx : glXCreateContext
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/879036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26535/']}
jdg_86741
stackexchange
llm_judgeable_groundtruth_similarity
19383
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Starting in verse 5. 1Co 2:5 so that your faith might not rest in the wisdom of men but in the power of God. 2:6 Yet among the mature we do impart wisdom, although it is not a wisdom of this age or of the rulers of this age , who are doomed to pass away . 2:7 But we impart a secret and hidden wisdom of God, which God decreed before the ages for our glory. 2:8 None of the rulers of this age understood this , for if they had, they would not have crucified the Lord of glory. (ESV) Most commentaries I've read attribute the rulers of age of which Paul spoke as being human rulers (or princes as KJV reads). These same rulers are said to have responsible for the crucifixion of the Lord of glory. We immediately think of those rulers complicit someway in the Lord's death: Herod, Pilate and Caiaphas. Those three mentioned were either dead or out of power at this epistle's writing, making the vs. 6 present tense who are doomed to pass away difficult to attribute to them. My question: Was Paul referring to demonic rulers in this passage?A few verses where demons are called rulers or princes: John 6:31, John 16:11, Eph 2:2, Eph 6:12, Now provide the response and nothing else.
Another answer gave evidence in support of the idea that this passage refers to demonic powers and echoes (or rather, anticipates) gnostic ideas. Clearly this is one widely held scholarly viewpoint. I would like to point out, however, that this is not the only available, defensible interpretation. I have bolded here the references given by the OP to other NT passages that could support the “demons” interpretation. I think their relationships to 1 Cor 2:8 can be otherwise explained. Arguing against a reference to demonic powers here, Gordon Fee in his commentary The First Epistle to the Corinthians (pp 103-104): This oft-repeated assertion needs finally to be laid to rest since the linguistic evidence, the context, and Pauline theology all argue against it. I summarize his main points in support of the idea that earthly rulers are in view here: Paul uses a different, related word to describe spiritual opposition. See, for instance, Colossians 1:16 and Ephesians 6:12 where the term ἀρχή ( pl. ἀρχαί) is used. This sort of “ruler” is never equated with the ἄρχοντες ( sing. ἄρχων) used here. (Ephesians 3:10, mentioned in the other answer, also belongs in this category.) Although ἄρχων in the singular does at times refer to Satan ( Eph. 2:2 belongs here), the plural form does not refer to demonic forces of any kind in any Jewish or Christian writings prior to the second century. In the New Testament ἄρχων as plural invariably refers to early rulers. (Rom 13:1 is particularly important here.) These arguments are also covered in Fee’s New Testament Exegesis (pp 87-89). For broader contextual support, including refutation of the idea that this passage and others in Pauline literature invoke gnosticism, see Wesley Carr’s monograph Angels and Principalities: The Background, Meaning and Development of the the Pauline Phrase kai archai kai hai exousia . With regard to the term sofia , see Gene Miller’s ΑΡΧΟΝΤΩΝ ΤΟΥ ΑΙΩΝΟΣ ΤΟΥΤΟΥ -- A New Look at 1 Corinthians 2:6-8 . Here, Miller challenges the arguments of those such as Héring that the attribution of sofia to these powers is evidence that they are of the supernatural, gnostic type: The theory is decisively refuted by the fact that in this passage and its entire context the wisdom which Paul sets over against the "wisdom of God” is specifically human wisdom (cf. 1:25, 26; 2:5,13). The question also mentioned John 16:11 (cf. 12:31, 14:30) (I’m not sure of the relevance of John 6:31 - perhaps a typo?) where Satan is referred to as ὁ ἄρχων· These references in John are all singular (see bullet 2 above) but have indeed been used in support of a spiritual referent for 1 Cor 6:8 due to the shared attributive "τοῦ κόσμου [τούτου]" ("of [this] world"). Fee points out that, in addition to being singular, this phrase is particular to John and has no parallel in Pauline writing.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/19383', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/2436/']}
jdg_86742
stackexchange
llm_judgeable_groundtruth_similarity
22335103
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 program where I use a class store settings. I need it to use set and get functions to change and store settings. I have tried this, and I don't get it to work. Can anyone help me with this one? private enum _Difficulty { Easy, Normal, Hard }; public void SetDifficulty(Difficulty) { _Difficulty = Difficulty; } public enum GetDifficulty() { return _Difficulty; } Is there no way to use enums in a class with get and set ? I also need this with bool and int . Now provide the response and nothing else.
There are several things wrong here: Your enum is private, but your methods are public. Therefore you can't make your methods return type be the enum type, or have parameters with that type Your SetDifficulty method has a parameter of just Difficulty - is that meant to be the parameter name or the type? Your SetDifficulty method is trying to set the type rather than a field Your GetDifficulty method is trying to use enum as a return type, and is then returning a type rather than a field Basically, you seem to be confused about what your enum declaration is declaring - it's not declaring a field , it's declaring a type (and specifying what the named values of that type are). I suspect you want: // Try not to use nested types unless there's a clear benefit.public enum Difficulty { Easy, Normal, Hard }public class Foo{ // Declares a property of *type* Difficulty, and with a *name* of Difficulty public Difficulty Difficulty { get; set; }} You can use get/set methods if you really want to make your code look like Java instead of C#: public enum Difficulty { Easy, Normal, Hard }public class Foo{ private Difficulty difficulty; public void SetDifficulty(Difficulty value) { difficulty = value; } public Difficulty GetDifficulty() { return difficulty; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22335103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3407591/']}
jdg_86743
stackexchange
llm_judgeable_groundtruth_similarity
9610277
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 2 models class Sport < ActiveRecord::Base has_many :charts, order: "sortWeight ASC" has_one :product, :as => :productable accepts_nested_attributes_for :product, :allow_destroy => trueendclass Product < ActiveRecord::Base belongs_to :category belongs_to :productable, :polymorphic => trueend A sport can't exist without the product, so in my sports_controller.rb I had: def new @sport = Sport.new @sport.product = Product.new...end I tried to move the creation of the product to the sport model, using after_initialize : after_initialize :create_productdef create_product self.product = Product.newend I quickly learned that after_initialize is called whenever a model is instantiated (i.e., from a find call). So that wasn't the behavior I was looking for. Whats the way I should be modeling the requirement that all sport have a product ? Thanks Now provide the response and nothing else.
Putting the logic in the controller could be the best answer as you stated, but you could get the after_initialize to work by doing the following: after_initialize :add_productdef add_product self.product ||= Product.newend That way, it only sets product if no product exists. It may not be worth the overhead and/or be less clear than having the logic in the controller. Edit: Per Ryan's answer, performance-wise the following would likely be better: after_initialize :add_productdef add_product self.product ||= Product.new if self.new_record?end
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9610277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716082/']}
jdg_86744
stackexchange
llm_judgeable_groundtruth_similarity
197573
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am currently studying CFT chapter of Becker,Becker,Schwarz and am trying to understand what the ghost number is in BRST Quantization. From what I gather BRST Quantization is used to add an extra symmetry to the theory by adding things called ghost fields to the Lagrangian. This symmetry provides you with a nilpotent charge that then allows you to identify physical string states as BRST cohomology classes. The book keeps mentioning these quantities called ghost numbers but doesn't explain exactly what they are and how they are affecting the results of certain formulas. The book also mentions a ghost number operator $$U = {1 \over {2\pi i}}\oint {\;:c(z)b(z):} \;dz$$ but doesn't really explain its significance either. Can someone help me understand what these things are and how they are used? Now provide the response and nothing else.
Caveat: The first part of this answer takes a very technical stance on the BRST procedure, and additionally works with a finite-dimensional phase space for convenience. It could appear quite far from the understanding of ghosts in the average application of BRST transformations or ghosts as a tool. The general conception of ghosts There are many different levels at which one may discuss the appearance of ghosts, anti-ghosts, and their numbers in constrained Hamiltonian mechanics (which is the same as gauge theories on a Lagrangian level). One of them is partly sketched in this answer of mine , where the BRST operator is exhibited as the differential in the gauge Lie algebra cohomology. We will look at a slightly different way of looking at ghosts, namely by "extending the phase space", in this answer, although this can be seen as a rephrasing of the Lie algebra cohomology approach in "phase space terms": The BRST formalism, on an abstract level, seeks to implement the reduction to a constraint surface $\Sigma$ in a phase space $X$ not by solving the constraints $G_a$ , but by searching a suitable enlargement of the phase space such that the functions on the enlarged phase space have a graded derivation $\delta$ living on them whose homology computes the functions on the constraint surface, which are the gauge-invariant observables. 1 The enlarged phase space is obtained as follows: A function on the constraint surface $\Sigma$ is given by the quotient of all phase space functions modulo the functions vanishing on the surface. Every function $f$ vanishing on the surface is given by $$ f = f^a G_a$$ where the $f^a$ are arbitrary phase space functions. If one introduces as many variables $P_a$ as there are constraints, and defines $\delta P_a = G_a$ as well as $\delta z = 0$ for any original phase space variable, then the image of $\delta$ is exactly all functions that vanish on $\Sigma$ . For $\delta$ to be graded, $P_a$ has to be taken to be of degree $1$ . The degree of a function as simply the degree of it as a polynomial in the $P_a$ is called the anti-ghost number . 2 The $P_a$ are lonely, and they need conjugate variables. These are given by so-called longitudinal 1-forms on the constraint surface, where a longitudinal vector field on the constraint surface is one that is tangent to the gauge orbits. Their duals are 1-forms which are only defined on longitudinal vectors. It should be geometrically intuitive (and it is in fact true) that the longitudinal vector fields are precisely the fields generating the gauge transformations (they are again just another incarnation of the gauge Lie algebra). Therefore, there are as many basic longitudinal 1-forms $\eta^a$ as there are constraints, and as there are anti-ghosts $P_a$ . Since there is the natural action $\eta^a(P_b) = \delta^a_b$ by definition of the dual, it is also natural to just define the Poisson bracket on an enlarged phase space with coordinates $(x^i,p_i,\eta^a,P_a)$ by $$ [\eta^a,P_b] = \delta^a_b$$ so the pairs $(\eta^a,P_a)$ act as additional pairs of canonical variables. The derivation is extended to the $\eta$ simply by $\delta(\eta^a) = 0$ . Functions on this enlarged phase space are now assigned a pure ghost number based on their degree in the $\eta$ . Given any function on the enlarged phase space, the ghost number is simply the pure ghost number minus the anti-ghost number. The nice thing about the ghost number is that it is the charge of a certain generator - it is measured by the operator 3 $$ \mathcal{G} := \mathrm{i}\eta^a P_a$$ which fulfills $$ [f,\mathcal{G}] = \mathrm{i}\operatorname{gh}(f)f$$ for any function of definite ghost number. The ghost number is physically important because being a state of ghost number zero is, together with the condition of being BRST invariant, the necessary and sufficient condition of being a physical state. Obtaining this condition, however, requires now obtaining the BRST differential by adding another differential $\mathrm{d}$ to $\delta$ , and showing that the $\delta + \mathrm{d}$ gives, when "small perturbations" are added to it, the nilpotent operator required for the BRST formalism. (The derivation of this is very technical, and sometimes known as the "theorem of homological perturbation theory") Examining then again the actions of $\mathrm{d},\delta$ , one finds that the gauge-invariant functions are precisely those invariant under the BRST operator with zero ghost number, so the quantum theory should also impose this restriction. 1 "whose homology computes" is math speak for it being an operator $\delta$ , where the gauge-invariant functions are precisely the functions with $\delta(f) = 0$ and where we identify $f$ and $g$ if there is an $h$ such that $\delta(h) = f - g$ . Also, this gets a bit more complicated in the case of reducible constraints. 2 In the case of irreducible constraints, this already correctly computes the gauge-invariant functions, and one could in principle stop here. However, it is unsatisfactory to have added the $P_a$ , but not have suitably conjugate variables for them in the Hamiltonian formalism. 3 This definition is the discrete, non-conformal analogon to the expression for $U$ that is written in the question. Main reference: "Quantization of Gauge Systems" by Henneaux/Teitelboim The specific case of $bc$ -CFT A general " $bc$ -CFT", i.e. a 2D conformal field theory with ghost-like fields is given by the ghost action $$ \frac{1}{2\pi}\left(b(z)\bar\partial c(z) + b(z)\partial c(z)\right)$$ when the fields $b$ and $c$ have conformal weights $h_b$ and $h_c = 1 - h_b$ , respectively. Phase space functions with ghost number zero translate now to operators with conformal weight $1$ (since they have equal numbers of ghosts and anti-ghosts in them, and the weight behaves additively). This shows that primary physical states (by the state-field correspondence of 2D CFTs) in such a theory must necessarily have conformal weight $1$ . This is of importance in string theory, where a $bc$ -CFT with $h_b = 2$ is naturally added to the $X$ -CFT of the worldsheet fields. For a generic CFT, all possible primaries could, in principle, be physical states, but the BRST procedure forces ghost number zero states, i.e. fields with weight $1$ , as the only allowed physical states.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/197573', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_86745
stackexchange
llm_judgeable_groundtruth_similarity
28380923
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 just figured out what is an unwind segue and how to use it with the great answers from this question. Thanks a lot. However, here's a question like this: Let's say there is a button in scene B which unwind segues to scene A, and before it segues I want something to be done, such as saving the data to database. I created an action for this button in B.swift, but it seems it goes directly to scene A without taking the action appointed. Anyone knows why or how to do this? Thank you. Now provide the response and nothing else.
You can do it the way you describe, or by using a prepareForSegue override function in the viewController you are unwinding from: @IBAction func actionForUnwindButton(sender: AnyObject) { println("actionForUnwindButton");} or... override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { println("prepareForSegue");} The first example is as you describe. The button is wired up to the unwind segue and to the button action in Interface Builder. The button action will be triggered before the segue action. Perhaps you didn't connect the action to the button in interface builder? The second example gives you have access to the segue's sourceViewController and destinationViewController in case that is also useful (you also get these in the unwind segue's function in the destination view controller). If you want to delay the unwind segue until the button's local action is complete, you can invoke the segue directly from the button action (instead of hooking it up in the storyboard) using self.performSegueWithIdentifier (or follow wrUS61's suggestion) EDIT you seem to have some doubts whether you can work this by wiring up your button both to an unwind segue and to a button action. I have set up a little test project like this: class BlueViewController: UIViewController { @IBAction func actionForUnwindButton(sender: AnyObject) { println("actionForUnwindButton"); } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { println("prepareForSegue"); }}class RedViewController: UIViewController { @IBAction func unwindToRed(sender: UIStoryboardSegue) { println("unwindToRed"); }} BlueViewController has a button that is connected in the storyboard to BOTH the unwindToRed unwind segue AND the actionForUnwindButton button. It also overrides prepareForSegue so we can log the order of play. Output: actionForUnwindButtonprepareForSegueunwindToRed Storyboard: EDIT 2 your demo project shows this not working. The difference is that you are using a barButtonItem to trigger the action, whereas I am using a regular button. A barButtonItem fails, whereas a regular button succeeds. I suspect that this is due to differences in the order of message passing (what follows is conjecture, but fits with the observed behaviour): (A) UIButton in View Controller ViewController's button receives touchupInside - (1) sends action to it's method - (2) sends segue unwind action to storyboard segue all messages received, and methods executed in this order: actionForUnwindButtonprepareForSegueunwindToRed (B) UIBarButtonItem in Navigation Controller Toolbar Tool bar buttonItem receives touchupInside - (1) sends segue unwind action to storyboard segue - (2) (possibly, then) sends action to viewController's method Order of execution is prepareForSegueunwindToRedactionForUnwindButton prepareForSegue and unwind messages received. However actionForUnwindButton message is sent to nil as viewController is destroyed during the segue. So it doesn't get executed, and the log prints prepareForSegueunwindToRed In the case of (B), the viewController is destroyed before the method reaches it, so does not get triggered So it seems your options are... (a) use a UIButton with action and unwind segue (b) trigger your actions using prepareForSegue , which will be triggered while the viewController is still alive, and before the segue takes place. (c) don't use an unwind segue, just use a button action. In the action method you can 'unwind' by calling popToViewController on your navigation controller. By the way, if you implement a toolBar on the viewController (not using the navigation controller's toolbar) the result is the same: segue gets triggered first, so button action fails.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28380923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4540195/']}
jdg_86746
stackexchange
llm_judgeable_groundtruth_similarity
49308530
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 time series dataframe, the dataframe is quite big and contain some missing values in the 2 columns('Humidity' and 'Pressure'). I would like to impute this missing values in a clever way, for example using the value of the nearest neighbor or the average of the previous and following timestamp.Is there an easy way to do it? I have tried with fancyimpute but the dataset contain around 180000 examples and give a memory error Now provide the response and nothing else.
Consider interpolate ( Series - DataFrame ). This example shows how to fill gaps of any size with a straight line: df = pd.DataFrame({'date': pd.date_range(start='2013-01-01', periods=10, freq='H'), 'value': range(10)})df.loc[2:3, 'value'] = np.nandf.loc[6, 'value'] = np.nandf date value0 2013-01-01 00:00:00 0.01 2013-01-01 01:00:00 1.02 2013-01-01 02:00:00 NaN3 2013-01-01 03:00:00 NaN4 2013-01-01 04:00:00 4.05 2013-01-01 05:00:00 5.06 2013-01-01 06:00:00 NaN7 2013-01-01 07:00:00 7.08 2013-01-01 08:00:00 8.09 2013-01-01 09:00:00 9.0df['value'].interpolate(method='linear', inplace=True) date value0 2013-01-01 00:00:00 0.01 2013-01-01 01:00:00 1.02 2013-01-01 02:00:00 2.03 2013-01-01 03:00:00 3.04 2013-01-01 04:00:00 4.05 2013-01-01 05:00:00 5.06 2013-01-01 06:00:00 6.07 2013-01-01 07:00:00 7.08 2013-01-01 08:00:00 8.09 2013-01-01 09:00:00 9.0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49308530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8901144/']}
jdg_86747
stackexchange
llm_judgeable_groundtruth_similarity
26972615
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Go programming language specification states: "To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name." For example: import _ "foo/bar" I am having difficulty imagining a use case for this construct. The accepted answer for Usage of the `import` statement mentions a use case where a database driver may be loaded without the need for the importing program to use any of the exported functions of that package, but it leaves out the details to reader's imagination. Are there real life examples (with code snippets and explanation) that illustrate this use case? Now provide the response and nothing else.
I was writing a program that resizes images. I wanted it to be able to recognize images in different formats like JPEG , PNG , GIF and convert them to JPEG . So in addition to the image and image/jpeg packages, I also had to import image/png and image/gif only to register their respective decoders. Had I not imported those, the scaler would only be able to read JPEG images. package mainimport( "image" "image/jpeg" // I wanted to export the images as JPEG _ "image/png" _ "image/gif")// ... The relevant documentation from the image package: Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format's package so that, to decode a PNG image, it suffices to have: import _ "image/png"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26972615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_86748
stackexchange
llm_judgeable_groundtruth_similarity
101255
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm playing the FIFA Panini Online Sticker Album , which is an Internet adaption of the classic Panini albums that are usually published for the soccer world cup, European championship, and possibly other tournaments. The album has placeholders for 424 different stickers. The purpose of the game is to collect all 424. The stickers come in packs of 5, which can be obtained through codes found online (or, in case of the classic printed album, bought at your local newsstand). I make the following assumptions: All stickers are published in the same quantity. One pack of stickers does not contain duplicates. How can I find out how many packs of stickers I need to acquire in order to be reasonably sure (let's say 90%) that I have all 424 unique stickers? Now provide the response and nothing else.
That is a beautiful Coupon Collector's Problem, with a little twist introduced by the fact that stickers come in packs of 5. If the stickers were bought individually the result are known, as you can see here . All the estimates for a 90% upper bound for individually-bought stickers are also upper bounds for the problem with a pack of 5, but a less close upper bound. I think that getting a better 90%-probability upper bound, using the pack of 5 dependence, would get a lot more difficult and would not give you a far better result. So, using the tail estimate $ P[T>\beta n \log n] \leq n^{-\beta+1}$ with $n=424$ and $n^{-\beta+1} = 0.1$ , you'll get to a good answer. EDIT : The article "The collector’s problem with group drawings" (Wolfgang Stadje), a reference of the article brought by Assuranceturix, presents an exact analytical solution for the Coupon Collector's Problem with "sticker packs". Before writing the theorem, some notation definitions: $S$ would be the set of all possible stickers, $s = |S|$ . $A \subset S$ would be the subset that interests you (in the OP, $A = S$ ), and $l = |A|$ . We're going to draw, with replacement, $k$ random subsets of $m$ different stickers. $X_{k}(A)$ will be the number of elements of $A$ that appear in at least one of those subsets. The theorem says that: $$ P(X_{k}(A) = n) = {l \choose n} \sum_{j=0}^{n}(-1)^j {n \choose j}\left[\frac{s+n-l-j \choose m}{s \choose m}\right]^k $$ So, for the OP we have $ l=s=n=424$ and $m=5$ . I did some tries with values of $k$ near the estimate for the classical coupon collector's problem (729 packs) and I got a probability of 90.02% for k equals to 700 . So it was not so far from the upper bound :)
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/101255', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/43884/']}
jdg_86749
stackexchange
llm_judgeable_groundtruth_similarity
13150
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I extract rotation and scale values from a 2D transformation matrix? matrix = [1, 0, 0, 1, 0, 0]matrix.rotate(45 / 180 * PI)matrix.scale(3, 4)matrix.translate(50, 100)matrix.rotate(30 / 180 * PI)matrix.scale(-2, 4) Now my matrix have values [a, b, c, d, tx, ty] . Lets forget about the processes above and imagine that we have only the values a, b, c, d, tx, and ty. How can I find final rotation and scale values? Now provide the response and nothing else.
Essentially you need to solve the following $$\left[\begin{array}{ccc}\mathrm{a} & \mathrm{b} & \mathrm{tx}\\\mathrm{c} & \mathrm{d} & \mathrm{ty}\end{array}\right]=\left[\begin{array}{ccc}s_{x}\cos\psi & -s_{x}\sin\psi & x_{c}\\s_{y}\sin\psi & s_{y}\cos\psi & y_{c}\end{array}\right]$$ where $s_x$, $s_y$ are the scalings, $x_c$, $y_c$ is the translation and $\psi$ is the rotation angle. The results I get are: $$x_{c}=\mathrm{tx}$$ $$y_{c}=\mathrm{ty}$$ $$s_{x}=\mathrm{sign(a)\,}\sqrt{\mathrm{a}^{2}+\mathrm{b}^{2}}$$ $$s_{y}=\mathrm{sign(d)\,}\sqrt{\mathrm{c}^{2}+\mathrm{d}^{2}}$$ $$\tan\psi=-\frac{\mathrm{b}}{\mathrm{a}}=\frac{\mathrm{c}}{\mathrm{d}}$$ So the angle is either $\psi = {\rm atan2}(-b,a)$ or $\psi = {\rm atan2}(c,d)$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/13150', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_86750
stackexchange
llm_judgeable_groundtruth_similarity
45382486
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 profile.rb with following association class User < ActiveRecord::Base has_one :profileendclass Profile < ActiveRecord::Base has_many :skills belongs_to :userend I have a model skills.rb with following association class Skill < ActiveRecord::Base belongs_to :profileend I have following entries in skills table id: name: profile_id:====================================================1 accounting 12 martial arts 23 law 14 accounting 25 journalist 36 administration 1 and so on , how can i query all the profiles with ,lets say, "accounting" & "administration" skills which will be profile with id 1 considering the above recode. so far i have tried following Profile.includes(:skills).where(skills: {name: ["accounting" , "administration"]} ) but instead of finding profile with id 1 - It gets me [ 1, 2 ] because profile with id 2 holds "accounting" skills and it's performing an "IN" operation in database Note: I'm using postgresql and question is not only about a specific id of profile as described (which i used only as an example) - The original question is to get all the profiles which contain these two mentioned skills. My activerecord join fires the following query in postgres SELECT FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" IN ('Accounting', 'Administration') In below Vijay Agrawal 's answer is something which i already have in my application and both, his and mine, query use IN wildcard which result in profile ids which contain either of skills while my question is to get profile ids which contain both the skills. I'm sure that there must be a way to fix this thing in the same query way which is listed in original question and i'm curious to learn that way . I hope that i'll get some more help with you guys - thanks For clarity, I want to query all the profiles with multiple skills in a model with has_many relationship with profile model - using the Profile as primary table not the skills Reason for using Profile as primary table is that in pagination i don't want to get all skills from related table ,say 20_000 or more rows and then filter according to profile.state column . instead anyone would like to select only 5 records which meet the profile.state , profile.user.is_active and other columns condition and match the skills without retrieving thousands of irrelevant records and then filter them again. Now provide the response and nothing else.
You should do this to get all profile_id s which have both accounting and administration skills : Skill.where(name: ["accounting", "administration"]).group(:profile_id).having("count('id') = 2").pluck(:profile_id) If you need profiles details, you can put this query in where clause of Profile for id . Note the number 2 in query, it is length of your array used in where clause. In this case ["accounting", "administration"].length UPDATE:: Based on updated question description, instead of pluck you can use select and add subquery to make sure it happens in one query. Profile.where(id: Skill.where(name: ["accounting", "administration"]).group(:profile_id).having("count('id') = 2").select(:profile_id)) More over you have control over sorting, pagination and additional where clause. Don't see any concerns over there which are mentioned in question edit. UPDATE 2:: Another way to get intersect of profiles with both the skills (likely to be less efficient than above solution): profiles = Profile["accounting", "administration"].each do |name| profiles = profiles.where(id: Skill.where(name: name).select(:profile_id))end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45382486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3728916/']}
jdg_86751
stackexchange
llm_judgeable_groundtruth_similarity
42176866
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to use md5() instead of bcrypt() for storing passwords. But when I just do this: protected function create(array $data){ return Account::create([ 'username' => $data['username'], 'email' => $data['email'], 'password' => md5($data['password']), 'datetoday' => Carbon::now(), 'lastip' => request()->ip(), 'confirmation' => bcrypt($data['password']), ]);} When I try to login it says the credentials are wrong. Now provide the response and nothing else.
Using md5() over bcrypt() is not recommended. However you can manually authenticate user. Override login() method in LoginController public function login(Request $request) { $user = User::where('username', $request->username) ->where('password',md5($request->password)) ->first(); Auth::login($user); return redirect('/'); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42176866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1421775/']}
jdg_86752
stackexchange
llm_judgeable_groundtruth_similarity
222754
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 two text files: string.txt and lengths.txt String.txt: abcdefghijklmnopqrstuvwxyz lengths.txt 54107 I want to get the file >Entry_1abcde>Entry_2fghi>Entry_3jklmnopqrs>Entry_4tuvwxyz I'm working with about 28,000 entries and they vary between 200 and 56,000 characters. At the moment, I'm using: start=1end=0i=0while read read_ldo let i=i+1 let end=end+read_l echo -e ">Entry_$i" >>outfile.txt echo "$(cut -c$start-$end String.txt)" >>outfile.txt let start=start+read_l echo $idone <lengths.txt But it's very inefficient. Any better ideas? Now provide the response and nothing else.
You can do { while read l<&3; do { head -c"$l" echo } 3<&- done 3<lengths.txt} <String.txt It requires some explanation: The main idea is to use { head ; } <file and is derived from the underestimated @mikeserv answer . However in this case we need to use many head s, so while loop is introduced and a little bit of tweaking with file descriptors in order to pass to head input from both files (file String.txt as a main file to process and lines from length.txt as an argument to -c option). The idea is that benefit in speed should come from not needing to seek through the String.txt each time a command like head or cut is invoked. The echo is just to print newline after each iteration. How much it is faster (if any) and adding >Entry_i between lines is left as an exercise.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/222754', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/128136/']}
jdg_86753
stackexchange
llm_judgeable_groundtruth_similarity
8309557
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 redirect user to the OAuth 2.0 authorization endpoint in popup window.What is best way to close this popup and refresh main window after OAuth 2.0 authorization server redirects user back with an authorization code? Thanks in advance for any help. Now provide the response and nothing else.
I think popup you can close by parent.close(); And to refresh main window I used this trick: $(function() { var win; var checkConnect; var $connect = $("#some_button"); var oAuthURL = "http://example.com/account/_oauth?redirect_url=" + redirect_url; $connect.click(function() { win = window.open(oAuthURL, 'SomeAuthentication', 'width=972,height=660,modal=yes,alwaysRaised=yes'); }); checkConnect = setInterval(function() { if (!win || !win.closed) return; clearInterval(checkConnect); window.location.reload(); }, 100);}); Opener ( main window ) just checks every time if the popup still live and if win.closed returns true - the main window reloads Hope it will help somebody
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8309557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380987/']}
jdg_86754
stackexchange
llm_judgeable_groundtruth_similarity
60986878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using MaterialButtonToggleGroup with single selection (only one button checked at a time). How to check if none of the buttons is checked? toggleGroup?.addOnButtonCheckedListener { group, checkedId, isChecked -> if (isChecked) { when (checkedId) { R.id.first_materialButton -> { // do something when selected } R.id.second_materialButton -> { // do something when selected } } } } Now provide the response and nothing else.
The solution would be to get the checkedButtonId from the group on the else branch for isChecked , and if it the value is -1, then no button is selected. toggleGroup?.addOnButtonCheckedListener { group, checkedId, isChecked -> if (isChecked) { when (checkedId) { R.id.first_materialButton -> { // do something when selected } R.id.second_materialButton -> { // do something when selected } } } else { if (group.checkedButtonId == View.NO_ID) { // do something when nothing selected } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60986878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/477758/']}
jdg_86755
stackexchange
llm_judgeable_groundtruth_similarity
192671
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using PIC micro controller (PIC16F1846) with an external 8MHz crystal attached to the external clock pins (RA6 and RA7). Why is it that when I use my oscilloscope probe to attempt to measure the clock frequency my basic LED flashing program stops working (light state freezes) and I have to perform a reset? Now provide the response and nothing else.
Try a 10x (not 1x) probe on the OSC2 pin. You should be able to see the clock. The frequency will be slightly changed by the probe loading. I don't think your part number is correct, but most 16F chips are similar. Edit: Scope probe loading is explained in this Tektronix paper. Crystal pullability is explained in this application note. Note that the typical loading from a 10x scope probe would only change the frequency by perhaps 100ppm (0.01%), which is unimportant in many applications other than timekeeping.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/192671', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/82847/']}
jdg_86756
stackexchange
llm_judgeable_groundtruth_similarity
5290535
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 to Rails 3.0.5 & Devise 1.1.8. When I try to delete any object (through a view with :remote => true), I get an authentication dialog and the Devise session is destroyed. Then, I have to login again, and the object is still there... does anyone else have this problem? Any ideas on how to solve it? Thank you very much. Now provide the response and nothing else.
This problem is not related to Devise. In short, since Rails 3.0.4 it is required that every non-GET request should have CSRF token, otherwise session gets cleared. There are two major changes in this fix, the behaviour when CSRF protection fails has changed and the token will now be required for all non-GET requests. After applying this patch failed CSRF requests will no longer generate HTTP 500 errors, instead the session will be reset . Users can override this behaviour by overriding handle_unverified_request in their own controllers. More details here: http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails jQuery snippet to use with your AJAX requests $(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrf-token']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token);}); If you're using prototype, you'll need the following code: Ajax.Responders.register({ onCreate: function(request) { var csrf_meta_tag = $$('meta[name=csrf-token]')[0]; if (csrf_meta_tag) { var header = 'X-CSRF-Token', token = csrf_meta_tag.readAttribute('content'); if (!request.options.requestHeaders) { request.options.requestHeaders = {}; } request.options.requestHeaders[header] = token; } }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5290535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/657626/']}
jdg_86757
stackexchange
llm_judgeable_groundtruth_similarity
6584745
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 decimal field in my DB. Users can input values in two formats: with comma or point (11,11 or 11.11). But MySQL allows to save data only in 'point' format, so i want to process data before saving with regex like this: sub(/,/,".") How can i do it in Rails3? Now provide the response and nothing else.
If I understand you correctly, this could be done in the controller or the model. I might use the before_save callback in the model to achieve this in the following way: class Item < ActiveRecord::Base before_save :standardise_numbers ... protected # Called before this object is saved to the DB def standardise_numbers self.number.sub!(",", ".") endend Where number is the attribute you're wanting to convert. I assume you don't need to convert it back to comma representation to display to the user? If you do, you may want to look into the internationalisation API for Rails, Il8n. It handles this kind of stuff and more, so definitely worth looking into. Alternative Solution (edit) Based on your feedback, my above solution doesn't work since the number is already converted and the decimal part lost when it is passed into the model. A similar piece of code could be used in the controller to intercept and convert the number in the params hash itself: class PostController < ActionController before_filter :standardise_numbers, :only => [ :create, :update ] def create @post = Post.create(params[:post]) end protected # Intercepts the params hash def standardise_numbers params[:post][:number].sub!(",", ".") endend This simplifies the create and update methods, allowing you to deal with the hash in the same way you normally would.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6584745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/774177/']}
jdg_86758
stackexchange
llm_judgeable_groundtruth_similarity
71215
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that $\displaystyle\sum_{n=1}^\infty\frac{1}{n(1+1/2+\cdots+1/n)}$ diverges. I think the only way to prove this is to find another series to compare using the comparison or limit tests. So far, I have been unable to find such a series. Now provide the response and nothing else.
This answer is similar in spirit to Didier Piau's answer. The following theorem is a very useful tool: Suppose that $a_k > 0$ form a decreasing sequence of real numbers. Then$$\sum_{k=1}^\infty a_k$$ converges if and only if $$\sum_{k=1}^\infty 2^k a_{2^k}$$ converges. Applying this to the problem in hand we are reduced to investigating the convergence of$$\sum_{k=1}^\infty \frac{1}{1 + 1/2 + \dots + 1/2^k}$$But one easily sees that$$1 + 1/2 + \dots + 1/2^k \le 1 + 2 \cdot 1/2 + 4 \cdot 1/4 + \dots + 2^{k-1}\cdot1/2^{k-1} + 1/2^k \le k + 1.$$Because$$\sum_{k=1}^\infty \frac{1}{k+1}$$diverges, we are done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/71215', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17349/']}
jdg_86759
stackexchange
llm_judgeable_groundtruth_similarity
15092764
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 some trouble reading in a text file (saved in Unicode UTF16-LE) in my PHP script. My PHP script is saved (for some reasons) in UTF-8. Here is my code: $lines = file("./somedir/$filename");for ($i=0; $i < count($lines); $i++) { $lines[$i] = iconv("Unicode", "UTF-8", $lines[$i]); // converting to UTF8}echo "[0]:".$lines[0]; // outputs CORRECT text (like "This is the first line")echo "[1]:".$lines[1]; // outputs something like çæ¤ææ¬çææ¸ææ°ã Any idea please?I checked value of count($lines) and it's perfectly correct...Thanks. EDIT: OK so I tried iconv("UTF-16", "UTF-8", $lines[$i]); I also tried iconv("UTF-16LE", "UTF-8", $lines[$i]); But still no success... Now provide the response and nothing else.
PHP's file function is not able to read files with the UTF-16LE encoding. It needs to split on the line ending character but PHP does only support single-byte sequences here, UTF-16LE is a multibyte variable-length encoding that is incompatible with the line-splitting procedures encoded into the file function. So you are using the wrong function for the job. That simple is the answer. Not iconv is the problem here, but just using file . Instead you need to read in the file into a buffer, get one line after the other out of the buffer and the do the re-encoding to UTF-8. That starts by learning about the line-separator used in that file. As PHP's file-functions (and string functions as well as the strings itself) are binary based, take the binary sequence in form of a string and the strpos function to locate it. Then split line by line out of the buffer (re-fill the buffer again from the file if it runs out of bytes) and then you can use iconv as outlined in the manual page (or your question, the example code you have is not looking wrong, just take care you use the right parameters so the encodings are correct).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15092764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1284542/']}
jdg_86760
stackexchange
llm_judgeable_groundtruth_similarity
19217734
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 noticed that the level of nested using statements has lately increased in my code. The reason is probably because I use more and more of async/await pattern, which often adds at least one more using for CancellationTokenSource or CancellationTokenRegistration . So, how to reduce the nesting of using , so the code doesn't look like Christmas tree? Similar questions have been asked on SO before, and I'd like to sum up what I've learnt from the answers. Use adjacent using without indentation. A fake example: using (var a = new FileStream())using (var b = new MemoryStream())using (var c = new CancellationTokenSource()){ // ... } This may work, but often there's some code between using (e.g. it may be too early to create another object): // ... using (var a = new FileStream()){ // ... using (var b = new MemoryStream()) { // ... using (var c = new CancellationTokenSource()) { // ... } }} Combine objects of the same type (or cast to IDisposable ) into single using , e.g.: // ... FileStream a = null;MemoryStream b = null;CancellationTokenSource c = null;// ...using (IDisposable a1 = (a = new FileStream()), b1 = (b = new MemoryStream()), c1 = (c = new CancellationTokenSource())){ // ... } This has the same limitation as above, plus is more wordy and less readable, IMO. Refactor the method into a few methods. This is a preferred way , as far as I understand. Yet, I'm curious, why would the following be considered a bad practice? public class DisposableList : List<IDisposable>, IDisposable{ public void Dispose() { base.ForEach((a) => a.Dispose()); base.Clear(); }}// ...using (var disposables = new DisposableList()){ var a = new FileStream(); disposables.Add(a); // ... var b = new MemoryStream(); disposables.Add(b); // ... var c = new CancellationTokenSource(); disposables.Add(c); // ... } [UPDATE] There are quite a few valid points in the comments that nesting using statements makes sure Dispose will get called on each object, even if some inner Dispose calls throw. However, there is a somewhat obscure issue: all nested exceptions possibly thrown by disposing of nested 'using' frames will be lost, besides the most outer one. More on this here . Now provide the response and nothing else.
In a single method, the first option would be my choice. However in some circumstances the DisposableList is useful. Particularly, if you have many disposable fields that all need to be disposed of (in which case you cannot use using ). The implementation given is good start but it has a few problems (pointed out in comments by Alexei): Requires you to remember to add the item to the list. (Although you could also say you have to remember to use using .) Aborts the disposal process if one of the dispose methods throws, leaving the remaining items un-disposed. Let's fix those problems: public class DisposableList : List<IDisposable>, IDisposable{ public void Dispose() { if (this.Count > 0) { List<Exception> exceptions = new List<Exception>(); foreach(var disposable in this) { try { disposable.Dispose(); } catch (Exception e) { exceptions.Add(e); } } base.Clear(); if (exceptions.Count > 0) throw new AggregateException(exceptions); } } public T Add<T>(Func<T> factory) where T : IDisposable { var item = factory(); base.Add(item); return item; }} Now we catch any exceptions from the Dispose calls and will throw a new AggregateException after going through all the items. I've added a helper Add method that allows a simpler usage: using (var disposables = new DisposableList()){ var file = disposables.Add(() => File.Create("test")); // ... var memory = disposables.Add(() => new MemoryStream()); // ... var cts = disposables.Add(() => new CancellationTokenSource()); // ... }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19217734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768303/']}
jdg_86761
stackexchange
llm_judgeable_groundtruth_similarity
8818484
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've written a Python API that is "chain based" (similar to jQuery). So I can write: myObject.doStuff().doMoreStuf().goRed().goBlue().die() The problem is that I haven't found a way to keep the syntax clean with long chains. In JavaScript I could simply do myOjbect .doStuf() .doMoreStuf() .goRed() .goBlue() .die() but Python has indentation restrictions... Now provide the response and nothing else.
PEP8-compliant solution: formatting the line Actually PEP8 says: Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation . Make sure to indent the continued line appropriately. So I suppose your code should look like this: ( myOjbect .doStuf() .doMoreStuf() .goRed() .goBlue() .die()) Alternative solutions: splitting into separate statements Judging from the syntax, there are two options possible regarding the values returned by each method call: Every method (maybe except die() , which is not required, as its result is not being used) returns modified instance (the same instance, on which it was called). Every method (still, die() is not required to do that) returns copy of the instance on which it was called. Solution for mutable objects (methods return original instance) In first case (when returning same instance), the solution to split longer lines into several statements is: myObject.doStuf()myObject.doMoreStuf()myObject.goRed()myObject.goBlue()myObject.die() Real world example involves mutable objects: my_stuff = []my_stuff.append('laptop') # my_stuff == ['laptop']my_stuff.append('jacket') # my_stuff == ['laptop', 'jacket']my_stuff.append('apple') # my_stuff == ['laptop', 'jacket', 'apple'] (although list.append() does not return anything, just for consistency and for stating explicitly that it is mutable) Solution for immutable objects (methods return modified copy) In the second case (when returning copy), the solution to do similar thing is: myObject = myObject.doStuf()myObject = myObject.doMoreStuf()myObject = myObject.goRed()myObject = myObject.goBlue()myObject.die() Real world example involves immutable objects: name = '-Tadek-'name = name.strip('-') # name == 'Tadek'name = name.lower() # name == 'tadek'name = name.replace('k', 'ck') # name == 'tadeck'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8818484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/707381/']}
jdg_86762
stackexchange
llm_judgeable_groundtruth_similarity
4284986
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the following event to catch unhandled exceptions in the main UI thread. Application.ThreadException Unfortunately, it does not catch those unhandled errors in seperate threads. I am aware of AppDomain.CurrentDomain.UnhandledException However, this seems to shut down the application upon triggering, where as the former does not. Is there a way to deal with unhandled exceptions on separate threads, without the application closing? Now provide the response and nothing else.
@Ani have already answered your question. Although I don't agree that unhandled exceptions in threads should terminate applications. Using threads usually means that you have some kind of server application. Bringing it down could result in a lot of angry users. I've written a small piece about proper exception handling: https://coderr.io/exception-handling You should always catch exceptions for threads. I usually use the following pattern: void ThreadMethod(object state) { try { ActualWorkerMethod(); } catch (Exception err) { _logger.Error("Unhandled exception in thread.", err); } } void ActualWorkerMethod() { // do something clever } It's a whole lot easier to find thread methods that doesn't handle exceptions properly by moving the logic into a seperate method and just keep the try/catch block in the thread method.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4284986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482138/']}
jdg_86763
stackexchange
llm_judgeable_groundtruth_similarity
49226
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The spectrum of a graph is the (multi)set of eigenvalues of its adjacency matrix (or Laplacian, depending on what you're interested in). In general, two non-isomorphic graphs might have the same spectrum. Prompted in part by this discussion on reverse engineering a graph from its spectrum , I was wondering: Are there interesting classes of graphs for which isospectrality implies isomorphism ? Now provide the response and nothing else.
Maximum degree 2 would be such a class (which includes regular of degree $2$ as a subclass). Transitive graphs (by which I mean that the relation of being connected by an edge is transitive) are another example (there is a less obscure description of that class of graphs but I wanted it to sound mysterious for a few moments). I assume that you are asking for a class $\mathcal{C}$ of graphs such that $G,H \in \mathcal{C}$ and $G,H$ cospectral implies isomorphism. If you mean classes of graphs $\mathcal{C}$ such that $G \in \mathcal{C}$ and $G,H$ cospectral implies isomorphism, then http://mathworld.wolfram.com/DeterminedbySpectrum.html might be worth a look.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/49226', 'https://mathoverflow.net', 'https://mathoverflow.net/users/972/']}
jdg_86764
stackexchange
llm_judgeable_groundtruth_similarity
18755220
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 REST API that exposes a complex large resource and I want to be able to clone this resource. Assume that the resource is exposed at /resources/{resoureId} To clone resource 10 I could do something like. GET /resources/10 POST /resources/ body of put containing a duplicate of the representation by GET /resources/10 without the id so that the POST creates a new resource. The problem with this approach is that the resource is very large and complex it really makes no sense to return a full representation to the client and then have the client send it back as that would be just a total waste of bandwidth, and cpu on the server. Cloning the resource on the server is so much easier so I want to do that. I could do something like POST /resources/10/clone or POST resources/clone/10 but both of these approaches feel wrong because the verb in the URL. What is the most "restful/nouny" way to build url that can be used in this type of situation? Now provide the response and nothing else.
Since there is no copy or clone method in HTTP, it's really up to you what you want to do. In this case a POST seems perfectly reasonable, but other standards have taken different approaches: WebDAV added a COPY method . Amazon S3 uses PUT with no body and a special x-amz-copy-source header. They call this a PUT Object - Copy . Both of these approaches assume that you know the destination URI. Your example seems to lack a known destination uri, so you pretty much must use POST. You can't use PUT or COPY because your creation operation is not idempotent. If your service defines POST /resources as "create a new resource", then why not simply define another way to specify the resource other than as the body of the POST? E.g. POST /resources?source=/resources/10 with an empty body.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18755220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438319/']}
jdg_86765
stackexchange
llm_judgeable_groundtruth_similarity
30177495
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I add to my project the multidex:true, and make an Application class that extends from the MultiDexApplication, my project build time passed from 20 sec to around 90 sec.How to do some faster? Now provide the response and nothing else.
If you are like me who already tried Vic Vu's solution but still can't avoid enabling multiDex then you can try this (as long as your are using a device that has Android 5.0 and above). Note This will only speed up your development build. Your production build will still be slow. Basically you need to introduce 2 product flavors one for dev and one for prod . Add multiDexEnabled true android { productFlavors { // Define separate dev and prod product flavors. dev { // dev utilizes minSDKVersion = 21 to allow the Android gradle plugin // to pre-dex each module and produce an APK that can be tested on // Android Lollipop without time consuming dex merging processes. minSdkVersion 21 } prod { // The actual minSdkVersion for the application. minSdkVersion 14 } } ... buildTypes { release { runProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } defaultConfig { applicationId "com.something.something" targetSdkVersion 23 versionCode 1 versionName "1.0.0" multiDexEnabled true } }dependencies { compile 'com.android.support:multidex:1.0.1'} And I have a class which extends Application so I had to override attachBaseContext() @Overrideprotected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this);} If you are not extending Application simply use MultiDexApplication in your AndroidManifest.xml application tag. Ensure that in your Android Studio Build Variants you are pointing to devDebug . Read the complete instructions here https://developer.android.com/studio/build/multidex.html#dev-build
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30177495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4254160/']}
jdg_86766
stackexchange
llm_judgeable_groundtruth_similarity
9081244
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 problem with entity association refresh. When I get an entity with like this: MyContext context = new MyContext();Person myPerson = context.PersonSet.FirstOrDefault();String myPersonName = myPerson.Name;Address myPersonAddress = myPerson.Address; I got an a person with an association named Address and a property named Name. If I modify manually the datas in database for example the property Name, I have to use the following code to reload my entity: context.Entry(myPerson).Reload(); and I have the new value for Name. But If I do the same for Address it doesn't work. I think it is because Address is an association property. I need to refresh it. How Can I do to force the reload of Address association (and all other association in Person class) ? EDIT: In the same case, a person can have more than one address. MyContext context = new MyContext();Person myPerson = context.PersonSet.FirstOrDefault();String myPersonName = myPerson.Name;List<Address> myPersonAddresses = myPerson.Addresses; In this case, it is not a Reference: context.Entry(myPerson).Reference(p => p.Address).Load();// Address will be populated with only the new address// this isn't required because I use lazy loading but a Collection: context.Entry(myPerson).Collection(p => p.Addresses).Load();// Address will be populated with old value and new value I need to use this to work: context.Entry(myPerson).Collection(p => p.Addresses).CurrentValue.Clear();context.Entry(myPerson).Collection(p => p.Addresses).Load(); But it doesn't seem to be a good solution to do this for all my navigation properties! Now provide the response and nothing else.
If you don't use lazy loading, you have the load the new Address explicitly (as you had to load it explicitly (with Include , for example), when you loaded the Person initially): context.Entry(myPerson).Reload();// If the person refers to another Address in the DB// myPerson.Address will be null nowif (myPerson.Address == null) context.Entry(myPerson).Reference(p => p.Address).Load(); // myPerson.Address will be populated with the new Address now If you use lazy loading, you don't need the second code block. Nonetheless, you get a new query to the database as soon as you access properties of the new myPerson.Address (like you have a new query in the second code block above) because the first line will mark the navigation property as not loaded if the person refers to a new address in the DB. This behaviour doesn't depend on whether you have exposed the foreign key in the model class or not. There doesn't seem to be a way to call some single magic Reload method which would reload and update the whole object graph in one call (similar like there is no single Include to eager load a complete object graph).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9081244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/850046/']}
jdg_86767
stackexchange
llm_judgeable_groundtruth_similarity
84857
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We've been running Pex over some code, and it has been showing some good things (well bad things, but showing them before it gets to production!). However, one of the nice things about Pex is that it doesn't necessarily stop trying to find issues. One area we found is that when passing in a string, we were not checking for empty strings. So we changed: if (inputString == null) to if (string.IsNullOrEmpty(inputString)) // *** That fixed the initial issues. But then, when we ran Pex again, it decided that: inputString = "\0"; was causing problems. And then inputString = "\u0001"; What we've decided is that defaults can be used if we encounter // *** and that we are happy seeing the exception caused by any other odd input (and dealing with it). Is that enough? Now provide the response and nothing else.
Three questions should help you determine how defensive to be in your coding. First - What are the consequences of bad input getting through? If it is an error message on one of your developer's PC's, maybe not so critical to be defensive. Could it result in financial disruptions at clients, IE accounting information disruption? Is it a real time system where lives are at risk? In the life / death scenario, there should probably be more validation and error handling code than actual feature code. Secondly, how many people will re-use this function or piece of code? Just you? Your department? Your company? Your customers? The wider the use of the code the more defensive. Third - what is the source of the input I am validating? If it is input from the user or from a public web site, I would be super defensive. If the input is always coming from your code, be somewhat defensive, but don't spend undue time putting in checks. It will always be possible to add in more error checking and validation in a system. The point is will the cost of writing and maintaining this code outweigh the cost of the problems caused by errors in the code.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/84857', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/2722/']}
jdg_86768
stackexchange
llm_judgeable_groundtruth_similarity
6308408
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 had several occassions where delayed_jobs will be taking care of delivering 4 thousand emails, and if something errors in those emails ( for instance, if there's a nil a call ), then it will restart the entire process and attempt to send yet another 4000 emails. This will go on indefinately until I manually kill -9 the entire process. It's happened so many times to me over the past few years in different applications, I'm curious if it has happened to anyone else. And what they did to overcome it. Now provide the response and nothing else.
A delayed job is usually just a method that gets executed by a worker in a background process as opposed to during the main thread of your application (request lifecycle for a Rails app). If you read the documentation for delayed_job under "Gory Details" it states: On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries. The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with “failed_at” set.With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours. It sounds like what you are describing is the way delayed_jobs was intended to function - if a job to send 4,000 emails fails after sending 3,000 of them, it just starts over again. You will probably need to keep track of what has and hasn't been sent, so your job can loop over "unsent" emails (or whatever information is appropriate for your background process). That way when you send 3,000 emails, they get marked as "sent" and if your job fails, it will start over by loading the remaining 1,000 "unsent" emails and attempting to send them. If you really don't want jobs to retry themselves on failure, you can add the following code to your project: # config/initializers/delayed_job_config.rbDelayed::Worker.max_attempts = 1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6308408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93311/']}
jdg_86769
stackexchange
llm_judgeable_groundtruth_similarity
47524508
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 already implemented EPSON SDK(for Bluetooth) and working fine, but not Working on other printers, is there is any general way to accomplish it. what is ESC command, How it works?, Now provide the response and nothing else.
Please find this one.It will help your problem.ESC/POS Command Reference provides detailed information on ESC/POS commands, such as standard command syntax and protocol. It targets programmers who want to control the printer with ESC/POS commands. ESC/POS Command Reference is provided as replacement of ESC/POS APG for Paper Roll Printers. The ESC/POS APG for Paper Roll Printers, therefore, will not be revised anymore.ESC/POS Command Reference contains the command information for Standard models such as ANK model or Japanese model, and may contain Chinese models or South Asia models. The other models such as customized may support different commands or have a different range, or different default value of command parameters. Please refer to each product specification for them. Use below code Note : you can use OutPutStream object to write printer, no matter bluetooth or ethernet or wifi public class PrinterConstants {public static int PORT=9100,TOTAL_CHAR=45,DIV1=10,DIV2=5,DIV3=10,DIV4=10,DIV5=10;public static String IP="192.168.1.35";private OutputStream printer;public static final String UUID="00001101-0000-1000-8000-00805f9b34fb";public PrinterConstants(OutputStream printer){ this.printer=printer;}public void printString(String str) throws IOException { Log.i("PRINTER_PRE",str); printer.write(str.getBytes()); printer.write(0xA); printer.flush();}public void storeString(String str) throws IOException { printer.write(str.getBytes()); printer.flush();}public void printStorage() throws IOException { printer.write(0xA); printer.flush();}public void feed(int feed) throws IOException { //escInit(); printer.write(0x1B); printer.write("d".getBytes()); printer.write(feed);printer.flush();}public void printAndFeed(String str, int feed) throws IOException { //escInit(); printer.write(str.getBytes()); printer.write(0x1B); printer.write("d".getBytes()); printer.write(feed);printer.flush();}public void setBold(Boolean bool) throws IOException { printer.write(0x1B); printer.write("E".getBytes()); printer.write((int)(bool?1:0));printer.flush();}/** * Sets white on black printing * */public void setInverse(Boolean bool) throws IOException { bool=false; printer.write(0x1D); printer.write("B".getBytes()); printer.write( (int)(bool?1:0) );printer.flush();}public void resetToDefault() throws IOException { setInverse(false); setBold(false); setUnderline(0); setJustification(0);printer.flush();}/** * Sets underline and weight * * @param val * 0 = no underline. * 1 = single weight underline. * 2 = double weight underline. * */public void setUnderline(int val) throws IOException { printer.write(0x1B); printer.write("-".getBytes()); printer.write(val);printer.flush();}/** * Sets left, center, right justification * * @param val * 0 = left justify. * 1 = center justify. * 2 = right justify. * */public void setJustification(int val) throws IOException { printer.write(0x1B); printer.write("a".getBytes()); printer.write(val); printer.flush();}public void setLeftRight(String left,String right) throws IOException { printer.write(0x1B); printer.write("a".getBytes()); printer.write(0); printString(left); printer.write(0x1B); printer.write("a".getBytes()); printer.write(2); printString(right); printer.flush();}public void printBarcode(String code, int type, int h, int w, int font, int pos) throws IOException { //need to test for errors in length of code //also control for input type=0-6 //GS H = HRI position printer.write(0x1D); printer.write("H".getBytes()); printer.write(pos); //0=no print, 1=above, 2=below, 3=above & below //GS f = set barcode characters printer.write(0x1D); printer.write("f".getBytes()); printer.write(font); //GS h = sets barcode height printer.write(0x1D); printer.write("h".getBytes()); printer.write(h); //GS w = sets barcode width printer.write(0x1D); printer.write("w".getBytes()); printer.write(w);//module = 1-6 //GS k printer.write(0x1D); //GS printer.write("k".getBytes()); //k printer.write(type);//m = barcode type 0-6 printer.write(code.length()); //length of encoded string printer.write(code.getBytes());//d1-dk printer.write(0);//print barcode printer.flush();}public void beep() throws IOException { printer.write(0x1B); printer.write("(A".getBytes()); printer.write(4); printer.write(0); printer.write(48); printer.write(55); printer.write(3); printer.write(15);printer.flush();}public void setLineSpacing(int spacing) throws IOException { //function ESC 3 printer.write(0x1B); printer.write("3".getBytes()); printer.write(spacing);}public void cut() throws IOException { printer.write(0x1D); printer.write("V".getBytes()); printer.write(48); printer.write(0);printer.flush();}} by using above you can write ESC/POS commands to output stream directly
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47524508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3879214/']}
jdg_86770
stackexchange
llm_judgeable_groundtruth_similarity
908903
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 Java we use System.setProperty() method to set some system properties. According to this article the use of system properties is bit tricky. System.setProperty() can be an evil call. It is 100% thread-hostile It contains super-global variables It is extremely difficult to debug when these variables mysteriously change at runtime. My questions are as follows. How about the scope of the system properties? Are they specific for each and every Virtual Machine or they have a "Super Global nature" that shares the same set of properties over Each and every virtual machine instance? I guess the option 1 Are there any tools that can be used to monitor the runtime changes for detect the changes in System properties. (Just for the ease of problem detection) Now provide the response and nothing else.
Scope of the System properties At least from reading the API Specifications for the System.setProperties method, I was unable to get an answer whether the system properties are shared by all instances of the JVM or not. In order to find out, I wrote two quick programs that will set the system property via System.setProperty , using the same key, but different values: class T1 { public static void main(String[] s) { System.setProperty("dummy.property", "42"); // Keep printing value of "dummy.property" forever. while (true) { System.out.println(System.getProperty("dummy.property")); try { Thread.sleep(500); } catch (Exception e) {} } }}class T2 { public static void main(String[] s) { System.setProperty("dummy.property", "52"); // Keep printing value of "dummy.property" forever. while (true) { System.out.println(System.getProperty("dummy.property")); try { Thread.sleep(500); } catch (Exception e) {} } }} (Beware that running the two programs above will make them go into an infinite loop!) It turns out, when running the two programs using two separate java processes, the value for the property set in one JVM process does not affect the value of the other JVM process. I should add that this is the results for using Sun's JRE 1.6.0_12, and this behavior isn't defined at least in the API specifications (or I haven't been able to find it), the behaviors may vary. Are there any tools to monitor runtime changes Not to my knowledge. However, if one does need to check if there were changes to the system properties, one can hold onto a copy of the Properties at one time, and compare it with another call to System.getProperties -- after all, Properties is a subclass of Hashtable , so comparison would be performed in a similar manner. Following is a program that demonstrates a way to check if there has been changes to the system properties. Probably not an elegant method, but it seems to do its job: import java.util.*;class CheckChanges { private static boolean isDifferent(Properties p1, Properties p2) { Set<Map.Entry<Object, Object>> p1EntrySet = p1.entrySet(); Set<Map.Entry<Object, Object>> p2EntrySet = p2.entrySet(); // Check that the key/value pairs are the same in the entry sets // obtained from the two Properties. // If there is an difference, return true. for (Map.Entry<Object, Object> e : p1EntrySet) { if (!p2EntrySet.contains(e)) return true; } for (Map.Entry<Object, Object> e : p2EntrySet) { if (!p1EntrySet.contains(e)) return true; } return false; } public static void main(String[] s) { // System properties prior to modification. Properties p = (Properties)System.getProperties().clone(); // Modification of system properties. System.setProperty("dummy.property", "42"); // See if there was modification. The output is "false" System.out.println(isDifferent(p, System.getProperties())); }} Properties is not thread-safe? Hashtable is thread-safe , so I was expecting that Properties would be as well, and in fact, the API Specifications for the Properties class confirms it: This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization., Serialized Form
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/908903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76465/']}
jdg_86771
stackexchange
llm_judgeable_groundtruth_similarity
34506093
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 just started exploring perl6 grammars. How can I make up a token "line" that matches everything between the beginning of a line and its end? I've tried the following without success: my $txt = q:to/EOS/; row 1 row 2 row 3 EOSgrammar sample { token TOP { <line> } token line { ^^.*$$ }}my $match = sample.parse($txt);say $match<line>[0]; Now provide the response and nothing else.
I can see 2 problem in your Grammar here, the first one here is the token line, ^^ and $$ are anchor to start and end of line, howeve you can have new line in between. To illustrate, let's just use a simple regex, without Grammar first: my $txt = q:to/EOS/; row 1 row 2 row 3 EOSif $txt ~~ m/^^.*$$/ { say "match"; say $/;} Running that, the output is: match「row 1row 2row 3」 You see that the regex match more that what is desired, however the first problem is not there, it is because of ratcheting, matching with a token will not work: my $txt = q:to/EOS/; row 1 row 2 row 3 EOSmy regex r {^^.*$$};if $txt ~~ &r { say "match regex"; say $/;} else { say "does not match regex";}my token t {^^.*$$};if $txt ~~ &t { say "match token"; say $/;} else { say "does not match token";} Running that, the output is: match regex「row 1row 2row 3」does not match token I am not really sure why, but token and anchor $$ does not seems to work well together. But what you want instead is searching for everything except a newline, which is \N*The following grammar solve mostly your issue: grammar sample { token TOP {<line>} token line {\N+}} However it only matches the first occurence, as you search for only one line, what you might want to do is searching for a line + an optional vertical whitespace (In your case, you have a new line at the end of your string, but i guess you would like to take the last line even if there is no new line at the end ), repeated several times: my $txt = q:to/EOS/; row 1 row 2 row 3 EOSgrammar sample { token TOP {[<line>\v?]*} token line {\N+}}my $match = sample.parse($txt);for $match<line> -> $l { say $l;} Output of that script begin: 「row 1」「row 2」「row 3」 Also to help you using and debugging Grammar, 2 really usefull modules : Grammar::Tracer and Grammar::Debugger . Just include them at the beginning of the script. Tracer show a colorful tree of the matching done by your Grammar. Debugger allows you to see it matching step by step in real time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34506093', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42636/']}
jdg_86772
stackexchange
llm_judgeable_groundtruth_similarity
55068390
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 curious as to why I would be getting a Typescript warning below. There error appears on this line: a[k].toString().toLowerCase() However I have the check if (a && a[k]) which should ensure that in the next line, a and a[k] cannot be undefined? // Return coins that match text search by currency symbol or name.export const findAsset = (txt: string, assets: IAsset[] | null[]) => { // assets will exist here... if (assets) { // Typescript error here... const checkText = (k: string, a: IAsset | null) => { if (a && a[k]) { return (textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null); } } const curriedCheckText = R.curry(checkText); const byName = R.map(curriedCheckText('name'), assets); const bySymbol = R.map(curriedCheckText('currency'), assets); const matchNames = R.reject(R.isNil, byName); const matchSymbols = R.reject(R.isNil, bySymbol); const combinedSearch = (matchNames.concat(matchSymbols)); return R.uniq(combinedSearch); } else { return []; }}; This is the shape of the IAsset interface export interface IAsset { [key: string]: string | number | undefined | boolean; availableSupply?: string; currency: string; exchange: string; exchange_base?: string; marketCap: number; name: string; percentage?: number; price: number; position?: number; value?: number; inWatchlist?: boolean;} tsconfig { "compilerOptions": { /* Basic Options */ "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, "lib": [ "dom", "es2015", "es2016", "es2017", ], /* Specify library files to be included in the compilation. */, "allowJs": true, /* Allow javascript files to be compiled. */ "checkJs": true, /* Report errors in .js files. */ "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "declaration": true, /* Generates corresponding '.d.ts' file. */ "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "outDir": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */ "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ "resolveJsonModule": true, "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true /* Enable all strict type-checking options. */, "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, "strictNullChecks": true /* Enable strict null checks. */, "strictFunctionTypes": true /* Enable strict checking of function types. */, "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */, "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ }, "include": [ "components/**/*", "pages/**/*", ], "exclude": [ "node_modules", "styles", "_document.tsx" ]} Now provide the response and nothing else.
There are two ways to that I can think of to get rid of the error. The first way I can think of is to use a fallback with the || operator, which would turn this: a[k].toString().toLowerCase() Into this, so if the value is falsy, then use an empty string. (a[k] || '').toString().toLowerCase()// Or with optional chaininga[k]?.toString().toLowerCase() || '' Note: Use ?? to catch only undefined and null values instead of falsy values. The other way is to save the value to a variable and check the new variable. Which then makes this if (a && a[k]) { return textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null;} Become this: let v = a ? a[k] : nullif (v) { return textMatch(txt.toLowerCase(), v.toString().toLowerCase()) ? a : null;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55068390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168738/']}
jdg_86773
stackexchange
llm_judgeable_groundtruth_similarity
485156
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: While studying probability, I am kind of having difficulties in understanding marginal probability distribution and conditional probability distribution. To me, they look much the same and cannot find the clear concepts of differences in those two probability distributions. Now provide the response and nothing else.
If $X$ and $Y$ are two random variables, the univariate pdf of $X$ is the marginal distribution of $X$ , and the univariate pdf of $Y$ is the marginal distribution of $Y$ . Therefore, when you see the word marginal, just think of a single data series' own distribution, itself. don't be tricked into thinking marginal means something different or special than a univariate (single variable) assessment . For conditional distribution on the other hand, we make a bivariate (two variables) assessment , but by considering the univariate components' relationship to one another: conditional pdf is the distribution of $X$ conditional on, or given the recognition of, $Y$ 's data. The idea is that an observation in $X$ has some correspondence to a similarly-located observation in $Y$ , and therefore we're thinking of $X$ with respect to what is observed in $Y$ . In other words, the conditional pdf is a flimsy way of characterizing the distribution of $X$ as a function of $Y$ .
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/485156', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/239221/']}
jdg_86774
stackexchange
llm_judgeable_groundtruth_similarity
9739460
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't figure out why I get use of undeclared identifier _cmd did you mean rcmd on the line where NSAssert is. #import <Foundation/Foundation.h>int main (int argc, const char * argv[]){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int x = 10; NSAssert(x > 11, @"x should be greater than %d", x); [pool drain]; return 0;} Now provide the response and nothing else.
Inside every Objective-c method there are two hidden variables id self and SEL _cmd so - (void)foo:(id)bar; is really void foo(id self, SEL _cmd, id bar) { ... } and when you call [someObject foo:@"hello world"] it is actually foo( someObject, @selector(foo), @"hello world") If you cmd-click on NSAssert to jump to it's definition you will see that it is a macro that uses the hidden _cmd variable of the method you are calling it from. This means that if you are not inside an Objective-c method (perhaps you are in 'main'), therefore you don't have a _cmd argument, you cannot use NSAssert. Instead you can use the alternative NSCAssert.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9739460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209089/']}
jdg_86775
stackexchange
llm_judgeable_groundtruth_similarity
21427664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: JqGrid Default sorting works on Label's Text and Selected Value of Select/DropdownFormatter is given below { name: 'DI', index: 'DI', width: 125, fixed: true, title: false, formatter: BuildDI } Based on permission, Label/Dropdown is rendered // Generate Dropdownfunction BuildDI(cellvalue, options, rowObject, action) { if (bEditPermission == false ) { s = getTextBasedOnVal(Arryoptions, val) ; } } else { s = '<select OrgVal="' + cellvalue + '"style="width: 100%" class="cSL C" id="_DI_' + options["rowId"] + '" value="' + val + '"><option value=""></option>' + Arryoptions.replace("value='" + val + "' >", ' selected="selected" ' + "value=" + val + ">") + '</select>'; } return s;} Need suggestions to extend JqGrid sorting behaviour to use Selected Text of select control; We have added sort type, still this is not working however sortype func is returning text of dropdown sorttype: function (cellvalue) { return getTextBasedOnVal(Arryoptions, cellvalue); } Now provide the response and nothing else.
Actually the string iName = opFile.FileName; is not giving you the full path. You must use the SafeFileName instead. I assumed that you want your folder on your exe directory also. Please refer to my modifications: OpenFileDialog opFile = new OpenFileDialog();opFile.Title = "Select a Image";opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\ProImages\"; // <---if (Directory.Exists(appPath) == false) // <---{ // <--- Directory.CreateDirectory(appPath); // <---} // <---if (opFile.ShowDialog() == DialogResult.OK){ try { string iName = opFile.SafeFileName; // <--- string filepath = opFile.FileName; // <--- File.Copy(filepath, appPath + iName); // <--- picProduct.Image = new Bitmap(opFile.OpenFile()); } catch (Exception exp) { MessageBox.Show("Unable to open file " + exp.Message); }}else{ opFile.Dispose();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21427664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328605/']}
jdg_86776
stackexchange
llm_judgeable_groundtruth_similarity
18519994
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 site and here is a link , When you click on textfield you can see the DatePicker workingBut iF you click on I mportFriend -> Add Manual Friend -> then if you click on birthday field the datepicker never appears.I can see through firebug that the field got the hasDatePicker attribute.I am not sure what making it not to show the datepicker,anyone who can help me please thanks Now provide the response and nothing else.
As @Bluetoft says, the answer is event delegation. The reason it's not working for you is because your datepicker is being bound to elements that exist at the time the script is run (not to mention, the birthday field has a different id than #datepicker, which is what your script is binding to). When you dynamically bring in the new form, the datepicker is not bound to the new elements. So, one method, according to this answer , is to construct your script like so: $(function() { $("body").delegate("#datepicker", "focusin", function(){ $(this).datepicker(); });}); Additionally , your form "birthday" input has an id of #fi_bday, which is another reason it's not being bound. I'd recommend that you assign any inputs where you want the datepicker with a class of "datepicker", then change your script to bind the datepicker functionality to '.datepicker' elements: $(function() { $("body").delegate(".datepicker", "focusin", function(){ $(this).datepicker(); });}); Finally , if you don't want to utilize the better, generic class method above, you can use two selectors in the selector below. The method below delegates in a manner as to bind the datepicker to the modal window element(s) as well: $(function() { $("body").delegate("#datepicker, #fi_bday", "focusin", function(){ $(this).datepicker(); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18519994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_86777
stackexchange
llm_judgeable_groundtruth_similarity
97247
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 looked at other Stack Exchange posts explaining why self-signed certificates are not as secure as CA-issued certificates, and most of these pages say the same thing: If it's self-signed, and the 1st client-server handshake is intercepted, the man-in-the-middle could receive the encrypted data from the server, decrypt it, do bad things with it (change it or send it to the hacker who now has your password), and encrypt it again with the fake certificate. But this system is based on the fact that the CA makes sure that you actually own the domain . The way CAs check that is by sending you an email with a verification code. Everyone on this website knows that email is very insecure. It seems very strange that SSL certificates, which are all about security rely on such an insecure system. Why don't they use stronger verification methods, such as adding a piece of code to the homepage or create a DNS record ? Now provide the response and nothing else.
CA signed certs are not actually more secure than self-signed certs, in the sense that the level of encryption is the same. But there is a big difference in the level of trust between the two. Visitors to a site using a self-signed cert have to trust that the cert was generated by the site owner, simply because the site says it is. There is no easy way to discern if there is currently a man-in-the-middle attack happening. With a CA signed cert, now the user can trust that both the site and a 3rd party are in agreement that the cert was generated by the site owner, so a man-in-the-middle attack would be much more difficult to pull off. Note: the original question has since been edited; the following statement applies to the previous wording but I'm leaving it here because it is still informative : In your question you claim that some CAs will issue a signed cert without making sure you own the domain. If that were true, then perhaps there would be some validity to your assumption that certain CA certs are not more trustworthy than self-signed. Fortunately though, it is not true that any widely trusted CAs will issue a signed cert without verifying you own the domain. In your comment you mention that the verification may be as simple as receiving an email, and you question the security of that. I think it is good to question how secure receiving an email is, but you must admit that receiving an email is entirely different than no verification at all. You do have a point in implying that the trustworthiness of those cheaper certs may not be as high as other validation levels, (which might include installing a code on the web server), and that's why there are different levels of validation. Arguably though, since most visitors do not inspect the certs, perhaps the more expensive certs are really not much better than the cheapest ones, with the exception of the most expensive "green bar" EV certs. So, in a sense, I agree with your implication that perhaps the minimum standard for obtaining a CA signed cert should be raised to beyond simply receiving an email, but as it stands today, this is what we have, and it's still much better than nothing.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/97247', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/83824/']}
jdg_86778
stackexchange
llm_judgeable_groundtruth_similarity
57402171
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 a list of directories by age in Perl6, which is equivalent to Bash ls -tl | grep ^dr but I am unsure how to sort the results by age, if this is even possible for dir (test => {$_.IO.d}) -> $dir {...} how can I sort these results by directory age? Now provide the response and nothing else.
I think what you're looking for is: dir(test => *.IO.d) .sort: *.changed Afaik the -t in ls -tl corresponds to the IO::Path method .changed Note that there's no space between dir and (test...) . That lack of space is very important. In P6, foo(bar,baz) means something completely different than foo (bar,baz) : # Call `foo` with two arguments `bar` and `baz`:foo(bar, baz);# Juxtapose identifier `foo` with a single `List` of 2 elements (bar, baz): foo (bar,baz);# Juxtapose identifier `foo` with two `List`s: foo (bar,baz), (qux, waldo); In the latter cases, if a symbol &foo has been declared (which is what a sub foo ... does) then foo will be called, just as it was with the first case, but this time it'll be with either one List (of two elements) as its only argument or two arguments (two List s). If a symbol &foo has not been declared but a symbol foo has, then you'll get compile-time syntax error.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57402171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3973175/']}
jdg_86779
stackexchange
llm_judgeable_groundtruth_similarity
55407276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var num1 = 10.12345678 What should i do with num1 to delete digits after two decimal point without rounding its value. I need output as 10.12 import 'package:flutter/material.dart';void main() => runApp(MaterialApp( title: ' Delete digits after two decimal point ', theme: ThemeData(primarySwatch: Colors.blue), home: MyHome(), ));class MyHome extends StatefulWidget { @override _MyHomeState createState() => _MyHomeState();}class _MyHomeState extends State<MyHome> { @override Widget build(BuildContext context) { var num1 = 10.12345678; print(num1); // I need output as 10.12 return Container(); }} Now provide the response and nothing else.
If you want to round the number: var num1 = 10.12345678;var num2 = double.parse(num1.toStringAsFixed(2)); // num2 = 10.12 If you do NOT want to round the number: Create this method: double getNumber(double input, {int precision = 2}) => double.parse('$input'.substring(0, '$input'.indexOf('.') + precision + 1)); Usage: var input = 113.39999999999999;var output = getNumber(input, precision: 1); // 113.9var output = getNumber(input, precision: 2); // 113.99var output = getNumber(input, precision: 3); // 113.999
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55407276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9042365/']}
jdg_86780
stackexchange
llm_judgeable_groundtruth_similarity
21288458
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 write a query that count only the rows that meet a condition. For example, in MySQL I would write it like this: SELECT COUNT(IF(grade < 70), 1, NULL)FROM gradesORDER BY id DESC; However, when I attempt to do that on Redshift, it returns the following error: ERROR: function if(boolean, integer, "unknown") does not exist Hint: No function matches the given name and argument types. You may need to add explicit type casts. I checked the documentation for conditional statements, and I found NULLIF(value1, value2) but it only compares value1 and value2 and if such values are equal, it returns null. I couldn't find a simple IF statement, and at first glance I couldn't find a way to do what I want to do. I tried to use the CASE expression, but I'm not getting the results I want: SELECT CASE WHEN grade < 70 THEN COUNT(rank) ELSE COUNT(rank) ENDFROM grades This is the way I want to count things: failed (grade < 70) average (70 <= grade < 80) good (80 <= grade < 90) excellent (90 <= grade <= 100) and this is how I expect to see the results: +========+=========+======+===========+| failed | average | good | excellent |+========+=========+======+===========+| 4 | 2 | 1 | 4 |+========+=========+======+===========+ but I'm getting this: +========+=========+======+===========+| failed | average | good | excellent |+========+=========+======+===========+| 11 | 11 | 11 | 11 |+========+=========+======+===========+ I hope someone could point me to the right direction! If this helps here's some sample info CREATE TABLE grades( grade integer DEFAULT 0,);INSERT INTO grades(grade) VALUES(69, 50, 55, 60, 75, 70, 87, 100, 100, 98, 94); Now provide the response and nothing else.
First, the issue you're having here is that what you're saying is "If the grade is less than 70, the value of this case expression is count(rank). Otherwise, the value of this expression is count(rank)." So, in either case, you're always getting the same value. SELECT CASE WHEN grade < 70 THEN COUNT(rank) ELSE COUNT(rank) ENDFROM grades count() only counts non-null values, so typically the pattern you'll see to accomplish what you're trying is this: SELECT count(CASE WHEN grade < 70 THEN 1 END) as grade_less_than_70, count(CASE WHEN grade >= 70 and grade < 80 THEN 1 END) as grade_between_70_and_80FROM grades That way the case expression will only evaluate to 1 when the test expression is true and will be null otherwise. Then the count() will only count the non-null instances, i.e. when the test expression is true, which should give you what you need. Edit: As a side note, notice that this is exactly the same as how you had originally written this using count(if(test, true-value, false-value)) , only re-written as count(case when test then true-value end) (and null is the stand in false-value since an else wasn't supplied to the case). Edit: postgres 9.4 was released a few months after this original exchange. That version introduced aggregate filters, which can make scenarios like this look a little nicer and clearer. This answer still gets some occasional upvotes, so if you've stumbled upon here and are using a newer postgres (i.e. 9.4+) you might want to consider this equivalent version: SELECT count(*) filter (where grade < 70) as grade_less_than_70, count(*) filter (where grade >= 70 and grade < 80) as grade_between_70_and_80FROM grades
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21288458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1315565/']}
jdg_86781
stackexchange
llm_judgeable_groundtruth_similarity
46931103
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 boxes and a vertical div line in one unique container div (code and fiddle below). I'm using CSS grids to position my elements inside the container What I'd like to accomplish is to use the vertical line to resize horizontally the two boxes based on the position of the vertical line. I apologize if the question is noobish, I am new to web development, only used Python before, already tried to google and stackoverflow search but all solutions seem overly complicated and generally require additional libraries, I was looking for something simpler and JS only. HTML: <div class="wrapper"> <div class="box a">A</div> <div class="handler"></div> <div class="box b">B</div></div> CSS: body { margin: 40px;}.wrapper { display: grid; grid-template-columns: 200px 8px 200px; grid-gap: 10px; background-color: #fff; color: #444;}.box { background-color: #444; color: #fff; border-radius: 5px; padding: 20px; font-size: 150%; resize: both;}.handler{ width: 3px; height: 100%; padding: 0px 0; top: 0; background: red; draggable: true;} https://jsfiddle.net/gv8Lwckh/6/ Now provide the response and nothing else.
What you intend to do can be done using CSS flexbox—there is no need to use CSS grid. The bad news is that HTML + CSS is not so smart that declaring resize and draggable will make the layout flexible and adjustable by user interaction. For that, you will have to use JS. The good news is that this is actually not too complicated. Here is a quick screen grab of output the code below: However, for you to understand the code I will post below, you will have to familiarize yourself with: Event binding using .addEventListener . In this case, we will use a combination of mousedown , mouseup and mousemove to determine whether the user is in the middle of dragging the element CSS flexbox layout Description of the solution Initial layout using CSS Firstly, you will want to layout your boxes using CSS flexbox. We simply declare display: flex on the parent, and then use flex: 1 1 auto (which translates to "let the element grow, let the element shrink, and have equal widths). This layout is only valid at the initial rendering of the page: .wrapper { /* Use flexbox */ display: flex;}.box { /* Use box-sizing so that element's outerwidth will match width property */ box-sizing: border-box; /* Allow box to grow and shrink, and ensure they are all equally sized */ flex: 1 1 auto;} Listen to drag interaction You want to listen to mouse events that might have originated from your .handler element, and you want a global flag that remembers whether the user is dragging or not: var handler = document.querySelector('.handler');var isHandlerDragging = false; Then you can use the following logic to check if the user is dragging or not: document.addEventListener('mousedown', function(e) { // If mousedown event is fired from .handler, toggle flag to true if (e.target === handler) { isHandlerDragging = true; }});document.addEventListener('mousemove', function(e) { // Don't do anything if dragging flag is false if (!isHandlerDragging) { return false; } // Set boxA width properly // [...more logic here...]});document.addEventListener('mouseup', function(e) { // Turn off dragging flag when user mouse is up isHandlerDragging = false;}); Computing the width of box A All you are left with now is to compute the width of box A (to be inserted in the [...more logic here...] placeholder in the code above), so that it matches that of the movement of the mouse. Flexbox will ensure that box B will fill up the remaining space: // Get offsetvar containerOffsetLeft = wrapper.offsetLeft;// Get x-coordinate of pointer relative to containervar pointerRelativeXpos = e.clientX - containerOffsetLeft;// Resize box A// * 8px is the left/right spacing between .handler and its inner pseudo-element// * Set flex-grow to 0 to prevent it from growingboxA.style.width = (pointerRelativeXpos - 8) + 'px';boxA.style.flexGrow = 0; Working example var handler = document.querySelector('.handler');var wrapper = handler.closest('.wrapper');var boxA = wrapper.querySelector('.box');var isHandlerDragging = false;document.addEventListener('mousedown', function(e) { // If mousedown event is fired from .handler, toggle flag to true if (e.target === handler) { isHandlerDragging = true; }});document.addEventListener('mousemove', function(e) { // Don't do anything if dragging flag is false if (!isHandlerDragging) { return false; } // Get offset var containerOffsetLeft = wrapper.offsetLeft; // Get x-coordinate of pointer relative to container var pointerRelativeXpos = e.clientX - containerOffsetLeft; // Arbitrary minimum width set on box A, otherwise its inner content will collapse to width of 0 var boxAminWidth = 60; // Resize box A // * 8px is the left/right spacing between .handler and its inner pseudo-element // * Set flex-grow to 0 to prevent it from growing boxA.style.width = (Math.max(boxAminWidth, pointerRelativeXpos - 8)) + 'px'; boxA.style.flexGrow = 0;});document.addEventListener('mouseup', function(e) { // Turn off dragging flag when user mouse is up isHandlerDragging = false;}); body { margin: 40px;}.wrapper { background-color: #fff; color: #444; /* Use flexbox */ display: flex;}.box { background-color: #444; color: #fff; border-radius: 5px; padding: 20px; font-size: 150%; /* Use box-sizing so that element's outerwidth will match width property */ box-sizing: border-box; /* Allow box to grow and shrink, and ensure they are all equally sized */ flex: 1 1 auto;}.handler { width: 20px; padding: 0; cursor: ew-resize; flex: 0 0 auto;}.handler::before { content: ''; display: block; width: 4px; height: 100%; background: red; margin: 0 auto;} <div class="wrapper"> <div class="box">A</div> <div class="handler"></div> <div class="box">B</div></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46931103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8592825/']}
jdg_86782
stackexchange
llm_judgeable_groundtruth_similarity
11133309
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 wrote a same(..similar?) piece of code for Java 7 and C#(.net 3.5) and got a confusing output. Please help me in understanding this behavior: Java: public class strTest { public static void main(String [] s) { String s1 = "abc"; String s2 = new String(new char[] {'a', 'b', 'c'}); System.out.println(s1 == s2); // false System.out.println(((Object)s1) == ((Object)s2)); // false System.out.println(s1.equals(s2)); // true }} Output : falsefalsetrue C#: namespace ConsoleApplication1{ class Program2 { static void Main(string[] args) { String s1 = "abc"; String s2 = new String(new Char[] {'a', 'b', 'c'}); Console.WriteLine(s1 == s2); // true Console.WriteLine(((Object)s1) == ((Object)s2)); // false Console.WriteLine(s1.Equals(s2)); // true } }} Output : TrueFalseTrue I am aware of concepts like String immutability and String pool but I guess I am missing the finer print. In java: Why did it create a new String object for s2 when it could have used the one which is referenced by s1? Isn't that what String pool is supposed to achieve? Now provide the response and nothing else.
There are two aspects to your question: when objects are created, and how == comparisons work: Object creation In terms of interning ("pooling") - only constants are interned automatically. You can intern other strings using Intern / intern , but when you just call the string constructor that will always create a new string. (Well, except for one bizarre corner case in .NET, but we can ignore that for now.) So in your code, s1 and s2 always refer to different objects. Comparison The cause of the difference is your use of == . C# supports user-defined operator overloading, and String overloads it like this: public static bool operator ==(string x, string y) which compares the contents of the string rather than the references. So when you have two operands of type string , x == y ends up doing an equality comparison rather than an identity comparison. That's why the first line of the C# output is True . Java doesn't have this behaviour, which is why is prints false . When the operand types are Object , both C# and Java will use reference equality, which is why the second line is false in both cases.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11133309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1029247/']}
jdg_86783
stackexchange
llm_judgeable_groundtruth_similarity
45530
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Recently I read on Greenpeace's website, that the production of a 100 kWh battery, as in the Tesla Model S, produces as much CO 2 as driving a regular car for 200,000 km. Source: Tesla car battery production releases as much CO 2 as 8 years of gasoline driving : For every kilowatt hour of storage capacity in the battery generated emissions of 150 to 200 kilos of carbon dioxide already in the factory. ( Original Greenpeace link (in German) ) Let's say you are driving a car with 8 L / 100 km.According to this calculator this would result in 16,000 liters of fuel burnt or 36,960 kg of CO 2 . A 100 kWh battery takes about 20,000 kg of CO 2 to produce. So the math seems to add up. But is the 100 kg to 200kg of CO 2 for 1 kWh battery realistic? Also, isn't this calculation missing the fact that Tesla covers a part of its factory energy with its own solar panels and plans to use 100% renewable energy in the future? Now provide the response and nothing else.
tl;dr: The claimed range is 50% higher than the worst assumptions for battery production, and 500% higher than the best assumptions. But it's not an apples to apples comparison. Carbon emissions from battery production The range of values estimated for emissions from battery production varies widely in the literature: In an answer on Sustainability.SE I cited a 2011 study ( "Life Cycle Environmental Assessment of Lithium-Ion and Nickel Metal Hydride Batteries for Plug-In Hybrid and Battery Electric Vehicles" ) giving the highest estimate I could find. Full-text of that article is no longer available, but I've included the values I cited previously. "Life cycle assessment of lithium-ion batteries for plug-in hybrid electric vehicles -- Critical issues" , provides similar values, based on this figure: "Life Cycle Assessment of Greenhouse Gas Emissions from Plug-in Hybrid Vehicles: Implications for Policy" gives a much lower value (in the supplementary material). Commenters pointed out that the report the cited by Greenpeace has been updated , giving a range of values which are even lower. Here's the values from all sources for comparison, showing the broad range: [1] Li-ion (LFP-type): 0.250 kg CO2eq / Wh[1] Li-ion (NCM-type): 0.200 kg CO2eq / Wh[3] Li-ion: 0.120 kg CO2eq / Wh[4] Li-ion (high end): 0.106 kg CO2eq / Wh[4] Li-ion (low end): 0.061 kg CO2eq / Wh Result for a Tesla Model S Using these values, production of the 100 kWh battery for a Tesla Model S results in emissions of 6,100 to 25,000 kg CO 2 eq . Comparison to ICE vehicle When a liter of gasoline is burned, 2.3 kg of CO 2 are released ( source (PDF) ). Thus production of a Tesla battery equates to burning about 2,700 to 10,900 liters of gasoline. For a "regular car" (mentioned in the question) with fuel efficiency of 8 liters / 100 km, this amount of fuel equates to a driving range of 33,150 to 136,250 km . This is well below the 200,000 km mentioned in the claim. The claim is 47% high for the worst-case battery production emissions, and 503% high in the best case. What the claim (and this analysis) ignores If we give the benefit of the doubt to Greenpeace, they're not really trying to compare EVs to ICEVs. They're pointing out that production of batteries is carbon intensive, and giving a handy reference to understand just how intensive it is. But the comparison, as written, breaks down because of all that it ignores (thanks to the commenters for pointing out all these factors): 8 L / 100 km is arbitrary. Some ICEVs are better/worse. Production of gasoline also results in CO 2 emissions, before it's even in the tank. Production of all components of both ICEVs and EVs result in varying amounts of carbon emissions, and can be recycled at end-of-life to some extent. The electric energy used in battery production could be sourced from renewables -- the cited studies assume an "average" mix, comprising some coal and natural gas.
{}
{'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/45530', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/13971/']}
jdg_86784
stackexchange
llm_judgeable_groundtruth_similarity
1698275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just wondering under what circumstances would you prefer to generate a proxy from a WCF service when you can just invoke calls using the ChannelFactory? This way you won't have to generate a proxy and worry about regenerating a proxy when the server is updated? Thanks Now provide the response and nothing else.
There are 3 basic ways to create a WCF client: Let Visual Studio generate your proxy. This auto generates code that connects to the service by reading the WSDL. If the service changes for any reason you have to regenerate it. The big advantage of this is that it is easy to set up - VS has a wizard and it's all automatic. The disadvantage is that you're relying on VS to do all the hard work for you, and so you lose control. Use ChannelFactory with a known interface. This relies on you having local interfaces that describe the service (the service contract). The big advantage is that can manage change much more easily - you still have to recompile and fix changes, but now you're not regenerating code, you're referencing the new interfaces. Commonly this is used when you control both server and client as both can be much more easily mocked for unit testing. However the interfaces can be written for any service, even REST ones - take a look at this Twitter API . Write your own proxy - this is fairly easy to do, especially for REST services, using the HttpClient or WebClient . This gives you the most fine grain control, but at the cost of lots of service API being in strings. For instance: var content = new HttpClient().Get("http://yoursite.com/resource/id").Content; - if the details of the API change you won't encounter an error until runtime. Personally I've never liked option 1 - relying on the auto generated code is messy and loses too much control. Plus it often creates serialisation issues - I end up with two identical classes (one in the server code, one auto generated) which can be tided up but is a pain. Option 2 should be perfect, but Channels are a little too limiting - for instance they completely lose the content of HTTP errors . That said having interfaces that describe the service is much easier to code with and maintain.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1698275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195024/']}
jdg_86785
stackexchange
llm_judgeable_groundtruth_similarity
3535907
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 want to support app switching in my upcoming iPhone app and I've implemented all the proper delegate methods in my application delegate. So when the user resumes the application, I can see their activity in the NSLog and all. However, how can I tell my app has resumed a controller? Is there a method I can put in my controller to tell me the app has resumed in said controller? Reason I ask is because my application handles its own URL schema, and I want to update the view depending on the URL launched. Any help will be greatly appreciated. Thanks in advance Now provide the response and nothing else.
You can have you your controller observe the UIApplicationWillEnterForeground notification. It probably would look something like this: - (void) viewDidLoad{ [super viewDidLoad]; //do stuff here if(&UIApplicationWillEnterForegroundNotification) { //needed to run on older devices, otherwise you'll get EXC_BAD_ACCESS NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter addObserver:self selector:@selector(enteredForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; }}- (void)enteredForeground:(NSNotification*) not{ //do stuff here}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3535907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345282/']}
jdg_86786
stackexchange
llm_judgeable_groundtruth_similarity
3704273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can some one please tell me what is the difference between vector vs deque. I know the implementation of vector in C++ but not deque. Also interfaces of map and set seem similar to me. What is the difference between the two and when to use one. Now provide the response and nothing else.
std::vector : A dynamic-array class. The internal memory allocation makes sure that it always creates an array. Useful when the size of the data is known and is known to not change too often. It is also good when you want to have random-access to elements. std::deque : A double-ended queue that can act as a stack or queue. Good for when you are not sure about the number of elements and when accessing data-element are always in a serial manner. They are fast when elements are added/removed from front and end but not when they're added/removed to/from the middle. std::list : A double-linked list that can be used to create a 'list' of data. The advantage of a list is that elements can be inserted or deleted from any part of the list without affecting an iterator that is pointing to a list member (and is still a member of the list after deletion). Useful when you know that elements will be deleted very often from any part of the list. std::map : A dictionary that maps a 'key' to a 'value'. Useful for applications like 'arrays' whose index are not an integer. Basically can be used to create a map-list of name to an element, like a map that stores name-to-widget relationship. std::set : A list of 'unique' data values. For e.g. if you insert 1, 2, 2, 1, 3, the list will only have the elements 1, 2, 3. Note that the elements in this list are always ordered. Internally, they're usually implemented as binary search trees (like map).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3704273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384252/']}
jdg_86787
stackexchange
llm_judgeable_groundtruth_similarity
22635945
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 collection of BigDecimals (in this example, a LinkedList ) that I would like to add together. Is it possible to use streams for this? I noticed the Stream class has several methods Stream::mapToIntStream::mapToDoubleStream::mapToLong Each of which has a convenient sum() method. But, as we know, float and double arithmetic is almost always a bad idea. So, is there a convenient way to sum up BigDecimals? This is the code I have so far. public static void main(String[] args) { LinkedList<BigDecimal> values = new LinkedList<>(); values.add(BigDecimal.valueOf(.1)); values.add(BigDecimal.valueOf(1.1)); values.add(BigDecimal.valueOf(2.1)); values.add(BigDecimal.valueOf(.1)); // Classical Java approach BigDecimal sum = BigDecimal.ZERO; for(BigDecimal value : values) { System.out.println(value); sum = sum.add(value); } System.out.println("Sum = " + sum); // Java 8 approach values.forEach((value) -> System.out.println(value)); System.out.println("Sum = " + values.stream().mapToDouble(BigDecimal::doubleValue).sum()); System.out.println(values.stream().mapToDouble(BigDecimal::doubleValue).summaryStatistics().toString());} As you can see, I am summing up the BigDecimals using BigDecimal::doubleValue() , but this is (as expected) not precise. Post-answer edit for posterity: Both answers were extremely helpful. I wanted to add a little: my real-life scenario does not involve a collection of raw BigDecimal s, they are wrapped in an invoice. But, I was able to modify Aman Agnihotri's answer to account for this by using the map() function for stream: public static void main(String[] args) { LinkedList<Invoice> invoices = new LinkedList<>(); invoices.add(new Invoice("C1", "I-001", BigDecimal.valueOf(.1), BigDecimal.valueOf(10))); invoices.add(new Invoice("C2", "I-002", BigDecimal.valueOf(.7), BigDecimal.valueOf(13))); invoices.add(new Invoice("C3", "I-003", BigDecimal.valueOf(2.3), BigDecimal.valueOf(8))); invoices.add(new Invoice("C4", "I-004", BigDecimal.valueOf(1.2), BigDecimal.valueOf(7))); // Classical Java approach BigDecimal sum = BigDecimal.ZERO; for(Invoice invoice : invoices) { BigDecimal total = invoice.unit_price.multiply(invoice.quantity); System.out.println(total); sum = sum.add(total); } System.out.println("Sum = " + sum); // Java 8 approach invoices.forEach((invoice) -> System.out.println(invoice.total())); System.out.println("Sum = " + invoices.stream().map((x) -> x.total()).reduce((x, y) -> x.add(y)).get());}static class Invoice { String company; String invoice_number; BigDecimal unit_price; BigDecimal quantity; public Invoice() { unit_price = BigDecimal.ZERO; quantity = BigDecimal.ZERO; } public Invoice(String company, String invoice_number, BigDecimal unit_price, BigDecimal quantity) { this.company = company; this.invoice_number = invoice_number; this.unit_price = unit_price; this.quantity = quantity; } public BigDecimal total() { return unit_price.multiply(quantity); } public void setUnit_price(BigDecimal unit_price) { this.unit_price = unit_price; } public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } public void setInvoice_number(String invoice_number) { this.invoice_number = invoice_number; } public void setCompany(String company) { this.company = company; } public BigDecimal getUnit_price() { return unit_price; } public BigDecimal getQuantity() { return quantity; } public String getInvoice_number() { return invoice_number; } public String getCompany() { return company; }} Now provide the response and nothing else.
Original answer Yes, this is possible: List<BigDecimal> bdList = new ArrayList<>();//populate listBigDecimal result = bdList.stream() .reduce(BigDecimal.ZERO, BigDecimal::add); What it does is: Obtain a List<BigDecimal> . Turn it into a Stream<BigDecimal> Call the reduce method. 3.1. We supply an identity value for addition, namely BigDecimal.ZERO . 3.2. We specify the BinaryOperator<BigDecimal> , which adds two BigDecimal 's, via a method reference BigDecimal::add . Updated answer, after edit I see that you have added new data, therefore the new answer will become: List<Invoice> invoiceList = new ArrayList<>();//populateFunction<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());BigDecimal result = invoiceList.stream() .map(totalMapper) .reduce(BigDecimal.ZERO, BigDecimal::add); It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice. Then I obtain a Stream<Invoice> , map it to a Stream<BigDecimal> and then reduce it to a BigDecimal . Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier: List<Invoice> invoiceList = new ArrayList<>();//populateBigDecimal result = invoiceList.stream() .map(Invoice::total) .reduce(BigDecimal.ZERO, BigDecimal::add); Here we directly use the method reference in the map method.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/22635945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/963076/']}
jdg_86788
stackexchange
llm_judgeable_groundtruth_similarity
30761154
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 keep receiving Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:2013/socket.io/?EIO=3&transport=polling&t=1433950808025-0 . (Reason: CORS request failed). while I try to access my node.js. This doesn't work for me: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next();}); @edit: here is the updated full code: var express = require('express');var http = require('http');var expressvar = express();expressvar.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Headers', 'accept, authorization, content-type, x-requested-with'); res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); res.setHeader('Access-Control-Allow-Origin', req.header('origin')); next();});expressvar.use(express.static('../'));expressvar.use("/socket.io", express.static('../socket.io'));var app = http.createServer(expressvar);var io = require('socket.io').listen(app);app.listen(2013); Now provide the response and nothing else.
Try this solution (edited to include full working code) var app = require('express')();var server = require('http').Server(app);var io = require('socket.io')(server);io.set('origins', '*:*');app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', req.get('Origin') || '*'); res.header('Access-Control-Allow-Credentials', 'true'); res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); res.header('Access-Control-Expose-Headers', 'Content-Length'); res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range'); if (req.method === 'OPTIONS') { return res.send(200); } else { return next(); }});server.listen(80);app.get('/', function (req, res) { res.send('OK');});io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); });});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30761154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1742588/']}
jdg_86789
stackexchange
llm_judgeable_groundtruth_similarity
8018417
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 load a class and create Instance of it from It's .cs file? I want to open a custom class in a .cs file and create instance of it in my application thanks Now provide the response and nothing else.
in theory yes - it mainly depends on whether you have all dependencies available... IF so you can use the built-in CSharpCodeProvider to compile the .cs - file to an assembly (can be purely in-memory if need be) and then use Reflection to create an instance/use a class from that assembly... Since don't provide much detail I would suggest to checkout these links and come back with detail questions if some arrise: http://support.microsoft.com/kb/304655/en-us http://www.codeproject.com/KB/cs/codecompilation.aspx http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Compile-C-or-VB-source-code-run-time.html http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx http://www.csharp-examples.net/reflection-examples/ http://csharp.net-tutorials.com/reflection/introduction/ http://www.codeproject.com/KB/cs/C__Reflection_Tutorial.aspx http://www.dotnetperls.com/reflection-field C# Reflection: How to get class reference from string? http://msdn.microsoft.com/en-us/library/system.reflection.assembly.aspx http://msdn.microsoft.com/en-us/library/system.type.aspx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8018417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/648723/']}
jdg_86790
stackexchange
llm_judgeable_groundtruth_similarity
104678
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If, with a bit abuse of notation, $U\notin R\bigotimes{R}\bigotimes{R}\bigotimes{...}$ (i.e., regardless how long you clebsch up $R$, $U$ won't appear in the expansion), I call $U$ unsociable with respect to $R$ (in the group $G$). Clearly everything else is unsociable with the $1$ irrep, since (duh) $1\bigotimes{1}\bigotimes...=1$. For finite groups there can be nontrivial (ahem) cases: For $G=C_{3v}$ (the symmetry group), $A_2\bigotimes{A_2}=A_1$ and thus $E$ is unsociable w.r.t. $A_2$. But what is the deal with Lie groups? E.g. is the defining irrep of $E_7$ unsociable w.r.t. the adjoint one? Now provide the response and nothing else.
It follows from a theorem of Burnside/Steinberg that if G is a finite group then the tensor powers of a module V contain all irreps if and ony if V is faithful for G.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/104678', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11504/']}
jdg_86791
stackexchange
llm_judgeable_groundtruth_similarity
9407571
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using iOS 5 storyboards, on a button I am performing a segue, what I want is to do validation on my textfield and if validation is failed I have to stop segue and throw an alert. Whats the way to do it? Now provide the response and nothing else.
If your deployment target is iOS 6.0 or later You can simply implement the shouldPerformSegueWithIdentifier:sender: method on your source view controller. Make this method return YES if you want to perform the segue, or NO if you don't. If your deployment target is earlier than iOS 6.0 You will need to change the way your segue is connected in the storyboard and write a little more code. First, set up the segue from the button's view controller to the destination view controller, instead of directly from the button to the destination. Give the segue an identifier like ValidationSucceeded . Then, connect the button to an action on its view controller. In the action, perform the validation and either perform the segue or show an alert based on whether the validation succeeded. It will look something like this: - (IBAction)performSegueIfValid:(id)sender { if ([self validationIsSuccessful]) { [self performSegueWithIdentifier:@"ValidationSucceeded" sender:self]; } else { [self showAlertForValidationFailure]; }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9407571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/928763/']}
jdg_86792
stackexchange
llm_judgeable_groundtruth_similarity
21128478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Travis CI to test and build my project and as part of it I want travis to run grunt build i have tried the following but have had no luck. script: "grunt build" script: "./node_modules/grunt build" script: "./node_modules/grunt/grunt build" script: "./node_modules/grunt/grunt.js build" Now provide the response and nothing else.
Have you made sure to install grunt-cli globally on your Travis node? My Travis CI config looks like: language: node_jsnode_js: - "0.8"before_install: npm install -g grunt-cliinstall: npm installbefore_script: grunt build And my package.json: { ... "scripts": { "test": "grunt test" }, ...} I will explain the flow of steps that Travis will execute: The first step to be executed is the before_install . My only prerequisite (besides node.js) is grunt-cli so I use this step to install it. Next is the install step, in my case this will simply install my npm modules The before script is then executed, running grunt build Lastly Travis will look for scripts in the package.json, there I indicated the test step should run grunt test I'd like to note that this is my own opinion on how to configure Travis. I'm certainly not inclining you should use exactly the same approach.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21128478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_86793
stackexchange
llm_judgeable_groundtruth_similarity
37081943
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 going to import this d3gauge.js file into one of my angular2 component, memmon.component.ts file. import '../../../../js/d3gauge.js';export class MemMonComponent { createMemGauge() { new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js }} and in the corresponding template file, add <script src="../../../../js/d3gauge.js"></script> But it doesn't work, drawGauge can't be found. So, what're correct steps to import an external js file to angular2? since I'm using webpack, is it possible to do it in webpack? I refer to this question , the webpack solution there doesn't work for me as a result of .ensure can't be resolved. Now provide the response and nothing else.
Ideally you need to have .d.ts file for typings to let Linting work. But It seems that d3gauge doesn't have one, you can Ask the developers to provide and hope they will listen. Alternatively, you can solve this specific issue by doing this declare var drawGauge: any;import '../../../../js/d3gauge.js';export class MemMonComponent { createMemGauge() { new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js }} If you use it in multiple files, you can create a d3gauage.d.ts file with the content below declare var drawGauge: any; and reference it in your boot.ts (bootstrap) file at the top, like this ///<reference path="../path/to/d3gauage.d.ts"/>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37081943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1745535/']}
jdg_86794
stackexchange
llm_judgeable_groundtruth_similarity
45255167
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to use np.argwhere() to obtain the values in an np.array . For example: z = np.arange(9).reshape(3,3)[[0 1 2] [3 4 5] [6 7 8]]zi = np.argwhere(z % 3 == 0)[[0 0] [1 0] [2 0]] I want this array: [0, 3, 6] and did this: t = [z[tuple(i)] for i in zi] # -> [0, 3, 6] I assume there is an easier way. Now provide the response and nothing else.
Why not simply use masking here: z [z % 3 == 0] For your sample matrix, this will generate: >>> z[z % 3 == 0]array([0, 3, 6]) If you pass a matrix with the same dimensions with booleans as indices, you get an array with the elements of that matrix where the boolean matrix is True . This will furthermore work more efficient, since you do the filtering at the numpy level (whereas list comprehension works at the Python interpreter level).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45255167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1419236/']}
jdg_86795
stackexchange
llm_judgeable_groundtruth_similarity
104444
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: Heavy water (D 2 O) is known to be lethal to humans and other life in large quantities. All I've been able to find on the toxicity is that it's similar to chemotherapy chemistry. I'd like to know precisely how having a single neutron in two atoms of an otherwise non-toxic molecule can cause the body to degrade. What's the root cause here? Now provide the response and nothing else.
The question is already answered by Armand . I am just going to elaborate on that by referencing the paper. Different isotopes of chemical elements have slightly different chemical behaviors, but for most elements the differences are far too small to have a biological effect. In the case of hydrogen, differences in chemical properties among protium (light hydrogen), deuterium , and tritium occur, in part because chemical bond energy (the strength of a bond) changes with changed mass of the nucleus–electron system . The isotope effects are especially relevant in biological systems because of the prevalence of hydrogen atoms in biological molecules (even deuterated water can have significant effects in the human body). Note that enzymes have a finely-tuned network of hydrogen bonds, both in the active center with their substrates, and outside the active center, to stabilize their tertiary structures. In a deuterated environment, some hydrogen bonds will be replaced with deuterium bonds which have different strength ( Ref. 3 ), so normal reactions in cells can be disrupted. Studies and experiments* show that heavy water affects cell division(mitosis), cell membrane changes and cellular heat stability, possibly as a result of inhibition of chaperonin formation. Also noted among the presumably wide-ranging cellular effects was the display of an altered glucose metabolism under deuterated condition in cells. $D_2O$ is more toxic towards at least some malignant cells, but the difference in sensitivity vs. normal cells does not seem high enough for therapeutic use. In ref. 2, you will find a paper which shows the biochemical and pharmacological effects of heavy water on humans. Basically, to study the effects of heavy water on the metabolism humans, $D_2O$ and deuterated drugs were used and various changes were noted. Have a look for more details. References Effect on biological systems (Wikipedia) Kushner DJ, Baker A, Dunstall TG. Pharmacological uses and perspectives of heavy water and deuterated compounds. Can J Physiol Pharmacol. 1999 Feb;77(2):79-88. PMID: 10535697 . Steve Scheiner and Martin Čuma. Relative Stability of Hydrogen and Deuterium Bonds. J. Am. Chem. Soc. 1996 118, 6, 1511–1521 DOI: 10.1021/ja9530376 *Experiments with mice, rats, and dogs have shown that a degree of 25% deuteration causes (sometimes irreversible) sterility, because neither gametes nor zygotes can develop. Mammals (e.g. rats) were given heavy water to drink die after a week, at a time when their body water approaches about 50% deuteration. The mode of death appears to be the same as that in cytotoxic poisoning or in acute radiation syndrome , and is due to deuterium's action in generally inhibiting cell division.
{}
{'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/104444', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/67416/']}
jdg_86796
stackexchange
llm_judgeable_groundtruth_similarity
1532353
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to delphi and now I have to read create an xml. my code is the following: function foo.createXMLDocument(): TXMLDocument;var res: TXMLDocument; rootNode: IXMLNode; sl : TStringList;begin res := TXMLDocument.Create(nil); res.Active := true; rootNode := res.AddChild('label'); // create string for debug purposes sl := TStringList.Create; sl.Assign(res.XML);// sl is empty after this assignment //add more elements generateDOM(rootNode); Result := res;end; The problem is, the count of child nodes increases but res.XML is empty. Not to mention that the rest of elements in the generateDOM procedure doesn't seem to be doing anything. I will be very glad with your help. Now provide the response and nothing else.
Disclaimer: Tested with D2007. Your code does indeed create the XML ( <label/> ) as shown in this modified function: function createXMLDocument(): TXMLDocument;var res: TXMLDocument; rootNode: IXMLNode; sl : TStringList;begin res := TXMLDocument.Create(nil); res.Active := true; rootNode := res.AddChild('label'); // create string for debug purposes sl := TStringList.Create; // not needed sl.Assign(res.XML); // Not true: sl is empty after this assignment ShowMessage(sl.text);// sl is NOT empty! sl.Free; // don't forget to free it! use try..finally.. to guarantee it! //add more elements// generateDOM(rootNode); Result := res;end; But it calls for a lot of remarks : - You don't need a local res variable, just use the Result. - You don't need an extra StringList to see the XML: Result.Xml.Text - Don't forget to Free the sl StringList if you create one. - The XmlDocument you return is unusable outside the function and gives an AV if you try . Why? It's because an XMLDocument is intended to be used as a Component with an Owner , or as an Interface otherwise, in order to manage its lifetime . The fact that you use an Interface to hold rootNode causes it to be destroyed at the end of the CreateXmlDocument function. And if you look at the code in TXMLNode._Release , you'll see that it triggers TXMLDocument._Release which calls Destroy unless there is an Owner for the XMLDocument (or an interface holding a reference to it). This is why the XMLDocument is valid and populated inside the CreateXMLDocument function but not available outside it unless you return an Interface or provide an Owner . See the alternate solutions below : function createXMLDocumentWithOwner(AOwner: TComponent): TXMLDocument;var rootNode: IXMLNode;begin Assert(AOwner <> nil, 'createXMLDocumentWithOwner cannot accept a nil Owner'); Result := TXMLDocument.Create(AOwner); Result.Active := True; rootNode := Result.AddChild('label'); OutputDebugString(PChar(Result.Xml.Text)); //add more elements// generateDOM(rootNode);end;function createXMLDocumentInterface(): IXMLDocument;var rootNode: IXMLNode;begin Result := TXMLDocument.Create(nil); Result.Active := True; rootNode := Result.AddChild('label'); OutputDebugString(PChar(Result.Xml.Text)); //add more elements// generateDOM(rootNode);end;procedure TForm7.Button1Click(Sender: TObject);var doc: TXmlDocument; doc2: IXMLDocument;begin ReportMemoryLeaksOnShutdown := True; doc := createXMLDocument; // ShowMessage( doc.XML.Text ); // cannot use it => AV !!!! // already freed, cannot call doc.Free; doc := createXMLDocumentWithOwner(self); ShowMessage( doc.XML.Text ); doc2 := createXMLDocumentInterface; ShowMessage( doc2.XML.Text );end;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1532353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118750/']}
jdg_86797
stackexchange
llm_judgeable_groundtruth_similarity
7093003
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When an AJAX call returns html, is it possible to use jQuery to alter the contents of the response string? If so, how does one go about doing that? EDIT: This question is directed at editing the response before writing it to the page Now provide the response and nothing else.
Well that depends on how you request the data. If you have $.ajax etc, then you can do the necessary modifications in the success handler. I assume since you don't understand jQuery very well, that you are using $.load() to load the data, in which case it's easiest to replace it with $.get('/somecode.php', function(data) { data = $(data); // Find and remove all anchor tags for example data.find('a').remove(); $('#target-id').append(data);}); Or if you don't want to create a jQuery object, you can easily do something like $.get('/somecode.php', function(data) { // Replace all strings "foo" with "bar" for example data = data.replace('foo', 'bar'); // Manually append it to DOM or do whatever you want with it $('#target-id').append(data);});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7093003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/866022/']}
jdg_86798
stackexchange
llm_judgeable_groundtruth_similarity
10404067
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 UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal mark e.g. 2.5 OK 2..5 NOT OK Now provide the response and nothing else.
Implement the shouldChangeCharactersInRange method like this: // Only allow one decimal point// Example assumes ARC - Implement proper memory management if not using.- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSArray *arrayOfString = [newString componentsSeparatedByString:@"."]; if ([arrayOfString count] > 2 ) return NO; return YES;} This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10404067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1282180/']}
jdg_86799
stackexchange
llm_judgeable_groundtruth_similarity
35691051
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 UAA There are two Concepts, Authority and Scope. These concepts seems to overlap. I would like to know exact difference and purpose For example , oauth.login Now provide the response and nothing else.
Scopes are permissions of an OAuth Client acting on behalf of a User. They are granted after obtaining a user token with one of the following grant types: auth_code, password, implicit . Scopes signify what the application is allowed to access on User's behalf (referred to as delegated authorisation). Authorities are permissions of an OAuth Client acting on its own behalf and there is no User involvement. They are granted after obtaining a client token with grant_type of client_credentials . Typical use is an Application or API trying to access a resource with its own credentials without user involvement. In UAA , oauth.login is a system level permission and was being used by the legacy implementation of the login-server project (When UAA and Login Server were separate components). This permission allows admin level access for login server.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35691051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268085/']}
jdg_86800
stackexchange
llm_judgeable_groundtruth_similarity
37365824
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 which also has a column with a filename of an image. How can I display the image inside of the DataFrame? I tried the following: import pandas as pdfrom IPython.display import Imagedf = pd.DataFrame(['./image01.png', './image02.png'], columns = ['Image'])df['Image'] = Image(df['Image']) But when I show the frame, each column only shows the to_string representation of the Image Object. Image0 IPython.core.display.Image object1 IPython.core.display.Image object Is there any solution for this? Thanks for your help. Now provide the response and nothing else.
Instead of inserting the html code into the dataframe, I suggest to use a formatter. Unfortunately you need to set the truncation settings, so long text doesn't get truncated with "...". import pandas as pdfrom IPython.display import Image, HTMLdf = pd.DataFrame(['./image01.png', './image02.png'], columns = ['Image'])def path_to_image_html(path): return '<img src="'+ path + '"/>'pd.set_option('display.max_colwidth', -1)HTML(df.to_html(escape=False ,formatters=dict(Image=path_to_image_html)))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37365824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2166201/']}
jdg_86801
stackexchange
llm_judgeable_groundtruth_similarity
58979347
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 complex json file that I have to handle with TypeScript / Javascript to make it hierarchical, in order to later build a questionnaire. Every entry of the json has a Id (unique), ParentId (0 If root), Text, Description. My Typescript Interface export interface Question { Id: number; Text: string; Desc: string; ParentId: number; ChildAnswers?: Answer[];}export interface Answer { Id: number; Text: string; Desc: string; ParentId: number; ChildQuestion?: Question;} I can guarantee that when the object is an answer it will only have one child which we can assume to be a question. Flat Data Example : [{ Id: 1, Text: 'What kind of apple is it?', Desc: '', ParentId: 0},{ Id: 2, Text: 'Green Apple', Desc: '', ParentId: 1},{ Id: 3, Text: 'Red Apple', Desc: '', ParentId: 1},{ Id: 4, Text: 'Purple GMO Apple', Desc: '', ParentId: 1},{ Id: 5, Text: 'What is the issue with the apple?', Desc: '', ParentId: 2},{ Id: 6, Text: 'Spoiled.', Desc: '', ParentId: 5},{ Id: 7, Text: 'Taste Bad.', Desc: '', ParentId: 5},{ Id: 8, Text: 'Too Ripe.', Desc: '', ParentId: 5},{ Id: 9, Text: 'Is not an apple.', Desc: '', ParentId: 5},{ Id: 10, Text: 'The apple was not green.', Desc: '', ParentId: 5},... So on ...] My Goal { Id: 1, Text: 'What kind of apple is it?', Desc: '', ParentId: 0, ChildAnswers: [ { Id: 2, Text: 'Green Apple', Desc: '', ParentId: 1, ChildQuestion: { Id: 5, Text: 'What is the issue with the apple?', Desc: '', ParentId: 2, ChildAnswers: [ { Id: 6, Text: 'Spoiled.', Desc: '', ParentId: 5, ... So on ... }, { Id: 7, Text: 'Taste Bad.', Desc: '', ParentId: 5, ... So on ... }, { Id: 8, Text: 'Too Ripe.', Desc: '', ParentId: 5, ... So on ... }, { Id: 9, Text: 'Is not an apple.', Desc: '', ParentId: 5, ... So on ... }, { Id: 10, Text: 'The apple was not green.', Desc: '', ParentId: 5, ... So on ... }, ... So on ... ] } }, { Id: 3, Text: 'Red Apple', Desc: '', ParentId: 1, ... So on ... }, { Id: 4, Text: 'Red Apple', Desc: '', ParentId: 1, ... So on ... } ... So on ... ]} I'm currently using this list_to_tree function I found here on stackoverflow, I just don't know if how to tell a question and answer apart. Should I just check to see if the length is one for a question or at odd intervals mark it?: function list_to_tree(list) { var map = {}, node, roots = [], i; for (i = 0; i < list.length; i += 1) { map[list[i].Id] = i; // initialize the map list[i].Children = []; // initialize the children } for (i = 0; i < list.length; i += 1) { node = list[i]; if (node.ParentId !== 0) { // if you have dangling branches check that map[node.ParentId] exists list[map[node.ParentId]].Children.push(node); } else { roots.push(node); } } return roots;} Now provide the response and nothing else.
If I misunderstand anything, please let me know. You can use driver. Capabilities ['browserversion '] and driver. Capabilities ['chrome'] ['chromedriverversion ']. Split (' ') [0] to get the version of chrome and chromedriver. Then intercept the first 2 digits of the version number for comparison. If they are not the same, you can remind the user to download the correct chromedriver version if needed. Minimal example: from selenium import webdriverdriver = webdriver.Chrome()str1 = driver.capabilities['browserVersion']str2 = driver.capabilities['chrome']['chromedriverVersion'].split(' ')[0]print(str1)print(str2)print(str1[0:2])print(str2[0:2])if str1[0:2] != str2[0:2]: print("please download correct chromedriver version") Debug: You can also prompt the user with the correct version. Chrome and Chromedriver versions as stated on downloads page: If you are using Chrome version 79, please download ChromeDriver 79.0.3945.36 If you are using Chrome version 78, please download ChromeDriver 78.0.3904.70 If you are using Chrome version 77, please download ChromeDriver 77.0.3865.40 If you are using Chrome version 76, please download ChromeDriver 76.0.3809.126 If you are using Chrome version 75, please download ChromeDriver 75.0.3770.140 If you are using Chrome version 74, please download ChromeDriver 74.0.3729.6 If you are using Chrome version 73, please download ChromeDriver 73.0.3683.68 For older version of Chrome, please see Barett's anwer There is general guide to select version of crhomedriver for specific chrome version: https://sites.google.com/a/chromium.org/chromedriver/downloads/version-selection . For more details, please refer : https://stackoverflow.com/a/55266105/11128312 Note: Earlier version of chromedriver stored the chrome browser version driver.capabilities['version'] . If you want to get chrome browser version without having to worry about this, you can use the below code. if 'browserVersion' in driver.capabilities: print(driver.capabilities['browserVersion'])else: print(driver.capabilities['version']) Links that may be useful to you: How to work with a specific version of ChromeDriver while Chrome Browser gets updated automatically through Python selenium How can I get Chrome Browser Version running now with Python? [closed] Which ChromeDriver version is compatible with which Chrome Browser version?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58979347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5268911/']}
jdg_86802
stackexchange
llm_judgeable_groundtruth_similarity
2773974
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 read in an answer on MO that Nathan Jacobson had given a universal algebraic proof that a ring satisfying the equation $x^n=x$ is commutative. The sketch given in the answer is very clear : wlog one may assume that $R$ is subdirectly irreducible, as a result of a general result in universal algebra (that is, it has a minimum nonzero ideal). Then one proves that a subdirectly irreducible ring satisfying the equation is a finite (skew, a priori) field, and one concludes from Wedderburn's theorem that it's commutative. But I'm having trouble with the interesting step, that is A subdirectly irreducible ring satisfying the equation $x^n=x$ for some $n\geq 2$ is a finite division ring I had the folliwing idea : since $R$ has no nilpotent elements it should be a subdirect product of integral domains satisfying the same equations - however I know this property for commutative rings, and it relies on the well-known fact that $\displaystyle\bigcap\{p, p\in \mathrm{Spec}R\} = \{x, x$ is nilpotent $\}$ - and I don't know whether this is true for noncommutative rings. As a matter of fact I'm pretty much convinced that it's not true (in $M_n(K)$, $K$ a field, $n\geq 2$, the set of nilpotent elements isn't a bilateral ideal - indeed there are no nontrivial ones). So unless this idea can be saved by the specifics of the situation, I can't go any further with it. What I also noticed (I don't know if that can help though) is that $I^2 = I$, if $I$ denotes the minimum nonzero ideal. I can also sort of make a connection with Wedderburn's theorem by studying the case where $Z(R)$ (the center) is a field; and so $R$ is a $Z(R)$-vector space. Then, it's a finite field. I can't yet see why $Z(R)$ would be finite dimensional (this would probably help a lot). Am I anywhere near the right direction ? Can anyone give some hints to solve this ? (If possible - I know sometimes it's not- I'd rather see some hints than a full solution; and also if someone has read the article in question and saw that the proof in question was longer than what an MS answer can suggest, I'd also like to know haha) EDIT: Here's the MO question : https://mathoverflow.net/questions/30220/abstract-thought-vs-calculation The answer I'm mentioning should be recognizable Now provide the response and nothing else.
A subdirectly irreducible ring satisfying the equation $x^n=x$ for some $n\geq 2$ is a finite division ring First let's consider the elementary part of this statement. Observe Lemma. If $R$ is a subdirectly irreducible ring withno nonzero elements that square to zero, then $R$ has no nontrivial zero divisors. Reasoning: Assume not. Then $R$ has elements $a\neq 0\neq b$ such that $ab=0$ . The set $bRa$ consists of elements that square to zero, so $bRa=\{0\}$ .Then $(b)(a)=RbRaR=R\{0\}R=\{0\}=(0)$ .If $I$ is the least nonzero ideal of $R$ , then $I\subseteq (b)$ and $I\subseteq (a)$ , so $I^2\subseteq (b)(a)=(0)$ .This shows that all elements of $I$ square to zero, a contradiction. \\\ Here is how the lemma applies.No nonzero element $a\in R$ which squaresto zero can satisfy the equation $x^n=x$ ,so the lemma implies that if $R$ is subdirectlyirreducible and satisfies $x^n=x$ , then $R$ has no nontrivial zero divisors. Given any nonzero $a\in R$ we have $0=a^n-a = a(a^{n-1}-1)$ . Since $a\neq 0$ ,it must be that $a^{n-1}-1=0$ . Hence, any nonzero $a\in R$ satisfies $a^{n-1}=1$ , showing thatnonzero elements are units. Thus, $R$ is a division ring. The non-elementary part of the statement A subdirectly irreducible ring satisfying the equation $x^n=x$ for some $n\geq 2$ is a finite division ring is that a division $R$ whose nonzero elements satisfy $x^{n-1}=1$ must be finite. The idea for this is to first provethat any maximal subfield of $R$ is finite (which is easy),then to provethat any finite maximal subfield of $R$ has finite index in $R$ (see Lam's A First Course inNoncommutative Rings , Theorem 15.4).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2773974', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/408637/']}
jdg_86803
stackexchange
llm_judgeable_groundtruth_similarity
16169035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this error since a long time but can't figure it out : Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found It happens in admin when I try to add or modify on one of my models (display works fine) This is the model: class PS(models.Model): id_ps = models.IntegerField(null=True) client = models.ForeignKey(Client, null=True, blank=True) nom_du_site = models.CharField(max_length=250) rue_livraison = models.TextField(null=True) complement_adresse = models.TextField(null=True) code_postal_livraison = models.CharField(max_length=50, null=True) ville_livraison = models.CharField(max_length=200, null=True) pays_livraison = models.CharField(max_length=200, null=True) distributeur = models.CharField(max_length=50, null=True) tarif = models.CharField(max_length=250, null=True) type_tarif = models.CharField(max_length=50, null=True) type_installation = models.CharField(max_length=50, null=True) def __unicode__(self): return self.nom_du_site @property def pce(self): try: return PCE.objects.filter(ps=self)[0] except IndexError: return # def get_pce(self): from pce.models import PCE return PCE.objects.filter(ps=self).exclude(frequence='6M') # def get_pce_6m(self): from pce.models import PCE return PCE.objects.filter(ps=self,frequence='6M') Any idea what am i doing wrong here? Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8026/admin/ps/ps/add/ Django Version: 1.2.5 Python Version: 2.7.2 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'easy_thumbnails', 'django_extensions', 'contentadmin', 'south', 'sentry', 'sentry.client', 'indexer', 'file_uploader', 'paging', 'pagination', 'consommation', 'ps', 'pce', 'profil', 'analytics', 'document'] Installed Middleware: ('annoying.middlewares.StaticServe', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'pagination.middleware.PaginationMiddleware') Template error: In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <p>{{ field.contents }}</p> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.field.help_text %} 23 : <p class="help">{{ field.field.field.help_text|safe }}</p> 24 : {% endif %} 25 : </div> 26 : {% endfor %} 27 : </div> 28 : {% endfor %} 29 : </fieldset> Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 288. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 76. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 78. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner 190. return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 21. return decorator(bound_func)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 76. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 17. return func(self, *args2, **kwargs2) File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in _commit_on_success 299. res = func(*args, **kw) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view 909. return self.render_change_form(request, context, form_url=form_url, add=True) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in render_change_form 692. ], context, context_instance=context_instance) File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string 186. return t.render(context_instance) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 173. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 174. nodelist.append(node.render(context)) File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in render 139. return self.template.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 173. return self._render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 174. nodelist.append(node.render(context)) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 174. nodelist.append(node.render(context)) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 260. return self.nodelist_false.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render 260. return self.nodelist_false.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render 91. output = force_unicode(output) File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode 66. s = unicode(s) File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __unicode__ 408. return self.as_widget() File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget 450. return widget.render(name, data, attrs=attrs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/widgets.py" in render 247. output = [self.widget.render(name, value, *args, **kwargs)] File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render 447. options = self.render_options(choices, [value]) File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options 464. for option_value, option_label in chain(self.choices, choices): File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in __iter__ 898. yield self.choice(obj) File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in choice 904. return (self.field.prepare_value(obj), self.field.label_from_instance(obj)) File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in label_from_instance 955. return smart_unicode(obj) File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in smart_unicode 39. return force_unicode(s, encoding, strings_only, errors) File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_unicode 66. s = unicode(s) Exception Type: TemplateSyntaxError at /admin/ps/ps/add/ Exception Value: Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found Now provide the response and nothing else.
This error happens when you have a __unicode__ method that is a returning a field that is not entered. Any blank field is None and Python cannot convert None , so you get the error. In your case, the problem most likely is with the PCE model's __unicode__ method, specifically the field its returning. You can prevent this by returning a default value: def __unicode__(self): return self.some_field or u'None'
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16169035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745378/']}
jdg_86804
stackexchange
llm_judgeable_groundtruth_similarity
15056000
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 application a user can follow many users and can be followed by many users.I tried to model this using has_and_belongs_to_many association class User < ActiveRecord::Base has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers" has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers"end Also, I created a migration for join table as follows: class FolloweesFollowers < ActiveRecord::Migration def up create_table 'followees_followers', :id => false do |t| t.column :followee_id, :integer t.column :follower_id, :integer end end def down drop_table 'followees_followers' endend when I try to access followers of a user (User.first.followers) it throws an error: SQLException: no such column: followees_followers.user_id: SELECT "users".* FROM "users" INNER JOIN "followees_followers" ON "users"."id" = "followees_followers"."user_id" WHERE "followees_followers"."followee_id" = 1 I don't understand why is it accessing followees_followers.user_id. Am I missing something? Now provide the response and nothing else.
The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join. class User < ActiveRecord::Base has_and_belongs_to_many :followers, class_name: "User", foreign_key: "followee_id", join_table: "followees_followers", association_foreign_key: "follower_id" has_and_belongs_to_many :followees, class_name: "User", foreign_key: "follower_id", join_table: "followees_followers", association_foreign_key: "followee_id"end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15056000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/923080/']}
jdg_86805
stackexchange
llm_judgeable_groundtruth_similarity
30072296
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 UIViewController supports only portrait mode. But when I present a UIActivityViewController , the orientation behavior is strange. When the UIActivityViewController is presented, I can rotate the device to any orientation without the share sheet being rotated. This is correct.But when the share sheet is presenting, and I put the device horizontally, then click the "More" button, the "More" settings page will be horizontal. Then when I finish the settings and back to share sheet, the share sheet along with my presenting UIViewController becomes horizontal. This breaks my layout. I have tried the trick that enclose the UIActivityViewController in a UINavigationController , but that does not change the behavior after clicking "more" button. Is there anyway to solve this? Now provide the response and nothing else.
2D Arrays: For the given 2D array input, you can use 2D convolution - %// Perform 2D convolution with a kernel of `2 x 2` size with all onesconv2_out = conv2(A,ones(2,2),'same')%// Find starting row-col indices of the window that has the maximum conv value[~,idx] = max(conv2_out(:))[R,C] = ind2sub(size(A),idx)%// Get the window with max convolution valuemax_window = A(R:R+1,C:C+1)%// Get the average of the max windowout = mean2(max_window) Sample step-by-step run of the code - A = 1 2 2 1 1 2 1 1 2 2 2 3 4 4 3 1 2 6 10 5 2 2 8 9 5conv2_out = 6 6 6 6 3 8 9 11 11 5 8 15 24 22 8 7 18 33 29 10 4 10 17 14 5idx = 14R = 4C = 3max_window = 6 10 8 9out = 8.25 Multi-dimensional Arrays: For multi-dimensional array case, you need to perform ND convolution - %// Perform ND convolution with a kernel of 2 x 2 size with all ONESconv_out = convn(A,ones(2,2),'same')%// Get the average for all max windows in all frames/slices [~,idx] = max(reshape(conv_out,[],size(conv_out,3)),[],1)max_avg_vals = conv_out([0:size(A,3)-1]*numel(A(:,:,1)) + idx)/4%// If needed, get the max windows across all dim3 slices/framesnrows = size(A,1)start_idx = [0:size(A,3)-1]*numel(A(:,:,1)) + idxall_idx = bsxfun(@plus,permute(start_idx(:),[3 2 1]),[0 nrows;1 nrows+1])max_window = A(all_idx) Sample input, output - >> AA(:,:,1) = 4 1 9 9 3 7 5 5 9 6 1 6 7 1 1 5 4 2 2 1A(:,:,2) = 9 4 2 2 3 6 4 5 3 9 1 1 6 6 8 8 5 3 6 4A(:,:,3) = 5 5 7 7 6 1 9 9 7 7 5 4 4 1 3 7 1 9 3 1>> max_windowmax_window(:,:,1) = 9 9 5 5max_window(:,:,2) = 8 8 6 4max_window(:,:,3) = 7 7 9 9>> max_avg_valsmax_avg_vals = 7 6.5 8
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30072296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3894693/']}
jdg_86806
stackexchange
llm_judgeable_groundtruth_similarity
11313951
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 UITableViewController with a grouped static UITableView. I am defining the cells for my static table view on the storyboard. One of the cells has a textfield in it. When this textfield is called, the keyboard pops up, however, the tableview is not automatically resizing like it normally would on a table view controller. So now the keyboard is partially covering the textfield and I can't scroll up. My understanding is that when you are using a UITableViewController and a tableview, the viewable area should automatically shrink when the keyboard is called. It does work as intended in other parts of my app, just not with this static table view. Does it not work with static tables? Is there something else I am missing? Is there an easy way to solve this? Thanks Now provide the response and nothing else.
Answer It has nothing to do with static cells. They should work. If your controller is already a UITableViewController, check if you used the method viewWillAppear . If you did, you have to call [super viewWillAppear:YES] to get the 'automatic behavior' to work. -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:YES]; // This line is needed for the 'auto slide up' // Do other stuff} This problem turns up easily because the boilerplate code for the controllers don't come with the viewWillAppear method call and if you define it in your controller, you override it. Extra Information Look at this link. Apple Table View Programming Guide Note: UITableViewController has new capabilities in iOS 3.0. A table-view controller supports inline editing of table-view rows; if, for example, rows have embedded text fields in editing mode, it scrolls the row being edited above the virtual keyboard that is displayed.... blah.... The important bit The UITableViewController class implements the foregoing behavior by overriding loadView, viewWillAppear:, and other methods inherited from UIViewController. In your subclass of UITableViewController, you may also override these methods to acquire specialized behavior. If you do override these methods, be sure to invoke the superclass implementation of the method, usually as the first method call, to get the default behavior.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11313951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587618/']}
jdg_86807
stackexchange
llm_judgeable_groundtruth_similarity
22953
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $0 < a < 1$ be fixed, and integer $n$ tends to infinity. It is not hard to show that the number of integers $k$ coprime to $n$ such that $1\leq k\leq an$ asymtotically equals $(a+o(1))\varphi(n)$.The question is: what are the best known estimates for the remainder and where are they written? Many thanks! Now provide the response and nothing else.
Vinogradov, I. M. An introduction to the theory of numbers, Ch. 2, problem N 19. It gives error term $O(\tau(n))$. But direct application of inclusion-exclusion principle gives $O(2^{\omega(n)})$ (where $\tau$ is the number of divisors, and $\omega$ is the number of prime divisors. Standart solution with Mobius function also gives $O(2^{\omega(n)})$ if one take into account that $\mu(p^2)=0.$
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/22953', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4312/']}
jdg_86808
stackexchange
llm_judgeable_groundtruth_similarity
14498
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: Let's say I need to find the function GetTypes() in all C# source file ( .cs ) the directories/subdirectories. I used grep -rn GetTypes *.cs , but I got an error with grep: *.cs: No such file or directory . I had to use grep -rn GetTypes * , but in this case it shows all the files not *.cs only. What command do I need to use to find the string only in .cs files? Now provide the response and nothing else.
If your shell is bash ≥4, put shopt -s globstar in your ~/.bashrc . If your shell is zsh, you're good. Then you can run grep -n GetTypes **/*.cs **/*.cs means all the files matching *.cs in the current directory, or in its subdirectories, recursively. If you're not running a shell that supports ** but your grep supports --include , you can do a recursive grep and tell grep to only consider files matching certain patterns. Note the quotes around the file name pattern: it's interpreted by grep, not by the shell. grep -rn --include='*.cs' GetTypes . With only portable tools (some systems don't have grep -r at all), use find for the directory traversal part, and grep for the text search part. find . -name '*.cs' -exec grep -n GetTypes {} +
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/14498', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1090/']}
jdg_86809
stackexchange
llm_judgeable_groundtruth_similarity
62407829
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My function takes three lists as arguments. Then, it uses PrettyTable to make a table, with each list being a separate column. My problem is, that those lists are not always of equal length, and PrettyTable wants them equal. I wonder how to append some empty positions to the two of the shorter lists, so they are of equal length. Alternatively... is there a table-making tool, that doesn't want all columns of equal length? Now provide the response and nothing else.
I found an applicable solution for my concrete scenario and I want to share it with you. Note that this is not an explanation on how ViewBinding works. I created some pseudocode below. (Migrated from my solution using DialogFragments that display an AlertDialog ). I hope it's almost correctly adapted to Fragments ( onCreateView() vs. onCreateDialog() ). I got it to work that way. Imagine we have an abstract BaseFragment and two extending classes FragmentA and FragmentB . First have a look at all of our layouts. Note that I moved out the reusable parts of the layout into a separate file that will be included later from the concrete fragment's layouts. Specific views stay in their fragment's layouts. Using a common layout is important for this scenario. fragment_a.xml: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- FragmentA-specific views --> <EditText android:id="@+id/edit_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/edit_name"> <!-- Include the common layout --> <include layout="@layout/common_layout.xml" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout></RelativeLayout> fragment_b.xml: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- FragmentB-specific, differs from FragmentA --> <TextView android:id="@+id/text_explain" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/explain" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/text_explain"> <!-- Include the common layout --> <include layout="@layout/common_layout.xml" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout></RelativeLayout> common_layout.xml <?xml version="1.0" encoding="utf-8"?><merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:parentTag="android.widget.RelativeLayout"> <Button android:id="@+id/button_up" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/up"/> <Button android:id="@+id/button_down" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button_up" android:text="@string/down" /></merge> Next the fragment classes. First our BaseFragment implementation. onCreateView() is the place where the bindings are inflated. We're able to bind the CommonLayoutBinding based on the fragment's bindings where the common_layout.xml is included. I defined an abstract method onCreateViewBinding() called on top of onCreateView() that returns the ViewBinding from FragmentA and FragmentB . That way I ensure that the fragment's binding is present when I need to create the CommonLayoutBinding . Next I am able to create an instance of CommonLayoutBinding by calling commonBinding = CommonLayoutBinding.bind(binding.getRoot()); . Notice that the root-view from the concrete fragment's binding is passed to bind() . getCommonBinding() allows to provide access to the CommonLayoutBinding from the extending fragments. We could be more strict: the BaseFragment should provide concrete methods that access that binding instead of make it public to it's child-classes. private CommonLayoutBinding commonBinding; // common_layout.xml@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Make sure to create the concrete binding while it's required to // create the commonBinding from it ViewBinding binding = onCreateViewBinding(inflater); // We're using the concrete layout of the child class to create our // commonly used binding commonBinding = CommonLayoutBinding.bind(binding.getRoot()); // ... return binding.getRoot();}// Makes sure to create the concrete binding class from child-classes before // the commonBinding can be bound@NonNullprotected abstract ViewBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);// Allows child-classes to access the commonBinding to access common // used viewsprotected CommonLayoutBinding getCommonBinding() { return commonBinding;} Now have a look at one of the the child-classes, FragmentA .From onCreateViewBinding() we create our binding like we would do from onCreateView() . In principle it's still called from onCreateVIew() . This binding is used from the base class as described above. I am using getCommonBinding() to be able to access views from common_layout.xml . Every child class of BaseFragment is now able to access these views from the ViewBinding . That way I can move up all logic based on common views to the base class. private FragmentABinding binding; // fragment_a.xml@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Make sure commonBinding is present before calling super.onCreateView() // (onCreateViewBinding() needs to deliver a result!) View view = super.onCreateView(inflater, container, savedInstanceState); binding.editName.setText("Test"); // ... CommonLayoutBinding commonBinding = getCommonBinding(); commonBinding.buttonUp.setOnClickListener(v -> { // Handle onClick-event... }); // ... return view;}// This comes from the base class and makes sure we have the required // binding-instance, see BaseFragment@Overrideprotected ViewBinding onCreateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) { binding = FragmentABinding.inflate(inflater, container, false); return binding;} Pros: Reduced duplicate code by moving it to the base class. Code in all fragments is now much clearer, and reduced to the essentials Cleaner layout by moving reusable views into a layout that's included via <include /> Cons: Possibly not applicable where views can't be moved into a commonly used layout file Views might need to be positioned differently between fragments/layouts Many <included /> layouts would result in many Binding classes, nothing gained then Requires another binding instance ( CommonLayoutBinding ). There is not only one binding class for each child ( FragmentA , FragmentB ) that provides access to all views in the view hierarchy What if views can't be moved into a common layout? I am strongly interested in how to solve this as best practice! Let's think about it: introduce a wrapper class around the concrete ViewBinding . We could introduce an interface that provides access to commonly used views. From the Fragments we wrap our bindings in these wrapper classes. On the other hand, this would result in many wrappers for each ViewBinding-type. But we can provide these wrappers to the BaseFragment using an abstract method (an generics). BaseFragment is then able to access the views, or work on them using the defined interface methods. What do you think? In conclusion: Maybe it's simply an limitation of ViewBinding that one layout needs to have its own Binding-class. If you found a good solution in cases the layout can't be shared and needs to be declared duplicated in each layout, let me know please. I don't know if this is best practice or if there are better solutions. But while this is the only known solution for my use case, it seems to be a good start!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62407829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4205710/']}
jdg_86810
stackexchange
llm_judgeable_groundtruth_similarity
81096
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've built the entire Xserver from git for testing proposes using the build.sh provided by freedesktop.org as the easier method to compile all modules against the git tree, and installed under the /opt/xorg path. The problem is that I can't find how gdm decides from where to load the Xserver and related binaries. I've read on the X.org site the section: 'Actually running the conformance tests', but the scripts/helpers that I could use returns a 404. Although I know where the Xorg executable is and its links, I'm not sure that will be enough to make everything work as expected, as I want to test the Xserver built and installed in the custom path. I'm using Debian 7.0 and GDM 3.4.1. Any other method could be used too? Now provide the response and nothing else.
Answer in 2 words: The location of Xserver for GDM is hard-coded at compile time in configure.ac, line 1199 in X_SERVER variable and can't be configured. So, may be you could play with symlinks, linking /usr/bin/Xorg (or, less probably /usr/bin/X , see this ) to your build of Xserver. Details: I have a Debian 7, too and here's my process tree: |-gdm3-+-gdm-simple-slav-+-Xorg | | |-gdm-session-wor-+-gnome-session-+-bluetooth-apple---{bluetooth-apple} | | | | |-evolution-alarm---2*[{evolution-alarm}] | | | | |-gdu-notificatio | | | | |-gnome-fallback----2*[{gnome-fallback-}] | | | | |-gnome-panel-+-gnome-terminal-+-bash | | | | | | |-bash---vi | | | | | | |-bash-+-less | | | | | | | `-pstree | | | | | | |-gnome-pty-helpe | | | | | | `-3*[{gnome-terminal}] | | | | | |-iceweasel-+-plugin-containe-+-4*[gtk-gnash] | | | | | | | `-{plugin-containe} | | | | | | `-31*[{iceweasel}] | | | | | |-pidgin | | | | | `-3*[{gnome-panel}] | | | | |-gnome-screensav---2*[{gnome-screensav}] | | | | |-gnome-settings----2*[{gnome-settings-}] | | | | |-gnome-sound-app---{gnome-sound-app} | | | | |-metacity---3*[{metacity}] | | | | |-nm-applet---{nm-applet} | | | | |-notification-da---{notification-da} | | | | |-polkit-gnome-au---{polkit-gnome-au} | | | | |-ssh-agent | | | | |-tracker-miner-f---2*[{tracker-miner-f}] | | | | |-tracker-store---6*[{tracker-store}] | | | | `-3*[{gnome-session}] | | | `-2*[{gdm-session-wor}] | | `-{gdm-simple-slav} | `-{gdm3} So, Xorg is started via gdm-simple-slave. Definitly, /etc/gdm/Init/Default has nothing to do with starting Xserver, as it was said here and here . There were some indications , that it's impossible to configure, how X is started from gdm. I decided to go for source codes, which are pretty well structured. So: Go to the source codes , there is a daemon folder, which contains an INTERNALS file, explaining the structure of code. There you can read: ** GdmServer A class, used by the slave, that manages running a local X Server. So, the file we need is https://git.gnome.org/browse/gdm/tree/daemon/gdm-server.c There are several nested functions, responsible for calling X server and creating its command line arguments. The function directly responsible for running X server process is gdm_server_spawn , which spawns the X in the line 694 with glib's g_spawn_async_with_pipes . So, we're to find out, how its argv is formed. Well, in 2 words it's line 293 and we need the value of X_SERVER macro (unless you're using RedHat's systemd instead of sysVinit, but you aren't :)). Alas, this macro is seemingly formed in configure.ac, line 1199 and is hard-coded. So, it seems that the best option is to place a symlink to your build of Xserver to one of those locations.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/81096', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/41104/']}
jdg_86811
stackexchange
llm_judgeable_groundtruth_similarity
52512011
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 AWS AppSync, arguments send on the main query don't seem to be forwarded to all children resolvers. type Query { article(id: String!, consistentRead: Boolean): Article book(id: String!, consistentRead: Boolean): Book}type Article { title: String! id: String!}type Book { articleIds: [String]! articles: [Article]! id: String!} when I call: query GetBook { book(id: 123, consistentRead: true) { articles { title } }} the first query to get the book receives the consistentRead param in $context.arguments , but the subsequent query to retrieve the article does not. ( $context.arguments is empty) I also tried articles(consistentRead: Boolean): [Article]! inside book but no luck. Does anyone know if it's possible in AppSync to pass arguments to all queries part of the same request? Now provide the response and nothing else.
It is possible to pass arguments from parent to child via the response. Let me explain ... AppSync has several containers inside $context : arguments stash source arguments and stash are always cleared before invoking a child resolver as evident from these Cloudwatch logs: At the very end of the parent execution - arguments and stash data are present. { "errors": [], "mappingTemplateType": "After Mapping", "path": "[getLatestDeviceState]", "resolverArn": "arn:aws:appsync:us-east-1:xxx:apis/yyy/types/Query/fields/getLatestDeviceState", "context": { "arguments": { "device": "ddddd" }, "prev": { "result": { "items": [ { "version": "849", "device": "ddddd", "timestamp": "2019-01-29T12:18:34.504+13:00" } ] } }, "stash": {"testKey": "testValue"}, "outErrors": [] }, "fieldInError": false} and then at the very beginning of the child resolver - arguments and stash are always blank. {"errors": [],"mappingTemplateType": "Before Mapping","path": "[getLatestDeviceState, media]","resolverArn": "arn:aws:appsync:us-east-1:yyy:apis/xxx/types/DeviceStatePRODConnection/fields/media","context": { "arguments": {}, "source": { "items": [ { "version": "849", "device": "ddddd", "timestamp": "2019-01-29T12:18:34.504+13:00" } ] }, "stash": {}, "outErrors": []},"fieldInError": false} Workaround 1 - get the argument from the previous result. In the example above device is always present in the response of the parent resolver, so I inserted #set($device = $util.defaultIfNullOrBlank($ctx.args.device, $ctx.source.items[0].device)) into the request mapping template of the child resolver . It will try to get the ID it needs from the arguments and then fall back onto the previous result. Workaround 2 - add the argument to the parent response Modify your parent resolver response template to include the arguments: { "items": $utils.toJson($context.result.items), "device": "${ctx.args.device}"} and then retrieve it in the request mapping template of the child the same way as in the first workaround.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52512011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202726/']}
jdg_86812
stackexchange
llm_judgeable_groundtruth_similarity
50938519
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 seen a bunch of questions with similar titles but I still cant figure it out. All I want to do is replace the value thats in my dataframe in the fifth row and 5th column with the value 100.I thought simply this would do the trick df.loc['cheerios','rating']= 100 since cheerios is the row and rating is the column name sugar sodium rating0 fruit loop x x x1 trix x x x2 oreo x x x3 cocoa puff x x x4 cheerio x x 100 Now provide the response and nothing else.
.loc is an indexer . It looks for an entry in the index, but the column name is not an index. It is simply a column. The following solutions would work: df.loc[4, 'rating'] = 100 # Because 4 is in the index, but how do you know? or: df.loc[df['name']=='cheerio', 'rating'] = 100 # Find the row by column or: df.set_index('name', inplace=True) # Make 'name' the indexdf.loc['cheerios', 'rating'] = 100 # Use the indexer
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50938519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9927674/']}
jdg_86813
stackexchange
llm_judgeable_groundtruth_similarity
23287357
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my error: rake aborted!Gem::LoadError: You have already activated rake 10.3.1, but your Gemfile requires rake 10.2.2. Prepending `bundle exec` to your command may solve this./Users/AaronWilliamson/.gem/ruby/2.1.0/gems/bundler-1.5.3/lib/bundler/runtime.rb:34:in `block in setup'/Users/AaronWilliamson/.gem/ruby/2.1.0/gems/bundler-1.5.3/lib/bundler/runtime.rb:19:in `setup'/Users/AaronWilliamson/.gem/ruby/2.1.0/gems/bundler-1.5.3/lib/bundler.rb:119:in `setup'/Users/AaronWilliamson/.gem/ruby/2.1.0/gems/bundler-1.5.3/lib/bundler/setup.rb:7:in `<top (required)>'/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/config/boot.rb:4:in `<top (required)>'/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/config/application.rb:1:in `<top (required)>'/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/Rakefile:4:in `<top (required)>'LoadError: cannot load such file -- bundler/setup/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/config/boot.rb:4:in `<top (required)>'/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/config/application.rb:1:in `<top (required)>'/Users/AaronWilliamson/Desktop/Ripelist-Classifieds/Rakefile:4:in `<top (required)>'(See full trace by running task with --trace) I can't run any rake tasks and this seems to be the root of all my other problems. It wasn't like this a couple days ago when I was running rake commands. Can anyone explain what's going on here and how to get my app back on track? I've hit a wall. Also, bundle exec doesn't fix the root of the problem for me. I never had to do that in the past and it's still not working now. Now provide the response and nothing else.
EDIT 2: You should look at bundle update and change your workflow a little. Refer to this question for further assistance. Original answer This is a simple issue which happens when your gemset has a rake version that is newer than the version number your Gemfile.lock mentions. As is mentioned in the error message, you can use bundle exec to get things working. My solution in such cases is to just remove Gemfile.lock if I am not too worried other gem versions and their endless dependencies. Otherwise, you can try just removing the one line in Gemfile.lock which talks about the version of rake. run bundle install and the world should be a happy place again. ( edit 2 : Run bundle update --source instead of this. Don't do this.) PS: Try using gemsets and organising your gems with rvm for different projects. Edit I prefer using rbenv now for managing installations and all gems for a project reside in vendor/bundle using bundle install --path option. Later scope every gem command with bundle exec . Hence, rails s becomes bundle exec rails s . A little more typing is, in my opinion, better if it means that things will remain clean and conflicts such as this one don't happen.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23287357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2981132/']}
jdg_86814
stackexchange
llm_judgeable_groundtruth_similarity
15683975
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working in SQL Server 2008 and trying to use a IF, ELIF, ELSE statement in the SELECT section of my code. What I want to do is the following: IF BO.VALUE < BO.REFERENCELOWERLIMIT THEN (BO.VALUE - BO.REFERENCELOWERLIMIT) #I WANT THIS TO BE NEGATIVEELSE IF BO.REFERENCELOWERLIMIT <= BO.VALUE <= BO.REFERENCEUPPERLIMIT THEN BO.VALUEELSE (BO.REFERENCEUPPERLIMIT - BO.VALUE) The problem is that I do not understand how to do a IF, ELIF, ELSE type transaction in SQL. I have tried to search for this type of example and came across python examples...wrong language so I did a search on the MSDBN site and did not see this sort of work, just IF/ELSE. Thank You Now provide the response and nothing else.
You want a CASE expression. CASE evaluates in order and the first match is what is returned in the query. SELECT CASE WHEN BO.VALUE < BO.REFERENCELOWERLIMIT THEN (BO.VALUE - BO.REFERENCELOWERLIMIT) WHEN BO.VALUE BETWEEN BO.REFERENCELOWERLIMIT AND BO.REFERENCEUPPERLIMIT THEN BO.VALUE ELSE (BO.REFERENCEUPPERLIMIT - BO.VALUE) END as MyColumnAlias...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15683975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1510267/']}
jdg_86815
stackexchange
llm_judgeable_groundtruth_similarity
52678469
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Anyone please give some information why this is happening? When I try to add a class AppBarDesign which implements appBar flutter is giving the below error. error: The argument type 'AppBarDesign' can't be assigned to the parameter type 'PreferredSizeWidget'. (argument_type_not_assignable at [flutterbyrajath] lib\main.dart:27) import 'package:flutter/material.dart'; main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Rajath\'s design ', debugShowCheckedModeBanner: false, theme: new ThemeData(primarySwatch: Colors.amber), home: new MyHomePage(key, 'App is Fun'), ); } } class MyHomePage extends StatelessWidget { MyHomePage(Key key, this.title) : super(key: key); final title; @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBarDesign(key, title), ); } } class AppBarDesign extends StatelessWidget { AppBarDesign(Key key, this.title) : super(key: key); final title; @override Widget build(BuildContext context) { return new AppBar( title: new Text(title), ); } } Now provide the response and nothing else.
Scaffold requires as appbar a class that implements PreferredSizeWidget Either wrap your custom appbar into a PreferredSize Scaffold( appBar: PreferredSize( preferredSize: const Size.fromHeight(100), child: Container(color: Colors.red), ),) or implement PreferredSizeWidget : Scaffold( appBar: MyAppBar(),)...class MyAppBar extends StatelessWidget implements PreferredSizeWidget { @override Size get preferredSize => const Size.fromHeight(100); @override Widget build(BuildContext context) { return Container(color: Colors.red); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52678469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6532133/']}
jdg_86816
stackexchange
llm_judgeable_groundtruth_similarity
30557521
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lets say I am setting a value on the http context in my middleware. For example HttpContext.User. How can test the http context in my unit test. Here is an example of what I am trying to do Middleware public class MyAuthMiddleware{ private readonly RequestDelegate _next; public MyAuthMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { context.User = SetUser(); await next(context); }} Test [Fact]public async Task UserShouldBeAuthenticated(){ var server = TestServer.Create((app) => { app.UseMiddleware<MyAuthMiddleware>(); }); using(server) { var response = await server.CreateClient().GetAsync("/"); // After calling the middleware I want to assert that // the user in the HttpContext was set correctly // but how can I access the HttpContext here? }} Now provide the response and nothing else.
Following are two approaches you could use: // Directly test the middleware itself without setting up the pipeline[Fact]public async Task Approach1(){ // Arrange var httpContext = new DefaultHttpContext(); var authMiddleware = new MyAuthMiddleware(next: (innerHttpContext) => Task.FromResult(0)); // Act await authMiddleware.Invoke(httpContext); // Assert // Note that the User property on DefaultHttpContext is never null and so do // specific checks for the contents of the principal (ex: claims) Assert.NotNull(httpContext.User); var claims = httpContext.User.Claims; //todo: verify the claims}[Fact]public async Task Approach2(){ // Arrange var server = TestServer.Create((app) => { app.UseMiddleware<MyAuthMiddleware>(); app.Run(async (httpContext) => { if(httpContext.User != null) { await httpContext.Response.WriteAsync("Claims: " + string.Join( ",", httpContext.User.Claims.Select(claim => string.Format("{0}:{1}", claim.Type, claim.Value)))); } }); }); using (server) { // Act var response = await server.CreateClient().GetAsync("/"); // Assert var actual = await response.Content.ReadAsStringAsync(); Assert.Equal("Claims: ClaimType1:ClaimType1-value", actual); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30557521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2919398/']}
jdg_86817
stackexchange
llm_judgeable_groundtruth_similarity
545080
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: Note : I am a beginner. I noticed on the STM32-410RB datasheet page 100 ( https://www.st.com/resource/en/datasheet/stm32f410rb.pdf ), protection resistors were used in series on the SDA and SCL line. Further research showed that using protection resistors for devices connected to I2C is commonplace. How would I choose/calculate what resistor to to "protect devices" on the I2C bus or generally? Could this method be: (input voltage - Forward voltage)/ Forward current ? This was the method I found for protecting and LED using a resistor in series, would this be the same for the I2C bus? Now provide the response and nothing else.
The series Rs resistors aren't for 'protection' pe se, the I2C spec notwithstanding (more about this below.) In any event, for Standard (100 KHz) and Fast (400 KHz) mode they're optional. For the higher-speed I2C modes (1 and 3 Mbit) they are used as series damping to reduce ringing and thus improve signal integrity. For that case, choose an Rs value such that the driver impedance (Rds(on)) and Rs together are roughly the same as the board trace impedance. Typical Rs values are 22 to 33 Ohms, which when combined with the driver Rds(on) resistance, yields about 60-70 Ohms, a reasonably good match for typical trace routing. MORE: The I2C spec states the reason for Rs is to suppress noise spikes, and that Rs is optional. In reality, the limiting value for Rs depends on several factors: Bus speed chosen Max allowable risetime Total bus capacitance Strength of pull-up The bigger your I2C bus (# devices, signal length), the stronger your pullup needs to be to overcome capacitance. Same with faster bus speed: to meet risetime, a stronger pullup is called for. On the other hand, the driver Rds(on) resistance and Rs form a voltage divider with the pullup resistor Rpu. If Rs is made too large, the output low on the bus might not be low enough to meet the Vin(low) spec for the other devices on the bus. Design accordingly. Finally, if ESD hardiness is a factor in your system (for example, if your I2C is going to a connector), don't rely on Rs to do this job . Instead, consider an I2C isolation device, and use TVS diodes on the lines for a more robust solution. (Experience: set-top boxes with HDMI as well as on-board I2C.)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/545080', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/271478/']}
jdg_86818
stackexchange
llm_judgeable_groundtruth_similarity
1362144
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The essence of this question is: Let $(M,g_M)$ and $(N,g_N)$ be Riemannian manifolds. How many different ways are there to embed $M$ isometrically in $N$? In this context, I say the embedding $i_1$ is different from $i_2$ if there is no isometry $\varphi:N\to N$ suct that $i_2=\varphi\circ i_1$. This question is rather easy for specific pairs of manifolds. For example, if $M$ is a line, any embedding has an arc length parametrization, which is just a different name for isometric embedding. Alternatively, let $M$ be Euclidean plane and $N$ Euclidean space. Then for every (smooth) function $f:\mathbb{R}\to\mathbb{R}$, the submanifold $$\{(x,y,z)|y=f(x)\}\subset\mathbb{R}^3,$$equipped with the Riemannian metric inherited from $\mathbb{R}^3$, is isometric to the plane. It is not hard to convince oneself that many of these submanifolds cannot be carried to one another by isometries of Euclidean space. However, there are other simple examples for which I don't know the answer. For example, what happens when $M$ is $S^2$ with the unit sphere metric, and $N$ is Euclidean space? Somehow, the only way I can imagine $S^2$ embedded in $\mathbb{R}^3$ is by the standard embedding, but I can't find an argument to prove that. Intuitively speaking, it may have something to do with curvature. If so, I guess the answer to the question changes when allowing $C^1$ embeddings. Anything regarding the last example, of the sphere and Euclidean space, would already make me happy. If, by any chance, someone has an answer to a more general case, that would be great. Insights about less smooth embeddings (e.g. $C^1$ embeddings) are also welcome, though I'm mostly interested in the smooth case. Now provide the response and nothing else.
You should have a look at Berger's monumental A Panoramic View of Riemannian Geometry (specifically section 3.4 p. 131-142 and section 4.6, p. 216-218). Two striking theorems are the following: Every Riemannian metric $g$ on $S^2$ with positive curvature is isometrically embeddable in $\mathbb R^3$, in a unique way. [Alexandrov, Weyl, Nirenberg, Pogorelov]. A consequence of Nash's embedding theorem is that there are $C^1$ isometric embeddings of the standard $S^2$ in an arbitrarily small ball in $\mathbb R^3$. Obviously, this is quite far from the standard embedding...
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1362144', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166201/']}
jdg_86819
stackexchange
llm_judgeable_groundtruth_similarity
35686569
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 preparing for my AS-Level Computer Science exam I came across a question in the pre-release material: Prompt the user to input a User ID and check if the format of the ID corresponds with pre-defined formatting rules and output accordingly. The Format (In order): One upper case letter Two Lower case letters Three numeric characters (digits) Example: "Abc123" I came up with a solution using my language of choice(Python), however, I was wondering if there is a more elegant or better way to solve this. Especially the third check. Here is my code: #Task 2.2u_id = input("Input User ID: ") #DECLARE u_id : stringnumbers = [str(num) for num in range(10)]#Checking if final 3 characters of User ID (u_id) are digitsfor i in list(u_id[3::]): if i not in numbers: digit_check = False #DECLARE digit_check : bool break else: digit_check = True#User ID format checkif (u_id[0:1].isupper() == True) and (u_id[1:3] == u_id[1:3].lower()) and (digit_check == True): print ("Correct Format")else: print ("Wrong Format") Ignore the DECLARATION comments. They are an exam requirement. Thanks Now provide the response and nothing else.
If you are allowed to import re : import reu_id = input("Input User ID: ") #DECLARE u_id : stringrex = re.compile("^[A-Z][a-z]{2}[0-9]{3}$")if rex.match(u_id): print("Correct format")else: print("Incorrect") Explanation of expression: ^ represents the beginning of a string. [A-Z] is a range, containing all uppercase letters (in the English alphabet). [a-z] is a range, containing all lowercase letters. [0-9] is a range, containing all numbers. {n} specifies that n items (items are whatever is before the curly brackets) will be matched. $ represents the end of the string. Also, you can see more detailed explanations and test arbitrary strings against this regular expression here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35686569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5994241/']}
jdg_86820
stackexchange
llm_judgeable_groundtruth_similarity
328946
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have to do the following. Let $F$ be an algebraically closed field. $I\in F[X_1,...,X_n]$ an ideal. Denote by $S(I)$ the subset in $F^n$ consisting of all $n$-tuples $(a_1,...,a_n)\in F^n$ such that $f(a_1,...,a_n)=0$ for all $f\in I$. A subset $S\subset F^n$ is called closed if there exists an ideal $I$ (of $F[X_1,...,X_n]$ such that $S=S(I)$. Prove that the union of any two closed sets is closed. Here is my attempt: First: I claim that if $S$ is closed then I can find an $I$ such that it is generated by one element and $S(I)=S$. Proof: By definition of closed we know there is a $J$ such that $S=S(J)$. Since our ring is Noetherian we know that $J$ is f.g. so $J=\langle f_1,..,f_k\rangle$. Let $h=\gcd(f_i)$. I claim that $I=\langle h\rangle $ works. If $(a_1,..,a_n)\in S$, then $f_i(a_1,..,a_n)=0$. Since $h=\sum \alpha_i f_i$ (Bezout), we just plug in $(a_1,...,a_n)$ at both sides and obtain that $h(a_1,...,a_n)=0$, so indeed $(a_1,...,a_n)\in S(I)$. For the reverse inclusion if $(a_1,..,a_n)\in S(I)$, then $h(a_1,...,a_n)=0$. As $h\mid f_i$, we have that $f_i(a_1,...,a_n)=0$, so $(a_1,...,a_n)\in S(J)$. Now using this fact, I will solve the question: Let $S_1$ and $S_2$ be closed with $I_1=\langle f\rangle$ and $I_2=\langle g\rangle$ such that $S_1=S(I_1)$, and $S_2=S(I_2)$. Then let $h=$lcm$ (f,g)$. Then we have that $S(\langle h\rangle)$ works. If $(a_1,...,a_n)\in S_1\cup S_2$, then either $f(a_1,...,a_n)$ or $g(a_1,...a_n)=0$ (wlog say the first case happens). Then since $f\mid h$ then $(a_1,...,a_n)\in S(\langle h\rangle)$. For the other inclusion just note that if $h(a_1,...,a_n)=0$ then eithe $f(a_1,...,a_n)=0$ or $g(a_1,...,a_n)=0$ (because otherwise we would have $fg(a_1,....,a_n)\neq 0$ and since $h\mid fg$ we would get a contradiction here) so we have that either $(a_1,...,a_n)\in S_1$ or $(a_1,...,a_n)\in S_2$. Question: Where do I need the algebraic closure here? Now provide the response and nothing else.
Your claim is not correct, there are many algebraic sets which can not be defined by a single equation. In your proof you use properties of the polynomial ring which only hold for one variable. The correct proof is much easier, just show $V(I \cdot J) = V(I) \cup V(J)$, where $V(I)$ denotes the vanishing set of the ideal $I$ (which you denote by $S(I)$, but this notation is not common). And in fact this holds over every field.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/328946', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64900/']}
jdg_86821
stackexchange
llm_judgeable_groundtruth_similarity
540277
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to do a digital clock using an Atmega8A, LCD display (2x16) and four tact switches. Key number 1 is connected to pin PD2, number 2 to PD3, number 3 to PB6, number 4 to PB7. When you press key 1 you can choose between hours, minutes, seconds, when you click key 2 you increment hours/minutes/seconds (chosen by button 1) by one. Key 3 is use to stop the clock. You can modify the clock only when the flag "ableToEdit" is set to one. Key 4 is used to start the clock again. Last thing that I need to do is debouncing. I have tested this method on my other Atmega8A microcontroller and it works. My method: #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #define KEY1 (1 << PD2) uint8_t key_pressed; int main(void) { DDRD &= ~(1 << PD2); DDRB |= (1 << PB0); DDRB |= (1 << PB1); PORTD |= (1 << PD2); PORTB |= (1 << PB0); _delay_ms(10); while(1) { if(!key_pressed && !(PIND & KEY1)) { key_pressed = 1; PORTB ^= (1 << PB1); }else if( key_pressed && (PIND & KEY1)) key_pressed++; } return 0; } When I tried to implement this in my clock code, it doesn't work as in the code above. When I click a tact switch the value of hours/minutes/seconds is incremented by one and later I can't do anything; only after a long while when I click a key again is the value incremented by one and so on. Other keys work similar. I click them and only after longer moment it does someting but sometimes I cant't do anything. By saying longer moment I mean a minute or several dozens of seconds. #include <avr/io.h>#include <avr/interrupt.h>#include <hd44780.c>#include <stdio.h>#include <stdlib.h>volatile int modeFlag = 1;volatile int ableToEdit = 1;volatile int seconds = 0;volatile int minutes = 0;volatile int hours = 0;uint8_t key_lock1;uint8_t key_lock2;uint8_t key_lock3;uint8_t key_lock4;char secondsBuffer[3];char minutesBuffer[3];char hoursBuffer[3];void key1Pressed(){ if(ableToEdit == 1) { if(!key_lock1 && !(PIND & (1 << PD2))) { key_lock1 = 1; modeFlag++; if (modeFlag > 3) { modeFlag = 1; } } else if(key_lock1 && (PIND & (1 << PD2))) { key_lock1 ++; if(key_lock1 == 255) { key_lock1 = 0; }; } }}void key2Pressed(){ if(ableToEdit == 1) { if(!key_lock2 && !(PIND & (1 << PD3))) { key_lock2 = 1; switch(modeFlag) { case 1: if(hours == 24) { hours = 0; } hours ++; break; case 2: if(minutes == 60) { minutes = 0; } minutes ++; break; case 3: if(seconds == 60) { seconds = 0; } seconds ++; break; } } else if(key_lock2 && (PIND & (1 << PD3))) { key_lock2 ++; if(key_lock2 == 256) { key_lock2 = 0; } } }}void key3Pressed(){ if(!key_lock3 && !(PINB & (1 << PB6))) { key_lock3 = 1; ableToEdit = 1; TCCR1B &= ~(1 << CS12); TCCR1B &= ~(1 << CS10); } else if(key_lock3 && (PINB & (1 << PB6))) { key_lock3 ++; }}void key4Pressed(){ if(!key_lock4 && !(PINB & (1 << PB7))) { key_lock4 = 1; ableToEdit = 0; TCCR1B |= (1 << CS12) | (1 << CS10); } else if(key_lock4 && (PIND & (1 << PB7))) { key_lock4 ++; }}ISR(TIMER1_COMPA_vect){ seconds++; if(seconds == 60) { seconds = 0; minutes ++; if(minutes == 60) { seconds = 0; minutes = 0; hours ++; if(hours == 24) { hours, minutes, seconds = 0; } } }}int main(void){ DDRD &= ~(1 << PD2); DDRD &= ~(1 << PD3); DDRB &= ~(1 << PB6); DDRB &= ~(1 << PB7); PORTD |= (1 << PD2); PORTD |= (1 << PD3); PORTB |= (1 << PB6); PORTB |= (1 << PB7); _delay_ms(20); // LCD init LCD_Initalize(); // Timer init TCCR1B |= (1 << WGM12); OCR1A = 977; TIMSK |= (1 << OCIE1A); sei(); while(1) { key1Pressed(); key2Pressed(); key3Pressed(); key4Pressed(); if(hours == 24) { hours = 0; } if(minutes == 60) { minutes = 0; } if(seconds == 60) { seconds = 0; } itoa(seconds, secondsBuffer, 10); itoa(minutes, minutesBuffer, 10); itoa(hours, hoursBuffer, 10); LCD_Clear(); LCD_GoTo(0, 0); LCD_WriteText("Aktualna godzina"); LCD_GoTo(4, 1); switch(hours) { case 24: LCD_WriteText("00"); break; case 0: LCD_WriteText("00"); break; case 1: LCD_WriteText("01"); break; case 2: LCD_WriteText("02"); break; case 3: LCD_WriteText("03"); break; case 4: LCD_WriteText("04"); break; case 5: LCD_WriteText("05"); break; case 6: LCD_WriteText("06"); break; case 7: LCD_WriteText("07"); break; case 8: LCD_WriteText("08"); break; case 9: LCD_WriteText("09"); break; default: LCD_WriteText(hoursBuffer); } LCD_GoTo(6, 1); LCD_WriteText(":"); LCD_GoTo(7, 1); switch(minutes) { case 0: LCD_WriteText("00"); break; case 1: LCD_WriteText("01"); break; case 2: LCD_WriteText("02"); break; case 3: LCD_WriteText("03"); break; case 4: LCD_WriteText("04"); break; case 5: LCD_WriteText("05"); break; case 6: LCD_WriteText("06"); break; case 7: LCD_WriteText("07"); break; case 8: LCD_WriteText("08"); break; case 9: LCD_WriteText("09"); break; default: LCD_WriteText(minutesBuffer); } LCD_GoTo(9, 1); LCD_WriteText(":"); LCD_GoTo(10, 1); switch(seconds) { case 0: LCD_WriteText("00"); break; case 1: LCD_WriteText("01"); break; case 2: LCD_WriteText("02"); break; case 3: LCD_WriteText("03"); break; case 4: LCD_WriteText("04"); break; case 5: LCD_WriteText("05"); break; case 6: LCD_WriteText("06"); break; case 7: LCD_WriteText("07"); break; case 8: LCD_WriteText("08"); break; case 9: LCD_WriteText("09"); break; default: LCD_WriteText(secondsBuffer); } _delay_ms(200); } return 0;} I tried to change the value of the "ableToEdit" variable but it doesn't help. I also tried using INT0 and INT1 interrupts and don't see any effects.Why doesn't it work? The method in the second example is exactly the same as in the first example. How can I fix it? Now provide the response and nothing else.
I have several suggestions. First up, I would not swap the P and N over in the way you have shown. All via crossings must be symmetric, so dropping one half of the pair to the other side is a bad idea. If you can't curl the pair in from the opposite side of a set of pins (not possible for QFNs), then you have to do it by crossing over both P and N to the other side of the board. Here is an example of how you can reverse the P and N symmetrically. You will additionally need a pair of vias to get both traces back to the top side. When crossing the pair to the other side of the board, something which you should try to minimise, you should additionally have stitching vias nearby to ensure that return currents can swap between reference planes. Crossing traces over each other when there are reference planes between them is perfectly fine as you suspected. For phase matching of the P and N parts of the pairs, you need to keep the changes in spacing to a minimum to avoid large impedance discontinuities. The large humps that KiCAD has made for you are terrible and should not be used. You also want to do this matching as close as possible to where the shift occurs - that means matching each individual bend, not having one big correction part way along the pair. As a general rule, you want to try and keep the change in spacing to around 1.25x the normal spacing, and certainly no more than 1.5x. If we assuming a 1.5x spacing, then at each 45 degree bend you need four wibbles, two each side of the bend. For example, this is a 90 degree bend, matched using eight wibbles: As a passing note, you have lots of places where the traces cross over and then cross back again in an attempt to untangle the routing. I would suggest having another go at laying this out. I would look to try and keep the muxes on the same side of the board initially as it will reduce assembly costs (single side assembly is cheaper). Start with routing of the high speed traces, ignore the USB 2.0 lines initially (they are much more forgiving). You could draw thet traces initially as single-ended sketches on the silk layers to get an idea of where each trace will go (much easier to move around a silk line than a diff pair). Another helpful think to consider is that you may be able to reduce the cross-overs by swapping the two outputs of the mux. If you swap both RX1<->RX2 and TX1<->TX2, then it may help reduce congestion. You can compensate for this by adding a simple inverter (e.g. SN74LV1T34) to the select signal of the multiplexer. Similarly, the differential pairs use CML, which is a symmetrical standard. There would be no issues swapping the + and - lines of all the inputs and outputs on a multiplexer if it made it easier to route and avoided having to cross over the Ps and Ns. (With the device you've selected, as far as I can tell, it's a high-speed analogue mux. There doesn't appear to be any difference between the Tx and Rx signals (essentially two identical muxes, one used for Rx, one used for Tx). So you could for example use one of these muxes for both sets of transmit lines, and the other for both sets of receive lines. I'm not sure that will help you, and I would avoid doing it without checking with OnSemi first, but in a tight spot I might consider it).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/540277', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/272682/']}
jdg_86822
stackexchange
llm_judgeable_groundtruth_similarity
27172762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just stumbled upon the documentation for the new (proposed for ES6, but already implemented in Firefox, Chrome & Opera) datatype in JavaScript, Symbol : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol http://people.mozilla.org/~jorendorff/es6-draft.html#sec-symbol-objects I'm reading about it, but I just can't think of a possible usage scenario. The documentation says: A symbol is a unique and immutable data type and may be used as an identifier for object properties. OK, fine, let's say I do as the documentation says: obj[Symbol("a")] = "a"; but, since Symbol('a') always returns unique value (object) and: Symbols are not visible in for...in iterations. how do I retrieve my property from obj ? var obj = { normalProperty: 'just a string' };obj[Symbol('a')] = 'a';document.getElementById('retrieve').addEventListener('click', function() { document.write('Stringified object:' + JSON.stringify(obj) + '<br/><br/>'); document.write('Trying to get Symbol-property value, aaaand...: <br/>'); document.write(obj[Symbol('a')]); // undefined}, false); <button id="retrieve">Retrieve obj's property</button> Edit Of course, you can retrieve it like this: var x = Symbol('a');obj[x] = 'a';obj[x]; // "a" but what's the purpose of doing it this way? Thanks in advance :) Now provide the response and nothing else.
After reading the documentation and playing a little bit with this Symbol type in chrome, it appears that a Symbol is a way to define a name -- not a value --, and the fact that properties defined using symbols are not visible using for..in , Object.getOwnPropertyNames() or JSON.stringify() makes symbols useful for metadata properties: // define metadata symbolsvar Metadata = { Date: Symbol('Message date')};var email = function(recipient, message) { this.Recipient = recipient; this.Message = message; this[Metadata.Date] = new Date();};var email1 = new email('@Me', 'test');JSON.stringify(email1);// {// Recipient: '@Me',// Message: 'test'// }// Date is still accessible usingemail1[Metadata.Date];// Thu Nov 27 2014 16:50:00 GMT+0000// Debugging in Console:// {// Recipient: '@Me',// Message: 'test'// Symbol(Message date): Thu Nov 27 2014 16:50:00 GMT+0000// } Symbols can be made global using the Symbol.for function, so metadata names can be created once and used across all project files. Accessing the value using a symbol requires having a reference to the symbol when created. Each call to Symbol() creates a new one even if the same description is used: var a = Symbol('a');var b = Symbol('a');a != b// anda != Symbol('a') but, creating a symbol using Symbol.for , it will be registered in a global registry and the description becomes a key, meanong only one symbol with the same key will exist in the global registry: var a = Symbol.for('a');var b = Symbol.for('a');a == b// anda == Symbol.for('a')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27172762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1827921/']}
jdg_86823
stackexchange
llm_judgeable_groundtruth_similarity
9227835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To start an Activity you need an Intent, like: Intent i = new Intent(context, class) So to fill in the context parameter, a couple of options are available: Use MyActivity.this or just this Use getApplicationContext() Use getBaseContext() And I'm sure there are one or two more options.These options all appear in some sort of tutorial, one uses the first, the next uses the third option. So which one should I use? Does it even matter? Is it different for different cases? Now provide the response and nothing else.
Yes its different for different cases, It depends on the scope. Suppose if you are creating a method in a global class that extends Application to create a Toast that is used in every class of your Application you can use getApplicationContext() to create it. If you want to create a view that is restricted to that particular Activity you can use Activity.this Also if you want to create an AlertDialog in some inner class say AsyncTask , then you have to use Activity.this , because the AlertDialog is to be linked to Activity itself. Also don't use getBaseContext() just use the Context that you are having. For getting further information for the same you can see this Answer . So, the answer to the real question is better to use Activity.this to start a new Activity . Intent intent = new Intent(Current_Activity.this, Calling.class);startActivity(intent);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9227835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/675383/']}
jdg_86824
stackexchange
llm_judgeable_groundtruth_similarity
6714591
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 catch 'Trying to get property of non-object' error with a try/catch statement but it is failing, I still get a PHP error. I am using as: try{ $id = Model()->find('id=1')->id;}catch(Exception $e){ echo 'failed';} My find function returns an object (Active Record) and I can access the id column as shown via object prop. However, it will be null object if AR is not found. I thought the try statement would catch this. A work around for myself would be to use an isset(). But I am confused as to why the try statement does not accept and catch this error. Now provide the response and nothing else.
try..catch works on thrown exceptions . Errors are not exceptions. You can silence errors, but please don't do that. Instead, properly check what you're getting: $result = Model()->find('id=1');if ($result) { $id = $result->id;} else { // handle this situation}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6714591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/847372/']}
jdg_86825
stackexchange
llm_judgeable_groundtruth_similarity
433475
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The categories $\mathbf{Top}$ of topological spaces, $\mathbf{sSet}$ of simplicial sets and $\mathbf{Cat}$ of small categories are all equipped with a functor $\pi_0$ into the category $\mathbf{Set}$ of sets, which is a left adjoint and measures the number of connected components. There are also plenty of functors between the upper categories, which gives rise to the question, if they preserve the number of connected components. I have already proven this for $|-|\colon\mathbf{sSet}\leftrightarrows\mathbf{Top}\colon \operatorname{Sing}$ , for $\tau\colon\mathbf{sSet}\leftrightarrows\mathbf{Cat}\colon N$ and for $\operatorname{Sd}\colon\mathbf{sSet}\leftrightarrows\mathbf{sSet}\colon\operatorname{Ex}$ . The functor $\operatorname{Ex}^\infty=\varinjlim_{n\in\mathbb{N}}\operatorname{Ex}^n\colon\mathbf{sSet}\rightarrow\mathbf{sSet}$ still works fine since the colimit commutes with the left adjoint $\pi_0$ . The problem is, that $\operatorname{Sd}^\infty=\varprojlim_{n\in\mathbb{N}}\operatorname{Sd}^n\colon\mathbf{sSet}\rightarrow\mathbf{sSet}$ does not work fine because of the limit and since it is not the left adjoint of $\operatorname{Ex}^\infty$ and also writing either $X$ or $\operatorname{Sd}^n(X)$ as a colimit doesn't seem to work out. Does $\operatorname{Sd}^\infty$ also preserve the number of connected components? If yes, how is it proven and if no, is there a counterexample? The fact, that there are many other categories with a forgetful functor to $\mathbf{Set}$ and left adjoints ( free object functor ) or right adjoints (cofree object functor) like we have for the three categories above, gives also rise to some more questions: Are there more categories with a functor like $\pi_0$ (like for example the category $\mathbf{Graph}$ of graphs) giving the number of connected components and functors to other categories with one, which I have not yet considered? If yes, is the number of connected components preserved? Are there other categories with functors similar to $\pi_0$ in the sense that they measure something similar, so we can look at more possible preservations? Now provide the response and nothing else.
Ignoring issues with what TOP really should be, let me focus on the question whether $\pi_0(Sd^\infty(X))=\pi_0(X)$ for a simplicial set $X$ . If we look at $X=\Delta^1$ , we should get a counterexample. Here $\pi_0$ should denote the equivalence class of vertices, where two vertices are equivalent, if there is a finite path (a list of one simplices ignoring the direction) joining them.In the inverse limit, we have uncountably many zero simplices, but only countably many (non-degenerate) one simplices. Thus $\pi_0(Sd^\infty(\Delta^1))$ must be uncountable. A long time ago I thought a bit about these situations. Morally, I think there category of sets is somehow the wrong category for such questions. We can view any set as a discrete topological space. But then that functor $SET\to TOP$ is not compatible with limits. I believe I could show a statement of the form that if $(X_n)_{n\in \mathbb{B}}$ is a inverse system of m-dimensional, simplicial (totally disconnected compact Hausdorff-spaces), then the canonical map $|\lim_n X_n|\to \lim_n |X_n|$ is a homeomorphism, where $m$ -dimensional means that $Sk^m(X_n)\to X_n$ is a homeomorphism for all $n$ and $|-|$ is the non-fat geometric realization (the one that people would call the wrong one). My motivation was just to write the Hawaiian earrings or compatifications of a tree as the geometric realization of something. That seemes to work, as long as we also allow a topology on the $n$ -simplices. Funnily then one can also write $\Delta^1$ as the geometric realization with the Cantor-Set as its Zero-Skeleton. I haven't published that but I might look it up if there is interest.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/433475', 'https://mathoverflow.net', 'https://mathoverflow.net/users/479945/']}
jdg_86826
stackexchange
llm_judgeable_groundtruth_similarity
51292799
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 are functions prepended with __consuming in Sequence.swift (most likely other places too, but I haven't really looked around). I know it's some type of declaration modifier but I'm not sure what it does. Now provide the response and nothing else.
As I understand it, __consuming doesn't actually do anything yet. It has been added in anticipation of the implementation of move-only types , at which point it will be used to in order to denote a method that consumes the value it is called upon (i.e the value will be moved from the caller to the callee). To illustrate, consider this pseudocode: // Foo is a move-only type, it cannot be copied.moveonly struct Foo { consuming func bar() { // Method is marked consuming, therefore `self` is moved into it. print(self) // We now 'own' `self`, and it will be deinitialised at the end of the call. }}let f = Foo()f.bar() // `bar` is a `consuming` method, so `f` is moved from the caller to the callee.print(f) // Invalid, because we no longer own `f`. The attribute is currently prefixed by two underscores in order to indicate that it shouldn't be used by users until move-only types are actually implemented, at which point it will likely be renamed to consuming . As you've found out, some standard library protocol requirements have been marked __consuming in order to indicate that they can be satisfied by a consuming method of a move-only type, as well as a non-consuming method. This is in much the same way that a mutating protocol requirement indicates that it can be satisfied by a mutating method on a value-type, or an otherwise non-mutating method (but as far as I'm aware, no actual compiler logic backs the checking of __consuming yet). For example, the filter(_:) requirement on Sequence has been marked consuming, as an adopting sequence of move-only elements would need to be able to move the applicable elements into the resulting array, thereby invalidating the sequence. The reason why the attribute has been added well before the implementation of move-only types is in preparation for the Swift 5 ABI stability freeze. As Martin says , this is discussed in more detail on the forums: Preparing the iteration ABI for move-only types
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51292799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4446167/']}
jdg_86827
stackexchange
llm_judgeable_groundtruth_similarity
3474093
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In abstract algebra I have only ever seen division introduced via multiplicative inverses, namely starting from a ring with unity $R$ and then adding the condition that each element $x$ has an inverse element $x^{-1}$ such that $xx^{-1}=x^{-1}x=1$ . But I can also imagine a concept of division without having a unit element, defined as follows: Let $R$ be a ring with the property that for each ordered pair $(a,b)\in R$ with $b\neq 0$ , there exists a unique $c\in R$ such that $a=bc=cb$ . Therefore it makes sense to define $a/b:=c$ , where $c$ is the unique element corresponding to $(a,b)$ as specified above. Is it possible for such a structure to exist on a ring without unity? Now provide the response and nothing else.
Let $R$ be a ring without unit. Suppose for each ordered pair $(a,b)\in R$ with $b\neq 0$ , there exists a unique $c\in R$ such that $a=bc=cb$ . We claim that $R$ is a ring with unit. Let $b \in R$ , $b \ne 0$ . Then there is a unique $e_b$ such that $b = be_b = e_bb$ . We must show that $e_a = e_b$ for all nonzero $a,b$ . Then this will be the unit in $R$ . Let $a,b \in R$ , both nonzero. There is $c$ so that $a = cb = bc$ . So $$e_b a = e_b b c = b c = a,\qquadae_b= c b e_b = c b = a.$$ Thus, $e_b$ satisfies the defining property of $e_a$ . By the uniqueness, $e_a = e_b$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3474093', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477746/']}
jdg_86828
stackexchange
llm_judgeable_groundtruth_similarity
215712
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When explaining the Y combinator in the context of Haskell, it's usually noted that the straight-forward implementation won't type-check in Haskell because of its recursive type. For example, from Rosettacode : The obvious definition of the Y combinator in Haskell canot be usedbecause it contains an infinite recursive type (a = a -> b). Defining a data type (Mu) allows this recursion to be broken. newtype Mu a = Roll { unroll :: Mu a -> a }fix :: (a -> a) -> afix = \f -> (\x -> f (unroll x x)) $ Roll (\x -> f (unroll x x)) And indeed, the “obvious” definition does not type check: λ> let fix f g = (\x -> \a -> f (x x) a) (\x -> \a -> f (x x) a) g<interactive>:10:33: Occurs check: cannot construct the infinite type: t2 = t2 -> t0 -> t1 Expected type: t2 -> t0 -> t1 Actual type: (t2 -> t0 -> t1) -> t0 -> t1 In the first argument of `x', namely `x' In the first argument of `f', namely `(x x)' In the expression: f (x x) a<interactive>:10:57: Occurs check: cannot construct the infinite type: t2 = t2 -> t0 -> t1 In the first argument of `x', namely `x' In the first argument of `f', namely `(x x)' In the expression: f (x x) a(0.01 secs, 1033328 bytes) The same limitation exists in Ocaml: utop # let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g;;Error: This expression has type 'a -> 'b but an expression was expected of type 'a The type variable 'a occurs inside 'a -> 'b However, in Ocaml, one can allow recursive types by passing in the -rectypes switch: -rectypes Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. By using -rectypes , everything works: utop # let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g;;val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = <fun>utop # let fact_improver partial n = if n = 0 then 1 else n*partial (n-1);;val fact_improver : (int -> int) -> int -> int = <fun>utop # (fix fact_improver) 5;;- : int = 120 Being curious about type systems and type inference, this raises some questions I'm still not able to answer. First, how does the type checker come up with the type t2 = t2 -> t0 -> t1 ? Having come up with that type, I guess the problem isthat the type ( t2 ) refers to itself on the right side? Second, andperhaps most interesting, what is the reason for the Haskell/Ocamltype systems to disallow this? I guess there is a good reasonsince Ocaml also will not allow it by default even if it can dealwith recursive types if given the -rectypes switch. If these are really big topics, I'd appreciate pointers to relevant literature. Now provide the response and nothing else.
First, the GHC error, GHC is attempting to unify a few constraints with x , first, we use it as a function so x :: a -> b Next we use it as a value to that function x :: a And finally we unify it with the original argument expression so x :: (a -> b) -> c -> d Now x x becomes an attempt to unify t2 -> t1 -> t0 , however, We can't unify this since it would require unifying t2 , the first argument of x , with x . Hence our error message. Next, why not general recursive types. Well the first point worth noting is the difference between equi and iso recursive types, equi-recursive are what you'd expect mu X . Type is exactly equivalent to expanding or folding it arbitrarily. iso-recursive types provide a pair of operators, fold and unfold which fold and unfold the recursive definitions of types. Now equi-recursive types sound ideal, but are absurdly hard to get right in complex types systems. It can actually make type checking undecidable. I'm not familiar with every detail of OCaml's type system but fully equirecursive types in Haskell can cause the typechecker to loop arbitrarily trying to unify types, by default, Haskell makes sure that type checking terminates. Further more, in Haskell, type synonyms are dumb, the most useful recursive types would be defined like type T = T -> () , however are inlined almost immediately in Haskell, but you can't inline a recursive type, it's infinite! Therefore, recursive types in Haskell would demand a huge overhaul to how synonyms are handled, probably not worth the effort to put even as a language extension. Iso-recursive types are a bit of a pain to use, you more or less have to explicitly tell the type checker how to fold and unfold your types, making your programs more complex to read and write. However, this is very similar to what your doing with your Mu type. Roll is fold, and unroll is unfold. So actually, we do have iso-recursive types baked in. However, equi-recursive types are just too complex so systems like OCaml and Haskell force you to pass recurrences through type level fixpoints. Now if this interests you, I'd recommend Types and Programming Languages. My copy is sitting open in my lap as I'm writing this to make sure I've got the right terminology :)
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/215712', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/45839/']}
jdg_86829
stackexchange
llm_judgeable_groundtruth_similarity
372159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: AFAIK, you never need to specify the protocol in an onclick: onclick="javascript:myFunction()" Bad onclick="myFunction()" Good Today I noticed in this article on Google Anallytics that they are using it: <a href="http://www.example.com" onClick="javascript: pageTracker._trackPageview('/outgoing/example.com');"> Is this example just plain wrong, or is there ever a reason to specify javascript: in anything other than a href ? Now provide the response and nothing else.
Some of the responses here claim that the "javascript:" prefix is a "leftover from the old days", implying that it's intentionally, specially handled by the browsers for backwards compatibility. Is there solid evidence that this is the case (has anyone checked source code)? <span onclick="javascript:alert(42)">Test</span> To me, this just reads as: javascript: alert(42); Meaning, that "javascript:" is just a label and has no effect. This works, too: <span onclick="foobar:alert(42)">Test</span> Update: I did a little experiment and it turns out that, yes, "javascript:" is handled specially by IE, but definitely not so by Firefox, Safari, Opera or Chrome: <span onclick="javascript:while (true) { alert('once'); break javascript; }">Test</span> On non-IE, this will just alert "once", once and then break out of the loop. On IE, I get a "Label not found" error. The following works fine in all browsers: <span onclick="foo:while (true) { alert('once'); break foo; }">Test</span> Update 2: I just realized the link http://crisp.tweakblogs.net/blog/the-useless-javascript-pseudo-protocol.html in one of the answers above pretty much talks about the same thing.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/372159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12579/']}
jdg_86830
stackexchange
llm_judgeable_groundtruth_similarity
2141957
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: According to the math book, every ellipse has the form $$ax^2+bxy+cy^2+dx+ey+f=0$$We'll find a,b,c,d,e,f given 5 points. A post suggested uses Singular value decomposition to find the coefficients ( How to find an ellipse, given five points? ) but I dont know how. Someone can explain to me the steps to obtain the coefficients. Hint: In a webpage I read the last column vector of V (Right Singular Vectors) are the coefficient a,b,c,d,f,g but these values are not exactly what I was expecting. Now provide the response and nothing else.
First we rewrite the congruence:$$4x(x+1)=4\pmod{4n}\quad\Leftrightarrow\quad (2x+1)^2=5\pmod{4n}\ .$$Now write $y=2x+1$ and consider various cases. If $n$ is even then the above implies $y^2=5\pmod8$, which has no solution. If $5^2\mid n$ then we get$$\eqalign{y^2=5\pmod{25}\quad &\Rightarrow\quad 5\mid y^2\cr &\Rightarrow\quad 25\mid y^2\cr &\Rightarrow\quad 25\mid 5\cr}$$and again there is no solution. So for solutions to exist, $n$ is a product of $5$ (possibly) and prime powers $p^\alpha$ where $p$ is not $2$ or $5$. There is a solution iff$$y^2=5\pmod{p^\alpha}$$has a solution for every such prime power, which can be proved to be equivalent to$$y^2=5\pmod p$$having a solution for every $p\mid n$ (except $p=2,5$). Using the Legendre symbol one can show that this comes down to the following. The congruence $x(x+1)=1\pmod n$ has a solution if and only if $n$ is a product of primes in which $5$ occurs only once (or not at all), and every other prime is congruent to $1$ or $4$ modulo $5$. Here is a table of some low values of $n$. I have listed "ok" if the congruence has a solution, otherwise I have given a "bad" prime factor of $n$.$$\def\ok{{\rm ok}} \matrix{3&5&7&9&11&13&15&17&19&21&23&25&27&29&31&\cdots&55\cr 3&\ok&7&3&\ok&13&3&17&\ok&3&23&5&3&\ok&\ok&\cdots&\ok\cr}$$Note that $p=5$ is "bad" for $n=25$ because it occurs twice, but it is "ok" for $n=5$ and $n=55$ because it only occurs once.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2141957', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415824/']}
jdg_86831
stackexchange
llm_judgeable_groundtruth_similarity
144895
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: Everybody knows its easy to develop a proof of concept for an embedded device on a rasbperry pi or even a PC, although when it comes down to choosing a microprocessor for your product, it is difficult to be sure your choice will allow your concept to work optimally. I currently have a media streaming project successfully working on the raspberry pi, although the pi is much to big and bulky for it to be proper as an end device. Also it is stated that the end device is custom. I'm having a hard time finding confidence in processors that I can use. What is a good process as to finding out if a processor is powerful enough to run my application? Basically my requirements are: USB host or embedded TCP/IP stack for WiFi operation I2S/PCM media protocol I2C for peripheral configuration Finding chips with those properties is very very simply. It honestly couldn't be simpler. The issue is being able to tell if the chip is fast enough, processing and operation-wise. I've looked at the LPC4337 quite a bit and I feel like it would be suitable although the development environment is giving me quite a bit of trouble, for that reason I'm still looking around, which led me to the CC3200 from Texas Instruments, although that controller only runs at 80 MHz and I'm not sure if that will be strong enough for real-time media streaming. What are some steps to make sure a processor is fast enough for my application? Like how do I know if an 80 MHz processor will be good enough or do I need something on the order of 204 MHz or even higher? Now provide the response and nothing else.
It depends on how confident you need to be. I work in the space industry and this is typically achieved via what we call "CPU, RAM, ROM budgets". A budget, be it cost power mass or anything else, is breaking down your process in manageable items which you can quantify and sum them all up to get the overall demand. You then take a safety factor that depends on the maturity of your project, decreasing with time to account for the growth in demand. Early on, it heavily relies on experience and then is refined over time as technologies are selected. ROM is relatively easy. You know how much a stack/library/driver roughly takes in ROM memory: either given by the author, or you can compile it without uploading it. That figure can change a lot every time you change your code though because of compiler optimisations. RAM is a lot trickier. Some tools in specialised integrated development environments give you runtime estimates , and I can see how this could be done but I'm not aware of any generic tool - say, provided by GCC (anyone knows otherwise?). Sadly it does sound like it's down to counting the biggest or most allocated elements of your code (accounting for variables lifetime). CPU is more complex in that depending on the architecture (CISC or RISC) the MIPS (Millions of Instructions Per Second, proportional to the CPU clock frequency) could or could not be representative. Because if you have the code at hand, you can break the most critical section down into instructions and calculate the required MIPS from the time requirement. Any non-disabled interrupt SHOULD be considered to be triggered at that point - Murphy's law and all that. The above is extremely difficult to accurately determine when schedulers kick in, as soon as you have threads (unless threads are manually allocated to cores) and operating systems. It should be manageable for simple microcontroller codes, but is it worth it for your application? This is only my participation: even though I design integrated systems I have not been responsible for those particular budgets (which are inputs for me), and I'm actually very interested to know experts' stories on that. Addendum : With real-time systems, it is usually easier to assess the adequacy of the system to the task via the maximum sampling time which depends on latency/delays in the transmission of the information throughout the workflow, and the maximum time taken by each sample of task.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/144895', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/28592/']}
jdg_86832
stackexchange
llm_judgeable_groundtruth_similarity
81040
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: Here's my predicament. One of several programs I've recently inherited is built with a horrible database on the backend. The esteemed creators of it apparently did not appreciate relational concepts. A table for each and every client, named as a unique client ID. Eighty-three cryptically named fields. The code is all procedural with dozens of concatenated inline SQL statements. As we weren't provided with an important ancillary application that runs off the same database, I've been tasked with recreating it from scratch. I'm a sole developer, which isn't even my primary responsibility as at least half of my time is taken up by operations stuff. There's an unavoidable deadline set for 30 days from now. Despite my inexperience, I'm certain I could have designed this database and existing application much better than they were, but I don't really think it's realistic for me to alter the database, adjust the existing application, and be sure I didn't break anything while needing to create the additional application this quickly. So let's assume I am stuck with the terrible database. Needing to work with such a bad structure, would anything I write that conforms to it just add to the heaping pile of technical debt to be shelved away until something completely breaks or new functionality is needed? How could I approach this situation and get something good out of it besides a hopefully functional application? edit: In case anyone's interested, we ended up scrapping this horrible database and the application that ran on it. We outsourced the creation of the ancillary application (I wasn't involved in setting this up) to ultimately two different contractors who both ended up falling through on us, accomplishing nothing. I ended up having to rush out a horrific, partially functional hack of a fix in three days that's still in use today. Now provide the response and nothing else.
There's hope, but it's an uphill battle, especially if nobody realizes the database design is horrible. You can try to abstract the nastiness away with abstraction layers, but chances are it won't be worth the battle. My advice would be to create enough abstractions over the database that the application itself is clean and properly designed; that way if you can ever fix the database, the application won't be affected since it doesn't care how the database was designed. This is the approach I normally use when dealing with a database that is in place and, more often than not, designed with zero thought. A few choice applications of the Repository or Gateway patterns, with some service layers to talk to the gateway/repository, should help to quarantine the poor design.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/81040', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/5747/']}
jdg_86833
stackexchange
llm_judgeable_groundtruth_similarity
554243
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In QFT the propagator is divergent for the on-shell momentum of the particles. When e.g. calculating the amplitude for a box loop, the propagator diverges for on-shell particles running in the box-loop. Is there a physical interpretation for this divergent behavior? Now provide the response and nothing else.
In equation (7) you have the expression $$−P\ln(P−Rv(n+1))+P\ln(P)$$ But since this a difference between two logarithmsyou can rewrite the expression (remember $\ln a - \ln b = \ln \frac ab$ ) as $$P\ln\left(\frac{P}{P−Rv(n+1)}\right)$$ Now you have the logarithm of a dimension-less quantity,as it should be.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/554243', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/257521/']}
jdg_86834
stackexchange
llm_judgeable_groundtruth_similarity
943386
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Sorry if this is a really basic question but I've searched and googled everywhere and haven't found any relevant answers so I have to ask my question here. Please excuse me for any misuse or ignorance of basic concepts and terminology. In my understanding, in general, the position of an object should be absolute. What if you have relative positions of objects that disagree with each other? For example, imagine a 1 dimensional world (a line) composed of 3 objects, X, Y and Z: For X, Y is 5 units to its right, and Z is 10 units to its right. For Y, X does not exist, and Z is 10 units to its right. For Z, X is 5 units to its right, and Y does not exist. Now obviously these 3 statements are inconsistent with each other, you cannot draw a map of the 3 objects X, Y and Z. But you CAN draw 3 maps, one for each object. These 3 maps do not agree with each other, but the whole idea is that this concept of relative space encompasses "absolute" space, where the 3 statements agree with each other and are consistent. So, to me, the concept of relative space, which INCLUDES sets of inconsistent statements such as the ones I made above, is MORE GENERAL than the concept of absolute space where these sets of statements must be in agreement with each other i.e describe the same map. Now what I'm asking here is, is there an EVEN MORE GENERAL concept than the idea of relative space that I described above? A more general concept that removes more restrictions, that is what I'm after. What I really hope for is if the idea of coordinates is generalized away altogether to be replaced by something more general. Thanks for reading my question, I hope it made sense. Now provide the response and nothing else.
It's possible to encompass your notion, at least in the sense I read it, in that of a generalized quasimetric space. This kind of space has a weak distance function $d$ which takes pairs of points to nonnegative real numbers or $\infty$. We don't require $d(x,y)=d(y,x)$, but we do require that if $x\neq y$ then $d(x,y)$ and $d(y,x)$ are greater than $0$ and that $d(x,y)+d(y,z)\geq d(x,z)$. So your "line" could be described by a quasimetric with $d(x,y)=5,d(x,z)=10,d(y,x)=\infty,d(y,z)=10,d(z,x)=5,d(z,y)=\infty$. I do think this will satisfy the triangle inequality just stated-for a space that doesn't, you could just ignore the triangle inequality, so that you're using a premetric , which Wikipedia says is a somewhat nonstandard term. I will point out that this model of your problem loses the 1-dimensionality that you wanted. One way to get it back would be simply to put an ordering on the underlying set, which would be completely independent of the quasimetric. And it is indeed possible to generalize even further. One well-known generalization is the topological space , which can be described as a set $X$ together with a collection of symmetric relations $r,s,t,...$ where $r(x,y)$ can be interpreted as "$x$ is $r$-close to $y$". These relations satisfy some axioms to make them reasonably space-like, but can encompass much stranger phenomena even than the one you describe. Topological spaces aren't the only such possible generalization-it's a question of finding a balance between great generality and retaining something geometric. Others that come to mind mostly require notions from category theory, which might not fit your needs well. Anyway, as you already admit, we have to add more structure back in to get much of anything interesting-the diversity of topological spaces is far beyond comprehensibility. But you might want to pick up an introduction to topology, if this intrigues you.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/943386', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117411/']}
jdg_86835
stackexchange
llm_judgeable_groundtruth_similarity
12180765
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 possibility to somehow force maven to fail the build if there are some checkstyle errors? Now I have to run site goal to generate javadocs and checkstyle reports. I want to make it on install goal and if checkstyle has some error I need build to fail. Is this possible to achieve? Now I have my checkstyle in reporting block of maven: <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.9.1</version> <configuration> <configLocation>src/test/resources/checkstyle.xml</configLocation> </configuration> </plugin> </plugins></reporting> Now provide the response and nothing else.
You need to bind checkstyle:check to a Maven lifecycle phase (e.g. validate ) and set failOnViolation to true. Something like: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.9.1</version> <executions> <execution> <id>checkstyle</id> <phase>validate</phase> <goals> <goal>check</goal> </goals> <configuration> <failOnViolation>true</failOnViolation> </configuration> </execution> </executions></plugin>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12180765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1147529/']}
jdg_86836
stackexchange
llm_judgeable_groundtruth_similarity
310221
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 3 buttons (R13-81 PUSH SWITCH) for a school project. In the specifications, it is written that they take Voltage Rating (AC) : 125V ( Source ) Problem is I only have 3.3V or 5V as power supplies. Will it still work ? I don't understand if it takes between 0 and 125V or if it has to take 125V every time. Also, the output needs to be 3.3V maximum... What should I do ? Now provide the response and nothing else.
Your question is wisely asked. In general, an AC-rated switch should be derated for DC use. AC ratings are usually higher than the DC rating, if available, for the exact same switch. There's a reason for that. AC has zeroes , twice per AC cycle. A manually opened (or closed) switch happens "randomly," relative to the AC cycle. Any "arcing" drawn out as the metal contacts open up will soon be extinguished because the AC cycle will hit one of those zeros. DC doesn't have any zeros. So there is no inherent self-extinguishing process and therefore they may have to cope with more prolonged arcing when operating at the same voltage. In your case, the DC voltage is so low and is also so much lower than the AC switch rating, that there is almost certainly no problem using it. I wouldn't worry at all. But it was still wise to ask. (There is also the problem of current compliance, but you've not mentioned it. I'm assuming from the context of your question that we aren't talking about large currents.) P.S. A manual switch is just a bit of mechanical components arranged to make it easy for a human to operate, and includes metal conductive contacts that are placed into direct contact with each other when the switch is engaged. The metal contacts are just physical bits of metal and do not have to have a specific voltage in order to work. They will make contact, regardless, because the mechanical design for operation is independent of the voltage it is switching.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/310221', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/151734/']}
jdg_86837
stackexchange
llm_judgeable_groundtruth_similarity
43730255
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 deal with duplicate methods in Go interface? package mainimport ( "fmt")type Person interface { Hello()}type Joker interface { Person Joke()}type Jumper interface { Person Jump()}type Entertainer interface { Joker Jumper}func main() { fmt.Println("hello, world")} The following error occurs if I run this code. $ go run foo.go# command-line-arguments./foo.go:24: duplicate method Hello How to deal with situations like this and how can we avoid duplicatemethods in such a scenario? Now provide the response and nothing else.
The way to do this is to explicitly provide the required methods instead of using the shorthand syntax: type Entertainer interface { Hello() Joke() Jump()} This may seem like code duplication, but note that duplicate code isn't an untypical thing in Go, especially when it leads to clearer code. Also note this: If you think in terms of typical inheritance in other languages, it may seem like you're losing some information by doing this, because you're not recording the fact that Entertainer inherits from, say, Person . But Go interfaces are purely structural, there is no inheritance. Because an Entertainer has a Hello() method, every Entertainer is automatically a Person , whether or not you explicitly mention Person insided the Entertainer declaration. All of this compiles without problems (except for a "declared and not used" error) even when you don't use the shorthand syntax for any of the interfaces: var e Entertainervar ju Jumpervar jo Jokervar p Personp = e // every Entertainer is also a Personp = ju // every Jumper is also a Personp = jo // every Joker is also a Personju = e // every Entertainer is also a Jumperjo = e // every Entertainer is also a Joker Here's a complete program that compiles and runs just fine. Given these declarations: package mainimport ( "fmt")type Person interface { Hello()}type Joker interface { Hello() Joke()}type Jumper interface { Hello() Jump()}type Entertainer interface { Hello() Joke() Jump()} let's create a Clown type: type Clown struct {}func (c Clown) Hello() { fmt.Println("Hello everybody")}func (c Clown) Joke() { fmt.Println("I'm funny")}func (c Clown) Jump() { fmt.Println("And up I go")} A Clown can greet, jump, and joke, and so it implements all of our interfaces. Given these four functions: func PersonSayHello(p Person) { p.Hello()}func JumperJump(j Jumper) { j.Jump()}func JokerJoke(j Joker) { j.Joke()}func EntertainerEntertain(e Entertainer) { e.Joke() e.Jump()} you can pass a Clown to any of them: func main() { c := Clown{} PersonSayHello(c) JokerJoke(c) JumperJump(c) EntertainerEntertain(c)} Here's a link to a Go Playground with the above code . One final thing – you could argue something like this: "But if I later make a change to Person , it won't be reflected in the other interfaces." It's true, you have to make such an adjustment manually, but the compiler will let you know about it. If you have this function: func JumperSayHello(j Jumper) { PersonSayHello(j)} your code will work without any issues. But if you add another method to Person , code that relies on the fact that a Jumper is a Person will no longer compile. With type Person interface { Hello() Think()} you get .\main.go:18: cannot use j (type Jumper) as type Person in argument to PersonSayHello: Jumper does not implement Person (missing Think method) This will be the case as long as you have code anywhere that relies on the fact that a Jumper is always a Person . And if you don't, not even in your tests, then – well, maybe it doesn't actually matter that the jumper doesn't think? But if for whatever reason you actually need to ensure that a Jumper is always a Person , no matter what changes you make to these interfaces, but this fact isn't actually used anywhere, you can always create code just for this purpose: package maintype Person interface { Hello()}type Jumper interface { Hello() Jump()}// this function is never used, it just exists to ensure// interface compatibility at compile timefunc ensureJumperIsPerson(j Jumper) { var p Person = j _ = p}func main() {}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43730255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175080/']}
jdg_86838
stackexchange
llm_judgeable_groundtruth_similarity
3403579
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: Angles A, B and C meet the circle at P, Q and R respectively. I made the picture below, but what would the solution be? Now provide the response and nothing else.
Let $a,b,c$ be the sides of the given triangle $\Delta =\Delta ABC$ , we denote by $p=(a+b+c)/2$ its half -perimeter, by $R,r$ the radius of the circumcircle, respectively of the inscribed circle, and by $S$ the area of $\Delta$ . Euler's relation, wiki link , gives $$r^2=R(R-2r)\ .$$ The corresponding equation of second degree is $0=R^2-2rR-r^2$ , giving $R/r=1\pm \sqrt 2$ , and we of course take only the positive choice. It is time to norm, let us consider below the case with $$R = 1\ ,\qquad r=\sqrt 2-1\ .$$ We show first algebraically that under these circumstances there is exactly one solution of the given problem (with $b>c$ ). Then we explore also a geometric path. From $\frac a{\sin A}=2R$ we obtain $a=2R\sin 60^\circ=\sqrt 3$ . Then we also have by the generalized theorem of Pythagoras a relation between $b,c$ : $$ b^2+c^2-bc = b^2 +c^2-2bc\cos A=a^2 =3\ .$$ We need one more equation.The area $S$ appears in the formulas involving $r,R$ $\displaystyle R=\frac {abc}{4S}$ , and $\displaystyle S = pr$ , joining them, we get $$2(a+b+c)(\sqrt 2-1) = 4p\; rR = 4RS = abc\ .$$ This is the second equation in $b,c$ . The two homogenous equations can be written simpler using the sum $\Sigma =b+c$ , and the product $\Pi=bc$ of the two unknowns $b,c$ , we get the system $$\left\{\begin{aligned}\Sigma^2-3\Pi &= 3\ ,\\2(\sqrt 3+\Sigma )(\sqrt 2-1) &= \sqrt 3\Pi\ .\end{aligned}\right.$$ We substitute $\Pi$ from the second equation in the first one, eliminate it, and obtain for $\Sigma$ the equation: $$ \Sigma^2 - 2\sqrt 3(\sqrt 3+\Sigma )(\sqrt 2-1) = 3 \ .$$ The roots are $\Sigma = \sqrt3(\sqrt 2-1)\pm\sqrt6$ . Only the positive solution counts, $\Sigma=\sqrt3(2\sqrt 2-1)$ . Then $\Pi = 8-4\sqrt 2$ . Then $\Sigma^2-4\Pi = 4\sqrt 2-5= (\sqrt 2-1)^2(2\sqrt 2+1)$ . We get the explicit formulas for $b,c$ , $$b,c =\frac 12\Big(\ \sqrt3(2\sqrt 2-1)\pm (\sqrt 2-1)\sqrt{2\sqrt 2+1}\ \Big)\ .$$ Please allow here a quick computer check, so that i can go on. sage: R, r, a, Sigma, Pi = 1, sqrt(2)-1, sqrt(3), sqrt(3)*(2*sqrt(2) - 1), 8-4*sqrt(2)sage: b = ( sqrt(3)*(2*sqrt(2)-1) + (sqrt(2)-1)*sqrt(2*sqrt(2)+1) ) / 2sage: c = ( sqrt(3)*(2*sqrt(2)-1) - (sqrt(2)-1)*sqrt(2*sqrt(2)+1) ) / 2sage: ( b^2 + c^2 - b*c ).n()3.00000000000000sage: ( b+c - Sigma ).n()0.000000000000000sage: ( b*c - Pi ).n()8.88178419700125e-16sage: ( 2*(a+Sigma)*r*R - a*Pi ).n()1.77635683940025e-15sage: ( arcsin( b/2*R ) / pi * 180 ).n()83.9057117814039 Well, numerically the angle in $B$ in our triangle is slightly bigger than $83.9^\circ$ , and we have to show that it is $<84^\circ$ . This is a very close approximation. Can we really find a (simple) geometric argument (instead of the above algebraic computation)? Some geometric thoughts to construct the triangle are as follows. We draw a circle of radius one, $R=1$ , centered in a point $O$ , consider the points $M,B,C$ on it so that $\Delta MBC$ is equilateral, and search the "right place" on the same circle for the vertex $A$ , so that the circle inscribed in $\Delta ABC$ passes through $O$ . We assume the knowledge of its existence and uniqueness. Let $L$ be the symmetric of $M$ w.r.t. $O$ , so $ML$ is a diameter. Then $I$ is on $AL$ , since $L$ is on the angle bisector $AI$ of the angle $A$ , since it divides the arc $\overset \frown{BC}$ in two equal arcs. So $I$ is on the circle centered in $O$ with radius $r=\sqrt 2-1$ . Let $D,E,F$ be the projections of $I$ on the sides $BC$ , $CA$ , $AB$ . Then $\Delta AIE=\Delta AIF$ have the angles $30^\circ$ , $60^\circ$ , $90^\circ$ , which implies $AI=2IE=2IF=2r$ . In the triangle $\Delta BIL$ the angles in $B$ and $I$ are equal, so $IL=BL=BO=R=1$ . So $LA=1+2r=1+2(\sqrt 2-1)=2\sqrt 2-1< 2$ . We can now construct $A$ in this way. We can compute now explicitly also $AM$ , well $AM^2=4\sqrt 2-5$ . The fact that $\hat B=\widehat{ABC}=\widehat{ABM}+\widehat{MBC}=\widehat{ABM}+60^\circ<84^\circ$ is equivalent to $$ \widehat{ABM}=\widehat{ALM}<24^\circ\ ,$$ and we may work to get a proof by comparing $AM$ with the side $XM$ of the corresponding regular polygon with $\widehat{XLM}=24^\circ$ . (Or we may compute the chord corresponding to the triple of the above angle, and use the knowledge of the side of the $5$ -gon to compare explicitly.) I may come back with a picture and more details if this is still relevant, please mention the point to put accent on in a short comment. Below there is a geogebra picture of the construction of $\Delta ABC$ following the above description. Since the figure is overloaded, here is the order of introducing the objects. We draw a circle with (blue) radius $R=1$ centered in a point $O$ , and draw a point $M$ on it. We call this circle $(O)$ below. We construct the regular polygons with three and four vertices, inscribed in the circle $(O)$ with one vertex in $M$ . The equilateral triangle constructed is denoted by $\Delta MBC$ . From the square we need later only the construction of $\sqrt 2$ . Let $L$ be so that $ML$ is a diameter, so $ML=2R=2$ . We construct as in the figure the length $2\sqrt 2-1< 2$ and draw a big circle centered in $L$ with this radius. It intersects the circle $(O)$ in two points, we denote by $A$ the intersection point closer to $B$ . We construct $I$ , the incenter of $\Delta ABC$ . Then $O$ is on the circle centered in $I$ and radius $r=\sqrt 2-1$ . Geogebra can mark angles with their value, so asking it for this service, we get the approximative value shown in the figure, $\color{magenta}{\approx 83.9057^\circ}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3403579', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/666297/']}
jdg_86839
stackexchange
llm_judgeable_groundtruth_similarity
11573164
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's a load of questions which ask this: Can I get UIWebView to view a self signed HTTPS website? And the answers always involve either: Use the private api call for NSURLRequest : allowsAnyHTTPSCertificateForHost Use NSURLConnection instead and the delegate canAuthenticateAgainstProtectionSpace etc For me, these won't do. (1) - means I can't submit to the app store successfully. (2) - using NSURLConnection means the CSS, images and other things that have to be fetched from the server after receiving the initial HTML page do not load. Does anyone know how to use UIWebView to view a self-signed https webpage please, which does not involve the two methods above? Or - If using NSURLConnection can in fact be used to render a webpage complete with CSS, images and everything else - that would be great! Cheers, Stretch. Now provide the response and nothing else.
Finally I got it! What you can do is this: Initiate your request using UIWebView as normal. Then - in webView:shouldStartLoadWithRequest - we reply NO , and instead start an NSURLConnection with the same request. Using NSURLConnection , you can communicate with a self-signed server, as we have the ability to control the authentication through the extra delegate methods which are not available to a UIWebView . So using connection:didReceiveAuthenticationChallenge we can authenticate against the self signed server. Then, in connection:didReceiveData , we cancel the NSURLConnection request, and start the same request again using UIWebView - which will work now, because we've already got through the server authentication :) Here are the relevant code snippets below. Note: Instance variables you will see are of the following type: UIWebView *_web NSURLConnection *_urlConnection NSURLRequest *_request (I use an instance var for _request as in my case it's a POST with lots of login details, but you could change to use the request passed in as arguments to the methods if you needed.) #pragma mark - Webview delegate// Note: This method is particularly important. As the server is using a self signed certificate,// we cannot use just UIWebView - as it doesn't allow for using self-certs. Instead, we stop the// request in this method below, create an NSURLConnection (which can allow self-certs via the delegate methods// which UIWebView does not have), authenticate using NSURLConnection, then use another UIWebView to complete// the loading and viewing of the page. See connection:didReceiveAuthenticationChallenge to see how this works.- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;{ NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated); if (!_authenticated) { _authenticated = NO; _urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self]; [_urlConnection start]; return NO; } return YES;}#pragma mark - NURLConnection delegate- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;{ NSLog(@"WebController Got auth challange via NSURLConnection"); if ([challenge previousFailureCount] == 0) { _authenticated = YES; NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; }}- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;{ NSLog(@"WebController received response via NSURLConnection"); // remake a webview call now that authentication has passed ok. _authenticated = YES; [_web loadRequest:_request]; // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!) [_urlConnection cancel];}// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{ return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];} I hope this helps others with the same issue I was having!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11573164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/917224/']}
jdg_86840