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
14464226
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 recently seen that one can declare a return type that is also bounded by an interface. Consider the following class and interface: public class Foo { public String getFoo() { ... }}public interface Bar { public void setBar(String bar);} I can declare a return type like this: public class FooBar { public static <T extends Foo & Bar> T getFooBar() { //some implementation that returns a Foo object, //which is forced to implement Bar }} If I call that method from somewhere, my IDE is telling me that the return type has the method String getFoo() as well as setBar(String) , but only If I point a dot behind the Function like this: FooBar.getFooBar(). // here the IDE is showing the available methods. Is there a way to get a reference to such an Object? I mean, if I would do something like this: //bar only has the method setBar(String)Bar bar = FooBar.getFooBar();//foo only has the getFoo():String methodFoo foo = FooBar.getFooBar(); I would like to have a reference like this (pseudo code): <T extents Foo & Bar> fooBar = FooBar.getFooBar();//or maybe$1Bar bar = FooBar.getFooBar();//or else maybeFoo&Bar bar = FooBar.getFooBar(); Is this possible somehow in Java, or am I only able to declare return types like this? I think Java has to type it also, somehow. I'd prefer not to resort to a wrapper like this, as it feels like cheating: public class FooBarWrapper<T extends Foo&Bar> extends Foo implements Bar { public T foobar; public FooBarWrapper(T val){ foobar = val; } @Override public void setBar(String bar) { foobar.setBar(bar); } @Override public String getFoo() { return foobar.getFoo(); }} Did Java really invent such a nice feature, but forget that one would like to have a reference to it? Now provide the response and nothing else.
While the type parameters of a generic method can be restricted by bounds, such as extends Foo & Bar , they are ultimately decided by the caller. When you call getFooBar() , the call site already knows what T is being resolved to. Often, these type parameters will be inferred by the compiler, which is why you don't usually need to specify them, like this: FooBar.<FooAndBar>getFooBar(); But even when T is inferred to be FooAndBar , that's really whats happening behind the scenes. So, to answer your question, such a syntax like this: Foo&Bar bothFooAndBar = FooBar.getFooBar(); Would never be useful in practice. The reason is that the caller must already know what T is. Either T is some concrete type: FooAndBar bothFooAndBar = FooBar.<FooAndBar>getFooBar(); // T is FooAndBar Or, T is an unresolved type parameter, and we're in its scope: <U extends Foo & Bar> void someGenericMethod() { U bothFooAndBar = FooBar.<U>getFooBar(); // T is U} Another example of that: class SomeGenericClass<V extends Foo & Bar> { void someMethod() { V bothFooAndBar = FooBar.<V>getFooBar(); // T is V }} Technically, that wraps up the answer. But I'd also like to point out that your example method getFooBar is inherently unsafe. Remember that the caller decides what T gets to be, not the method. Since getFooBar doesn't take any parameters related to T , and because of type erasure , its only options would be to return null or to "lie" by making an unchecked cast, risking heap pollution . A typical workaround would be for getFooBar to take a Class<T> argument, or else a FooFactory<T> for example. Update It turns out I was wrong when I asserted that the caller of getFooBar must always know what T is. As @MiserableVariable points out, there are some situations where the type argument of a generic method is inferred to be a wildcard capture , rather than a concrete type or type variable. See his answer for a great example of a getFooBar implementation that uses a proxy to drive home his point that T is unknown. As we discussed in the comments, an example using getFooBar created confusion because it takes no arguments to infer T from. Certain compilers throw an error on a contextless call to getFooBar() while others are fine with it . I thought that the inconsistent compile errors - along with the fact that calling FooBar.<?>getFooBar() is illegal - validated my point, but these turned out to be red herrings. Based on @MiserableVariable's answer, I put together an new example that uses a generic method with an argument, to remove the confusion. Assume we have interfaces Foo and Bar and an implementation FooBarImpl : interface Foo { }interface Bar { }static class FooBarImpl implements Foo, Bar { } We also have a simple container class that wraps an instance of some type implementing Foo and Bar . It declares a silly static method unwrap that takes a FooBarContainer and returns its referent: static class FooBarContainer<T extends Foo & Bar> { private final T fooBar; public FooBarContainer(T fooBar) { this.fooBar = fooBar; } public T get() { return fooBar; } static <T extends Foo & Bar> T unwrap(FooBarContainer<T> fooBarContainer) { return fooBarContainer.get(); }} Now let's say we have a wildcard parameterized type of FooBarContainer : FooBarContainer<?> unknownFooBarContainer = ...; We're allowed to pass unknownFooBarContainer into unwrap . This shows my earlier assertion was wrong, because the call site doesn't know what T is - only that it is some type within the bounds extends Foo & Bar . FooBarContainer.unwrap(unknownFooBarContainer); // T is a wildcard capture, ? As I noted, calling unwrap with a wildcard is illegal: FooBarContainer.<?>unwrap(unknownFooBarContainer); // compiler error I can only guess that this is because wildcard captures can never match each other - the ? argument provided at the call site is ambiguous, with no way of saying that it should specifically match the wildcard in the type of unknownFooBarContainer . So, here's the use case for the syntax the OP is asking about. Calling unwrap on unknownFooBarContainer returns a reference of type ? extends Foo & Bar . We can assign that reference to Foo or Bar , but not both: Foo foo = FooBarContainer.unwrap(unknownFooBarContainer);Bar bar = FooBarContainer.unwrap(unknownFooBarContainer); If for some reason unwrap were expensive and we only wanted to call it once, we would be forced to cast: Foo foo = FooBarContainer.unwrap(unknownFooBarContainer);Bar bar = (Bar)foo; So this is where the hypothetical syntax would come in handy: Foo&Bar fooBar = FooBarContainer.unwrap(unknownFooBarContainer); This is just one fairly obscure use case. There would be pretty far-ranging implications for allowing such a syntax, both good and bad. It would open up room for abuse where it wasn't needed, and it's completely understandable why the language designers didn't implement such a thing. But I still think it's interesting to think about. Note - Since JDK 10 there is the var reserved type name, which makes this possible: var fooBar = FooBarContainer.unwrap(unknownFooBarContainer); The variable fooBar is inferred to have a type that implements both Foo and Bar and that cannot be denoted explicitly in source code. A note about heap pollution ( Mostly for @MiserableVariable ) Here's a walkthrough of how an unsafe method like getFooBar causes heap pollution, and its implications. Given the following interface and implementations: interface Foo { }static class Foo1 implements Foo { public void foo1Method() { }}static class Foo2 implements Foo { } Let's implement an unsafe method getFoo , similar to getFooBar but simplified for this example: @SuppressWarnings("unchecked")static <T extends Foo> T getFoo() { //unchecked cast - ClassCastException is not thrown here if T is wrong return (T)new Foo2();}public static void main(String[] args) { Foo1 foo1 = getFoo(); //ClassCastException is thrown here} Here, when the new Foo2 is cast to T , it is "unchecked", meaning because of type erasure the runtime doesn't know it should fail, even though it should in this case since T was Foo1 . Instead, the heap is "polluted", meaning references are pointing to objects they shouldn't have been allowed to. The failure happens after the method returns, when the Foo2 instance tries to get assigned to the foo1 reference, which has the reifiable type Foo1 . You're probably thinking, "Okay so it blew up at the call site instead of the method, big deal." But it can easily get more complicated when more generics are involved. For example: static <T extends Foo> List<T> getFooList(int size) { List<T> fooList = new ArrayList<T>(size); for (int i = 0; i < size; i++) { T foo = getFoo(); fooList.add(foo); } return fooList;}public static void main(String[] args) { List<Foo1> foo1List = getFooList(5); // a bunch of things happen //sometime later maybe, depending on state foo1List.get(0).foo1Method(); //ClassCastException is thrown here} Now it doesn't blow up at the call site. It blows up sometime later when the contents of foo1List get used. This is how heap pollution gets harder to debug, because the exception stacktrace doesn't point you to the actual problem. It gets even more complicated when the caller is in generic scope itself. Imagine instead of getting a List<Foo1> we're getting a List<T> , putting it in a Map<K, List<T>> and returning it to yet another method. You get the idea I hope.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14464226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/620053/']}
jdg_372741
stackexchange
llm_judgeable_groundtruth_similarity
271177
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 got some linear actuators today and found out that when I give them +9V they extend and -9V makes them contract. This is easy enough to test by hand, simply by wiring the actuator up to the battery backwards for the negative voltage, but when I hook it all up I'm going to be driving all of them from my Atmega1284, which uses 5V logic. In anticipation of this, I got a bunch of relays that run on 5V logic as well so I can control whether or not there's +9V running through with my 5V microcontroller. However, I have no way to programmatically provide -9V. My question here is how can I switch between giving +9V and -9V when all I can do from my microcontroller is either push out 5V or 0V? Will I need more than just my relays? Is there some spiffy EE trick to make this work? Thanks! Now provide the response and nothing else.
You can use two SPDT relays to select +9 or -9 or 0V. Both energized = off, Both de-energized = off, and if one is energized and the other is not it will drive the actuator in one direction or the other. simulate this circuit – Schematic created using CircuitLab To suppress electrical noise, add a bridge rectifier ( W04G , for example) across the actuator (the AC input terminals) and connect the + terminal to +9 and the - terminal to 0V
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/271177', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/130969/']}
jdg_372742
stackexchange
llm_judgeable_groundtruth_similarity
21349408
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 looking for a function in haskell to zip two lists that may vary in length. All zip functions I could find just drop all values of a lists that is longer than the other. For example:In my exercise I have two example lists. If the first one is shorter than the second one I have to fill up using 0's. Otherwise I have to use 1's. I'm not allowed to use any recursion. I just have to use higher order functions. Is there any function I can use? I really could not find any solution so far. Now provide the response and nothing else.
There is some structure to this problem, and here it comes. I'll be using this stuff: import Control.Applicativeimport Data.Traversableimport Data.List First up, lists-with-padding are a useful concept, so let's have a type for them. data Padme m = (:-) {padded :: [m], padder :: m} deriving (Show, Eq) Next, I remember that the truncating- zip operation gives rise to an Applicative instance, in the library as newtype ZipList (a popular example of a non- Monad ). The Applicative ZipList amounts to a decoration of the monoid given by infinity and minimum. Padme has a similar structure, except that its underlying monoid is positive numbers (with infinity), using one and maximum. instance Applicative Padme where pure = ([] :-) (fs :- f) <*> (ss :- s) = zapp fs ss :- f s where zapp [] ss = map f ss zapp fs [] = map ($ s) fs zapp (f : fs) (s : ss) = f s : zapp fs ss I am obliged to utter the usual incantation to generate a default Functor instance. instance Functor Padme where fmap = (<*>) . pure Thus equipped, we can pad away! For example, the function which takes a ragged list of strings and pads them with spaces becomes a one liner. deggar :: [String] -> [String]deggar = transpose . padded . traverse (:- ' ') See? *Padme> deggar ["om", "mane", "padme", "hum"]["om ","mane ","padme","hum "]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21349408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1223253/']}
jdg_372743
stackexchange
llm_judgeable_groundtruth_similarity
11449803
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What I'm trying to do is create a JSONObject that contains an Array of other JSONObjects that are organized by a String? for example i want to create a JSONObject that contains an array of objects that contain fixtures that are also organized by match date to give you a visual reference of what i am trying to acheive JSONObject (JSONArray("Object 10/10/12" {(fixtures content)(fixtures content)}") ("Object 11/10/12" {(fixtures content)(fixtures content)}")) heres what i have tried so far but just can't get it to work String matchDate1 = null; JSONArray datesArray = null; JSONObject fixturesInfo = null; JSONArray fixturesInfoArray = null; String matchDateTemp = null; for(int f = 0; f < fixturesArray.length(); f++){ JSONObject matchDateDict = fixturesArray.getJSONObject(f); matchDate1 = matchDateDict.getString("matchdate"); JSONArray fixturesInfoDict = fixturesInfo.getJSONArray(matchDate1); if(fixturesInfoDict == null){ tempArray = null; } else { tempArray = fixturesInfoDict; } if(matchDateTemp != matchDate1){ fixturesInfoArray.put(matchDate1); } matchDateTemp = matchDate1; tempArray.put(fixturesArray.getJSONObject(f)); fixturesInfo.put(matchDate1, tempArray); } Log.v("MyFix", "fixturesInfo = " + fixturesInfo); }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } heres the json feed { "code": 200, "error": null, "data": { "fixtures": [{ "kickoff": "15:00:00", "matchdate": "2012-07-14", "homescore": null, "awayscore": null, "attendance": null, "homepens": null, "awaypens": null, "division_id": "5059", "division": "Testing 1", "comp": "LGE", "location": null, "fixture_note": null, "hometeam_id": "64930", "hometeam": "Team 1", "awayteam_id": "64933", "awayteam": "Team 4" }, { "kickoff": "15:00:00", "matchdate": "2012-07-14", "homescore": null, "awayscore": null, "attendance": null, "homepens": null, "awaypens": null, "division_id": "5059", "division": "Testing 1", "comp": "LGE", "location": null, "fixture_note": null, "hometeam_id": "64935", "hometeam": "Team 6", "awayteam_id": "64937", "awayteam": "Team 8" }, { "kickoff": "15:00:00", "matchdate": "2012-07-28", "homescore": null, "awayscore": null, "attendance": null, "homepens": null, "awaypens": null, "division_id": "5059", "division": "Testing 1", "comp": "LGE", "location": null, "fixture_note": null, "hometeam_id": "64930", "hometeam": "Team 1", "awayteam_id": "64931", "awayteam": "Team 2" }, { "kickoff": "15:00:00", "matchdate": "2012-07-28", "homescore": null, "awayscore": null, "attendance": null, "homepens": null, "awaypens": null, "division_id": "5059", "division": "Testing 1", "comp": "LGE", "location": null, "fixture_note": null, "hometeam_id": "64930", "hometeam": "Team 1", "awayteam_id": "64931", "awayteam": "Team 2" }] }} Now provide the response and nothing else.
From what you say, you seem like trying to build a JSONArray out of some JSONObjects . This might help: public void writeJSON() { JSONObject user = new JSONObject(); JSONObject user2; user2 = new JSONObject(); try { user.put("dish_id", "1"); user.put("dish_custom", "2"); user.put("quantity", "2"); user.put("shared", "2"); user2.put("dish_id", "2"); user2.put("dish_custom", "2"); user2.put("quantity", "4"); user2.put("shared", "3"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray notebookUsers = new JSONArray(); notebookUsers.put(user); notebookUsers.put(user2); System.out.println("the JSON ARRAY is"+notebookUsers); Here 2 json objects are added to 1 JSONArray. The output of the System.out.println will look something like this: the JSON ARRAY is[{"shared":"2","dish_custom":"2","dish_id":"1","quantity":"2"},{"shared":"3","dish_custom":"2","dish_id":"2","quantity":"4"}] And the string comparison you are using is not right. if(matchDateTemp != matchDate1) u cannot compare strings like that. u can use something like: if(!(matchDateTemp.equals(matchDate1)))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11449803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1375363/']}
jdg_372744
stackexchange
llm_judgeable_groundtruth_similarity
30146642
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Go's 6a assembler has conditional jump instructions: JCCJCSJCXZLJEQJGEJGTJHIJLEJLSJLTJMIJNEJOCJOSJPCJPLJPS But how do they map to x86 conditional jumps? Now provide the response and nothing else.
I'm answering this so I don't lose the information, and so other people don't have to go through the same sleuthing game as me. Looking at optab.c and the x86 jumps we can match up the instruction encodings to solve the puzzle. JCC JAEJCS JBJCXZL JECXZJEQ JE,JZJGE JGEJGT JGJHI JAJLE JLEJLS JBEJLT JLJMI JSJNE JNE, JNZJOC JNOJOS JOJPC JNP, JPOJPL JNSJPS JP, JPE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30146642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152580/']}
jdg_372745
stackexchange
llm_judgeable_groundtruth_similarity
6739946
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 C# form application which I want to have listening for incoming HTTP requests from other computers. How would I go about doing this? Now provide the response and nothing else.
For simple needs, the HttpListener class is a good and simple choice. There is an example on the linked MSDN page. If, for some reason, you cannot use HttpListener , the process would be to listen to a port using TcpClient (or even the sockets API if you need the gritty details), and then implement the HTTP Protocol . I highly recommend HttpListener over rolling your own, unless you have specific requirements that HttpListener does not meet.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6739946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/850463/']}
jdg_372746
stackexchange
llm_judgeable_groundtruth_similarity
1195112
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 gather some system information for the application I'm developing. The memory available and the CPU load are easy to get using C#. Unfortunately, the CPU temperature it's not that easy. I have tried using WMI, but I couldn't get anything using Win32_TemperatureProbe or MSAcpi_ThermalZoneTemperature How can I do this? I'm wondering how monitoring programs, as SiSoftware Sandra, can get that information... Here is the code of the class: public class SystemInformation{ private System.Diagnostics.PerformanceCounter m_memoryCounter; private System.Diagnostics.PerformanceCounter m_CPUCounter; public SystemInformation() { m_memoryCounter = new System.Diagnostics.PerformanceCounter(); m_memoryCounter.CategoryName = "Memory"; m_memoryCounter.CounterName = "Available MBytes"; m_CPUCounter = new System.Diagnostics.PerformanceCounter(); m_CPUCounter.CategoryName = "Processor"; m_CPUCounter.CounterName = "% Processor Time"; m_CPUCounter.InstanceName = "_Total"; } public float GetAvailableMemory() { return m_memoryCounter.NextValue(); } public float GetCPULoad() { return m_CPUCounter.NextValue(); } public float GetCPUTemperature() { //... return 0; }} Now provide the response and nothing else.
For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/ Follow that link and at first you might think, "Hey, that's an application , and that is why it was removed. The question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is. They also include a data interface. Here is the description: Data Interface The Open Hardware Monitor publishes all sensor data toWMI (Windows Management Instrumentation). This allows otherapplications to read and use the sensor information as well. Apreliminary documentation of the interface can be found here (click) . When you download it, it contains the OpenHardwareMonitor.exe application, and you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, and you're looking for that one. It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap yourself if you feel like it. I have tried this out from a C# application myself, and it works. Although it was still in beta, it seemed rather stable. It is also open source, so it could be a good starting point instead.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1195112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110466/']}
jdg_372747
stackexchange
llm_judgeable_groundtruth_similarity
59157595
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 animate value change in a text using withAnimation but it doesn't seem to work. I have come across a similar question but the answer is not animating the text value. I am trying to recreate this behaviour in pure SwiftUI( UIKit Example ): I have tried this code but it doesn't animate the text change: struct TextAnimationView: View { @State private var textValue = "0" var body: some View { VStack (spacing: 50) { Text(textValue) .font(.largeTitle) .frame(width: 200, height: 200) .transition(.opacity) Button("Next") { withAnimation (.easeInOut(duration: 1)) { self.textValue = "\(Int.random(in: 1...100))" } } } }} I have a very little experience with SwiftUI, is there another way to achieve this? Thanks in advance :) Now provide the response and nothing else.
So it turns out this is really easy Text(textValue) .font(.largeTitle) .frame(width: 200, height: 200) .transition(.opacity) .id("MyTitleComponent" + textValue) Note the additional id at the end. SwiftUI uses this to decide if it's dealing with the same view or not when doing a redraw. If the id is different then it assumes the previous view was removed and this one has been added. Because it's adding a new view it applies the specified transition as expected. NB: It's quite possible that this id should be unique for the entire view tree so you probably want to take care to namespace it accordingly (hence the MyTitleComponent prefix in the example).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/59157595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4366237/']}
jdg_372748
stackexchange
llm_judgeable_groundtruth_similarity
7222
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am faced with a problem where I have to design a reinforced masonry beam for biaxial bending. The governing code is ACI 530-11. I cannot find a provision in this Code for biaxial bending. The only part that addresses this issue is in Section 2.2.3.1 which states: The unity formula can be extended when biaxial bending is present by replacing the bending stress quotients with the quotients of the calculated bending stress over the allowable bending stress for both axes Unfortunately this section deals with unreinforced masonry. It is very strange to me that reinforced masonry is not addressed. Any ideas? Now provide the response and nothing else.
Unity Equation The Unity Equation is a very standard method of analyzing a section under combined loads. Even though the masonry code doesn't specifically call it out in the reinforced pages, it would be hard to argue that it wasn't a reasonable assumption. $$\frac{f_b^1}{F_b^1}+\frac{f_b^2}{F_b^2}\le1$$ The equation could even be $\le\frac{4}{3}$ if stress increases were acceptable. Code I agree that I couldn't find any other reference to biaxial bending in the masonry code. I also didn't find any more clear discussion in the masonry design handbooks that I had available.
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/7222', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/4808/']}
jdg_372749
stackexchange
llm_judgeable_groundtruth_similarity
220106
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is an embarrassingly simple question, but I was not able to find a definitive answer from literature search. Suppose one has some collection of functions $f_1: X \to Y_1, \dots, f_n: X \to Y_n$ on a common domain $X$. Then one can form the function $(f_1,\dots,f_n): X \to Y_1 \times \dots \times Y_n$ in the usual fashion: $$ (f_1,\dots,f_n)(x) := (f_1(x),\dots,f_n(x)).$$ My question is: what does one call the function $(f_1,\dots,f_n)$? I had (without thinking much about it) used to call it the "direct sum" of $f_1,\dots,f_n$, before realising that this actually had no relation with the usual meaning of direct sum. In category theory, one might call $(f_1,\dots,f_n)$ the "product" of $f_1,\dots,f_n$, but this could get confusing if $f_1,\dots,f_n$ already take values in some ring, so that there is also a pointwise product. Is there some other commonly accepted term for describing the function $(f_1,\dots,f_n)$? It doesn't sound quite right grammatically to refer to it as the "tuple" of $f_1,\dots,f_n$, and "concatenation" or "join" don't quite seem to fit either. Now provide the response and nothing else.
I was encouraged to make my comment an answer: In the case $n = 2$, I would call it the pairing. Similarly, one has "tripling", "quadrupling", and so in general one might call it the ($n$-) tupling of the list $f_1, \ldots, f_n$. And indeed that is what the nLab calls it: see here . Whatever this should be called, I would not call it the cartesian product of $f_1, \ldots, f_n$. The product is a functor $\mathcal{C}^n \to \mathcal{C}$ whose value at a morphism $(f_1: X \to Y_1, \ldots, f_n: X \to Y_n)$ of $\mathcal{C}^n$ is rather the morphism $f_1 \times \ldots \times f_n: X \times \ldots \times X \to Y_1 \times \ldots \times Y_n$ of $\mathcal{C}$, and it's the latter that I would call the product of $f_1, \ldots, f_n$. I will see if I can track down further citations for $n$-tupling.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/220106', 'https://mathoverflow.net', 'https://mathoverflow.net/users/766/']}
jdg_372750
stackexchange
llm_judgeable_groundtruth_similarity
53546775
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 simply want to use geopandas to get a union and intersection of two polygonal areas. I define: import geopandas as gpdfrom shapely.geometry import Polygonpolys1 = gpd.GeoSeries([Polygon([(0,0), (2,0), (2,2), (0,2)]), Polygon([(2,2), (4,2), (4,4), (2,4)])])polys2 = gpd.GeoSeries([Polygon([(1,1), (3,1), (3,3), (1,3)]), Polygon([(3,3), (5,3), (5,5), (3,5)])])df1 = gpd.GeoDataFrame({'geometry': polys1, 'df1':[1,2]})df2 = gpd.GeoDataFrame({'geometry': polys2, 'df2':[1,2]}) I try the following to get the union : res_union = gpd.overlay(df1, df2, how='union') and it fails with the following ERROR: AttributeError: 'NoneType' object has no attribute 'intersection' I am following the instructions here . Now provide the response and nothing else.
Despite I don't know the OP's operational system I think that I figured out how to solve the problem, at least for GNU/Linux systems (I'm not able to test in other systems). Direct explanation To be able to use the overlay function you need more than just install geopandas , you need install rtree , but rtree is a wrapper to the C library libspatialindex . So to use rtree library you need to install libspatialindex C library. To install libspatialindex open a terminal end type: sudo apt-get update && apt-get install -y libspatialindex-dev Note: actually you only need the sudo apt-get install libspatialindex-dev , but it is good practice update the system, and the -y flag is just to don't stop the installation process to ask for continue with the installation or not. Now it should solve your problem. Note: make sure you have rtree installed in your system, you can do this using pip3 freeze (I am supposing that you use python3 ). Long explanation I faced the same error, and spent a lot of time to figure out what was the problem. The answer to this question libspatialindex and Rtree on python give to me a tip on how to solve the problem. Consider the bellow code (the OP's code example) and save named as script.py : import geopandas as gpdfrom shapely.geometry import Polygonpolys1 = gpd.GeoSeries([Polygon([(0,0), (2,0), (2,2), (0,2)]), Polygon([(2,2), (4,2), (4,4), (2,4)])])polys2 = gpd.GeoSeries([Polygon([(1,1), (3,1), (3,3), (1,3)]), Polygon([(3,3), (5,3), (5,5), (3,5)])])df1 = gpd.GeoDataFrame({'geometry': polys1, 'df1':[1,2]})df2 = gpd.GeoDataFrame({'geometry': polys2, 'df2':[1,2]})res_union = gpd.overlay(df1, df2, how='union') Consider the following requirements.txt : Shapely==1.6.4.post2descartes==1.1.0geopandas==0.4.0matplotlib==3.0.2 If you try to only install the libraries in the requirements.txt and run scrip.py , and not install rtree library according to the requirements.txt , it is going to show the following error message: /usr/local/lib/python3.6/site-packages/geopandas/base.py:76: UserWarning: Cannot generate spatial index: Missing package `rtree`. warn("Cannot generate spatial index: Missing package `rtree`.")Traceback (most recent call last): File "script.py", line 17, in <module> res_union = gpd.overlay(df1, df2, how='union') File "/usr/local/lib/python3.6/site-packages/geopandas/tools/overlay.py", line 371, in overlay result = _overlay_union(df1, df2) File "/usr/local/lib/python3.6/site-packages/geopandas/tools/overlay.py", line 298, in _overlay_union dfinter = _overlay_intersection(df1, df2) File "/usr/local/lib/python3.6/site-packages/geopandas/tools/overlay.py", line 212, in _overlay_intersection sidx = bbox.apply(lambda x: list(spatial_index.intersection(x))) File "/usr/local/lib/python3.6/site-packages/pandas/core/series.py", line 3194, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas/_libs/src/inference.pyx", line 1472, in pandas._libs.lib.map_infer File "/usr/local/lib/python3.6/site-packages/geopandas/tools/overlay.py", line 212, in <lambda> sidx = bbox.apply(lambda x: list(spatial_index.intersection(x)))AttributeError: 'NoneType' object has no attribute 'intersection' The last line of the error message AttributeError: 'NoneType' object has no attribute 'intersection' is not so useful. But if you look to the first line: /usr/local/lib/python3.6/site-packages/geopandas/base.py:76: UserWarning: Cannot generate spatial index: Missing package rtree . it is complaining about the rtree library. So lets install rtree and see what happens. requirements.txt now is updated to: Shapely==1.6.4.post2descartes==1.1.0geopandas==0.4.0matplotlib==3.0.2rtree==0.8.3 Runing again the script.py I get the following error: Traceback (most recent call last): File "script.py", line 3, in <module> import geopandas as gpd File "/usr/local/lib/python3.6/site-packages/geopandas/__init__.py", line 1, in <module> from geopandas.geoseries import GeoSeries File "/usr/local/lib/python3.6/site-packages/geopandas/geoseries.py", line 12, in <module> from geopandas.base import GeoPandasBase, _series_unary_op, _CoordinateIndexer File "/usr/local/lib/python3.6/site-packages/geopandas/base.py", line 14, in <module> from rtree.core import RTreeError File "/usr/local/lib/python3.6/site-packages/rtree/__init__.py", line 1, in <module> from .index import Rtree File "/usr/local/lib/python3.6/site-packages/rtree/index.py", line 5, in <module> from . import core File "/usr/local/lib/python3.6/site-packages/rtree/core.py", line 125, in <module> raise OSError("Could not find libspatialindex_c library file")OSError: Could not find libspatialindex_c library file The last line complain about libspatialindex_c , so as explained in the first part of my answer, the "Direct explanation", just run the bellow code to install libspatialindex and the script.py should work. sudo apt-get update && apt-get install -y libspatialindex-dev At least for me the problem is solved.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53546775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2762897/']}
jdg_372751
stackexchange
llm_judgeable_groundtruth_similarity
506977
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: This video from Brian Greene suggests this is so: https://www.youtube.com/watch?v=2sZUNud6rRw&list=PLj6DWzIvBi4PFDXCCV1bNhVUgDLTwVbFc&index=60 It shows if you stop a pole in the barn (ignoring all the obvious engineering challenges of doing so) it will end up permanently length contracted just like the returning twin will end up permanently younger than her earth bound twin in the twin paradox. Ignoring the practical problems with infinite deceleration, she stops when she turns around and that causes her permanent age difference but does she also end up permanently flatter? Again just consider the relativistic math and not all the physical impossibilities this example entails. Relativity allows a frame jump without deceleration, it's called a clock handoff in the twin paradox. Since a clock is used to measure length for length contraction, a clock handoff could also keep a record of both permanent age difference and permanent length contraction when the twin hands off her clock readings to a ship passing her to return to earth. There's no physical crunching of the pole in a clock handoff. So does relativity sanction permanent length contraction along with permanent age difference in the clock handoff twin paradox? Now provide the response and nothing else.
Does relativity sanction permanent length contraction along with permanent age difference in the twin paradox? No, it does not. However, given the many analogies between time and space this may seem disturbing. What makes time different from space in this context? The issue is that a clock does something different than a ruler does: it maintains a record. A ruler merely measures the distance between its endpoints, and as a moving ruler is brought (gently) to rest that measurement agrees with a permanently resting ruler. The device that most closely resembles a ruler for time is not a clock but rather a metronome. There is no permanent time dilation for a metronome, and as a moving metronome is brought (gently) to rest that measurement agrees with a permanently resting metronome. In this way it is symmetric with the impermanence of length contraction. If you want a device that resembles a clock for distance that would not be a ruler, but rather an odometer. An odometer maintains a record and will register permanent length contraction in the same manner as a clock. In this way the symmetry between time and space is recognized again. The difference was not due to differences in the physics of time and space, but rather differences in the measuring devices. We were comparing a memory-less device for space to a device with memory for time. With a proper comparison of similar devices the issue is resolved.
{}
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/506977', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/220981/']}
jdg_372752
stackexchange
llm_judgeable_groundtruth_similarity
1357853
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to have a textbox control that suggests and append values from a database in a Windows application with C# 2008 and LINQ. I do it with a combobox but I can't do it with a textbox. How do I do it? Now provide the response and nothing else.
This might not be the best way to do things, but should work: this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;private void textBox1_TextChanged(object sender, EventArgs e){ TextBox t = sender as TextBox; if (t != null) { //say you want to do a search when user types 3 or more chars if (t.Text.Length >= 3) { //SuggestStrings will have the logic to return array of strings either from cache/db string[] arr = SuggestStrings(t.Text); AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); collection.AddRange(arr); this.textBox1.AutoCompleteCustomSource = collection; } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1357853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91188/']}
jdg_372753
stackexchange
llm_judgeable_groundtruth_similarity
2881296
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Over the years my application has grown from 1MB to 25MB and I expect it to grow further to 40, 50 MB. I don't use DLL's, but put everything in this one big executable. Having one big executable has certain advantages: Installing my application at the customer is really: copy and run. Upgrades can be easily zipped and sent to the customer There is no risk of having conflicting DLL's (where the customer has not version X of the EXE, but version Y of the DLL) The big disadvantage of the big EXE is that linking times seem to grow exponentially. Additional problem is that a part of the code (let's say about 40%) is shared with another application. Again, the advantages are that: There is no risk on having a mix of incorrect DLL versions Every developer can make changes on the common code which speeds up developments. But again, this has a serious impact on compilation times (everyone compiles the common code again on his PC) and on linking times. The question Grouping DLL's for use in Executable mentions the possibility of mixing DLL's in one executable, but it looks like this still requires you to link all functions manually in your application (using LoadLibrary, GetProcAddress, ...). What is your opinion on executable sizes, the use of DLL's and the best 'balance' between easy deployment and easy/fast development? Now provide the response and nothing else.
A single executable has a huge positive impact on maintainability. It is easier to debug, deploy (size issues aside) and diagnose in the field. As you point out, it completely sidesteps DLL hell. The most straightforward solution to your problem is to have two compilation modes, one that builds a single exe for production and one that builds lots of little DLLs for development.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2881296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163551/']}
jdg_372754
stackexchange
llm_judgeable_groundtruth_similarity
404277
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: Given the following diagram: Where: W = (-1, 0) X = (-1, 2) Y = (1, 2) Z = (1, 0) How can I find M? The ellipse can be assumed to be a semi-ellipse with one of the foci on $\bar{XY}$. I'm guessing that this means that one focus is at (0, 2), with the other focus at (0, -2). Now, by the definition of an ellipse, I know that the sum of the distances from those two points to any other point on the ellipse is a constant. But, having reasoned that far, I've hit a dead end. Where do I go from here? Now provide the response and nothing else.
If $10^{-x} = 5^{2x}$, then $-x\log(10) = 2x\log(5)$ thus either $x=0$ or $-\log(10)=2\log(5)$ (or both). Since $-\log(10)\neq2\log(5)$ we must conclude that $x=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/404277', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7873/']}
jdg_372755
stackexchange
llm_judgeable_groundtruth_similarity
445349
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am using provider mail hosting to send emails. On my Webserver I also have Postfix running and configured. Here is my main.cf smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)biff = noappend_dot_mydomain = yesreadme_directory = nosmtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scachesmtp_tls_session_cache_database = btree:${data_directory}/smtp_scachemyhostname = 2-5-8.bih.net.baalias_maps = hash:/etc/aliasesalias_database = hash:/etc/aliasesmyorigin = /etc/mailnamemydestination = bhcom.info, 2-5-8.bih.net.ba, localhost.bih.net.ba, localhostrelayhost = mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128mailbox_command = mailbox_size_limit = 10485760recipient_delimiter = +inet_interfaces = 80.65.85.114 When I try sending email to my hosted domain name, every message gets bounced with this error: Nov 4 20:38:34 2-5-8 postfix/pickup[802]: 1492A3E0C6C: uid=0 from=<razvoj@bhcom.info>Nov 4 20:38:34 2-5-8 postfix/cleanup[988]: 1492A3E0C6C: message-id=<20121104193834.1492A3E0C6C@2-5-8.bih.net.ba>Nov 4 20:38:34 2-5-8 postfix/qmgr[803]: 1492A3E0C6C: from=<razvoj@bhcom.info>, size=348, nrcpt=1 (queue active)Nov 4 20:38:34 2-5-8 postfix/local[990]: 1492A3E0C6C: to=<info@bhcom.info>, relay=local, delay=0.12, delays=0.08/0.01/0/0.04, dsn=5.1.1, status=bounced (unknown user: "info")Nov 4 20:38:34 2-5-8 postfix/cleanup[988]: 28ED53E0C6D: message-id=<20121104193834.28ED53E0C6D@2-5-8.bih.net.ba>Nov 4 20:38:34 2-5-8 postfix/qmgr[803]: 28ED53E0C6D: from=<>, size=2056, nrcpt=1 (queue active)Nov 4 20:38:34 2-5-8 postfix/bounce[991]: 1492A3E0C6C: sender non-delivery notification: 28ED53E0C6DNov 4 20:38:34 2-5-8 postfix/qmgr[803]: 1492A3E0C6C: removedNov 4 20:38:34 2-5-8 postfix/local[990]: 28ED53E0C6D: to=<razvoj@bhcom.info>, relay=local, delay=0.06, delays=0.03/0/0/0.02, dsn=5.1.1, status=bounced (unknown user: "razvoj")Nov 4 20:38:34 2-5-8 postfix/qmgr[803]: 28ED53E0C6D: removed However, when I try to @gmail.com, it sends message without problems, and here is log. What might be the issue? Nov 4 20:41:23 2-5-8 postfix/pickup[802]: B2EC63E0C6C: uid=0 from=<razvoj@bhcom.info>Nov 4 20:41:23 2-5-8 postfix/cleanup[1022]: B2EC63E0C6C: message-id=<20121104194123.B2EC63E0C6C@2-5-8.bih.net.ba>Nov 4 20:41:23 2-5-8 postfix/qmgr[803]: B2EC63E0C6C: from=<razvoj@bhcom.info>, size=350, nrcpt=1 (queue active)Nov 4 20:41:23 2-5-8 postfix/smtp[1024]: connect to gmail-smtp-in.l.google.com[2a00:1450:4001:c02::1a]:25: Network is unreachableNov 4 20:41:24 2-5-8 postfix/smtp[1024]: B2EC63E0C6C: to=<amerzec@gmail.com>, relay=gmail-smtp-in.l.google.com[173.194.70.26]:25, delay=0.97, delays=0.08/0.01/0.27/0.62, dsn=2.0.0, status=sent (250 2.0.0 OK 1352058066 f7si2180442eeo.46)Nov 4 20:41:24 2-5-8 postfix/qmgr[803]: B2EC63E0C6C: removed Now provide the response and nothing else.
Well, the log says it: Nov 4 20:38:34 2-5-8 postfix/local[990]: 1492A3E0C6C: to=<info@bhcom.info>, relay=local, delay=0.12, delays=0.08/0.01/0/0.04, dsn=5.1.1, status=bounced (unknown user: "info")Nov 4 20:38:34 2-5-8 postfix/local[990]: 28ED53E0C6D: to=<razvoj@bhcom.info>, relay=local, delay=0.06, delays=0.03/0/0/0.02, dsn=5.1.1, status=bounced (unknown user: "razvoj") You have no local user info and no razvoj the local delivery could deliver mail to.If I understood your post correctly, you do want to send mail from that machine, but this is not your mail server where you want to receive and read it, right? If it's correct, just drop bhcom.info from mydestination and everything should be fine. A bit of background: every hostname listed in mydestination is considered local by Postfix and then itr tries to deliver the mail to that local user, which in your case does not exists.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/445349', 'https://serverfault.com', 'https://serverfault.com/users/111824/']}
jdg_372756
stackexchange
llm_judgeable_groundtruth_similarity
325881
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need several duplex channels between two hosts. There are a number of advantages to establish only one TCP connection. But I doubt multiplexing would cause some inevitable problems. Will it harm performance or increase latency significantly? And what about memory usage and CPU usage? Is there any suggestion or caveat you'd like to give? Now provide the response and nothing else.
TLDR: The major drawback you might notice when multiplexing multiple channels on top of TCP (if you do it right) is an increased latency because of head-of-line blocking between the channels. Corollary: If you don't care about latency you should be fine. On the other hand using a single TCP connection “means less competition with other flows and longer-livedconnections, which in turn lead to better utilization ofavailable network capacity“ . Head-of-line blocking blocking over TCP If you multiplex multiple channels on top of the same TCP stream, the channels might suffer of head-of-line blocking : Head-of-line blocking (HOL) can occur when transport protocolsoffer ordered or partial-ordered service: If segments getlost, subsequent messages have to wait for the successfulretransmission in the receiver queue and are thus delayed. When you multiplex multiple streams on top of TCP you get HOL between the channels . If channel A has filled up the TCP send buffer, you will have to wait before all of this data is received before any new data of channel B can effectively be transmitted to the remote application layer. See "Multiplexing on top of TCP" for more details about multiplexing channels on top of TCP and the discussion on hackernews . Examples of multiplexing over TCP Channel multiplexing over SSH (over TCP) A typical example of this is SSH. SSH can multiplex multiple channels (see ControlMaster , ControlPath and ControlPersist in OpenSSH). Using this reduces the cost of initializing a new SSH session (initial latency) but heavy transfer on one channel usually increases the latency/interactivity of the other ones (which does not happen if you use multiple TCP stream): if you are using a interactive sessions and start trigerring a heavy file transfer over the same channel, your session will start getting a lot less interactive. Multiplexed HTTP/2 over TCP HTTP/2 uses multiplexing of requests/responses over TCP in order to fix the HOL blocking. This feature is advertised in many articles and papers about HTTP/2. The HTTP/2 RFC claims: HTTP/1.1 added request pipelining, but this only partiallyaddressed request concurrency and still suffers fromhead-of-line blocking. [...] The resulting protocol is more friendly to the network because fewerTCP connections can be used in comparison to HTTP/1.x.This means less competition with other flows and longer-livedconnections, which in turn lead to better utilization ofavailable network capacity. However what is not discussed is that HOL blocking is not resolved entirely. HTTP/2 over TCP still suffers ) from TCP-level HOL blocking . This is discussed in this LWN article about QUIC: HTTP/2 was designed to address this problem using multiple "streams"built into a single connection .[...] it creates a new problem: the loss of a single packetwill stall transmission of all of the streams at once,creating newlatency issues. This variant on the head-of-line-blocking problem isbuilt into TCP itself and cannot be fixed with more tweaks at the HTTPlevel. Other multiplexing strategies SCTP That's one of the distinguishing features of SCTP (multistreaming), you can have multiple independent streams in the same SCTP association and each stream does not block the other ones. See SSH over SCTP — Optimizing a Multi-ChannelProtocol by Adapting It to SCTP for the effect of using SCTP in order to avoid cross-channel HOL blocking in SSH: SCTP only preserves the order of the messages within a singlestream to mitigate an effect known as head-of-line blocking.If a message is lost, the subsequent messageshave to be delayed until the lost one is retransmittedto preserve the order. Since only messages of the samestream have to be delayed, the number of affectedmessages after a loss is reduced. [...] By mapping the channels of SSH onto SCTP’s streams, thebenefit of multi-streaming is made available to SSH, whichis the mitigation of head-of-line blocking . SCTP is not necessarily easy to deploy (because of OS availability, middlebox interaction, etc.). A possibility is to implement it over UDP in userspace . QUIC (multiplexing over UDP) Another example, is the experimental QUIC protocol used for multiplexing HTTP over UDP (because multiplexing multiple streams on top of of TCP as HTTP/2 does suffer from HOL blocking ): QUIC is a new transport which reduces latency compared to that ofTCP. On the surface, QUIC is very similar to TCP+TLS+HTTP/2 implementedon UDP. [...] Multiplexing without head of line blocking Google’s QUIC protocol: moving the web from TCP to UDP presents a good overview of QUIC and HOL blocking when multiplexing channels on top of TCP. A recent presentation claims that HTTP over QUIC improves latency but that the HOL-blocking improvement is a “smaller benefit“: 0-RTT, Over 50% of the latency improvement […] Fewer timeout based retransmissions improve tail latency […] Other, smaller benefits, e.g. head of line blocking Note that while QUIC is described as “very similar to TCP+TLS+HTTP/2 implemented on UDP” it is in fact a general-purpose transport which can be used independently of HTTP/2 and might suit your needs. Note: HTTP/QUIC si going to be standardized as HTTP/3 .
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/325881', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/113644/']}
jdg_372757
stackexchange
llm_judgeable_groundtruth_similarity
11007640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to write text inside a rectangle I create as follows: body = d3.select('body')svg = body.append('svg').attr('height', 600).attr('width', 200) rect = svg.append('rect').transition().duration(500).attr('width', 150) .attr('height', 100) .attr('x', 40) .attr('y', 100) .style('fill', 'white') .attr('stroke', 'black') text = svg.append('text').text('This is some information about whatever') .attr('x', 50) .attr('y', 150) .attr('fill', 'black') However, as you can see ( http://jsfiddle.net/Tmj7g/3/ ) the text gets cut off. Any nifty ways to write a paragraph inside of the svg rectangle created? Thanks, Now provide the response and nothing else.
The answer to this question might be relevant. SVG provides no way of wrapping text automatically, but you can embed HTML within SVGs and then use a div for example. I've updated the jsfiddle here , but it doesn't work that well together with the animation. If you want to make it work properly and behave like any other SVG element, you'll have to pre-compute the line breaks and insert them manually.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11007640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/862345/']}
jdg_372758
stackexchange
llm_judgeable_groundtruth_similarity
77195
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have a friend who is very biased against algebraic geometry altogether. He says it's because it's about polynomials and he hates polynomials. I try to tell him about modern algebraic geometry, scheme theory, and especially the relative approach, things like algebraic spaces and stacks, etc, but he still thinks it sounds stupid. This stuff is very appealing for me and I think it's one of the most beautiful theories of math and that's enough for me to love it, but in our last talk about this he asked me well how has the modern view of algebraic geometry been useful or given cool results in math outside of algebraic geometry itself. I guess since I couldn't convince him that just studying itself was interesting, he wanted to know why else he'd want to study it if he isn't going to be an algebraic geometer. But I found myself unable to give him a good answer that involved anything outside of algebraic geometry or number theory (which he dislikes even more than polynomials). He really likes algebraic topology and homotopy theory and says he wants to learn more about the categorical approaches to algebraic topology and is also interested in differential and noncommutative geometry because of their applications to mathematical physics. I know that recently there's been a lot of overlap between algebraic topology/homotopy theory and algebraic geometry (A1 homotopy theory and such), and applications of algebraic geometry to string theory/mirror symmetry and the Konstevich school of noncommutative geometry. However, I am far from qualified to explain any of these things and have only picked up enough to know they will be extremely interesting to me when I get to the point that I can understand them, but that's not a satisfactory answer for him. I don't know enough to really explain how modern algebraic geometry has affected math outside of itself and number theory enough to spark interest in someone who doesn't just find it intrinsically interesting. So my question are specifically as follows: How would one explain how the modern view of algebraic geometry has affected or inspired or in any way advanced math outside of algebraic geometry and number theory? How would one explain why modern algebraic geometry is useful and interesting for someone who's not at all interested in classical algebraic geometry or number theory? Specifically why should someone who wants to learn modern algebraic topology/homotopy theory care or appreciate modern algebraic geometry? I'm not sure if this should be CW or not so tell me if it should. Now provide the response and nothing else.
As others have suggested, your friend is getting it backwards. He's like a hammer asking what a carpenter is useful for. Given a field (of mathematics, say), there are typically some fields that are more structured than it and others that are less structured. In mathematics, people often say the more structured ones are 'harder', and the less structured are 'softer'. For instance, in increasing order of hardness, we have sets, topological spaces, topological manifolds, differential manifolds, complex manifolds, complex algebraic varieties, algebraic varieties over the rational numbers, integral algebraic varieties. These are in a linear order, but if you throw in other subjects, you'll get a non-linear one. (p-adic algebraic geometry and Riemannian geometry immediately come to mind.) (I think Gromov has some remarks at the end of an ICM address where he talks about this and gives other examples. Also, don't confuse 'harder' and 'softer' in this sense with what they mean in the sciences, which is essentially 'more precise' and 'less precise'. For instance, in science people say that biology is softer than chemistry. In fact, the two meanings are opposites because in science, more structured objects are less amenable to a precise analysis. But this typically isn't the case in mathematics.) Now given a subject S and a harder subject H, it's usually true that most objects in S don't admit the structure of an object in H. For instance, most topological manifolds don't admit a complex structure. On the other hand, for the objects of S that do admit such a structure, their theory from the point of view of H is typically much richer than that from the point of view of S. For instance, the study of Riemann surfaces as topological spaces is less rich than their study as complex manifolds. You might say that softer subjects are broad and flexible and harder ones are rich and rigid. Mathematicians tend to view subjects that are softer than their specialty as general nonsense, and harder ones as excessively particular. This is not to say that a soft field is easier or less interesting than a harder one. Even if it is true that the directly analogous question in the soft subject is easier (e.g. classify Riemann surfaces topologically rather than holomorphically), it just means that the people in the soft subject can move on and study more sophisticated objects. So they just get stuck later rather than sooner. For instance, over the past 50 years, a big fraction of the best number theorists have been studying elliptic curves over number fields. Now elliptic curves over the complex numbers are much easier (I think there hasn't been much new since the 19th century), so the algebraic geometers just moved on to higher genus or higher dimension and are grappling with the issues there, issues that are way out of reach in the presence of arithmetic structure. Now my main point here is that soft subjects were typically invented to break up the study of harder ones into smaller pieces. (This is surely something of a creation myth, but one with a fair amount of truth.) For instance, the real numbers were invented to break up the study of polynomial equations into two steps: when a polynomial has a real solution and when that real solution is rational. I know very little about modern analysis, but I think that much of it was invented to do the same with differential equations. You first find solutions in some soft sense and then see whether it comes from a solution in the harder sense of original interest. So the role of soft subjects is to aid in the study of harder ones---people usually don't ask for applications of partial differential equations to the study of topological vector spaces, but it's considered a mark of respectability to ask for the opposite. Similarly, no one talks about applications of engineering to mathematics. Since algebraic geometry is at the hard end of the spectrum above, there aren't many fields in which it is natural to ask for applications. Number theory, or arithmetic algebraic geometry, is harder and of course there are zillions of applications there, but that's not what your friend wants. Just about all mathematicians work in a subject that is softer than some and harder than others (and if you include non-mathematical subjects, then all mathematicians do). That's all good---it takes a whole food chain to make an ecosystem. But it's backwards to ask about the nutritional value of something that typically eats you . [This picture of mathematics is of course simplistic. There are examples of hard subjects with applications to softer ones. See Donu Arapura's answer, for example. There are also applications of arithmetic algebraic geometry to complex algebraic geometry. For instance, Grothendieck's proof of the Ax-Grothendieck theorem, or the proof of the decomposition theorem for perverse sheaves using the theory of weights and the Weil conjectures. But I think it's fair to say that such applications are the exception---and are prized because of it---rather than the rule.]
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/77195', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12402/']}
jdg_372759
stackexchange
llm_judgeable_groundtruth_similarity
32260
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do it? Now provide the response and nothing else.
Be sure to use System.Net.Mail , not the deprecated System.Web.Mail . Doing SSL with System.Web.Mail is a gross mess of hacky extensions. using System.Net;using System.Net.Mail;var fromAddress = new MailAddress("from@gmail.com", "From Name");var toAddress = new MailAddress("to@example.com", "To Name");const string fromPassword = "fromPassword";const string subject = "Subject";const string body = "Body";var smtp = new SmtpClient{ Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword)};using (var message = new MailMessage(fromAddress, toAddress){ Subject = subject, Body = body}){ smtp.Send(message);} Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting. If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords , select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password. If it is disabled, then you have to turn on Less secure app access , which is not recommended! So better enable the 2-Step verification.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/32260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2535/']}
jdg_372760
stackexchange
llm_judgeable_groundtruth_similarity
51410633
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created a service account in Google Cloud Console and selected role Storage / Storage Admin (i.e. full control of GCS resources). gcloud projects get-iam-policy my_project seems to indicate that the role was actually selected: - members: - serviceAccount:my_sa@my_project.iam.gserviceaccount.com role: roles/storage.admin- members: - serviceAccount:my_sa@my_project.iam.gserviceaccount.com role: roles/storage.objectAdmin- members: - serviceAccount:my_sa@my_project.iam.gserviceaccount.com role: roles/storage.objectCreator And documentation clearly indicates that role roles/storage.admin comprises permissions storage.objects.* (as well as storage.buckets.* ). But when I try using that service account in conjunction with the Google Cloud Storage Client Library for Python, I receive this error message: my_sa@my_project.iam.gserviceaccount.com does not have storage.objects.get access to my_project/my_bucket. So why would the selected role not be sufficient in this context? Now provide the response and nothing else.
The problem was apparently that the service account was associated with too many roles, perhaps as a results of previous configuration attempts. These steps resolved the issue: removed all (three) roles for the offending service account (member) my_sa under IAM & Admin / IAM deleted my_sa under IAM & Admin / Service accounts recreated my_sa (again with role Storage / Storage Admin ) Effects are like this: my_sa shows up with one role ( Storage Admin ) under IAM & Admin / IAM my_sa shows up as member under Storage / Browser / my_bucket / Edit bucket permissions
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51410633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1789384/']}
jdg_372761
stackexchange
llm_judgeable_groundtruth_similarity
152162
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 a book on rational series, a blunt statement is made to the effect that: For $K$ a field, $I$ an ideal of $K[x]$, $K[x]/I$ is finitely generated iff $I$ is nonnull. The statement elaborates with the not-so-enlightening (to me) sentence This is true since a nonnull ideal in $K[x]$ always has a finite codimension ⁽¹⁾, and the latter is equal to the degree of any generator of this ideal ⁽²⁾. I gather that if (2) is true, then $K[x]$ may be finitely generated if $K$ itself is finitely generated, but this is as far as I can go. As for (1), I have a feeling of why this is true, but no proof.Thus I need help in proving the whole statement :-) Thanks ! Now provide the response and nothing else.
The set of the classes of the powers of $x$ are clearly generators of $K[x]/I$. Recall that since $K$ is a field, $K[x]$ is euclidian so $I$ is generated by a polynomial, says $P$, of degree $n$. Now consider any power $x^l$, with $l>n$. The euclidian division gives two polynomials $Q$ and $R$ such that$$x^l=QP +R$$with $R$ of degree lesser than $n-1$. In particular the class of $x^l$ in $K[x]/I$ is generated by the classes of the $x^k$, with $0\leq k \leq n-1$, and thus the dimension of $K[x]/I$ is lesser than $n$. To finish, show that those classes are indeed a base, and check the case where $I$ is reduced to $0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/152162', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5270/']}
jdg_372762
stackexchange
llm_judgeable_groundtruth_similarity
7164412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With current practices (at least with WPF and Silverlight) we see views bound via command bindings in the view model or we at least see view events handled in view models. This appears to be a violation of SRP because the view model doesn't just model the view state, but responds to the view (user). Others have asked how to build view models without violating SRP or asked whether their implementations do so (this last is the controller in MVC, but roughly analogous). So are current practices a violation of SRP? Or is "view model" really a collection of things that don't violate SRP? To frame this a bit, it seems we need to know what is the single responsibility or if there are multiple responsibilities in the concept , are the individual responsibilities split out, conforming to SRP. I'm not sure. Wikipedia's definition of view model says [T]he ViewModel is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model This seems good enough for SRP, but then the entry later says (my emphasis added) [The ViewModel] acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model In a Prism blog post about the view model's role, the author says (again, my emphasis) What it boils down is that the view model is a composite of the following : an abstraction of the view commands value converters view state I'm sure I've missed many definitions out there, but they seem to fall into these categories: Single "vague" responsibility of modeling view state (so what do we mean by state) Multiple responsibilities (view state, user interaction (i.e.commands)) A composite of single specific responsibilities (abstraction,state, interaction, conversion), thus having a singleresponsibility: "managing all that stuff". If you're curious, I "care" about this because (2) feels right, but seems counter to the prevailing implementations. Now provide the response and nothing else.
Single Responsibility as Martin defines it : "THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE." A ViewModel, as far as MVVM is concerned is really just a specialized implementation of a Presentation Model . So while it could be argued that a Presentation Model should only represent the state of the UI, and that a Presenter/Controller should always broker the commands between the UI and the Presentation Model. If one follows this idea, with SRP dividing on State and Commands , then adding a command should not affect the class that represents state. Therefore MVVM would break SRP. However... I think this is grasping at straws. MVVM is a fairly specialized implementation used basically in WPF/Silverlight ( and now browser clients ). Patterns are designed to make designs simpler where the alternative would be more cumbersome or less maintainable . Since MVVM is designed to take advantage of the extremely rich data binding capabilities of the presentation technologies, then it is a worthwhile trade off.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7164412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64348/']}
jdg_372763
stackexchange
llm_judgeable_groundtruth_similarity
39781996
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have the following 2 models: public class Blog{ public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; }}public class Post{ public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; }} Now if I want to configure the models relationships in DbContext is there any difference between: modelBuilder.Entity<Post>() .HasOne(p => p.Blog) .WithMany(b => b.Posts); and modelBuilder.Entity<Blog>() .HasMany(b => b.Posts) .WithOne(p => p.blog); and if there is a diffrence, what is it? should I write both or just one of them? As a side note: Do I have to define foreign keys? Based on my knowledge about databases, you can't create relationships without foreign keys but EF doesn't require you to have foreign key fields. So how does EF handles relationships without knowing foreign keys? Does it cause performance drops or bugs? Now provide the response and nothing else.
You're right, you can create relations in DbContext without foreign keys in database. Also: WithOne : One to one relationships have a reference navigation property on both sides. They follow the same conventions as one-to-many relationships, but a unique index is introduced on the foreign key property to ensure only one dependent is related to each principal. Many-to-many : relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships. You only need to define one relation, because in some cases you'll create a relation for parent-child without navigation properties (one or collection). For your example: you add a relation for Blog -> Posts because you have navigation properties in both objects, the two lines make the same but in different way: Blog -> Posts (Parent -> child) Posts -> Blog (Child -> Parent)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39781996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5052848/']}
jdg_372764
stackexchange
llm_judgeable_groundtruth_similarity
5544536
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why is type inference failing here? scala> val xs = List(1, 2, 3, 3)xs: List[Int] = List(1, 2, 3, 3)scala> xs.toSet map(_*2)<console>:9: error: missing parameter type for expanded function ((x$1) => x$1.$times(2)) xs.toSet map(_*2) However, if xs.toSet is assigned, it compiles. scala> xs.toSetres42: scala.collection.immutable.Set[Int] = Set(1, 2, 3)scala> res42 map (_*2)res43: scala.collection.immutable.Set[Int] = Set(2, 4, 6) Also, going the other way, converting to Set from List , and mapping on List complies. scala> Set(5, 6, 7)res44: scala.collection.immutable.Set[Int] = Set(5, 6, 7)scala> res44.toList map(_*2)res45: List[Int] = List(10, 12, 14) Now provide the response and nothing else.
I agree it would be nice to infer "the only possible" type, even when calls are chained, but there are technical limitations. You can think of inference as a breadth-first sweep over the expression, collecting constraints (which arise from subtype bounds and required implicit arguments) on type variables, followed by solving those constraints. This approach allows, e.g., implicits to guide type inference. In your example, even though there is a single solution if you only look at the xs.toSet subexpression, later chained calls could introduce constraints that make the system unsatisfiable. The downside of leaving the type variables unsolved is that type inference for closures requires the target type to be known, and will thus fail (it needs something concrete to go on -- the required type of the closure and the type of its argument types must not both be unknown). Now, when delaying solving the constraints makes inference fail, we could backtrack, solve all the type variables, and retry, but this is tricky to implement (and probably quite inefficient).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5544536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/428768/']}
jdg_372765
stackexchange
llm_judgeable_groundtruth_similarity
70945
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I control my TV using only a Raspberry Pi and the Infrared diode from an old remote control. Plus how can I interpret IR commands from an existing remote control. Now provide the response and nothing else.
I can switch my TV on using the following command: irsend SEND_ONCE LG_AKB72915207 KEY_POWER This is how I set it up. Hardware Setup I am using a Raspberry Pi P1 2011.12. The bare Infrared LED connected to GPIO#18 and GND . Installing lirc sudo apt-get install lirc -y Update /etc/modules sudo nano /etc/modules And add the following lines which results in # /etc/modules: kernel modules to load at boot time.## This file contains the names of kernel modules that should be loaded# at boot time, one per line. Lines beginning with "#" are ignored.lirc_devlirc_rpi gpio_in_pin=4 gpio_out_pin=18 Please note that I'm not (yet) using the gpio_in_pin in my setup. Update /etc/lirc/hardware.conf This is my hardware.conf # /etc/lirc/hardware.conf## Arguments which will be used when launching lircdLIRCD_ARGS="--uinput"#Don't start lircmd even if there seems to be a good config file#START_LIRCMD=false#Don't start irexec, even if a good config file seems to exist.#START_IREXEC=false#Try to load appropriate kernel modulesLOAD_MODULES=true# Run "lircd --driver=help" for a list of supported drivers.DRIVER="default"# usually /dev/lirc0 is the correct setting for systems using udev DEVICE="/dev/lirc0"MODULES="lirc_rpi"# Default configuration files for your hardware if anyLIRCD_CONF=""LIRCMD_CONF="" Update /boot/config.txt sudo nano /boot/config.txt Update the line regarding lirc-rpi module # Uncomment this to enable the lirc-rpi moduledtoverlay=lirc-rpi,gpio_in_pin=4,gpio_out_pin=18# dtparam=gpio_in_pull=up Download the Remote Control Preset At lirc.sourceforge.net/remotes you find a huge repository of remote controls along with the presets. In my case the closest to my Remote Control LG AKB73275606 was the LG_AKB72915207 . Which looks more or less like my remote control . So I copied the contents of lirc.sourceforge.net/remotes/lg/AKB72915207 to /etc/lirc/lircd.conf : sudo nano /etc/lirc/lircd.conf ## this config file was automatically generated# using lirc-0.8.6(default) on Fri Sep 10 22:02:46 2010## contributed by## brand: TV LG 42"LD420# model no. of remote control: AKB72915207# devices being controlled by this remote:#begin remote name LG_AKB72915207 bits 16 flags SPACE_ENC|CONST_LENGTH eps 30 aeps 100 header 9056 4448 one 601 1647 zero 601 538 ptrail 601 repeat 9081 2199 pre_data_bits 16 pre_data 0x20DF gap 108229 toggle_bit_mask 0x0 begin codes KEY_POWER 0x10EF # Was: power energy 0xA956 avmode 0x0CF3 input 0xD02F tvrad 0x0FF0 KEY_1 0x8877 # Was: 1 KEY_2 0x48B7 # Was: 2 KEY_3 0xC837 # Was: 3 KEY_4 0x28D7 # Was: 4 KEY_5 0xA857 # Was: 5 KEY_6 0x6897 # Was: 6 KEY_7 0xE817 # Was: 7 KEY_8 0x18E7 # Was: 8 KEY_9 0x9867 # Was: 9 KEY_0 0x08F7 # Was: 0 KEY_LIST 0xCA35 # Was: list q.view 0x58A7 KEY_VOLUMEUP 0x40BF # Was: vol_up KEY_VOLUMEDOWN 0xC03F # Was: vol_down KEY_CHANNELUP 0x00FF # Was: ch_up KEY_CHANNELDOWN 0x807F # Was: ch_down KEY_FAVORITES 0x7887 # Was: fav ratio 0x9E61 KEY_MUTE 0x906F # Was: mute KEY_MENU 0xC23D # Was: menu KEY_INFO 0xD52A # Was: guide q.menu 0xA25D KEY_UP 0x02FD # Was: up KEY_DOWN 0x827D # Was: down KEY_LEFT 0xE01F # Was: left KEY_RIGHT 0x609F # Was: right KEY_OK 0x22DD # Was: ok KEY_BACK 0x14EB # Was: back KEY_INFO 0x55AA # Was: info KEY_EXIT 0xDA25 # Was: exit KEY_RED 0x4EB1 # Was: red KEY_GREEN 0x8E71 # Was: green ellow 0xC639 KEY_BLUE 0x8679 # Was: blue exit2 0x04FB t.opt 0x847B KEY_SUBTITLE 0x9C63 # Was: subtitle KEY_STOP 0x8D72 # Was: stop KEY_PLAY 0x0DF2 # Was: play KEY_PAUSE 0x5DA2 # Was: pause KEY_REWIND 0xF10E # Was: << KEY_FORWARD 0x718E # Was: >> simplink 0x7E81 end codesend remote Now restart the lirc service: sudo /etc/init.d/lirc restart Sending commands Now I'm able to switch my TV on and off like so: irsend SEND_ONCE <DEVICE> <KEY> namely: irsend SEND_ONCE LG_AKB72915207 KEY_POWER And voilà my TV switches on and off. Update: Adding a receiver Update /etc/modules snd-bcm2835lirc_devlirc_rpi gpio_in_pin=18 gpio_out_pin=17 Update /etc/lirc/hardware.conf # /etc/lirc/hardware.conf## Arguments which will be used when launching lircdLIRCD_ARGS="--uinput"#Don't start lircmd even if there seems to be a good config file#START_LIRCMD=false#Don't start irexec, even if a good config file seems to exist.#START_IREXEC=false#Try to load appropriate kernel modulesLOAD_MODULES=true# Run "lircd --driver=help" for a list of supported drivers.DRIVER="default"# usually /dev/lirc0 is the correct setting for systems using udev DEVICE="/dev/lirc0"MODULES="lirc_rpi"# Default configuration files for your hardware if anyLIRCD_CONF=""LIRCMD_CONF="" Append the following to /boot/config.txt : # LIRCdtoverlay=lirc-rpi,gpio_in_pin=18,gpio_out_pin=17dtparam=gpio_in_pull=up To test the remote run the following, which will show you the pulses sudo /etc/init.d/lirc stopmode2 -d /dev/lirc0 To record a new remote use the following commands. Make sure to share your remote with the lirc community by sending the config to lirc@bartelmus.de. irrecord --list-namespace # Shows the allowed identifiers for the commandsirrecord -f -d /dev/lirc0 ~/lirc.conf Now to test the config you start the lirc service and run irw # sudo /etc/init.d/lirc start[ ok ] Loading LIRC modules:.[ ok ] Starting remote control daemon(s) : LIRC :.root@phone2:~# irw0000000008087887 00 KEY_POWER LG_6710CMAM09D0000000008087887 01 KEY_POWER LG_6710CMAM09D0000000008087887 02 KEY_POWER LG_6710CMAM09D000000000808c837 00 KEY_PAGEUP LG_6710CMAM09D000000000808c837 01 KEY_PAGEUP LG_6710CMAM09D00000000080848b7 00 KEY_PAGEDOWN LG_6710CMAM09D000000000808c837 00 KEY_PAGEUP LG_6710CMAM09D Troubleshooting Manually start the socket daemon sudo lircd --device /dev/lirc0 Tutorials that helped me out http://alexba.in/blog/2013/01/06/setting-up-lirc-on-the-raspberrypi/ http://www.raspberry-pi-geek.com/Archive/2015/10/Raspberry-Pi-IR-remote#article_l1 https://www.hackster.io/duculete/ir-remote-with-raspberry-pi-d5cf5f http://www.raspberrypiwiki.com/index.php/Raspberry_Pi_IR_Control_Expansion_Board http://alexba.in/blog/2013/02/23/controlling-lirc-from-the-web/ http://learn.linksprite.com/raspberry-pi/shield/infrared-transceiver-on-raspberry-pi-lirc-software-installation-and-configuration http://filter-failure.eu/2015/11/raspberry-pi-2-lirc-with-an-active-low-ir-receiver-with-raspbian-jessie/ http://aron.ws/projects/lirc_rpi Error messages I got during my setup irsend: hardware does not support sendingirsend: command failed: SEND_ONCE LG_AKB72915207 KEY_POWERirsend: unknown remote: "/etc/lirc/lircd.conf"lirc_rpi: gpio chip not found! Other posts about lirc LIRC won't transmit (irsend: hardware does not support sending) LIRC remote control won't send (irsend: hardware does not support sending) LIRC won't transmit irsend: unknown remote https://stackoverflow.com/questions/30118014/how-to-record-an-ir-signal-from-an-ac-remote-using-lirc-in-raspberry-pi LIRC - Unable to load module Lirc doesn't show a remote when I do irsend list lsmod lsmod ...lirc_dev 10211 1 lirc_rpirc_core 23776 1 lirc_dev Showing errors related to the lirc process: dmesg | grep -i lirc [ 5.118133] lirc_dev: IR Remote Control driver registered, major 244[ 7.148664] lirc_rpi: module is from the staging directory, the quality is unknown, you have been warned.[ 8.269729] lirc_rpi: auto-detected active high receiver on GPIO pin 4[ 8.270174] lirc_rpi lirc_rpi: lirc_dev: driver lirc_rpi registered at minor = 0[ 8.270188] lirc_rpi: driver registered![ 16.197900] input: lircd as /devices/virtual/input/input0 Listing a remote: Listing all remotes: irsend LIST "" "" irsend: LG_AKB72915207 Listing the commands for a given Remote irsend LIST LG_AKB72915207 "" irsend: 00000000000010ef KEY_POWERirsend: 000000000000a956 energyirsend: 0000000000000cf3 avmodeirsend: 000000000000d02f inputirsend: 0000000000000ff0 tvradirsend: 0000000000008877 KEY_1irsend: 00000000000048b7 KEY_2irsend: 000000000000c837 KEY_3irsend: 00000000000028d7 KEY_4irsend: 000000000000a857 KEY_5irsend: 0000000000006897 KEY_6irsend: 000000000000e817 KEY_7irsend: 00000000000018e7 KEY_8irsend: 0000000000009867 KEY_9irsend: 00000000000008f7 KEY_0irsend: 000000000000ca35 KEY_LISTirsend: 00000000000058a7 q.viewirsend: 00000000000040bf KEY_VOLUMEUPirsend: 000000000000c03f KEY_VOLUMEDOWNirsend: 00000000000000ff KEY_CHANNELUPirsend: 000000000000807f KEY_CHANNELDOWNirsend: 0000000000007887 KEY_FAVORITESirsend: 0000000000009e61 ratioirsend: 000000000000906f KEY_MUTEirsend: 000000000000c23d KEY_MENUirsend: 000000000000d52a KEY_INFOirsend: 000000000000a25d q.menuirsend: 00000000000002fd KEY_UPirsend: 000000000000827d KEY_DOWNirsend: 000000000000e01f KEY_LEFTirsend: 000000000000609f KEY_RIGHTirsend: 00000000000022dd KEY_OKirsend: 00000000000014eb KEY_BACKirsend: 00000000000055aa KEY_INFOirsend: 000000000000da25 KEY_EXITirsend: 0000000000004eb1 KEY_REDirsend: 0000000000008e71 KEY_GREENirsend: 000000000000c639 ellowirsend: 0000000000008679 KEY_BLUEirsend: 00000000000004fb exit2irsend: 000000000000847b t.optirsend: 0000000000009c63 KEY_SUBTITLEirsend: 0000000000008d72 KEY_STOPirsend: 0000000000000df2 KEY_PLAYirsend: 0000000000005da2 KEY_PAUSEirsend: 000000000000f10e KEY_REWINDirsend: 000000000000718e KEY_FORWARDirsend: 0000000000007e81 simplink Displaying the lirc status: The following command should not show any errors sudo /etc/init.d/lirc status This is what I see on my working setup: $ sudo /etc/init.d/lirc status● lirc.service - LSB: Starts LIRC daemon. Loaded: loaded (/etc/init.d/lirc) Active: active (running) since Wed 2017-08-09 08:21:34 UTC; 21min ago Process: 385 ExecStart=/etc/init.d/lirc start (code=exited, status=0/SUCCESS) CGroup: /system.slice/lirc.service ├─444 /usr/sbin/lircd --driver=default --device=/dev/lirc0 --uinput └─458 /usr/sbin/lircmdAug 09 08:36:22 JHD lircd-0.9.0-pre1[444]: accepted new client on /var/run/lirc/lircdAug 09 08:36:22 JHD lircd-0.9.0-pre1[444]: removed clientAug 09 08:36:24 JHD lircd-0.9.0-pre1[444]: accepted new client on /var/run/lirc/lircdAug 09 08:36:25 JHD lircd-0.9.0-pre1[444]: removed clientAug 09 08:36:26 JHD lircd-0.9.0-pre1[444]: accepted new client on /var/run/lirc/lircdAug 09 08:36:26 JHD lircd-0.9.0-pre1[444]: removed clientAug 09 08:36:27 JHD lircd-0.9.0-pre1[444]: accepted new client on /var/run/lirc/lircdAug 09 08:36:27 JHD lircd-0.9.0-pre1[444]: removed clientAug 09 08:36:29 JHD lircd-0.9.0-pre1[444]: accepted new client on /var/run/lirc/lircdAug 09 08:36:29 JHD lircd-0.9.0-pre1[444]: removed client Badly formatted quotes taken from online tutorials Badly formatted quotes in the config files caused some troubles that took me quite some time to resolve. ”/dev/lirc0″ instead of proper quotes "/dev/lirc0"
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/70945', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/12404/']}
jdg_372766
stackexchange
llm_judgeable_groundtruth_similarity
142819
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am currently studying Serge Lang's book "Algebra", on page 25 it is proved that if $G$ is a cyclic group of order $n$, and if $d$ is a divisor of $n$, then there exists a unique subgroup $H$ of $G$ of order $d$. I have trouble seeing why the proof (as explained below) settles the uniqueness part. The proof (as I understand it) goes as follows: First we show existence of the subgroup $H$, given any choice of a divisor $d$ of $n$. So suppose $n = dm$. Obviously, one can construct a surjective homomorphism $f : \mathbb{Z} \to G$, and it is also clear that $f(m\mathbb{Z}) \subset G$ is a subgroup of $G$. The resulting isomorphism $\mathbb{Z}/m\mathbb{Z} \cong G/f(m\mathbb{Z})$ leads us to conclude that the index of $f(m\mathbb{Z})$ in $G$ is $m$ and so the order of $f(m\mathbb{Z})$ must be $d$. Ok, so we have shown that a subgroup having order $d$ exists. The second part is then to show uniqueness - and here is where I am lost as I don't understand why the following argument serves this end: Suppose $H$ is any subgroup of order $d$. Looking at the inverse image of $f^{-1}(H)$ in $\mathbb{Z}$ we know it must be of the form $k\mathbb{Z}$ for some positive integer $k$ (since all non - trivial subgroups in $\mathbb{Z}$ can be written in this form). Now $H = f(k\mathbb{Z})$ has order $d$, and $\mathbb{Z}/k\mathbb{Z} \cong G/H$, where the group on the right hand side has order $n/d = m$. From this isomorphism we can therefore conclude that $k = m$. Here Lang ends by saying ".. and H is uniquely determined". But why is this ? Does he mean uniquely determined up to isomorphism ? Because, what I think I have shown is that any subgroup of order $d$ must be isomorphic to $m\mathbb{Z}$ - yet this gives me uniqueness only up to isomorphism.. what am I missing ? Thanks for your help! Now provide the response and nothing else.
What you're missing is that the homomorphism $f$ is fixed. Every subgroup $H$ of $G$ of order $d$ is the group $f[m\Bbb Z]$, so they're all the same subgroup of $G$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/142819', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22194/']}
jdg_372767
stackexchange
llm_judgeable_groundtruth_similarity
1692773
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a follow-up question to my post on Stack Overflow . I want to (either analytically or numerically) integrate: $I=\displaystyle\int_{-\infty}^{\infty}\dfrac{1}{(z+1)^2+4} \dfrac{1}{\exp(-z)-1} dz$ using MATLAB, but it tells me that the integral may not exist – the integral is undefined at $z=0$. The Cauchy principal value doesn't seem to exist either, so what does this tell us about the integral? Does it mean we can't evaluate $I$ (numerically or otherwise)? Now provide the response and nothing else.
If you expand $\frac{1}{\exp(-z)-1}$ in a Taylor series around $z=0$, you notice that$$\frac{1}{\exp(-z)-1}\approx -\frac{1}{z}-\frac{1}{2}-\frac{z}{12}+\ldots$$so the function has indeed a non-integrable singularity at $z=0$. One way to assign a finite result to your integral is to subtract and re-add the singular part to your integral as$$\int_{-\infty}^{\infty}\dfrac{1}{(z+1)^2+4} \left[\dfrac{1}{\exp(-z)-1}+\frac{1}{z}-\frac{1}{z}\right]=$$$$\int_{-\infty}^{\infty}\dfrac{1}{(z+1)^2+4} \left[\dfrac{1}{\exp(-z)-1}+\frac{1}{z}\right]-\mathcal{P}\int_{-\infty}^{\infty}\dfrac{1}{(z+1)^2+4} \frac{1}{z}\ ,$$where $\mathcal{P}$ is Cauchy's principal part. The final result is $-0.383448...$ (checked and agreed with Claude's answer below.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1692773', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157511/']}
jdg_372768
stackexchange
llm_judgeable_groundtruth_similarity
450940
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a website hosted on Amazon S3. It is the new version of an old website hosted on WordPress. I have set up some files with the metadata Website Redirect Location to handle old location and redirect them to the new website pages. For example: I had http://www.mysite.com/solution that I want to redirect to http://mysite.s3-website-us-east-1.amazonaws.com/product.html So I created an empty file named solution inside my bucket with the correct metadata: Website Redirect Location = /product.html The S3 redirect metadata is equivalent to a 301 Moved Permanently that is great for SEO.This works great when accessing the URL directly from S3 domain. I have also set up a CloudFront distribution based on the website bucket.And when I try to access through my distribution, the redirect does not work, ie: http://xxxx123.cloudfront.net/solution does not redirect but download the empty file instead. So my question is how to keep the redirection through the CloudFront distribution ?Or any idea on how to handle the redirection without deteriorate SEO ? Thanks Now provide the response and nothing else.
I ran into this problem recently and I found a workaround that seemed to work. I created a Cloudfront distribution with a custom origin pointing to the S3 static website hostname instead of the bucket hostname. In the OP's case, the desired origin would be. mysite.s3-website-us-east-1.amazonaws.com Hitting a Cloudfront distribution just using the bucket as the origin does not work because the bucket does not actually serve redirects. It only serves files and stores metadata. Hope that helps.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/450940', 'https://serverfault.com', 'https://serverfault.com/users/143492/']}
jdg_372769
stackexchange
llm_judgeable_groundtruth_similarity
49924
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a production SQL Server 2008 running on Windows Server and I do testing and development on my laptop. My laptop is running Win XP and SQL Server Express 2008. In addition to having SQL Server Express I would like to install SSIS from the full SQL server on my laptop. I realize that SSIS does not come with SQL Server Express. But it does come with SQL Server 2008, which I have. I would like to install SSIS 2008 on my laptop along with SQL Server Express in order to build my ETL routines locally and then deploy them later to my production server. I can't figure out how to install ONLY SSIS on my laptop using the SQL Server 2008 install media (Clarification: NOT the SQL Server Express media). When I get to the "Feature Selection" step in the SQL Server Complete install, the options to install "Database Engine Services" and "SQL Server Replication" are checked but gray so I can't un-check them. How do I install only SSIS on my laptop? A related question would be "is it possible to install SSIS on a computer which does not have any version of the SQL Server DB installed?" I get the feel that many people think of SSIS as "part of" SQL Server, but it's a stand alone app that can connect to any SQL Server on any machine. Why should it need to install SQL Server on my laptop in order for me to do ETL on my server? Am I just thinking about this wrong? Now provide the response and nothing else.
After continuing to dig around I finally found an article in MSDN that covers installing advanced services without installing SQL Server . That got me pointed in the right direction: The Crux of my mistake is that I thought of this as 'adding a feature to an existing instance of SQL Server 2008.' Therein lies my flaw. In the install process there is an option for 'Installation Type.' What I should have marked was 'perform a new installation of SQL Server 2008.' (even though I already have 2008 Express installed) Then when I get to the section with the License Terms I had to select my key, ctrl+x to cut it out the license key (it was correct), then ctrl+p to paste it back, THEN click next. Otherwise I would get the Express install, not the regular install. Apparently an 'on key' or 'on click' event was not being properly captured. At that point I could add SQL Server (non express) features to my laptop. The most important check box for SSIS is 'Integration Services' It appears that there are a few things that are confusing in the wording and a few things buggy in the tool flow.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/49924', 'https://serverfault.com', 'https://serverfault.com/users/14618/']}
jdg_372770
stackexchange
llm_judgeable_groundtruth_similarity
3357105
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 to evaluate, without contour integration the following integral: $$I=\int_0^1\frac{\ln^2x\ln(1+x)}{1+x^2}\ dx\ ?$$ @Cody mentioned in this solution that $$I=\frac{\pi^{2}}{6}G+\frac{\pi^{3}}{32}\ln2-\frac{1}{768}\left[\psi_{3}\left(1/4\right)-\psi_{3}\left(3/4\right)\right]$$ but no proof was provided there, so any idea how to approach it? The result from above can be further simplified by using digamma's reflection formula $$\psi(1-x)-\psi(x)=\pi\cot(\pi x)$$ And differentiating both sides three times then set $x=3/4$ to get $$\psi_{3}(3/4)=16\pi^4-\psi_{3}(1/4)$$ $$\Rightarrow I=\frac{\pi^2}{6}G+\frac{\pi^{3}}{32}\ln2+\frac{\pi^4}{48}-\frac{1}{384}\psi_{3}(1/4)$$ Added: Is it possible to evaluate $I$ using harmonic series? Now provide the response and nothing else.
$$\boxed{I=\int_0^1 \frac{\ln^2 x \ln(1+x)}{1+x^2}dx=\frac{\pi^3}{32}\ln 2 +\frac{\pi^2}{6}G-2\beta(4)}$$ $$\boxed{\int_0^1 \frac{\operatorname{Li}_3(-x)}{1+x^2}dx=\frac{\pi^2}{12} G-\frac{3\pi}{128}\zeta(3)-\beta(4)}$$ Tools used for the integral: $$\int_0^1 \frac{\ln x}{1+x^2}dx=-\beta(2)=-G\tag 1$$ $$\int_0^1 \frac{\ln^2 x}{1+x^2}dx=2\beta(3)=\frac{\pi^3}{16}\tag 2$$ $$ \int_0^1 \frac{\ln^3 x}{1+x^2}dx=-6\beta(4)=\frac{\pi^4}{16}-\frac{1}{128}\psi_3\left(\frac14\right)\tag 3$$ $$I'(a)=\int_0^\infty \frac{\ln^2 x}{(a+x)(1+x^2)}dx=-\frac{1}{3}\frac{\ln^3 a}{1+a^2}-\frac{\pi^2 }{3}\frac{\ln a}{1+a^2}+\frac{\pi^3}{8}\frac{a}{1+a^2}\tag 4$$ $\beta(x)$ is the Dirichlet Beta function and $G$ is Catalan's constant . $(1)$ , $(2)$ and $(3)$ follows easily by expanding the denominator into power series. To prove $(4)$ we'll start by using partial fraction: $$I'(a)=\frac{1}{1+a^2}\int_0^\infty \ln^2 x\left(\frac{1}{a+x}-\frac{x}{1+x^2} \right)dx+\frac{a}{1+a^2}\int_0^\infty \frac{\ln^2 x}{1+x^2}dx$$ Now we will split the integrals in the point $1$ , then use the substitution $x\to \frac{1}{x}$ in the $\int_1^\infty$ part and add it with the $\int_0^1$ part to get: $$I'(a)=\frac{1}{1+a^2}\int_0^1 \ln^2 x\left(\frac{1}{a+x}-\frac{1}{1/a+x}\right)dx+\frac{2a}{1+a^2}\int_0^1 \frac{\ln^2 x}{1+x^2}dx$$ $$=-\frac{2}{1+a^2}\left(\operatorname{Li}_3\left(-\frac{1}{a}\right)-\operatorname{Li}_3\left(-a\right)\right)+\frac{\pi^3}{8}\frac{a}{1+a^2}=-\frac{\ln a}{3}\frac{\pi^2 +\ln^2 a}{1+a^2}+\frac{\pi^3}{8}\frac{a}{1+a^2}$$ Above follows using one trilogarithm functional equation, which can be found here . Evaluation of the integral: $$I=\int_0^1 \frac{\ln^2 x\ln(1+x)}{1+x^2}dx\overset{x\to \frac{1}{x}}=\int_1^\infty \frac{\ln^2 x(\ln(1+x)-\ln x)}{1+x^2}dx$$ $$\Rightarrow 2I=\int_0^\infty \frac{\ln^2 x \ln(1+x)}{1+x^2}dx-\int_1^\infty\frac{\ln^3 x}{1+x^2}dx$$ Now we will consider the following integral: $$I(a)=\int_0^\infty \frac{\ln^2 x\ln(a+x)}{1+x^2}dx -\int_1^\infty \frac{\ln^3 x}{1+x^2}dx$$ Taking a derivative with respect to $a$ gives: $$ I'(a)= \int_0^\infty \frac{\ln^2 x}{(a+x)(1+x^2)}dx=-\frac{1}{3}\frac{\ln^3 a}{1+a^2}-\frac{\pi^2 }{3}\frac{\ln a}{1+a^2}+\frac{\pi^3}{8}\frac{a}{1+a^2}$$ We also have that: $$I(0)=\int_0^\infty \frac{\ln^3 x}{1+x^2}dx-\int_1^\infty \frac{\ln^3 x}{1+x^2}dx=\int_0^1 \frac{\ln^3 x}{1+x^2}dx$$ And $2I= \left(I(1)-I(0)\right)+I(0)$ , so: $$2I=-\frac13 \int_0^1 \frac{\ln^3 a}{1+a^2}da-\frac{\pi^2}{3}\int_0^1 \frac{\ln a}{1+a^2}da+\frac{\pi^3}{8}\int_0^1 \frac{a}{1+a^2}da+\int_0^1 \frac{\ln^3 x}{1+x^2}dx$$ $$=\frac{\pi^3}{16}\ln 2+\frac{\pi^2}{3}G -4\beta(4)\Rightarrow I=\boxed{\frac{\pi^3}{32}\ln 2 +\frac{\pi^2}{6}G-2\beta(4)}$$ Bonus: We can also obtain a nice result from this if we consider: $$J(a)=\int_0^1 \frac{\ln^2 x\ln(1+ax)}{1+x^2}dx$$ $$\Rightarrow J'(a)=\frac{1}{1+a^2}\int_0^1\frac{x\ln^2 x}{1+x^2} dx+\frac{a}{1+a^2}\int_0^1 \frac{\ln^2 x}{1+x^2}dx-\frac{1}{1+a^2}\int_0^1\frac{\ln^2 x}{1/a+x}dx$$ $$=\frac{3\zeta(3)}{16}\frac{1}{1+a^2}+\frac{\pi^3}{16}\frac{a}{1+a^2}+\frac{2}{1+a^2}\operatorname{Li}_3(-a)$$ $$\Rightarrow I=\int_0^1 J'(a)da=\frac{3\pi}{64}\zeta(3)+\frac{\pi^3}{32}\ln 2+2\int_0^1 \frac{\operatorname{Li}_3(-a)}{1+a^2}da$$ And from this we can extract the last integral: $$\boxed{\int_0^1 \frac{\operatorname{Li}_3(-x)}{1+x^2}dx=\frac{\pi^2}{12} G-\frac{3\pi}{128}\zeta(3)-\beta(4)}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3357105', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/432085/']}
jdg_372771
stackexchange
llm_judgeable_groundtruth_similarity
1986451
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was in a talk and the speaker mentioned that it is easy to write down (real or complex?) polynomials whose zero loci are contractible connected manifolds but not homeomorphic to $\mathbb{R}^n$. Can someone give me some examples with proof of contractibility? Now provide the response and nothing else.
Here is what I know about the question which leads to the conclusion that while examples mentioned by the speaker do exist, they are by no means easy; I do not know any explicit examples (it does not mean that there aren't any). Definition. A topological manifold $M$ is called tame if $M$ is homeomorphic to the interior of a compact manifold $N$ with boundary. The Whitehead manifold (mentioned in Thomas Rot's answer) is the first (and the most famous) example of a non-tame contractible manifold. The relevance of this definition to real algebraic sets (sets given by polynomial equations in $R^k$ for some $k$) is that every real algebraic manifold is tame. Already this is not easy, it follows from the Lojasiewicz's theorem that every compact real algebraic set admits a triangulation. Definition. A tame manifold $M$ is simply connected at infinity if it admits a compactification $M\subset N$ as above such that $\partial N$ is simply connected. This is not the standard definition (which is a bit tricky, I can give one if you like), but one can show it to be equivalent to the standard one; in particular, simple connectivity at infinity (which is defined not only for tame manifolds) is independent of the compactification. The following theorem is worth a triple of Fields medals (Smale, Freedman and Perelman): Theorem. (J. Stallings, M. Freedman, G. Perelman) A contractible $n$-dimensional manifold is homeomorphic to $R^n$ if and only if it is simply connected at infinity. Thus, in order to construct examples mentioned by the speakers, one is looking for smooth compact contractible manifolds with boundary $N$ such that $\partial N$ is not simply connected. Such manifolds $N$ do not exist in dimensions $\le 3$ (I can explain why if you like), but exist in all dimensions $n\ge 4$. (Every smooth homology $n-1$-sphere bounds a smooth compact contractible manifold, as long as $n\ge 5$; in dimension $n=4$ the examples are called Mazur manifolds , they were first constructed independently by Mazur and Poenaru around 1960.) But you need more than that: you want examples where $int(N)$ is algebraic. Akbulut and King in: S. Akbulut and H. King, The topology of real algebraic sets with isolated singularities, Annals of Math. 113 (1981) 425-446. proved that the interior of any smooth compact manifold (with boundary) is diffeomorphic to a nonsingular real algebraic subset of some $R^k$. By putting it all together we obtain that for every $n\ge 4$ there exist contractible nonsingular real algebraic sets which are smooth $n$-dimensional manifolds not homeomorphic to $R^n$. On the other hand, such examples do not exist for $n\le 3$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1986451', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/227373/']}
jdg_372772
stackexchange
llm_judgeable_groundtruth_similarity
10976585
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 know whether 'pivot' in MS SQL can be used for converting rows to columns if there is no aggregate function to be used. i saw lot of examples with aggregate function only. my fields are string data type and i need to convert this row data to column data.This is why i wrote this question.i just did it with 'case'. Can anyone help me......Thanks in advance. Now provide the response and nothing else.
You can use a PIVOT to perform this operation. When doing the PIVOT you can do it one of two ways, with a Static Pivot that you will code the rows to transform or a Dynamic Pivot which will create the list of columns at run-time: Static Pivot (see SQL Fiddle with a Demo ): SELECT *FROM( select empid, wagecode, amount from t1) xpivot( sum(amount) for wagecode in ([basic], [TA], [DA])) p Dynamic Pivot: DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);select @cols = STUFF((SELECT distinct ',' + QUOTENAME(wagecode) FROM t1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')set @query = 'SELECT empid, ' + @cols + ' from ( select empid, wagecode, amount from t1 ) x pivot ( sum(amount) for wagecode in (' + @cols + ') ) p 'execute(@query) Both of these will give you the same results
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10976585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/932014/']}
jdg_372773
stackexchange
llm_judgeable_groundtruth_similarity
4562667
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to show this property of the symmetric difference.I want to show in which case this equality holds: $$\mathbb{P}(A\Delta C) = \mathbb{P}(A\Delta B)+\mathbb{P}(B\Delta C)$$ What I know is that $$\mathbb{P}(A\Delta C)\leq \mathbb{P}(A\Delta B)+\mathbb{P}(B\Delta C)$$ always holds and the $\subseteq$ comes from the monotonicity. To show the equality i was thinking about using " $[(A \bigtriangleup B) \bigcup (B \bigtriangleup C)] \setminus (A \bigtriangleup C) = (A \bigtriangleup B) \bigcap (B \bigtriangleup C)$ " but I even have to show the latter and i don't know how to do it. Now provide the response and nothing else.
Yes. Here, $y_{|x=1}=2$ and $y(1)=2$ are the same. Indeed, this notation is widely used. General definition. For a mapping $f:A\to B$ and a subset $C\subset A$ , we use $f|_C$ to denote the mapping $g: C\to B$ given by $g(c)=f(c)$ for all $c\in C$ , and the mapping $f|_C$ is called the restriction of $f$ to $C$ . Here, we have a function $y:\mathbb R\to\mathbb R$ and $\{1\}\subset \mathbb R$ is a subset, and then $y|_{x=1}$ is the same as $y|_{\{x=1\}}$ , or $y|_{\{1\}}$ defined above. We often use $y|_{x=1}$ to emphasize that the independent variable is denoted by $x$ . If you've known $xy^3+y^2-y+2=C$ and $y|_{x=1}=2$ and you want to know the value of $C$ , then you just need to let $x=1$ and $y=2$ in $xy^3+y^2-y+2=C$ to get $$C=1\cdot2^3+2^2-2+2=12.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4562667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1098713/']}
jdg_372774
stackexchange
llm_judgeable_groundtruth_similarity
211482
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a good simple tool that runs on a standard OS (Windows or Linux) that I can used to test that multicast is being passed properly by a router. I have been asked by a client to enable multicast routing on a Linux box acting as their router since their phone system requires multicast to for a few features. Since I am not physically near the client I don't really have the ability to experiment with the various methods for setting up multicast routing on Linux. I can setup a router at my desk that is identical to what is deployed on their network, but I don't know of any good simple tools that I can use to generate or listen for multicast traffic. The one mulicast tool I have found is mcast.exe tool which is part of the Windows 2000/2003 resource kit. From what I have read online it seems that mcast.exe does not work across a router, and only works on the local network, so that doesn't seem to be useful for me to test multicast routing. So what do tool(s) do you use to test that multicast routing is properly setup? Now provide the response and nothing else.
iperf is perfect for this and it's readily available for most linux distributions and windows. On the listener side: % iperf -s -u -B 224.1.1.1 -i 1------------------------------------------------------------Server listening on UDP port 5001Binding to local address 224.1.1.1Joining multicast group 224.1.1.1Receiving 1470 byte datagramsUDP buffer size: 110 KByte (default)------------------------------------------------------------ ...and it will wait to hear from the source. On the source, begin sending: % iperf -c 224.1.1.1 -u -T 32 -t 3 -i 1------------------------------------------------------------Client connecting to 224.1.1.1, UDP port 5001Sending 1470 byte datagramsSetting multicast TTL to 32UDP buffer size: 110 KByte (default)------------------------------------------------------------[ 3] local 192.168.220.20 port 59347 connected with 224.1.1.1 port 5001[ ID] Interval Transfer Bandwidth[ 3] 0.0- 1.0 sec 129 KBytes 1.06 Mbits/sec[ 3] 1.0- 2.0 sec 128 KBytes 1.05 Mbits/sec[ 3] 2.0- 3.0 sec 128 KBytes 1.05 Mbits/sec[ 3] 0.0- 3.0 sec 386 KBytes 1.05 Mbits/sec[ 3] Sent 269 datagrams at the same time, you'll see the listener receive the traffic: ...[ 3] local 224.1.1.1 port 5001 connected with 192.168.220.20 port 59347[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams[ 3] 0.0- 1.0 sec 128 KBytes 1.05 Mbits/sec 0.035 ms 0/ 89 (0%)[ 3] 1.0- 2.0 sec 128 KBytes 1.05 Mbits/sec 0.015 ms 0/ 89 (0%)[ 3] 2.0- 3.0 sec 128 KBytes 1.05 Mbits/sec 0.025 ms 0/ 89 (0%)[ 3] 0.0- 3.0 sec 386 KBytes 1.05 Mbits/sec 0.068 ms 0/ 269 (0%) By specifying the -T 32 option on the sender, you're setting the TTL to 32 which will ensure the traffic can be routed (assuming IGMP, PIM, and whatnot on the routers are properly configured) BTW, the last time I tried using VLC in this scenario, I ran into an issue where VLC would ignore the TTL setting and always transmit packets with TTL set to 1. Read the bug report for a workaround.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/211482', 'https://serverfault.com', 'https://serverfault.com/users/984/']}
jdg_372775
stackexchange
llm_judgeable_groundtruth_similarity
147089
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What are all the translation invariant measures on $\mathbb{R}$? Except Lebesgue measure on $\mathbb R$ I didn't find any translation invariant measure. So I put this question? I know that if $\mu$ is a measure then $c \times \mu$ is again a measure where $c>0$. Now provide the response and nothing else.
Here is a way to argue out. I will let you fill in the details. If we let $\mu([0,1))=C$, then $\mu([0,1/n)) = C/n$, where $n \in \mathbb{Z}^+$. This follows from additivity and translation invariance. Now prove that if $(b-a) \in \mathbb{Q}^+$, then $\mu([a,b)) = C(b-a)$ using translation invariance and what you obtained from the previous result. Now use the monotonicity of the measure to get lower continuity of the measure for all intervals $[a,b)$. Hence, $\mu([a,b)) = \mu([0,1]) \times(b-a)$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/147089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31526/']}
jdg_372776
stackexchange
llm_judgeable_groundtruth_similarity
252507
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: Many years ago I had an issue with Linux where processes would randomly go to sleep. Back then, I knew a trick with the /proc filesystem to trigger a wakeup of the process. I vaguely remember being able to do something like "echo R" >/proc/pid/stat but that doesn't appear to be the right command. There are lots of hits on the internet for "how do I wake a sleeping process?" and so many of the answers are "oh, just kill it!" I know there's another way, but my memory is failing me now. So far I've tried: kill -SIGCONT <pid>echo "R" > /proc/<pid>/statusecho "R" > /proc/<pid>/stat Now provide the response and nothing else.
What do you mean by “sleep”? If you mean state S (interruptible sleep), that means that the process is waiting for I/O. The process is currently engaged in a blocking system call. You can't force it to “wake up” in a generic way — what would it do then? It'll wake up when the input or output operation it wants to make is possible (e.g. when data is available to read, when a write channel becomes ready, etc.). If you mean state T (stopped), that means that the process is currently suspended. You can unsuspend it by sending it a CONT signal (SIGCONT): kill -CONT PID . Processes do not “randomly go to sleep”. They sleep when they have nothing to do. They get suspended if they receive a signal that stops them: SIGTSTP, SIGSTOP, SIGTTIN, SIGTTOU. These last two signals are sent by the terminal interface in the kernel when a background process tries to read from the terminal (resp. write to the terminal); if you aren't aware of that, you might think that the process randomly stops. If that's what happened, you need to bring it to the foreground; run fg in the shell from which you started that background job, with the right argument to indicate the job that the process is part of, e.g. fg %3 . The stat* files in Linux's /proc are read-only and I'm not aware of any time when they were writable. I don't know what you could hope to write there. The data reported by this file is kernel-managed data, and some of it can be changed more or less directly by the process, but it isn't something you can modify from the outside. For example you can't magically make a process become runnable.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/252507', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15189/']}
jdg_372777
stackexchange
llm_judgeable_groundtruth_similarity
16837844
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is Asp.Net Webform application This is my POST method in my Apicontroller public void Post([FromBody]string value){} I'm with fiddler post process. I did so experiment. But it did not. What is the problem. Can you help? I've tried it, I've failed. public void Post(MyViewModel model){ string aa = model.Value;}public class MyViewModel{ public string Value { get; set; }} In Fiddler: Request Body: Value=hakan Now provide the response and nothing else.
The POST body payload in Fiddler should be: =foo_bar instead of: value=foo_bar That's just one of those strange things about the model binding in the Web API. If you want to support value=foo_bar in the POST body payload you could always write a view model: public class MyViewModel{ public string Value { get; set; }} and then have your method take this view model as parameter: public void Post(MyViewModel model){ ... work with model.Value here as usual}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16837844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1234343/']}
jdg_372778
stackexchange
llm_judgeable_groundtruth_similarity
1725455
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 don't understand why the interior of $\mathbb{Q}$ in $\mathbb{R}$ is empty, since, for every ball with the center being a rational number, given an $\epsilon>0$, I can find an infinite sequence of rational numbers that approach this point. For example, take $\frac{1}{2}$. The sequence $\frac{1}{2}+\frac{1}{n}$ can be made as close as I want to the number $\frac{1}{2}$, therefore I can always have open balls with center $\frac{1}{2}$ such that there are rationals inside it. Now provide the response and nothing else.
It doesn’t matter that there are rationals inside the ball: what matters is that your open ball is not a subset of $\Bbb Q$. In order for $\Bbb Q$ to be open in $\Bbb R$, for each $q\in\Bbb Q$ there would have to be an open ball $B(q,\epsilon)$ about $q$ such that $B(q,\epsilon)\subseteq\Bbb Q$, and that is never the case: every open interval in $\Bbb R$ contains irrational numbers.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1725455', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166180/']}
jdg_372779
stackexchange
llm_judgeable_groundtruth_similarity
4789894
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 seem to be having some trouble getting this code to work: import Image, ImageDrawim = Image.open("1.jpg")draw = ImageDraw.Draw(im)draw.ellipse((60, 60, 40, 40), fill=128)del draw im.save('output.png')im.show() This should draw an ellipse at (60,60) which is 40 by 40 pixels. The image returns nothing. This code works fine however: draw.ellipse ((0,0,40,40), fill=128) It just seems that when i change the first 2 co-ords (for where the ellipse should be placed) it won't work if they are larger than the size of the ellipse to be drawn. For example: draw.ellipse ((5,5,15,15), fill=128) Works, but only shows part of the rect. Whereas draw.ellipse ((5,5,3,3), fill=128) shows nothing at all. This happens when drawing a rectangle too. Now provide the response and nothing else.
The bounding box is a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box and (x1, y1) is the lower-right bound of the box. To draw an ellipse to the center of the image, you need to define how large you want your ellipse's bounding box to be (variables eX and eY in my code snippet below). With that said, below is a code snippet that draws an ellipse to the center of an image: from PIL import Image, ImageDrawim = Image.open("1.jpg")x, y = im.sizeeX, eY = 30, 60 #Size of Bounding Box for ellipsebbox = (x/2 - eX/2, y/2 - eY/2, x/2 + eX/2, y/2 + eY/2)draw = ImageDraw.Draw(im)draw.ellipse(bbox, fill=128)del drawim.save("output.png")im.show() This yields the following result ( 1.jpg on left, output.png on right):
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4789894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/368699/']}
jdg_372780
stackexchange
llm_judgeable_groundtruth_similarity
19816703
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to replace one NSView to other view while keeping the constraints. I have a superview , subview as it's child and an placeholder that I'm planning to move to subview's place.But it seems like the code [[superview] replaceSubview:subview with:placeholder]; drops all the constraints related to subview and results in just removing the subview . How can constraints be "copied" from one view to another? Now provide the response and nothing else.
Here is some code I wrote a long time ago to do what you ask. My code is for swapping two NSViews within the same superview, but you can easily adapt it for replacement by stripping out the unneeded bits and doing view/constraint addition and removal in a careful order. In fact I have a shorter version of this code in a "proxy" view controller class that does exactly what you, but I cannot share it because it is a proprietary project that doesn't belong to me. I will tell you that what you need to do is copy the constraints from the proxy view to the new view then add the new view to the superview. After that copy the superview constraints for the proxy to the new view and only after you do that remove the proxy view from the superview. - (void)swapView:(NSView*) source withView:(NSView*) dest persist:(BOOL) persist{ NSLog(@"swapping %@ with %@", source.identifier, dest.identifier); // !!!: adjust the "Auto Layout" constraints for the superview. // otherwise changing the frames is impossible. (instant reversion) // we could disable "Auto Layout", but let's try for compatibility // TODO: we need to either enforce that the 2 controls have the same superview // before accepting the drag operation // or modify this code to take two diffrent superviews into account // we are altering the constraints so iterate a copy! NSArray* constraints = [dest.superview.constraints copy]; for (NSLayoutConstraint* constraint in constraints) { id first = constraint.firstItem; id second = constraint.secondItem; id newFirst = first; id newSecond = second; BOOL match = NO; if (first == dest) { newFirst = source; match = YES; } if (second == dest) { newSecond = source; match = YES; } if (first == source) { newFirst = dest; match = YES; } if (second == source) { newSecond = dest; match = YES; } if (match && newFirst) { [dest.superview removeConstraint:constraint]; @try { NSLayoutConstraint* newConstraint = nil; newConstraint = [NSLayoutConstraint constraintWithItem:newFirst attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:newSecond attribute:constraint.secondAttribute multiplier:constraint.multiplier constant:constraint.constant]; newConstraint.shouldBeArchived = constraint.shouldBeArchived; newConstraint.priority = NSLayoutPriorityWindowSizeStayPut; [dest.superview addConstraint:newConstraint]; } @catch (NSException *exception) { NSLog(@"Constraint exception: %@\nFor constraint: %@", exception, constraint); } } } [constraints release]; NSMutableArray* newSourceConstraints = [NSMutableArray array]; NSMutableArray* newDestConstraints = [NSMutableArray array]; // again we need a copy since we will be altering the original constraints = [source.constraints copy]; for (NSLayoutConstraint* constraint in constraints) { // WARNING: do not tamper with intrinsic layout constraints if ([constraint class] == [NSLayoutConstraint class] && constraint.firstItem == source) { // this is a source constraint. we need to copy it to the destination. NSLayoutConstraint* newConstraint = nil; newConstraint = [NSLayoutConstraint constraintWithItem:dest attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:constraint.secondItem attribute:constraint.secondAttribute multiplier:constraint.multiplier constant:constraint.constant]; newConstraint.shouldBeArchived = constraint.shouldBeArchived; [newDestConstraints addObject:newConstraint]; [source removeConstraint:constraint]; } } [constraints release]; // again we need a copy since we will be altering the original constraints = [dest.constraints copy]; for (NSLayoutConstraint* constraint in constraints) { // WARNING: do not tamper with intrinsic layout constraints if ([constraint class] == [NSLayoutConstraint class] && constraint.firstItem == dest) { // this is a destination constraint. we need to copy it to the source. NSLayoutConstraint* newConstraint = nil; newConstraint = [NSLayoutConstraint constraintWithItem:source attribute:constraint.firstAttribute relatedBy:constraint.relation toItem:constraint.secondItem attribute:constraint.secondAttribute multiplier:constraint.multiplier constant:constraint.constant]; newConstraint.shouldBeArchived = constraint.shouldBeArchived; [newSourceConstraints addObject:newConstraint]; [dest removeConstraint:constraint]; } } [constraints release]; [dest addConstraints:newDestConstraints]; [source addConstraints:newSourceConstraints]; // auto layout makes setting the frame unnecissary, but // we do it because its possible that a module is not using auto layout NSRect srcRect = source.frame; NSRect dstRect = dest.frame; // round the coordinates!!! // otherwise we will have problems with persistant values srcRect.origin.x = round(srcRect.origin.x); srcRect.origin.y = round(srcRect.origin.y); dstRect.origin.x = round(dstRect.origin.x); dstRect.origin.y = round(dstRect.origin.y); source.frame = dstRect; dest.frame = srcRect; if (persist) { NSString* rectString = NSStringFromRect(srcRect); [[_theme prefrences] setObject:rectString forKey:dest.identifier]; rectString = NSStringFromRect(dstRect); [[_theme prefrences] setObject:rectString forKey:source.identifier]; }} you can safely ignore the bits about persistence in your case I imagine. In my case I wanted to implement the iOS springboard functionality (being able to tap-and-hold a button, it jiggles, let me drag it to another button and swap places while persisting between launches)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19816703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683763/']}
jdg_372781
stackexchange
llm_judgeable_groundtruth_similarity
314412
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If you were to build a badge system similiar to how SO does it, would you put the logic/business layer in the database directly (via stored procedure, scheduled sql jobs) or put it in the server side? From what I can think of, you have to: list badges that pertain to the current user action check if the user has a badge already or not insert badge for user Potential options business logic in the web application that calls stored procedures etc. stored procedures ONLY sql server job that runs every x minutes windows service that runs every x minutes Would a combination of these be required? I think it would since some badges are based on milestones for a given question, maybe a batch job is better? Update A system where you can modify the badge system, then re-run the entire badge linking for everyone would be even better. i.e. say you change the logic for some badges, now you have to re-apply it to all the questions/answers/votes/etc. interesting problem to solve!! Now provide the response and nothing else.
I would recommend putting all business logic in the business layer. I recommend this for a few reasons: Keep the business logic in onelanguage / place Scalability -You can partition data, implementdifferent caching mechanisms, etc. Seperation of concerns - let your DB do what it does best...store data, let your programming language make decisions on that data.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/314412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39677/']}
jdg_372782
stackexchange
llm_judgeable_groundtruth_similarity
19276
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am playing around with Ettercap and ARP spoofing attacks. I have noticed that the computers that are involved in my attack not are displaying any messages telling that an IP conflict has occured. Isn't that the case when ARP spoofing? Then two (or more) computers will share the same IP. When does an IP conflict occur? The computers I spoof are a Windows 7 and Ubuntu machines. Now provide the response and nothing else.
Get to the roots ! If you know what ARP does, things will be clearer. On a subnet (machines plugged into the same set of hubs and switches), the machines talk to each other with MAC addresses: the MAC address uniquely identifies each ethernet/WiFi card. Machines, a priori , do not know MAC addresses; they just know IP addresses. So, when machine A wants to send a packet to machine B , it sends a broadcast frame following the ARP protocol; the packet says: "hey, does anybody knows the MAC address of B " ? If someone responds with the information (" B has MAC address xx:xx:xx:xx:xx:xx") then A will be able to send its data to B . To speed up the process, A maintains a cache of known mappings IP-to-MAC, but is ready to remove entries from the cache when the information is not renewed (information renewal is when a packet comes to A , tagged with the IP address of B as source, and, at the ethernet level, uses the MAC address of B ). The ARP cache entries must not be too long-lived because B is allowed to switch hardware (in case B 's ethernet adapter fries and is replaced, the new adapter will have a distinct MAC address, but may assume the same IP address). Other users of ARP are switches . Switch do not emit packets, but they observe a lot. The point of a switch, as opposed to a simpler hub , is to optimize things by sending packets only on relevant cables, instead of broadcasting all packets over the complete subnet. A switch "knows" that a given machine (i.e. a MAC address) lies at the other end of a specific link by observing traffic (i.e. the switch has noticed that all packets with that MAC address as source come from a given link). The switch maintains thus a mapping MAC->link in an internal table, which is confusingly (and inappropriately) also called an "ARP cache". Spoofing is the term some people came up with to designate what is otherwise known as a forgery , when in the context of network security (for some reason, perfectly usable words from previous centuries never seem to be good enough for the technology-addict). ARP spoofing is about sending packets which are forged at the ARP level, i.e. packets which will deceive other systems as to the mappings involving ARP (i.e. the ARP caches that machines and switches maintain). The attacker may gain some advantages so doing; for instance, he may convince a switch to send him some packets which would otherwise have been sent to another machine on another link. This kind of attack is also know as "ARP cache poisoning" because it ultimately fills some ARP caches with wrong entries. An IP conflict is when two machines, with distinct MAC addresses, want to assume the same IP. When an ARP request is sent ("what is the MAC address of B "), both machines will respond, with conflicting information. The requester ( A ) receives both answers and can warn about the problem: two concurrent mappings with one IP and two MAC addresses. ARP spoofing tries to do something different: two IP addresses (or two links) which map to one MAC address. The successful ARP attack is not really distinguishable from a machine which changed its IP address, something which, on a general basis, is normal (when machines get IP addresses dynamically with DHCP , their IP address may change from time to time), and thus triggers no special warning.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/19276', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/7066/']}
jdg_372783
stackexchange
llm_judgeable_groundtruth_similarity
25632356
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having problem to start a JavaFX Application from a Main method of a class which doesn't extend javafx.application.Application In my application there is the MainApp.java which should start the overriden method start() in the MainUIController.java , which extends Applciation When I start the Main method from the MainUIController.java everything works fine. MainApp.java public class MainApp { public static void main(String[] args) { PersonJDBCTemplate jdbc = connect(); MainUIController mUIc = new MainUIController(jdbc); mUIc.start(new Stage()); } public static PersonJDBCTemplate connect() { ApplicationContext context = new ClassPathXmlApplicationContext( "Beans.xml"); PersonJDBCTemplate personJDBCTemplate = (PersonJDBCTemplate) context .getBean("personJDBCTemplate"); return personJDBCTemplate; }} MainUIController.java public class MainUIController extends Application { private Stage stage; // private User loggedUser; private final double MINIMUM_WINDOW_WIDTH = 800.0; private final double MINIMUM_WINDOW_HEIGHT = 570.0; private String version = "0.6"; private PersonJDBCTemplate jdbc; public MainUIController(PersonJDBCTemplate jdbc) { this.jdbc = jdbc; } @Override public void start(Stage primaryStage) { try { stage = primaryStage; stage.setTitle("Sharp"); stage.setMinWidth(MINIMUM_WINDOW_WIDTH); stage.setMinHeight(MINIMUM_WINDOW_HEIGHT); stage.setResizable(false); gotoLogin(); primaryStage.show(); } catch (Exception ex) { Logger.getLogger(MainUIController.class.getName()).log( Level.SEVERE, null, ex); } } public void gotoLogin() { try { LoginController login = (LoginController) replaceSceneContent("/fxml/Login.fxml"); login.setApp(this); } catch (Exception ex) { Logger.getLogger(MainUIController.class.getName()).log( Level.SEVERE, null, ex); } }} After running the MainApp , I get the following Error : Exception in thread "main" java.lang.ExceptionInInitializerErrorat javafx.stage.Window.<init>(Window.java:1110)at javafx.stage.Stage.<init>(Stage.java:236)at javafx.stage.Stage.<init>(Stage.java:224)at ch.kit.sharp.main.MainApp.main(MainApp.java:15)Caused by: java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = mainat com.sun.glass.ui.Application.checkEventThread(Application.java:445)at com.sun.glass.ui.Screen.setEventHandler(Screen.java:245)at com.sun.javafx.tk.quantum.QuantumToolkit.setScreenConfigurationListener(QuantumToolkit.java:600)at javafx.stage.Screen.<clinit>(Screen.java:80)... 4 more Now provide the response and nothing else.
In addition to what Nejinx said, you must not directly call your start() , always call launch() , because it sets up the JavaFX environment , including creation of stage and calls start() passing the stage as an parameter to it. The docs has a note specially stating this NOTE: This method is called on the JavaFX Application Thread The launch() can be called from any class , taking into consideration if the class is directly not extending javafx.application.Application , then you must pass the class extending it as an argument to the launch method. For example, consider you have a class JavaFXMain which extends Application class JavaFXMain extends Application {...} You can use any other class, to start the JavaFX Application. class Main { ... public void someMethod() { ... JavaFXMain.launch(JavaFXMain.class); // Launch the JavaFX application ... }} In your case, you can try something like this inside the main method of MainApp : // You may remove args if you don't intend to pass any argumentsMainUIController.launch(MainUIController.class, args)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25632356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4000326/']}
jdg_372784
stackexchange
llm_judgeable_groundtruth_similarity
3605877
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 52 cards of a standard playing card deck are randomly distributed to two persons: 26 cards to each person. Find the probability that the first person receives all four Kings. Note: The 52 cards include four Kings. I had this question in my probability exam and my answer was $$ \frac{ {4 \choose 4} . {48 \choose 22}}{52 \choose 26} $$ However the teaching assistant's answer was $(\frac{1}{2})^4 = \frac{1}{16}$ as each card has a probability $\frac{1}{2}$ to go to either of the 2 persons Which answer is correct? Now provide the response and nothing else.
As Angina Sing noted, your TA is assuming that the $4$ events are independent, but they are not. If we correct his calculation, we arrive at the same answer you did. The probability that the first player is dealt the King of Spades is $\frac{26}{52}$ . Once he has the King of Spades, what is the probability that he also receives the King of Hearts? There are $25$ spots remaining in his hand, and $51$ spots overall, so the probability that he is dealt both Aces is $\frac{26}{52}\cdot\frac{25}{51}$ . (If you have learned about conditional probability, this is simply the fact that $\Pr(S\cap H)=\Pr(S)\Pr(H|S)$ .) Continuing in this manner, we get that the probability that he gets all $4$ Aces is $$\frac{26\cdot25\cdot24\cdot23}{52\cdot51\cdot50\cdot49}$$ the same answer you got.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3605877', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/363076/']}
jdg_372785
stackexchange
llm_judgeable_groundtruth_similarity
39916850
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'm trying to build the application it will show the android.view.InflateException in FloatingActionButton? I really don't know what causes the error. Login.xml <?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:background="@drawable/bg_image" ><RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/lLayout_logincontainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="40dp" android:orientation="vertical"> <ImageView android:layout_width="130dp" android:layout_height="125dp" android:src="@drawable/project"/> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp"> <EditText android:id="@+id/aTxt_UserName" style="@style/edittextstyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="User Name" android:imeOptions="actionNext" android:textColorHint="@color/white" > </EditText> </android.support.design.widget.TextInputLayout> <!-- Password Label --> <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp"> <EditText android:id="@+id/eTxt_PassWord" style="@style/edittextstyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" android:textColorHint="@color/white" android:textColor="@color/white" /> </android.support.design.widget.TextInputLayout> <android.support.v7.widget.AppCompatButton android:id="@+id/btn_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_marginTop="3dp" android:background="@drawable/button_shape" android:padding="12dp" android:text="Login" android:textAllCaps="false" android:textColor="#ffffff" /> </LinearLayout></RelativeLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:layout_gravity="bottom|end" android:layout_marginRight="@dimen/fab_margin" android:visibility="visible" app:backgroundTint="@color/colorTrade_2" app:elevation="6dp" app:pressedTranslationZ="12dp" app:fabSize="normal" app:rippleColor="@android:color/transparent" android:src="@drawable/ic_user_add" /></android.support.design.widget.CoordinatorLayout> styles.xml <resources> <style name="AppBaseTheme" parent="MyMaterialTheme.Base"> </style> <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="android:textColor">@color/colorPrimaryDark</item> <item name="android:itemBackground">@color/white</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab"> <item name="android:textSize">12sp</item> <item name="textAllCaps">false</item> </style> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> <style name="edittextstyle"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> <item name="android:padding">10dp</item> <item name="android:singleLine">true</item> <item name="android:textColorHint">@color/white</item> <item name="android:inputType">textFilter</item> </style> <style name="userProfileText"> <item name="android:textColor">@color/white</item> <item name="android:textSize">14sp</item> <item name="android:padding">5dp</item> </style></resources> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.trade.seems"><uses-library android:name="com.google.android.maps" android:required="true" /><application android:allowBackup="true" android:name=".utils.MyApplication" android:isolatedProcess="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:largeHeap="true" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_api_key" /> <activity android:name=".uil.SplashActivity" android:screenOrientation="sensorPortrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ual.login.LoginActivity" android:screenOrientation="sensorPortrait"/></application></manifest> build.gradle apply plugin: 'com.android.application'android { compileSdkVersion 23 buildToolsVersion '23.0.3' useLibrary 'org.apache.http.legacy' defaultConfig { applicationId "com.trade.seems" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" multiDexEnabled true } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/maven/ch.acra/acra/pom.xml' exclude 'META-INF/maven/ch.acra/acra/pom.properties' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { } } dexOptions { javaMaxHeapSize "2g" }}dependencies { testCompile 'junit:junit:4.12' compile files('libs/picasso-2.5.2.jar') compile files('libs/httpclient-4.3.6.jar') compile files('libs/httpcore-4.3.3.jar') compile files('libs/httpmime-4.3.6.jar') compile files('libs/YouTubeAndroidPlayerApi.jar') compile fileTree(include: ['*.jar'], dir: 'libs') /*Support Libraries */ compile project(':autocomplete_library') compile project(':ViewPagerIndicator-Library') /*Third party Libraries */ compile 'es.guiguegon:gallerymodule:1.3.1' compile 'de.hdodenhof:circleimageview:2.0.0' compile 'com.nineoldandroids:library:2.4.+' compile 'com.makeramen:roundedimageview:2.0.1' //Library to handle Material design for all Version of android compile 'com.rengwuxian.materialedittext:library:2.1.4' //Library Glide is to handle Images Instead of picasso compile 'com.github.bumptech.glide:glide:3.5.2' compile 'com.mcxiaoke.volley:library-aar:1.0.0' /*Google Android Support Library*/ compile 'com.google.android.gms:play-services-maps:9.4.0' compile 'com.google.android.gms:play-services-location:9.4.0' compile 'com.android.support:multidex:1.0.0' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.android.support:cardview-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.android.support:support-v4:23.1.1' } Complete Error Trace com.trade.seems E/AndroidRuntime: FATAL EXCEPTION: main Process: com.trade.seemys, PID: 8225 java.lang.RuntimeException: Unable to start activityComponentInfo{com.tradezap.seemysteps/com.trade.seems.ual.login.LoginActivity}: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton at android.view.LayoutInflater.inflate(LayoutInflater.java:539) at android.view.LayoutInflater.inflate(LayoutInflater.java:423) at android.view.LayoutInflater.inflate(LayoutInflater.java:374) at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55) at android.app.Activity.performCreate(Activity.java:6251) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  Caused by: android.view.InflateException: Binary XML file line #84: Error inflating class android.support.design.widget.FloatingActionButton at android.view.LayoutInflater.createView(LayoutInflater.java:645) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate(LayoutInflater.java:423)  at android.view.LayoutInflater.inflate(LayoutInflater.java:374)  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)  at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)  at android.app.Activity.performCreate(Activity.java:6251)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance(Native Method) at android.view.LayoutInflater.createView(LayoutInflater.java:619) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)  at android.view.LayoutInflater.inflate(LayoutInflater.java:515)  at android.view.LayoutInflater.inflate(LayoutInflater.java:423)  at android.view.LayoutInflater.inflate(LayoutInflater.java:374)  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)  at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)  at android.app.Activity.performCreate(Activity.java:6251)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  Caused by: java.lang.NoSuchMethodError: No direct method <init>(Landroid/widget/ImageView;Landroid/support/v7/widget/AppCompatDrawableManager;)V in class Landroid/support/v7/widget/AppCompatImageHelper; or its super classes (declaration of 'android.support.v7.widget.AppCompatImageHelper' appears in /data/app/com.tradezap.seemysteps-1/base.apk) at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:133) at android.support.design.widget.FloatingActionButton.<init>(FloatingActionButton.java:110) at java.lang.reflect.Constructor.newInstance(Native Method)  at android.view.LayoutInflater.createView(LayoutInflater.java:619)  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)  at android.view.LayoutInflater.inflate(LayoutInflater.java:515)  at android.view.LayoutInflater.inflate(LayoutInflater.java:423)  at android.view.LayoutInflater.inflate(LayoutInflater.java:374)  at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)  at com.trade.seems.ual.login.LoginActivity.onCreate(LoginActivity.java:55)  at android.app.Activity.performCreate(Activity.java:6251)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Now provide the response and nothing else.
In your Case, Problem is in your styles.xml, your base theme name is AppBaseTheme. Change it to AppTheme as you can see you have used AppTheme in your Mainfest file. I have listed all the reasons that may cause class android.support.design.widget.FloatingActionButton. Please read the points carefully. FAB button is Design Library Cpmponent. Your Activity must extend AppCompatActivity instead of Activity . Your activity theme also should be appropriate Theme.AppCompat theme. Also FAB requires colorAccent. Make sure you have them inside your styles.xml. <!-- Base application theme. --><style name="AppTheme" parent="Base.AppTheme"><!-- Customize your theme here. --></style><style name="Base.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"><item name="android:colorPrimary">@color/primary</item><item name="android:colorPrimaryDark">@color/primary_dark</item><item name="android:colorAccent">@color/accent</item></style> Use app:backgroundTint="@color/your_color" instead of android:backgroundTint. Don't miss out on adding design library inside your project build.gradle file dependencies { compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' ...} Update Support Library on SDK Manager in Extras > Android Support Repository and Android Support Library Hope it solves your error.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39916850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1921204/']}
jdg_372786
stackexchange
llm_judgeable_groundtruth_similarity
14985247
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 processes (A, B) sharing the same mutex (using WaitForSingleObject / ReleaseMutex calls). Everything works fine, but when process A crashes, process B is humming along happily. When I restart process A, there's a deadlock. Deeper investigation reveals that process B can successfully call ReleaseMutex() twice after process A crashes. My interpretation: After process A crashes, the mutex is still locked, but ownership of the mutex transfers readily to process B (which is a bug). That's why it's humming along happily, calling WaitForSingleObject (getting WAIT_OBJECT_0 in return) and ReleaseMutex (getting TRUE in return). Is it possible to use a named synchronization primitive similar to Mutex in such a way that a crash in process A will release the mutex? One solution is to use SEH and catch the crash and release mutex, but I really hope Windows has a robust primitive that doesn't deadlock like that on process crash. Now provide the response and nothing else.
Some basic assumptions you have to make here about how a mutex works on Windows: a mutex is an operating system object that's reference-counted. It will not disappear until the last handle on the mutex is closed any handle that's left unclosed when a process terminates is closed by the operating system, decrementing the reference count a mutex is re-entrant , calling WaitForSingleObject on a mutex on the same thread succeeds and needs to be balanced with an equal number of ReleaseMutex calls an owned mutex becomes abandoned when the thread that owns it terminates without calling ReleaseMutex. Calling WaitForSingleObject on a mutex in this state generates the WAIT_ABANDONED error return code it is never a bug in the operating system. So you can draw conclusions from this by what you observed. Nothing happens to the mutex when A crashes, B still has an handle on it. The only possible way B can notice that A crashed is when A crashed while it owned the mutex. Very low odds for that and easily observed since B will deadlock. Far more likely is that B will happily motor on since it is now completely unobstructed, nobody else is going to acquire the mutex anymore. Furthermore, a deadlock when A starts back proves something you already knew: B owns the mutex permanently for some reason. Possibly because it acquired the mutex recursively. You know this because you noticed you had to call ReleaseMutex twice. This is a bug you need to fix. You'll need to protect yourself against a crashing sibling process and you need to write explicit code for that. Call OpenProcess on the sibling to obtain a handle on the process object. A WaitForSingleObject call on the handle will complete when the process terminates.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14985247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/794885/']}
jdg_372787
stackexchange
llm_judgeable_groundtruth_similarity
13369626
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 connect to a PostgreSQL 8.4 DB in Ubuntu 10.10 via the JDBC drivers. I'm connecting via jdbc:postgresql:localhost:5433/dbname because PostgreSQL is running on a non-default port 5433 so I have to specify the port. I've already edited my postgresql.conf to set listen_addresses = "*" . I understand that even though it's localhost, it's still using TCP/IP to connect via JDBC. My problem is that I created a user without a password. If i do not specify a password with DriverManager.connect(url) , it errors indicating that I need to specify a password for authentication. Every password I try, including empty string, fails to authenticate with the DB. How can I connect? Edit:If connecting over wrong port, the error is : PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. When attempting to connect on the correct port, I'm getting PSQLException: FATAL: password authentication failed for user "user". THis is remedied by the accepted answer below. Now provide the response and nothing else.
If you have pg_hba.conf set to require md5 authentication and the user has no password, then no authentication can occur. ALTER USER the_user_name PASSWORD 'give_it_a_password'; Alternately, use ident or (for localhost only, unsafe) trust authentication for that user/db combo in pg_hba.conf if you really must have no password. This is usually a bad idea, it's much better to just set a password. Demo: $ psql -q -U postgres postgrespostgres=# CREATE USER nopw;CREATE ROLE$ psql -h localhost -U nopw postgresPassword for user nopw: [pressed enter]psql: fe_sendauth: no password supplied$ psql -q -U postgres postgrespostgres=# ALTER USER nopw PASSWORD 'test';postgres=# \q$ psql -q -h localhost -U nopw postgresPassword for user nopw: [entered 'test' then pressed enter]postgres=>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13369626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/680268/']}
jdg_372788
stackexchange
llm_judgeable_groundtruth_similarity
556745
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’m trying to figure out why raising zero to the zeroth power equals one. What kind of a scenario would occur in a laboratory experiment where something with a quantity of zero would be raised to the power of zero and you end up with one? How do I explain how something is created out of nothing? What is happening? Now provide the response and nothing else.
The thing is, zero to the zeroth power is not always one. It is technically undefined. We can try to get around that by asking the question; What happens if we take the limit of a function that approaches zero to the zeroth power? It should be easy to find two functions that both approach zero at some point (lets call them $f$ and $g$ ). Thus, $f$ to the power of $g$ approaches zero to the zero. However, using L'hospital's rule, we can see that it is possible to find $f$ and $g$ so that $f^g$ approaches a couple of different numbers (all real numbers, if you include the complex numbers) That will probably be too technical for your child, so to explain it to them, I would recommend asking them what zero to the power of $<$ any number besides zero $>$ is, and showing them that it is always zero. Then, ask them what $<$ any number besides zero $>$ to the zeroth power is, and show them that it is always one. Then explain that because these two properties conflict, there is no single right answer. To make it easier to understand, it is standard practice to say that it equals one, even though it is technically incorrect. Edit: I looked through my explanation of the math behind the weirdness, and found a number of errors. My math was wrong, and the example I gave didn't actually fit the requirements. I removed those parts of my answer. I believe that the simplified explanation for a child is still accurate, though.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/556745', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/82136/']}
jdg_372789
stackexchange
llm_judgeable_groundtruth_similarity
4116001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A few users have been asking me Android lock screen widgets for my app - I believe they want a widget that stays on their lock screens and allows them to interact with the app. I haven't been able to find any official documentation for this - the only thing I found was apps that will take home screen widgets and put them on the lock screen for you. Any clues on where I learn more about building true lock-screen widgets? Now provide the response and nothing else.
Lock screen interaction is difficult. Android allows basic operations with two window flags (FLAG_SHOW_WHEN_LOCKED and FLAG_DISMISS_KEYGUARD). FLAG_SHOW_WHEN_LOCKED works pretty consistently in that it will show on top of the lock screen even when security is enabled (the security isn't bypassed, you can't switch to another non-FLAG_SHOW_WHEN_LOCKED window). If you're just doing something temporary, like while music is playing or similar, you'll probably mostly be okay. If you're trying to create a custom lock screen then there's a lot of unusual interactions on all the different android platforms. ("Help! I can't turn off my alarm without rebooting my HTC phone"). getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html FLAG_SHOW_WHEN_LOCKED Window flag: special flag to let windows be shown when the screen is locked. FLAG_DISMISS_KEYGUARD Window flag: when set the window will cause the keyguard to be dismissed, only if it is not a secure lock keyguard. Because such a keyguard is not needed for security, it will never re-appear if the user navigates to another window (in contrast to FLAG_SHOW_WHEN_LOCKED, which will only temporarily hide both secure and non-secure keyguards but ensure they reappear when the user moves to another UI that doesn't hide them). If the keyguard is currently active and is secure (requires an unlock pattern) than the user will still need to confirm it before seeing this window, unless FLAG_SHOW_WHEN_LOCKED has also been set. Constant Value: 4194304 (0x00400000)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4116001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106095/']}
jdg_372790
stackexchange
llm_judgeable_groundtruth_similarity
27627164
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was looking for way to set upper y limit in ggplot to include label greater than the maximum value. I quickly found this answer using pretty . However, when I plot using my data it won't plot the value for 'fire' in year 2004. Here is my data: t <- structure(list(park = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L), .Label = c("apis", "indu", "isro", "miss", "piro", "sacn", "slbe", "voya"), class = "factor"), loc_01 = structure(c(16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L), .Label = c("apis", "indu", "isro", "miss", "non_apis", "non_indu", "non_isro", "non_miss", "non_piro", "non_sacn", "non_slbe", "non_voya", "piro", "sacn", "slbe", "voya"), class = "factor"), year = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L), .Label = c("2002", "2003", "2004", "2005", "2006", "2007"), class = "factor"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("agriculture", "beaver", "blowdown", "development", "fire", "flooding", "harvest_00_20", "harvest_30_60", "harvest_70_90", "insect_disease_defo", "insect_disease_mort", "unknown"), class = "factor"), value = c(0, 0, 0, 0, 0, 0, 0.0832931254278862, 0.0301695451904579, 0.0264171464103402, 0.0268075089513891, 0, 0.0131238087762612, 0.0900844930199918, 0, 0, 0.014770372800214, 0.0501002326005331, 0, 0, 0, 0.231917243175008, 0.108369509403789, 0, 0.000509329143326649)), row.names = c(NA, -24L), .Names = c("park", "loc_01", "year", "variable", "value"), class = "data.frame") This is the code I'm using... library(ggplot2)py <- pretty(t$value)p <- ggplot () + geom_bar(data=t,aes(x=year,y=value,fill=variable),stat='identity')p <- p + scale_y_continuous(breaks=py,limits=range(py))p Which produces this... If I look at t I see that there should be a 'fire' value for years 2004, 2005, and 2007. But in the stacked bar graph it is missing. I've tried the same graph without the pretty option and it works fine. So, my error must have something to do with use of the option. Any ideas? park loc_01 year variable value1 voya voya 2002 agriculture 0.00000000002 voya voya 2003 agriculture 0.00000000003 voya voya 2004 agriculture 0.00000000004 voya voya 2005 agriculture 0.00000000005 voya voya 2006 agriculture 0.00000000006 voya voya 2007 agriculture 0.00000000007 voya voya 2002 beaver 0.08329312548 voya voya 2003 beaver 0.03016954529 voya voya 2004 beaver 0.026417146410 voya voya 2005 beaver 0.026807509011 voya voya 2006 beaver 0.000000000012 voya voya 2007 beaver 0.013123808813 voya voya 2002 blowdown 0.090084493014 voya voya 2003 blowdown 0.000000000015 voya voya 2004 blowdown 0.000000000016 voya voya 2005 blowdown 0.014770372817 voya voya 2006 blowdown 0.050100232618 voya voya 2007 blowdown 0.000000000019 voya voya 2002 fire 0.000000000020 voya voya 2003 fire 0.000000000021 voya voya 2004 fire 0.231917243222 voya voya 2005 fire 0.108369509423 voya voya 2006 fire 0.000000000024 voya voya 2007 fire 0.0005093291 Now provide the response and nothing else.
I haven't seen any online deobfuscator that does this yet, but the principle is simple. Construct a text filter that parses the "key" array and then replaces each instance that that array is referenced, with the appropriate array value. For example, suppose you have a file, evil.js that looks like this (AFTER you have run it though jsbeautifier.org with the Detect packers and obfuscators? and the Unescape printable chars... options set): var _0xf17f = ["(", ")", 'div', "createElement", "id", "log", "console"];var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5); In that case, the "key" variable would be _0xf17f and the "key" array would be ["(", ")", ...] . The filter process would look like this: Extract the key name using text processing on the js file. Result: _0xf17f Extract the string src of the key array. Result: keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]'; In javascript, we can then use .replace() to parse the rest of the JS src. Like so: var keyArrayStr = '["(", ")", \'div\', "createElement", "id", "log", "console"]';var restOfSrc = "var _0x41dcx3 = eval(_0xf17f[0] + '{id: 3}' + _0xf17f[1]);\n" + "var _0x41dcx4 = document[_0xf17f[3]](_0xf17f[2]);\n" + "var _0x41dcx5 = _0x41dcx3[_0xf17f[4]];\n" + "window[_0xf17f[6]][_0xf17f[5]](_0x41dcx5);\n" ;var keyArray = eval (keyArrayStr);//-- Note that `_0xf17f` is the key name we already determined.var keyRegExp = /_0xf17f\s*\[\s*(\d+)\s*\]/g;var deObsTxt = restOfSrc.replace (keyRegExp, function (matchStr, p1Str) { return '"' + keyArray[ parseInt(p1Str, 10) ] + '"';} );console.log (deObsTxt); if you run that code , you get: var _0x41dcx3 = eval("(" + '{id: 3}' + ")");var _0x41dcx4 = document["createElement"]("div");var _0x41dcx5 = _0x41dcx3["id"];window["console"]["log"](_0x41dcx5); -- which is a bit easier to read/understand. I've also created an online page that takes JS source and does all 3 remapping steps in a slightly more automated and robust manner. You can see it at: jsbin.com/hazevo (Note that that tool expects the source to start with the "key" variable declaration, like your code samples do)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27627164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3178354/']}
jdg_372791
stackexchange
llm_judgeable_groundtruth_similarity
13378989
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From Stroustrup's TC++PL, 3rd Edition, Section 21.3.3: If we try to read into a variable v and the operation fails, the value of v should be unchanged (it is unchanged if v is one of the types handled by istream or ostream member functions). The following example appears to contradict the above quote. Based on the above quote, I was expecting the value of v to remain unchanged -- but it gets zeroed. What's the explanation for this apparent contradictory behaviour? #include <iostream>#include <sstream>int main( ){ std::stringstream ss; ss << "The quick brown fox."; int v = 123; std::cout << "Before: " << v << "\n"; if( ss >> v ) { std::cout << "Strange -- was successful at reading a word into an int!\n"; } std::cout << "After: " << v << "\n"; if( ss.rdstate() & std::stringstream::eofbit ) std::cout << "state: eofbit\n"; if( ss.rdstate() & std::stringstream::failbit ) std::cout << "state: failbit\n"; if( ss.rdstate() & std::stringstream::badbit ) std::cout << "state: badbit\n"; return 1;} The output I get using x86_64-w64-mingw32-g++.exe (rubenvb-4.7.2-release) 4.7.2 is: Before: 123After: 0state: failbit Thanks. Now provide the response and nothing else.
From this reference : If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set ( until C++11 ) If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. ( since C++11 ) It seems that your compiler is compiling in C++11 mode, which changes the behavior. The input operator uses the locale facet std::num_get whose get function invokes do_get . For C++11 it's specified to use std::strtoll et. al. type of functions. Before C++11 it apparently used std::scanf style parsing (going by the reference, I don't have access to the C++03 specification) to extract the numbers. The change in behavior is due to this change in parsing the input.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13378989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1823664/']}
jdg_372792
stackexchange
llm_judgeable_groundtruth_similarity
14065391
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 just messing around with strncpy. My program looks like this typedef struct{ char from_str[10];}test;main (){ test s1; memset(&s1,0,sizeof(test)); char src[10]="himansh"; char dest[10]; memset(dest,0,10); src[3]='\0'; printf("src is %s and strlen is %d \n", src,strlen(src)); fflush(stdout); strncpy(s1.from_str,src,100); printf("s1.from_str is %s , src is %s \n", s1.from_str,src); return 1;} Here before I do strncpy I have added a "\0" character in "src" string, length of "src" string becomes 3 , destination array is of size 10 .But in strncpy I have put number of bytes to be copied as 100. This means my source string is NULL terminated. Now strncpy like any string function should try to copy only 3 bytes even if the number of bytes I provide is more than 3 (in this case 100). It does that, but I get a segmentation fault too. My result is shown below src is him and strlen is 3s1.from_str is him , src is himSegmentation fault (core dumped) Why is this segmentation fault happening over here. Can any one help me out here. Now provide the response and nothing else.
I could point you to man pages, websites, etc, but ultimately what matters is the C standard itself. As part of the standard runtime library, the usage and behavior is defined in C99-§7.23.2.4 as: #include <string.h>char *strncpy(char * restrict s1, const char * restrict s2, size_t n); Description The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined. If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written. Returns The strncpy function returns the value of s1. There is significant implied information here, the most important being: strncpy() will NOT terminate your destination string with a null character if the source string length (not including its null character terminator) meets or exceeds the specified destination buffer length). Furthermore, though clearly specified in the standard (see above), it continues to confound me how many engineers are NOT aware that strncpy() tail-fills the destination string buffer with null characters until the specified length n is reached when the source string length is less than the destination buffer size. This draws the following inescapable conclusion: The strncpy() API will ALWAYS write n characters to the address referenced by the destination buffer. In your case, because the target-buffer is only 10-chars wide, you're writing 90 additional characters past the defined-end of writable memory, and thus walking into the land of undefined behavior . At this point you have to be asking yourself "So whats the use?" There is an arguably fundamental use-case. It allows you to copy up to n chars to the target buffer with the predictability of knowing you won't overrun past n chars. Period. Ultimately, though, you want a null-terminated string, so the proper usage is this: char dst[ N ]; strncpy(dst, src, N-1);dst[N-1] = 0; where N is the hard-length of the dst buffer in chars and is greater-than-or-equal to 1 . Note that dst could just-as-well be a dynamic-allocated memory pointer: char *dst = malloc( N * sizeof(char) ); strncpy(dst, src, N-1);dst[N-1] = 0; With the above, you will always have a null-terminated string at dst . If the source string length is smaller than the specified target buffer length, strncpy() will tail-fill the rest of the buffer with null characters until a total of source-chars-copied + tail-filled-null-characters equals n , and the final statement is redundant. If the source string length is equal to or greater than the target buffer length, strncpy() will stop copying once N-1 chars are reached, and the final statement sets a null character at the end of the buffer. This results in a "cut-down" prefix string of the original source, but most important, it ensures you will NOT exceed the boundaries of your target buffer with a later string-API call that scans for a terminator. The usefulness of the above technique is always debatable. I'm a C++ guy, so std::string saves my happy-self from all this insanity. But the reality is this: Sometimes you care if src isn't copied in its entirety to dst ; sometimes you don't. The usefulness is very situationally dependent. For presenting string-data in a UI this won't (likely) matter. For copying a string to be used for critical data, a partial-prefix-substring isn't going to be acceptable. When the police issue an arrest warrant to "Joseph Johnson Jr.", there will be some explaining to do when his father ("Joseph Johnson") is hauled into jail because the name-buffer of the warrant-issuance software only held 15 chars. All of that said, your segmentation fault comes down to this statement: strncpy(s1.from_str,src, 100); // length parameter is wrong. Recall the bold statement above: " strncpy() will ALWAYS write n characters to the address referenced by the destination buffer." . This means the above code will always write 100 chars to the target buffer, which in your case is only 10-chars wide, thus undefined behavior and likely ker-boom . Rectify this by doing the following if the target buffer is a fixed-length character array: strncpy(s1.from_str,src, sizeof(s1.from_str)/sizeof(s1.from_str[0])-1);s1.from_str[ sizeof(s1.from_str)/sizeof(s1.from_str[0])-1 ] = 0; See the prior usage for how to do this for dynamic string of length `N chars.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14065391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1213221/']}
jdg_372793
stackexchange
llm_judgeable_groundtruth_similarity
49005289
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 tabs in my project- outer Tab and inner Tab. In my inner Tab I have maps and lists which shows markers and details. Now I want to reload (fetch data) when i change the tab from either maps to lists or vice versa. I could only call them once ie first visit as i have been calling the API from component Will Mount(). How to recognise the tab movements and reload map? Any lead would be greatly appreciated Now provide the response and nothing else.
I supposed you are using react-navigation . They recently introduced navigation listener in their API (willBlur, willFocus, didBlur and didFocus events). Then, an idea would be to use those listeners in your screen to refresh the data you need. Example: class YourComponent extends Component { componentDidMount() { this.didFocusListener = this.props.navigation.addListener( 'didFocus', () => { console.log('did focus') }, ); } componentWillUnmount() { this.didFocusListener.remove(); } render() { return ( /* your render */ ); }} Documentation: Subscribe to updates to navigation lifecycle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49005289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8818318/']}
jdg_372794
stackexchange
llm_judgeable_groundtruth_similarity
91475
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: Say I have the following model: $$\text{Poisson}(\lambda) \sim \begin{cases} \lambda_1 & \text{if } t \lt \tau \\ \lambda_2 & \text{if } t \geq \tau \end{cases} $$ And I infer the posteriors for $\lambda_1$ and $\lambda_2$ shown below from my data. Is there a Bayesian way of telling (or quantifying) if $\lambda_1$ and $\lambda_2$ are the same or different ? Perhaps measuring the probability that $\lambda_1$ is different from $\lambda_2$ ? Or perhaps using KL divergences? For example, how can I measure $p(\lambda_2 \neq \lambda_1)$, or at least, $p(\lambda_2 \gt \lambda_1)$? In general, once you have the posteriors shown below (assume non-zero PDF values everywhere for both), what is a good way of answering this question? Update It seems that this question can be answered in two ways: If we have samples of the posteriors, we could look at the fraction of the samples where $\lambda_1 \neq \lambda_2$ (or equivalently $\lambda_2 > \lambda_1$). @Cam.Davidson.Pilon included an answer that would address this problem using such samples. Integrating some sort of difference of the posteriors. And that's an important part of my question. What would that integration look like? Presumably the sampling approach would approximate this integral, but I would like to know the formulation of this integral. Note: The plots above come from this material . Now provide the response and nothing else.
I think a better question is, are they significantly different? To answer this, we need to compute $P(\lambda_2 > \lambda_1)$. Call this quantity $p$. If $p \approx 0.50$, then there's equal chance one is larger than the other. On the other hand, If $p$ is really close to 1, then we can be confident that yes $\lambda_2$ is larger (read: different) than $\lambda_1$ . How do we compute $p$? It's trivial in a Bayesian MCMC framework. We have samples from the posterior, so lets just compute the chace that samples from $\lambda_2$ are larger than $\lambda_1$: p = np.mean( lambda_2_samples > lambda_1_samples ) print p I apologize for not including this in the book, I'll definetly add it as I think it's one of the most useful ideas in Bayesian inference
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/91475', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2798/']}
jdg_372795
stackexchange
llm_judgeable_groundtruth_similarity
5841
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for an easy example of two transition systems that are LTL equivalent, but not trace equivalent. I have read the proof of Trace Equivalence being finer than LTL Equivalence in the book "Principles of Model Checking" (Baier/Katoen) but I'm not sure I really understand it. I am unable to picture it, is there maybe a simple example that can visualize the difference? Now provide the response and nothing else.
Reading Baier and Katoen closely, they are considering both finite and infinite transition systems. See page 20 of that book for definitions. First, take the simple transition system $EVEN$: Lemma: No LTL formula recognizes the language $L_{even} = $Traces$(EVEN)$. A string $c \in L_{even}$ iff $c_i = a$ for even $i$. See Wolper '81 . You can prove this by first showing that no LTL formula with $n$ "next-time" operators can distinguish the strings of the form $p^i\neg p p^\omega$ for $i> n$, by a simple induction. Consider the following (infinite, non-deterministic) transition system $NOTEVEN$. Note that there are two different initial states: Its traces are precisely $\{a,\neg a\}^\omega - L_{even}$. Corollary to the Lemma: If $NOTEVEN \vDash \phi$ then $EVEN \not\vDash \neg\phi$ Now, consider this simple transition system $TOTAL$: Its traces are clearly $\{a,\neg a\}^\omega$. Thus, $NOTEVEN$ and $TOTAL$ are not trace equivalent. Suppose they were LTL inequivalent. Then we would have an LTL formula $\phi$ such that $NOTEVEN \vDash \phi$ and $TOTAL \not\vDash \phi$. But then, $EVEN\vDash \neg\phi$. This is a contradiction. Thanks to Sylvain for catching a stupid bug in the first version of this answer.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/5841', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/4516/']}
jdg_372796
stackexchange
llm_judgeable_groundtruth_similarity
28437
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 designing a H-bridge to drive a motor that is running at 12V / 3A. To prevent shoot-through I decided to select a IC with integrated dead time - IR2111 . What I got so far is the following circuit (showing just one half of the full bridge to conserve space): What I am curious about is the need for the bootstrap capacitor between \$V_B\$ and \$V_S\$ and the diode as shown in the datasheet: My understanding is that usually the drain of the high-side MOSFET is connected to a much higher voltage as the supply voltage for the IR2111. To switch the MOSFET a higher voltage has to be generated, therefore the bootstrap capacitor. But in my case the voltages (drain of the hide-side mosfet and supply voltage of the IR2111) are all 12V. So the voltage is high enough to switch the high-side MOSFET and I do not need the bootstrap capcitor. Am I right? Now provide the response and nothing else.
The datasheet shows this for a reason. If you are not completely sure what it's purpose is and know that you don't need it, then you have to include it. In this case, the FET driver is intended for N channel FETs both top and bottom. When the top FET turns on, it's drain and source voltage will be close. After all the purpose is for the FET to act like a switch. N channel FETs require a higher gate voltage than the source to turn on. This means a higher voltage than the top rail. The diode along with the cap between Vb and Vs are part of a charge pump to produce this higher voltage. If you happen to have the higher voltage already available, then you might be able to use it and not include the charge pump. To do so, you need to read the datasheet very carefully and see if this is possible with that device, and if so, exactly what requirements and restrictions there might be. One drawback of the charge pump method is that the FET needs to be regularly switched for the charge pump to maintain a voltage ready to switch the FET. If you will have long periods at 100% PWM, for example, you may have to consider other methods. Again, the datasheet for the FET driver should go into detail on all this.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/28437', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4950/']}
jdg_372797
stackexchange
llm_judgeable_groundtruth_similarity
906440
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $A$ and $B$ be two closed subsets of the set of real numbers. Define $A+B=\{a+b\in\mathbb{R}:a\in A ,b\in B\}$. Is it true that $A+B$ is closed in $\mathbb{R}$? If not, could you give a counter-example? Now provide the response and nothing else.
Let $A$ be the set of negative integers. Let $B$ be the set of all $n+\frac{1}{2^n}$ where $n$ ranges over the positive integers. Then $A$ and $B$ are closed. But $A+B$ is not closed, since it contains numbers arbitrarily close to $0$ but does not contain $0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/906440', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157516/']}
jdg_372798
stackexchange
llm_judgeable_groundtruth_similarity
41507292
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using BCP to bulk upload data from a CSV file to SQL Azure (because BULK INSERT is not supported). This command runs and uploads the rows: bcp [resource].dbo.TableName in C:\data.csv -t "," -r "0x0a" -c -U bcpuser@resource -S tcp:resource.database.windows.net But data.csv is UTF8 encoded and contains non-ASCII strings. These get corrupted. I've tried changing the -c option to -w: bcp [resource].dbo.TableName in C:\data.csv -t "," -r "0x0a" -w -U bcpuser@resource -S tcp:resource.database.windows.net But then I get '0 rows copied'. What am I doing wrong and how do I bulk insert Unicode characters using BCP? Now provide the response and nothing else.
But data.csv is UTF8 encoded The UTF-8 encoding is the primary issue. Using -w won't help because in Microsoft-land, the term "Unicode" nearly always refers to UTF-16 Little Endian. The solution will depend on which version of BCP you are using as an option was added in the newest version (13.0 / 2016): If you are using BCP that came with SQL Server prior to SQL Server 2016 (version 13.0) then you need to convert the csv file to UTF-16 Little Endian (LE) as that is what Windows / SQL Server / .NET use for all strings. And use the -w switch. I got this to work encoding a file as "UCS-2 LE BOM" in Notepad++, whereas that same import file failed using the -c switch. If you are using BCP that came with SQL Server 2016 (version 13.0) or newer, then you can simply add -c -C 65001 to the command line. -C is for "code page", and 65001 is the code page for UTF-8. The MSDN page for bcp Utility states (in the explanation of the -C switch): Versions prior to version 13 (SQL Server 2016) do not support code page 65001 (UTF-8 encoding). Versions beginning with 13 can import UTF-8 encoding to earlier versions of SQL Server. UPDATE Support for UTF-8 / code page 65001 was added to SQL Server 2014 via SP2, as noted in this Microsoft KB article: UTF-8 encoding support for the BCP utility and BULK INSERT Transact-SQL command in SQL Server 2014 SP2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41507292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/942635/']}
jdg_372799
stackexchange
llm_judgeable_groundtruth_similarity
217295
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: Am I wrong in my interpretation that I should basically just put first before all make rules: .PHONY: all of my rulesall: echo "Executing all ..."of: echo "Executing of ..."my: echo "Executing my ..."rules: echo "Executing rules ..." Is there ever a case where you would not want to follow this 'formula'? http://www.gnu.org/software/make/manual/make.html#Phony-Targets Now provide the response and nothing else.
Clark Grubb's Makefile style guide recommends that: All phony targets should be declared by making them prerequisites of .PHONY. add each phony target as a prerequisite of .PHONY immediately before the target declaration, rather than listing all the phony targets in a single place. No file targets should be prerequisites of .PHONY. phony targets should not be prerequisites of file targets. For your example, this would mean: .PHONY: allall: echo "Executing all ...".PHONY: ofof: echo "Executing of ...".PHONY: mymy: echo "Executing my ...".PHONY: rulesrules: echo "Executing rules ..." Multiple PHONY targets are allowed; see also this Stack Overflow question: "Is it possible to have multiple .PHONY targets in a gnu makefile?" Also, while this isn't mentioned directly in your question, care must be taken not to have a PHONY target with the same name of an actual input or intermediate files in your project. Eg, if your project hypothetically had a source code file named rules (with no suffix), the inclusion of that string in a PHONY target could break expected make behavior.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/217295', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/32951/']}
jdg_372800
stackexchange
llm_judgeable_groundtruth_similarity
21336976
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 someone explain/ redirect me, what is the difference between Node.js's async model(non blocking thread) vs any other language for example c#'s asynchronous way of handling the I/O. This looks to me that both are same model. Kindly suggest. Now provide the response and nothing else.
Both models are very similar. There are two primary differences, one of which is going away soon (for some definition of "soon"). One difference is that Node.js is asynchronously single-threaded, while ASP.NET is asynchronously multi-threaded. This means the Node.js code can make some simplifying assumptions, because all your code always runs on the same exact thread. So when your ASP.NET code await s, it could possibly resume on a different thread, and it's up to you to avoid things like thread-local state. However, this same difference is also a strength for ASP.NET, because it means async ASP.NET can scale out-of-the-box up to the full capabilities of your sever. If you consider, say, an 8-core machine, then ASP.NET can process (the synchronous portions of) 8 requests simultaneously. If you put Node.js on a souped-up server, then it's common to actually run 8 separate instances of Node.js and add something like nginx or a simple custom load balancer that handles routing requests for that server. This also means that if you want other resources shared server-wide (e.g., cache), then you'll need to move them out-of-proc as well. The other major difference is actually a difference in language, not platform. JavaScript's asynchronous support is limited to callbacks and promises, and even if you use the best libraries, you'll still end up with really awkward code when you do anything non-trivial. In contrast, the async / await support in C#/VB allow you to write very natural asynchronous code (and more importantly, maintainable asynchronous code). However, the language difference is going away. The next revision of JavaScript will introduce generators, which (along with a helper library) will make asynchronous code in Node.js just as natural as it is today using async / await . If you want to play with the "coming soon" stuff now, generators were added in V8 3.19, which was rolled into Node.js 0.11.2 (the Unstable branch). Pass --harmony or --harmony-generators to explicitly enable the generator support.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21336976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2928038/']}
jdg_372801
stackexchange
llm_judgeable_groundtruth_similarity
663415
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: i am trying to use following commands in a shell script.. any suggestions to do it a correct way? [root@testserver ~]# crontab -u oracle -e >> 0 0 * * * /usr/local/scrips/setup.shcrontab: usage error: no arguments permitted after this optionUsage: crontab [options] file crontab [options] crontab -n [hostname]Options: -u <user> define user -e edit user's crontab -l list user's crontab -r delete user's crontab -i prompt before deleting -n <host> set host in cluster to run users' crontabs -c get host in cluster to run users' crontabs -s selinux context -x <mask> enable debuggingDefault operation is replace, per 1003.2 Now provide the response and nothing else.
The -e switch will make crontab interactive, which isn't the wished behaviour. I suggest you use the crontab -u user file syntax. Below is an example: root@c:~# crontab -l -u userno crontab for userroot@c:~# echo "10 10 * * * /bin/true" >> to_installroot@c:~# crontab -u user to_installroot@c:~# crontab -l -u user10 10 * * * /bin/trueroot@c:~# crontab -l -u user > temproot@c:~# echo "12 12 * * * /bin/false" >> temproot@c:~# crontab -u user temproot@c:~# crontab -l -u user10 10 * * * /bin/true12 12 * * * /bin/false
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/663415', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/468332/']}
jdg_372802
stackexchange
llm_judgeable_groundtruth_similarity
13212521
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.My problem is that I can't find out how to declare static classes in TypeScript. In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.In vanilla JS, I used to do this with a simple JS object: var myStaticClass = { property: 10, method: function(){}} In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in TS. What is the appropriate solution for this problem ? Now provide the response and nothing else.
TypeScript is not C#, so you shouldn't expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes? In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however. If you're looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript's modules, e.g. module M { var s = "hello"; export function f() { return s; }} So that you can access M.f() externally, but not s, and you cannot extend the module. See the TypeScript specification for more details.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13212521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1397271/']}
jdg_372803
stackexchange
llm_judgeable_groundtruth_similarity
2686000
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 php script im currently using that creates thumbnails based on a max width and height. However, I'd like it to always create square images and crop the images when needed. Here is what I'm using now: function makeThumb( $filename, $type ) { global $max_width, $max_height; if ( $type == 'jpg' ) { $src = imagecreatefromjpeg("blocks/img/gallery/" . $filename); } else if ( $type == 'png' ) { $src = imagecreatefrompng("blocks/img/gallery/" . $filename); } else if ( $type == 'gif' ) { $src = imagecreatefromgif("blocks/img/gallery/" . $filename); } if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) { $newW = $oldW * ($max_width / $oldH); $newH = $max_height; } else { $newW = $max_width; $newH = $oldH * ($max_height / $oldW); } $new = imagecreatetruecolor($newW, $newH); imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH); if ( $type == 'jpg' ) { imagejpeg($new, 'blocks/img/gallery/thumbs/'.$filename); } else if ( $type == 'png' ) { imagepng($new, 'blocks/img/gallery/thumbs/'.$filename); } else if ( $type == 'gif' ) { imagegif($new, 'blocks/img/gallery/thumbs/'.$filename); } imagedestroy($new); imagedestroy($src); } How would I alter this to accomplish what I want (Square thumbs)? Thanks in advance. Now provide the response and nothing else.
function makeThumb( $filename , $thumbSize=100 ){ global $max_width, $max_height; /* Set Filenames */ $srcFile = 'blocks/img/gallery/'.$filename; $thumbFile = 'blocks/img/gallery/thumbs/'.$filename; /* Determine the File Type */ $type = substr( $filename , strrpos( $filename , '.' )+1 ); /* Create the Source Image */ switch( $type ){ case 'jpg' : case 'jpeg' : $src = imagecreatefromjpeg( $srcFile ); break; case 'png' : $src = imagecreatefrompng( $srcFile ); break; case 'gif' : $src = imagecreatefromgif( $srcFile ); break; } /* Determine the Image Dimensions */ $oldW = imagesx( $src ); $oldH = imagesy( $src ); /* Calculate the New Image Dimensions */ if( $oldH > $oldW ){ /* Portrait */ $newW = $thumbSize; $newH = $oldH * ( $thumbSize / $newW ); }else{ /* Landscape */ $newH = $thumbSize; $newW = $oldW * ( $thumbSize / $newH ); } /* Create the New Image */ $new = imagecreatetruecolor( $thumbSize , $thumbSize ); /* Transcribe the Source Image into the New (Square) Image */ imagecopyresampled( $new , $src , 0 , 0 , ( $newW-$thumbSize )/2 , ( $newH-$thumbSize )/2 , $thumbSize , $thumbSize , $oldW , $oldH ); switch( $type ){ case 'jpg' : case 'jpeg' : $src = imagejpeg( $new , $thumbFile ); break; case 'png' : $src = imagepng( $new , $thumbFile ); break; case 'gif' : $src = imagegif( $new , $thumbFile ); break; } imagedestroy( $new ); imagedestroy( $src );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2686000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275708/']}
jdg_372804
stackexchange
llm_judgeable_groundtruth_similarity
10770698
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Main Question I'm having issues with understanding why the handling of dates, labels and breaks is not working as I would have expected in R when trying to make a histogram with ggplot2. I'm looking for: A histogram of the frequency of my dates Tick marks centered under the matching bars Date labels in %Y-b format Appropriate limits; minimized empty space between edge of grid space and outermost bars I've uploaded my data to pastebin to make this reproducible. I've created several columns as I wasn't sure the best way to do this: > dates <- read.csv("http://pastebin.com/raw.php?i=sDzXKFxJ", sep=",", header=T)> head(dates) YM Date Year Month1 2008-Apr 2008-04-01 2008 42 2009-Apr 2009-04-01 2009 43 2009-Apr 2009-04-01 2009 44 2009-Apr 2009-04-01 2009 45 2009-Apr 2009-04-01 2009 46 2009-Apr 2009-04-01 2009 4 Here's what I tried: library(ggplot2)library(scales)dates$converted <- as.Date(dates$Date, format="%Y-%m-%d")ggplot(dates, aes(x=converted)) + geom_histogram()+ opts(axis.text.x = theme_text(angle=90)) Which yields this graph . I wanted %Y-%b formatting, though, so I hunted around and tried the following, based on this SO : ggplot(dates, aes(x=converted)) + geom_histogram()+ scale_x_date(labels=date_format("%Y-%b"),+ breaks = "1 month")+ opts(axis.text.x = theme_text(angle=90))stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this. That gives me this graph Correct x axis label format The frequency distribution has changed shape (binwidth issue?) Tick marks don't appear centered under bars The xlims have changed as well I worked through the example in the ggplot2 documentation at the scale_x_date section and geom_line() appears to break, label, and center ticks correctly when I use it with my same x-axis data. I don't understand why the histogram is different. Updates based on answers from edgester and gauden I initially thought gauden's answer helped me solve my problem, but am now puzzled after looking more closely. Note the differences between the two answers' resulting graphs after the code. Assume for both: library(ggplot2)library(scales)dates <- read.csv("http://pastebin.com/raw.php?i=sDzXKFxJ", sep=",", header=T) Based on @edgester's answer below, I was able to do the following: freqs <- aggregate(dates$Date, by=list(dates$Date), FUN=length)freqs$names <- as.Date(freqs$Group.1, format="%Y-%m-%d")ggplot(freqs, aes(x=names, y=x)) + geom_bar(stat="identity") + scale_x_date(breaks="1 month", labels=date_format("%Y-%b"), limits=c(as.Date("2008-04-30"),as.Date("2012-04-01"))) + ylab("Frequency") + xlab("Year and Month") + theme_bw() + opts(axis.text.x = theme_text(angle=90)) Here is my attempt based on gauden's answer: dates$Date <- as.Date(dates$Date)ggplot(dates, aes(x=Date)) + geom_histogram(binwidth=30, colour="white") + scale_x_date(labels = date_format("%Y-%b"), breaks = seq(min(dates$Date)-5, max(dates$Date)+5, 30), limits = c(as.Date("2008-05-01"), as.Date("2012-04-01"))) + ylab("Frequency") + xlab("Year and Month") + theme_bw() + opts(axis.text.x = theme_text(angle=90)) Plot based on edgester's approach: Plot based on gauden's approach: Note the following: gaps in gauden's plot for 2009-Dec and 2010-Mar; table(dates$Date) reveals that there are 19 instances of 2009-12-01 and 26 instances of 2010-03-01 in the data edgester's plot starts at 2008-Apr and ends at 2012-May. This is correct based on a minimum value in the data of 2008-04-01 and a max date of 2012-05-01. For some reason gauden's plot starts in 2008-Mar and still somehow manages to end at 2012-May. After counting bins and reading along the month labels, for the life of me I can't figure out which plot has an extra or is missing a bin of the histogram! Any thoughts on the differences here? edgester's method of creating a separate count Related References As an aside, here are other locations that have information about dates and ggplot2 for passers-by looking for help: Started here at learnr.wordpress, a popular R blog. It stated that I needed to get my data into POSIXct format, which I now think is false and wasted my time. Another learnr post recreates a time series in ggplot2, but wasn't really applicable to my situation. r-bloggers has a post on this , but it appears outdated. The simple format= option did not work for me. This SO question is playing with breaks and labels. I tried treating my Date vector as continuous and don't think it worked so well. It looked like it was overlaying the same label text over and over so the letters looked kind of odd. The distribution is sort of correct but there are odd breaks. My attempt based on the accepted answer was like so ( result here ). Now provide the response and nothing else.
UPDATE Version 2: Using Date class I update the example to demonstrate aligning the labels and setting limits on the plot. I also demonstrate that as.Date does indeed work when used consistently (actually it is probably a better fit for your data than my earlier example). The Target Plot v2 The Code v2 And here is (somewhat excessively) commented code: library("ggplot2")library("scales")dates <- read.csv("http://pastebin.com/raw.php?i=sDzXKFxJ", sep=",", header=T)dates$Date <- as.Date(dates$Date)# convert the Date to its numeric equivalent# Note that Dates are stored as number of days internally,# hence it is easy to convert back and forth mentallydates$num <- as.numeric(dates$Date)bin <- 60 # used for aggregating the data and aligning the labelsp <- ggplot(dates, aes(num, ..count..))p <- p + geom_histogram(binwidth = bin, colour="white")# The numeric data is treated as a date,# breaks are set to an interval equal to the binwidth,# and a set of labels is generated and adjusted in order to align with barsp <- p + scale_x_date(breaks = seq(min(dates$num)-20, # change -20 term to taste max(dates$num), bin), labels = date_format("%Y-%b"), limits = c(as.Date("2009-01-01"), as.Date("2011-12-01")))# from here, format at easep <- p + theme_bw() + xlab(NULL) + opts(axis.text.x = theme_text(angle=45, hjust = 1, vjust = 1))p Version 1: Using POSIXct I try a solution that does everything in ggplot2 , drawing without the aggregation, and setting the limits on the x-axis between the beginning of 2009 and the end of 2011. The Target Plot v1 The Code v1 library("ggplot2")library("scales")dates <- read.csv("http://pastebin.com/raw.php?i=sDzXKFxJ", sep=",", header=T)dates$Date <- as.POSIXct(dates$Date)p <- ggplot(dates, aes(Date, ..count..)) + geom_histogram() + theme_bw() + xlab(NULL) + scale_x_datetime(breaks = date_breaks("3 months"), labels = date_format("%Y-%b"), limits = c(as.POSIXct("2009-01-01"), as.POSIXct("2011-12-01")) )p Of course, it could do with playing with the label options on the axis, but this is to round off the plotting with a clean short routine in the plotting package.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10770698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495990/']}
jdg_372805
stackexchange
llm_judgeable_groundtruth_similarity
8537148
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 string: Main.Sub.SubOfSub And some kind of data, may be a string: SuperData How I can transform it all to this array above? Array([Main] => Array ( [Sub] => Array ( [SubOfSub] => SuperData ) ) ) Thanks for help,PK Now provide the response and nothing else.
Given the values $key = "Main.Sub.SubOfSub";$target = array();$value = "SuperData"; Here's some code I have lying around that does what you need¹: $path = explode('.', $key);$root = &$target;while(count($path) > 1) { $branch = array_shift($path); if (!isset($root[$branch])) { $root[$branch] = array(); } $root = &$root[$branch];}$root[$path[0]] = $value; See it in action . ¹ Actually it does slightly more than that: it can be trivially encapsulated inside a function, and it is configurable on all three input values (you can pass in an array with existing values, and it will expand it as necessary).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8537148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1017363/']}
jdg_372806
stackexchange
llm_judgeable_groundtruth_similarity
20580599
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 list which I iterate over by using ng-repeat: and the user can interact with thte list items by using up-arrow and down-arrow icons and on click of them i simply change the order of the element in the "list" this is what angular suggests change the model and the changes automatically reflect in the view. <div ng-repeat="item in list">{{item.name}} <div class="icon-up-arrow" ng-click="moveUp($index);"></div> <div class="icon-down-arrow" ng-click="moveDown($index);"></div></div> Logic in moveUp:- $scope.moveUp= function(position){ var temp=list[position-1]; list[position-1]=list[position]; list[position=temp];}; the above code works completely fine and similar is the logic for shifting the item down. But the problem that i want to resolve is how do i put animation? I know angular takes care of binding view and model on its own but is there any way to put in animation as the view is updated on pressing up an down arrow icons? Now provide the response and nothing else.
Following on from Marcel's comment: in AngularJS 1.2 you don't need to use the ng-animate directive. Instead: Include angular-animate[-min].js . Make your module depend on ngAnimate . Define your transitions in CSS using classes like .ng-enter and .ng-enter-active . Use ng-repeat as you normally would. HTML: <div ng-app="foo"> <!-- Set up controllers etc, and then: --> <ul> <li ng-repeat="item in items">{{item}}</li> </ul> JavaScript: angular.module('foo', ['ngAnimate']);// controllers not shown CSS: li { opacity: 1;}li.ng-enter { -webkit-transition: 1s; transition: 1s; opacity: 0;}li.ng-enter-active { opacity: 1;} Demo in (someone else's) Plunker . See the docs for $animate for details on the progression through the various CSS classes.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20580599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2427266/']}
jdg_372807
stackexchange
llm_judgeable_groundtruth_similarity
9689793
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 installed an application, when I try to run it (it's an executable jar) nothing happens. When I run it from the commandline with: java -jar "app.jar" I get the following message: no main manifest attribute, in "app.jar" Normally, if I had created the program myself, I would have added a main class attribute to the manifest file. But in this case, since the file is from an application, i cannot do that. I also tried extracting the jar to see if I could find the main class, but there are to many classes and none of them has the word "main" in it's name. There must be a way to fix this because the program runs fine on other systems. Now provide the response and nothing else.
First, it's kind of weird, to see you run java -jar "app" and not java -jar app.jar Second, to make a jar executable... you need to jar a file called META-INF/MANIFEST.MF the file itself should have (at least) this one liner: Main-Class: com.mypackage.MyClass Where com.mypackage.MyClass is the class holding the public static void main(String[] args) entry point. Note that there are several ways to get this done either with the CLI, Maven, Ant or Gradle: For CLI , the following command will do: (tks @ dvvrt ) jar cmvf META-INF/MANIFEST.MF <new-jar-filename>.jar <files to include> For Maven , something like the following snippet should do the trick. Note that this is only the plugin definition, not the full pom.xml : Latest doc on this plugin: see https://maven.apache.org/plugins/maven-jar-plugin/ <build> <plugins> <plugin> <!-- Build an executable JAR --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.mypackage.MyClass</mainClass> </manifest> </archive> </configuration> </plugin> </plugins></build> (Pick a <version> appropriate to your project.) For Ant , the snippet below should help: <jar destfile="build/main/checksites.jar"> <fileset dir="build/main/classes"/> <zipfileset includes="**/*.class" src="lib/main/some.jar"/> <manifest> <attribute name="Main-Class" value="com.acme.checksites.Main"/> </manifest></jar> Credits Michael Niemand - For Gradle : plugins { id 'java'}jar { manifest { attributes( 'Main-Class': 'com.mypackage.MyClass' ) }}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9689793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/923421/']}
jdg_372808
stackexchange
llm_judgeable_groundtruth_similarity
8372776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Specifically, this problem has come to me when I make a request with AFNeworking with JSONkit and receive a (id)JSON with several arrays and dictionaries nested. If I don't want to modify the data, I don't have any problem: self.myNSArray = [JSON objectForKey:@"result"]; But if I want to modify the data I must to store it in a mutable variable: self.myNSMutableArray = [[JSON objectForKey:@"result"] mutableCopy]; The last one doesn't convert nested arrays or dictionaries to mutable data; it works only for first level. The only way that I have found is on this link recursive mutable objects ; but I don't know if there is a best way to resolve this kind of problem. Thanks in advance. Now provide the response and nothing else.
You could use the CoreFoundation function CFPropertyListCreateDeepCopy with the mutability option kCFPropertyListMutableContainersAndLeaves : NSArray *immutableArray = [JSON objectForKey:@"result"];self.myMutableArray = [(NSMutableArray *)CFPropertyListCreateDeepCopy(NULL, immutableArray, kCFPropertyListMutableContainersAndLeaves) autorelease];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8372776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512378/']}
jdg_372809
stackexchange
llm_judgeable_groundtruth_similarity
4729013
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: can I call Java from Node.js via JNI ? Are there any examples? Now provide the response and nothing else.
You should try the node-java npm module which is a well-written wrapper over JNI. node-jave doesn't appear to (yet) have broad adoption, but playing with it, I've been impressed with how straightforward and robust it has been. It's as simple as: var list = java.newInstanceSync("java.util.ArrayList");list.addSync("item1");list.addSync("item2");console.log(list.getSync(1)); // prints "item2" You can do just about anything with your embedded JVM - create objects, call methods, access fields, etc. There is a slight impedance mismatch between Node and Java, so if you are going to interact with something complicated, I'd recommend writing most of your interactions in Java and exposing a simpler interface across the Node/Java barrier. It just makes for easier debugging that way. --- Dave p.s., RealWorldUseCase(tm): I worked at a place that had a pretty complex (and spaghetti-coded) protocol between multiple browser clients and a Java-based service. I wrote a pretty sweet test-harness which used jsdom to host N simulated browsers and used node-java as a wrapper around the Java service code. It was trivial to shim out the transport interfaces, both in JS for the clients, and in Java for the service, so whenever any of these things sends a message, I capture that and stick it in a queue for probabilistic delivery to the intended target (ie, I virtualized the network). In this way, I could run a full-on simulation of multiple clients interacting with and through a Java service, and run the whole thing inside a single process without any wire communication. And then I could do fun stuff like deliberately reorder message deliveries to make sure the code was resilient to timing bugs. And when a bug was discovered, I had the message orderings logged and could reproduce them to repro the bug. Oh, and the whole thing set up and ran a pretty complex scenario with a few thousand lines of logging and finished in under 1 second per run. 2-weeks well spent. Fun stuff. RealWorld Use Case #2: selenium-inproc - a module that wraps the SeleniumRC JAR file providing a node interface to browser automation testing w/ Selenium without having to run yet another localhost service.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4729013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203429/']}
jdg_372810
stackexchange
llm_judgeable_groundtruth_similarity
3462075
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 a way to make a process keep a certain file open forever. Here's an example of what I have so far: sleep 1000 > myfile & It works for a thousand seconds, but really don't want to make some complicated sleep/loop statement. This post suggested that cat is the same thing as sleep for infinite. So I tried this: cat > myfile & It almost looks like a mistake doesn't it? It seemed to work from the command line, but in a script the file connection did not stay open. Any other ideas? Now provide the response and nothing else.
The reason that cat>myfile& works is because it re-directs standard input into a file. if you launch it with an ampersand (in background), it won't get ANY input, including end-of-file, which means it will forever wait and print nothing to the output file. You can get an equivalent effect, except WITHOUT dependency on standard input (the latter is what makes it not work in your script), with this command: tail -f /dev/null > myfile &
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3462075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125380/']}
jdg_372811
stackexchange
llm_judgeable_groundtruth_similarity
6280360
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 experimenting with Blueimp's jQuery-File-Upload plugin, which judging by the demo looks very promising. It's really easy to implement: var $uploadButton = $("#fileop-upload");// <input type="file" id="fileop-upload" [etc] />$uploadButton.fileupload({ url : "//domain/path/to/receive-uploaded-files"}); The selected files are uploaded fine without refreshing the page as expected, but of course with a minimal configuration like this the user won't get any notification. Here's where the plugin's callbacks would come in handy. According to the documentation there are two ways to define callbacks. For example the add event (which fires whenever a file is selected for uploading) can be added in the original configuration object like this: $uploadButton.fileupload({ add : addFileListener, url : "//domain/path/to/receive-uploaded-files"}); or alternatively: $uploadButton.bind("fileuploadadd", addFileListener); However I've found that only the first approach works, the second one doesn't do anything. It is even more curious that no other callbacks -- especially progress and start -- seems to be firing not matter how I bind them: $uploadButton.fileupload({ add : addFileListener, progress : progressListener, start : startListener, url : "//domain/path/to/receive-uploaded-files"}); or $uploadButton.fileupload({ add : addFileListener, url : "//domain/path/to/receive-uploaded-files"});$uploadButton.bind("fileuploadprogress", progressListener");$uploadButton.bind("fileuploadstart", startListener"); I have the referred listener functions defined, and the code doesn't report any errors or warnings. What is the explanation for the .bind method's failure, and why doesn't the progress or the start listeners ever activate? Now provide the response and nothing else.
I'm the author of the jQuery File Upload plugin. I don't have an explanation why the fileuploadadd event in your third example code doesn't fire.However, if you override the add callback option, you have to make sure the file upload is started by calling the submit method on the data argument, as explained in the Options documentation for the add callback (and also documented in the source code of the plugin). e.g. the following code should print out the different callback events: $('#fileupload').fileupload({ add: function (e, data) { console.log('add'); data.submit(); }, progress: function (e, data) { console.log('progress'); }, start: function (e) { console.log('start'); }}).bind('fileuploadadd', function (e, data) { console.log('fileuploadadd');}).bind('fileuploadprogress', function (e, data) { console.log('fileuploadprogress');}).bind('fileuploadstart', function (e) { console.log('fileuploadstart');}); Note also that the plugin is modular and the UI version (used in the download example) makes use of the callback options which would be overridden with the above code.That's why the event binding is so useful, as it allows to define additional callback methods without overriding the callbacks set via the options object.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6280360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63377/']}
jdg_372812
stackexchange
llm_judgeable_groundtruth_similarity
44063644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new at Django and couldn't find solution for my problem. The problem is to force specific serializer for include different amount of fields in case of utilizing different views. I would like to use 'id' field in my 1st view, and in 2nd view - 'id' and 'name' fields. Here is my model.py class Processing(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() description = models.CharField() And here is my serializer.py class ProcessingSerializer(serializers.ModelSerializer): id = serializers.ModelField(model_field=Processing()._meta.get_field('id')) class Meta: model = Processing fields = ('id', 'name') Any help will be welcome. Now provide the response and nothing else.
When someone just starts using DRF, a common mistake is to try to make the same Serializer do everything under the sun. Certainly I went down that path myself. but life becomes a lot simpler when you use mutiple serializers for different tasks. You can easily switch serializers using the get_serializer_class method. Here is an example right from the manual that shows how to use one for admins and another for ordinary users def get_serializer_class(self): if self.request.user.is_staff: return FullAccountSerializer return BasicAccountSerializer Sometimes you want to use a single serializer for lists and another one for when providing details. Try something like this: def get_serializer_class(self): if self.action == 'retrieve': return serializers.PlayerDetailSerializer else : return serializers.PlayerSerializer Life is much simpler this way.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44063644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8034975/']}
jdg_372813
stackexchange
llm_judgeable_groundtruth_similarity
197649
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 working on SVG implementation for Internet Explorer to be based on its own VML format I came to a problem of translation of an SVG elliptical arc to an VML elliptical arc. In VML an arc is given by: two angles for two points on ellipse and lengths of radiuses,In SVG an arc is given by: two pairs of coordinates for two points on ellipse and sizes of ellipse boundary box So, the question is: How to express angles of two points on ellipse to two pairs of their coordinates. An intermediate question could be: How to find the center of an ellipse by coordinates of a pair of points on its curve. Update : Let's have a precondition saying that an ellipse is normally placed (its radiuses are parallel to linear coordinate system axis), thus no rotation is applied. Update : This question is not related to svg:ellipse element, rather to "a" elliptical arc command in svg:path element ( SVG Paths: The elliptical arc curve commands ) Now provide the response and nothing else.
So the solution is here: The parametrized formula of an ellipse: x = x0 + a * cos(t)y = y0 + b * sin(t) Let's put known coordinates of two points to it: x1 = x0 + a * cos(t1)x2 = x0 + a * cos(t2)y1 = y0 + b * sin(t1)y2 = y0 + b * sin(t2) Now we have a system of equations with 4 variables: center of ellipse (x0/y0) and two angles t1, t2 Let's subtract equations in order to get rid of center coordinates: x1 - x2 = a * (cos(t1) - cos(t2))y1 - y2 = b * (sin(t1) - sin(t2)) This can be rewritten (with product-to-sum identities formulas) as: (x1 - x2) / (2 * a) = sin((t1 + t2) / 2) * sin((t1 - t2) / 2)(y2 - y1) / (2 * b) = cos((t1 + t2) / 2) * sin((t1 - t2) / 2) Let's replace some of the equations: r1: (x1 - x2) / (2 * a)r2: (y2 - y1) / (2 * b)a1: (t1 + t2) / 2a2: (t1 - t2) / 2 Then we get simple equations system: r1 = sin(a1) * sin(a2)r2 = cos(a1) * sin(a2) Dividing first equation by second produces: a1 = arctan(r1/r2) Adding this result to the first equation gives: a2 = arcsin(r2 / cos(arctan(r1/r2))) Or, simple (using compositions of trig and inverse trig functions): a2 = arcsin(r2 / (1 / sqrt(1 + (r1/r2)^2))) or even more simple: a2 = arcsin(sqrt(r1^2 + r2^2)) Now the initial four-equations system can be resolved with easy and all angles as well as eclipse center coordinates can be found.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/197649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23815/']}
jdg_372814
stackexchange
llm_judgeable_groundtruth_similarity
287054
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 Four Squares Theorem says that every natural number is the sum of four squares in $\mathbb Z$. What is known about coprime representations? Here we call a presentation $n=a^2+b^2+c^2+d^2$ coprime if the g.c.d. of the four numbers $a,b,c,d$ is 1. Does every natural number have a coprime presentation? If not, is there a simple criterion characterising the numbers that have coprime presentations? What is known about the number of different coprime presentations of a given $n$? Now provide the response and nothing else.
Let $R(n)$ denote the number of ways of writing $n$ as a sum of $4$ squares, and $r(n)$ the number of ways where gcd of $(a,b,c,d) =1$. Then grouping representations of $n$ as a sum of $4$ squares according to the gcd of the variables, clearly we have $$ R(n) = \sum_{k^2 | n} r(n/k^2),$$ and so by Mobius inversion $$ r(n) = \sum_{k^2| n} \mu(k) R(n/k^2). $$ Now by Jacobi's four square theorem, $R(n)$ is given explicitly as $8$ times a multiplicative function $F(n)$ defined on prime powers by $$ F(2^k) = 3 \text{ for all } k\ge 1,$$ and, for odd primes $p$, $$ F(p^k) = p^k + p^{k-1} + \ldots + 1. $$So $r(n)$ is $8$ times a multiplicative function $f(n)$ which is defined on prime powers by $$f(2)= 3; \ \ f(4) = 2;\ \ f(2^k)=0 \text{ for } k \ge 3,$$and for odd primes $p$ and $k\ge 1$ $$ f(p^k) = p^k + p^{k-1}.$$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/287054', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_372815
stackexchange
llm_judgeable_groundtruth_similarity
18725
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $H$ be a maximum induced interval subgraph of a graph $G=(V,E)$. If $n=|V|$, then what is the smallest number of $V(H)$? The number is at most $3n/4$: consider a set of disjoint $4$-holes. Can it be smaller? Now provide the response and nothing else.
If your students have done any functional programming, the nicest approach I know is to start with the untyped lambda calculus, and then use the bracket abstraction theorem to translate it into SKI combinators. Then, you can use the $smn$ and $utm$ theorems to show that Turing machines form a partial combinatory algebra , and so can interpret the SKI combinators. I doubt this is the simplest possible approach, but I like how it rests on some of the most fundamental theorems in computability (which you may well wish to cover for other reasons). It appears that Andrej Bauer answered a similar question on Mathoverflow a few months back. If you are set on a C-like language, your path will be a lot rougher, since they have a rather complicated semantics -- you'll need to Show that Turing machines can simulate a stack and a heap at the same time, and Show how variables can be implemented with a stack, and Show that procedure calls can be implemented with a stack. This is much of the contents of a compilers class, honestly.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/18725', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/7059/']}
jdg_372816
stackexchange
llm_judgeable_groundtruth_similarity
47718508
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 wanting to front an AWS APIGateway URL with a reverse proxy in Apache. The reason is due to a process requiring a static IP to provision a service behind a strict firewall and that the current infrastructure has mod_proxy already in place. The solution I'm looking to implement is to simply to route https->https(apiGateway) via mod_proxy. But.. AWS uses SNI and I can not get mod_proxy to handshake. I have the following settings enabled <IfModule mod_ssl.c><VirtualHost *:443> ProxyPreserveHost On SSLProxyEngine On ProxyPass /api/1_0/ https://xxx.execute-api.eu-west-1.amazonaws.com/1_0/ ProxyPassReverse /api/1_0/ https://xxx.execute-api.eu-west-1.amazonaws.com/1_0/ The following logs are available in debug mode proxy_util.c(2020): AH00942: HTTPS: has acquired connection for (xxx.execute-api.eu-west-1.amazonaws.com)proxy_util.c(2610): AH00962: HTTPS: connection complete to 52.x.x.x:443 (xxx.execute-api.eu-west-1.amazonaws.com)AH01964: Connection to child 0 established (server domain.com:443)AH02003: SSL Proxy connect failedSSL Library Error: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failureAH01998: Connection closed to child 0 with abortive shutdown (server domain.com:443)AH01997: SSL handshake failed: sending 502 If I connect using openssl, I can demonstrate a similar error openssl s_client -tls1_2 -connect xxx.execute-api.eu-west-1.amazonaws.com:443CONNECTED(00000003)140735866254216:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:s3_pkt.c:1494:SSL alert number 40140735866254216:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:s3_pkt.c:659: adding -servername for SNI, results in a valid connection SSL handshake has read 3601 bytes and written 489 bytes---New, TLSv1/SSLv3, Cipher is ECDHE-RSA-AES128-GCM-SHA256... I therefore believe that mod_proxy and mod_ssl are not sending the servername to the remote https server and could be a bug. I am running Ubuntu 14.04 with Server version: Apache/2.4.7 (Ubuntu)Server built: Sep 18 2017 16:37:54OpenSSL 1.0.1f 6 Jan 2014 I have attempted to limit the SSLProxyProtocol to TLS1_2 and the cipher list too however the sslv3 alert handshake failure log still exists regardless. Has any one come across this and know how to ensure that the SNI values are being sent or is this a restriction in the Apache modules? Now provide the response and nothing else.
This is due to ProxyPreserveHost On being set early in the configuration. Setting ProxyPreserveHost Off under a proxy tag completes as expected: <Proxy "https://xxx.execute-api.eu-west-1.amazonaws.com/1_0"> ProxyAddHeaders off ProxyPreserveHost off</Proxy> Info on the directive: When enabled, this option will pass the Host: line from the incoming request to the proxied host, instead of the hostname specified in the ProxyPass line. This option should normally be turned Off. It is mostly useful in special configurations like proxied mass name-based virtual hosting, where the original Host header needs to be evaluated by the backend server.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47718508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3414144/']}
jdg_372817
stackexchange
llm_judgeable_groundtruth_similarity
2653567
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 Joda-Time 2, what is the difference between the three kinds of time spans: Period Interval Duration Why do we need three classes? Which one performs better? Why is dividing a Period or Duration or Interval instance not implemented? E.g. p = p.divideBy(2); Now provide the response and nothing else.
3 classes are needed because they represent different concepts so it is a matter of picking the appropriate one for the job rather than of relative performance. From the documentation with comments added by me in italics : An interval in Joda-Time represents an interval of time from one millisecond instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone. Specific times are defined e.g. this might be the interval between 20:00:00GMT yesterday and 09:00:00GMT this morning. A duration in Joda-Time represents a duration of time measured in milliseconds. The duration is often obtained from an interval. i.e. we can subtract start from end of an interval to derive a duration A period in Joda-Time represents a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours. This differs from a duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to. e.g. consider the period of 1 year, if we add this to January 1st we will always arrive at the next January 1st but the duration will depend on whether the intervening year is a leap year or not. Similarly if we add 1 month to the 1st of a month then we will arrive at the 1st of the next month but the duration (in milliseconds) will vary based on the month in question For question 3, A specific method to divide a duration is not really needed because we can always get the number of milliseconds from the duration as a long (using getMillis() ), divide it and construct a new duration (using new Duration(long duration) ). Dividing a period doesn't really have a real meaning based on the definition of a period above. e.g. what is half a month? (its length would depend on which month).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2653567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138078/']}
jdg_372818
stackexchange
llm_judgeable_groundtruth_similarity
218163
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I believe the scenario is common mostly in business workflows - for example: loan management the process starts with a loan application, then there's the loan offer, the 'live' loan, and maybe also finished loans. all these objects are related, and share many fields all these objects have also many fields that are unique for each entity the variety of objects maybe large, and the transformation between the may not be linear (for example: a single loan application may end up as several loans of different types) How would you model this? some options: an entity for each type, each containing the relevant fields (possibly grouping related fields as sub entities) - leads to duplication of data. an entity for each object, but instead of duplicating data, each object has a reference to it's predecessor (the loan doesn't contain the loaner details, but a reference to the loan application) - this causes coupling between the object structure, and the way it was created. if we change the loan application, it shouldn't effect the structure of the loan entity. one large entity, with fields for the whole life cycle - this can create 'mega objects' with many fields. it also doesn't work well when there's a one to many or many to many relation between the phases. Now provide the response and nothing else.
One of the most eye-opening events for me was learning about Color-Based Modeling . It totally transformed my approach to designing systems. The key idea is that there are four archetypes in object-oriented design: Moment-Interval represents an event, or a span of time. For instance applying for a loan is a Moment the entire process from application to closure of the loan would be an Interval Role represents participants in a Moment-Interval. Sticking with the loan, an Applicant would be one role, the loan officer would be another, underwriters would be a third. Descriptor represents a label or a "class" of objects. For example, you might have a descriptor for Home Loans versus Auto Loans but the loans themselves are fundamentally the same. The Descriptor can also act as a factory. I usually use descriptors where people normally use Enums. Person/Place/Thing represents a physical, tangible object. Michael Brown is a person, Global Corp. Headquarters is a Place, Dell Precision Laptop with serial number 12345 is a thing. (Note my specific Dell Precision Laptop would possibly have a descriptor attached to it in Dell's E-commerce system). Those are the 4 basic elements of an O-O model. And here is how it relates to your question. The very first archetype is the Moment-Interval. If you recall one of the guidelines for basic object-oriented programming "Objects are Nouns, Methods are Verbs" you might be tempted to represent the loan application as a method "ApplyForLoan" on the Applicant object and store all the information about the application on a single Loan object. Then you might be tempted to have a "LoanStatus" enumeration on the Loan that basically lists all the phases the loan goes through as it's being processed. The better way is to have an Application moment object. And an Applicant role object. Roles are attached to Person/Place/Thing and participate in moments (in practice, I usually give the responsibility for creating a Moment object to a Role that I identify as the "actor". In the case of the loan application the Applicant is the "actor". Within the book, Coad talks about the concept of Predecessors and Successors. I.e. before a RiskAssessment can be performed, there must be an Application . The Moments form a chain of events that are pertinent to the system being created. For instance the loan approval system would not care about payments on the loan so they wouldn't be mapped as part of the system. Although there might be another system that does deal with these details. The beautiful part of this approach is that the system becomes very flexible and extensible because rather than sticking new fields and methods on a bloated "LoanCustomer" object (or worse deriving from loan customer to represent different roles the customer might play in the system), we create new roles as the needs of the system grows. I'd HIGHLY recommend picking the book up and going through it. It's a very powerful technique despite the fact that UML is no longer in favor, the concepts are timeless.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/218163', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/18044/']}
jdg_372819
stackexchange
llm_judgeable_groundtruth_similarity
1634375
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there any other value you can assign to the substitution variable to solve this integral? $$\int \frac{x+3}{\sqrt{x+2}}dx$$ Substituting $u = x + 2$:$$du = dx; u +1 = x+3 ,$$and we get this new integral that we can then split into two different ones:$$\int \frac{u + 1}{\sqrt{u}}du = \int \frac{u}{\sqrt{u}}du + \int \frac{1}{\sqrt{u}}du .$$ We can substitute again $s = \sqrt u$ and get two immediate integrals: $$s = \sqrt{u}; \quad ds = \frac{1}{2\sqrt{u}}du; \quad 2s^2 =u .$$ Substituting back $u$ to $s$ and $x$ to $u$ we get this result,$$s^2 + \ln{\left | \sqrt{u} \right |} = u + \ln{\left | \sqrt{u} \right |} = x+2+\ln{\left | \sqrt{x+2} \right |},$$ which doesn't look quite to be right. What am I doing wrong? I'm pretty unsure about the second substitution, $2s^2 = u$. Is it correct? Now provide the response and nothing else.
let's make it easier than that! Use this:$$x + 2 = t^2 ~~~~~~~~~~~ x+3 = t^2 + 1 ~~~~~~~ \text{d}x = 2t\ \text{d}t$$ Obtaining $$I = \int\frac{t^2 + 1}{t}\ 2t\ \text{d}t = 2\int t^2 + 1\ \text{d}t = \frac{2}{3}t^3 + 2t$$ Coming back to $x$, having $t = \sqrt{x+2}$ and you'll have $$I = \frac{2}{3}\sqrt{x+2}(x+5)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1634375', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/250761/']}
jdg_372820
stackexchange
llm_judgeable_groundtruth_similarity
2023935
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Whats the best way to convert DT_NTEXT to DT_WSTR in Derived Colum Transformation. Regards Now provide the response and nothing else.
The problem here is that the max length of DT_NTEXT is 2^30 ~ 1.073 billion characters, while DT_WSTR max length is 4000 characters. If all your fields are less than 4000, try Data Conversion Transformation and it may only raise a warning at design time. You would add this before of after the Derived Column Transformation .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2023935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85952/']}
jdg_372821
stackexchange
llm_judgeable_groundtruth_similarity
195813
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What happens when the timestampers certificate expires? If the code is now untrusted, can it be re-stamped without re-signing? If not, what good does this timestamp do me if my cert is valid until the same date? TimeStamperCertificate : [Subject] CN=COMODO SHA-1 Time Stamping Signer, O=COMODO CA Limited, L=Salford, S=Greater Manchester, C=GB [Issuer] CN=UTN-USERFirst-Object, OU=http://www.usertrust.com, O=The USERTRUST Network, L=Salt Lake City, S=UT, C=US [Serial Number] 1688F039255E638E69143907E6330B [Not Before] 12/30/2015 6:00:00 PM [Not After] 7/9/2019 1:40:36 PM [Thumbprint] 03A5B14663EB12023091B84A6D6A68BC871DE66B Now provide the response and nothing else.
What happens when the timestampers certificate expires? Literally, nothing. If the code is now untrusted, can it be re-stamped without re-signing? it is not correct statement. Timestamped signature remains valid even when all certificates in chains (both, signing and timestamping) are expired. This is what timestamping does -- keeps signature valid after certificate expiration. Timestamp in signature proves the signing time and it must be within all certificates validity periods. Moreover, timestamped signature is still valid when signing certificate was revoked after signing time. Signature validation code can determine whether the signing certificate was valid (not revoked) at timestamping date and time. You can read my blog post on the subject in more details: Digital signatures and timestamps
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/195813', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/61016/']}
jdg_372822
stackexchange
llm_judgeable_groundtruth_similarity
16808384
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Python has enumerate() to iterate over objects with an index.I doubt that interpreters create a lot of int objects for the sole purpose of keeping track of where things are. The PEP page says the following, but I do not really understand what is going on under the hood: It provides all iterables with the same advantage that iteritems() affords to dictionaries -- a compact, readable, reliable index notation. So what is the magic here? Now provide the response and nothing else.
enumerate() is an iterator; it only produces the index int value on the fly ; it does not produce them all up front. You can try to read the enumobject.c source code , but it basically can be translated to Python like this: def enumerate(iterable, start=0): count = start for elem in iterable: yield count, elem count += 1 The yield keyword makes this a generator function , and you need to loop over the generator (or call next() on it) to advance the function to produce data, one yield call at a time. Python also interns int values, all values between -5 and 256 (inclusive) are singletons, so the above code doesn't even produce new int objects until you reach 257.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16808384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/986067/']}
jdg_372823
stackexchange
llm_judgeable_groundtruth_similarity
19238715
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to set the value of the Accept: in a request I am making using Spring's RestTemplate . Here is my Spring request handling code @RequestMapping( value= "/uom_matrix_save_or_edit", method = RequestMethod.POST, produces="application/json")public @ResponseBody ModelMap uomMatrixSaveOrEdit( ModelMap model, @RequestParam("parentId") String parentId){ model.addAttribute("attributeValues",parentId); return model;} and here is my Java REST client: public void post(){ MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add("parentId", "parentId"); String result = rest.postForObject( url, params, String.class) ; System.out.println(result);} This works for me; I get a JSON string from the server side. My question is: how can I specify the Accept: header (e.g. application/json , application/xml , ... ) and request method (e.g. GET , POST , ... ) when I use RestTemplate? Now provide the response and nothing else.
I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders . (You can also specify the HTTP method you want to use.) For example, RestTemplate restTemplate = new RestTemplate();HttpHeaders headers = new HttpHeaders();headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.exchange(url, HttpMethod.POST, entity, String.class); I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity . However, you can also pass that HttpEntity as a request argument to postForObject . HttpEntity<String> entity = new HttpEntity<>("body", headers);restTemplate.postForObject(url, entity, String.class); This is mentioned in the RestTemplate#postForObject Javadoc . The request parameter can be a HttpEntity in order to add additionalHTTP headers to the request .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/19238715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1837733/']}
jdg_372824
stackexchange
llm_judgeable_groundtruth_similarity
36183624
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 several beans of the same class defined: @Bean public FieldDescriptor fullSpotField() { FieldDescriptor ans = new FieldDescriptor("full_spot", String.class); return ans; } @Bean public FieldDescriptor annotationIdField() { FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class); return ans; } consequently when I autowire them @Autowired public FieldDescriptor fullSpotField; @Autowired public FieldDescriptor annotationIdField; I get an exception NoUniqueBeanDefinitionException: No qualifying bean of type [...FieldDescriptor] is defined: expected single matching bean but found ... How to autowire by name as it possible in XML config? Now provide the response and nothing else.
You can use @Qualifier to solve it. In your case you can make: @Bean(name="fullSpot") // Not mandatory. If not specified, it takes the method name i.e., "fullSpotField" as qualifier name. public FieldDescriptor fullSpotField() { FieldDescriptor ans = new FieldDescriptor("full_spot", String.class); return ans; } @Bean("annotationIdSpot") // Same as above comment. public FieldDescriptor annotationIdField() { FieldDescriptor ans = new FieldDescriptor("annotationID", Integer.class); return ans; } and subsequently you can inject using: @Autowired @Qualifier("fullSpot") public FieldDescriptor fullSpotField; @Autowired @Qualifier("annotationIdSpot") public FieldDescriptor annotationIdField;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36183624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258483/']}
jdg_372825
stackexchange
llm_judgeable_groundtruth_similarity
370
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 read a few days ago that in the LHC temperatures of billions of degrees were achieved. I'm curious to know what does it really mean such a temperature? The concept of temperature is easy to grasp when the numbers are familiar, such as 100 C, but when it's in the range of millions it's difficult to understand. Also, if you can provide some explanation of how the temperature is estimated it would be very helpful. Now provide the response and nothing else.
You posed two distinct questions: how is temperature defined as aphysical quantity? how is temperature measured in thesecircumstances? For the first question, temperature is defined as a thermodynamic quantity relating the change of entropy and the change of internal energy of a system. This is not very intuitive, I agree, but it is THE definition, and it make physicists sure they are talking about the same well-defined quantity. A somewhat less correct but a much more intuitive definition of temperature is the amount of energy of the chaotic motion per particle. If your particles move chaotically very fast, near the speed of light, so that energy per particle is very large, you temperature is large as well. As for the second question, physicists measure temperature of heavy-ion collisions indirectly, on the basis of several characteristics they observe in their detectors. The simplest way is by detecting of energetic photons and fitting them to thermal spectrum; another way is by studying the geometry of flow of hundreds of particles produced in the collision and fitting them to some models.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/370', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/57/']}
jdg_372826
stackexchange
llm_judgeable_groundtruth_similarity
26663495
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 have a fragment that does the following: Uses one AsyncTask in onCreate to grab a JSON object from a database entry, using a standard HTTP connection. The data is later displayed in a bunch of text fields. (Tested, works fine). Uses another AsyncTask in onStart to grab an image from a different URL, also over HTTP. For both tasks, the UI is updated with subroutines in onPostExecute; the TextViews and ImageView are initialized in onCreateView. Issue: The first time this fragment runs, the image is not displayed (the default appears in its place, suggesting that onPostExecute sees an empty photo URL). When I return to the main menu and select this activity again, the desired image is right where it's supposed to be. I suspect something needs to be "refreshed," but being a relative async noob, I'm not having any luck identifying it. Any suggestions? EDIT 1: To illustrate what I'm doing with the UI, here's the code for the photo async task: class FetchPhoto extends AsyncTask<ImageView,Void,Bitmap> { ImageView imgv = null; @Override protected Bitmap doInBackground(ImageView... imageViews) { Bitmap x = null; this.imgv = imageViews[0]; String tempURL = (String)imgv.getTag(); // the image's URL was previously loaded into the ImageView's tag // check if URL string is empty if (tempURL.equals("")) return x; HttpURLConnection connection = null; try { URL url = new URL(tempURL); connection = (HttpURLConnection) url.openConnection(); InputStream input = connection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = input.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); byte[] rawOutput = out.toByteArray(); x = BitmapFactory.decodeByteArray(rawOutput, 0, rawOutput.length); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { connection.disconnect(); } return x; } @Override protected void onPostExecute(Bitmap photo) { String finalURL = (String)imgv.getTag(); // update the view with the downloaded photo or the default graphic if (!finalURL.equals("")) { // assumes a valid URL was used to retrieve a photo imgv.setImageBitmap(photo); } else { Bitmap bmDefault = BitmapFactory.decodeResource(getResources(), R.drawable.default_photo); imgv.setImageBitmap(bmDefault); } }} EDIT 2: When I set a couple of breakpoints, I found that the async photo task (called from onStart()) is being run BEFORE the database task (called from onCreate()) which fetches the URL for the photo. I am baffled at how this can happen. Now provide the response and nothing else.
EXPLANATION FOR EVERYBODYI am a developer of a dj app and was searching for similar answers.So i will explain all about the music waveform you may see in any software including audacity. There are 3 types of waveforms used to display in any music software.Namely Samples, Average and RMS. 1) Samples are the actual music points presented in a graph, could be an array of raw audio data (points you see when you zoom the waveform in audacity). 2) Average: most commonly used, suppose you are displaying 3 minute song on screen, so a single point on screen must display atleast 100ms(approx) of the song which has many raw audio points, so for displaying we calculate the average of all the points in that 100ms duration, and so on for the rest of the track (dark blue big waveform in audacity). 3) RMS: similar to average but here instead of average, root mean square of the particular duration is taken (the small light blue waveform inside the blue one is rms waveform in audacity). Now how to calculate waveforms. 1) Samples is raw data when you decode a song using any technique you get raw samples/points. Now based on the format of points you convert them to range -1 to 1, example if format is 16-bit you divide all points by 32768(maximum range for 16 bit number) and then draw the points. 2) for average waveform - first add all points converting negative values to positive, then multiply by 2 and then take average. //samples is the array and nb_samples is the length of arrayfloat sum = 0;for(int i = 0 ; i < nb_samples ; i++){ if(samples[i] < 0) sum += -samples[i]; else sum += samples[i];}float average_point = (sum * 2) / nb_samples; //average after multiplying by 2//now draw this point 3) RMS: its simple take the root mean sqaure - so first square every sample, then take the sum and then calculate the mean and then sqaure root. I will show in programming //samples is the array and nb_samples is the length of arrayfloat squaredsum = 0;for(int i = 0 ; i < nb_samples ; i++){ squaredsum += samples[i] * samples[i]; // square and sum}float mean = squaredsum / nb_samples; // calculated meanfloat rms_point = Math.sqrt(mean); //now calculate square root in last//now draw this point Note here the samples is the array of points for calculating the point/pixel for a particular duration of song. example if you want to draw 1 minute of songs data in 60 pixels so the samples array will be the array of all points in 1 second, i.e the amount of audio points to be displayed in 1 pixel. Hope this will help someone to clarify the concepts about audio waveform.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26663495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4200232/']}
jdg_372827
stackexchange
llm_judgeable_groundtruth_similarity
5207489
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 Measurements table as follows: SourceId : int TimeStamp: date/time Measurement: int Sample data looks like this (more on the asterisks below): SID| TimeStamp | Measurement 10 | 02-01-2011 12:00:00 | 30 * 10 | 02-01-2011 12:10:00 | 30 10 | 02-01-2011 12:17:00 | 32 * 10 | 02-01-2011 12:29:00 | 30 * 10 | 02-01-2011 12:34:00 | 30 10 | 02-01-2011 12:39:00 | 35 * 10 | 02-01-2011 12:46:00 | 36 * 10 | 02-01-2011 12:39:00 | 36 10 | 02-01-2011 12:54:00 | 36 11 | 02-01-2011 12:00:00 | 36 * 11 | 02-01-2011 12:10:00 | 36 11 | 02-01-2011 12:17:00 | 37 * 11 | 02-01-2011 12:29:00 | 38 * 11 | 02-01-2011 12:34:00 | 38 11 | 02-01-2011 12:39:00 | 37 * 11 | 02-01-2011 12:46:00 | 36 * 11 | 02-01-2011 12:39:00 | 36 11 | 02-01-2011 12:54:00 | 36 I need a LINQ query that will return only the rows when the Measurement value is different from the prior row having the same SourceId (i.e. each row marked with an asterisk). The table should be sorted by SourceId, then TimeStamp. The data from the query will be used to plot a graph where each SourceId is a series. The source table has several million rows and the repeating measurements are in the thousands. Since these repeating measurement values don't make any difference to the resulting graph I'd like to eliminate them before passing the data to my graph control for rendering. I have tried using Distinct() in various ways, and reviewed the Aggregate queries here http://msdn.microsoft.com/en-us/vcsharp/aa336746 but don't see an obvious solution. Now provide the response and nothing else.
Here's what my previous research uncovered. I've seen each of these issues prevent a real-world application from working in Firefox. Please feel free to edit. The DOM document.createElement should take only a tag name, but IE lets youpass arbitrary HTML (with attributes, etc) http://msdn.microsoft.com/en-us/library/ms536389(VS.85).aspx document.getElementById should only find elements with the given id ,but IE also returns elements with the given name http://msdn.microsoft.com/en-us/library/ms536437(VS.85).aspx IE creates implicit global variables for DOM elements, but referencing an element this way in Firefox produces the following warning: "Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead." http://www.west-wind.com/weblog/posts/677442.aspx http://code.google.com/p/fbug/issues/detail?id=853 IE's document.all is a collection of all elements in the document. It is not supported by Firefox. http://msdn.microsoft.com/en-us/library/ms537434(v=vs.85).aspx An Element's text in IE is retrieved using the innerText property. Firefox calls this property textContent . http://msdn.microsoft.com/en-us/library/ms533899(v=vs.85).aspx IE allows items in collections to be referenced using function syntax (i.e. with parentheses) instead of the normal array indexing syntax (i.e. with brackets). For example, the following works in IE: document.forms(0) . Firefox does not support this usage. http://msdn.microsoft.com/en-us/library/ms537457(v=VS.85).aspx HTMLTableElement rows and cells should refer to HTMLCollections , butIE allows them to be called as functions; Firefox does not. http://msdn.microsoft.com/en-us/library/ms537484%28VS.85%29.aspx IE defaults insertRow 's index to -1; Firefox errors if the argument is omitted. http://msdn.microsoft.com/en-us/library/ms536457%28VS.85%29.aspx https://developer.mozilla.org/en/DOM/table.insertRow The Node.text property is IE-only http://msdn.microsoft.com/en-us/library/ms534677%28VS.85%29.aspx https://developer.mozilla.org/En/DOM/Node.textContent Events window.event is an IE-specific way to access event information; it's notsupported by Firefox. http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx http://www.quirksmode.org/js/events_access.html#link3 Events are attached to Elements in IE using attachEvent . Firefox uses addEventListener . Note, also, that the names of events are subtly different in each browser. http://msdn.microsoft.com/en-us/library/ms536343(v=vs.85).aspx In IE it's possible to get the mouse position from non-mouse events, but it's not in other browsers. In addition, the names of the mouse-coordinate properties are not the same in IE and Firefox. http://msdn.microsoft.com/en-us/library/ms533567(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/ms533568(v=vs.85).aspx http://www.quirksmode.org/js/events_properties.html#position IE supports a click method for triggering the onclick event on HTML elements. No such function exists in Firefox. http://msdn.microsoft.com/en-us/library/ms536363(v=vs.85).aspx http://lifescaler.com/2008/04/simulating-mouse-clicks-in-javascript/ http://www.devtoolshed.com/content/fix-firefox-click-event-issue XML Firefox splits text nodes into 4096-char blocks; IE does not. Thismeans that things like childNodes will be different in IE and Firefox. Is there a 4096 character limit for JavaScript XML text nodes? Internet Explorer defines a parseError.errorCode property onXMLDocuments for detecting parser errors. Firefox loads an XML document that contains error information in the document with documentElement.nodeName=="parsererror" . IE ignores whitespace in XML; firstChild always returns the first ELEMENT_NODE http://www.w3schools.com/dom/prop_element_firstchild.asp https://developer.mozilla.org/en/Whitespace_in_the_DOM The Node.xml property is IE-only http://www.w3schools.com/dom/prop_node_xml.asp http://www.grange.com.br/dicas-tecnicas/40-lotus/345-dom-xml-wrapper-for-javascript Further reading http://www.reloco.com.ar/mozilla/compat.html https://developer.mozilla.org/en/migrate_apps_from_internet_explorer_to_mozilla http://www.impressivewebs.com/7-javascript-differences-between-firefox-ie/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5207489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243458/']}
jdg_372828
stackexchange
llm_judgeable_groundtruth_similarity
8999953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently I am using [self presentModalViewController :newVC animated:YES] .I want to present newViewcontroller from left/right/top/bottom with a push effect. I tried to use CATransition but it displays a black screen in between the transition. Now provide the response and nothing else.
When present: CATransition *transition = [CATransition animation];transition.duration = 0.3;transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];transition.type = kCATransitionPush;transition.subtype = kCATransitionFromRight;[self.view.window.layer addAnimation:transition forKey:nil];[self presentModalViewController:viewCtrl animated:NO]; When dismiss: CATransition *transition = [CATransition animation];transition.duration = 0.3;transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];transition.type = kCATransitionPush;transition.subtype = kCATransitionFromLeft;[self.view.window.layer addAnimation:transition forKey:nil];[self dismissModalViewControllerAnimated:NO];
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8999953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1085093/']}
jdg_372829
stackexchange
llm_judgeable_groundtruth_similarity
442792
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: How to execute a shell script via a cronjob every 45 days? Now provide the response and nothing else.
If you don't need exactly 45 days, but "one and a half months" will do, then a straightforward method would be to run at the beginning of the month every three months, and at the middle of the next month after each of those: 0 12 1 1,4,7,10 * /path/to/script0 12 16 2,5,8,11 * /path/to/script For general arbitrary intervals, the other answers are obviously better, but 45 days sounds like it's based on the length of a month anyway. Human users might also be more used to something happening in the beginning or the middle of a month, instead of seeing the exact date drift a day or two each time.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/442792', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_372830
stackexchange
llm_judgeable_groundtruth_similarity
112472
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In an opamp, feedback on the positive input places it in saturation mode and the output is of the same sign as V+ - V-; feedback on the negative input places it in "regulator mode" and ideally Vout is such that V+ = V-. How does the opamp change its behaviour depending on the feedback? Is it part of a more general "behavioral law"? [Edit: Isn't it something in the lines of the voltage added increases the error instead of reducing it in the case of + feedback?] How can we analyse circuits where both are present? Whoever answers both at the same time in a coherent manner wins a pot of votes. Now provide the response and nothing else.
Op-amp always behaves as a differential amplifier and the behavior of circuit depends on the feedback network . If negative feedback dominates, the circuit works in linear region. Else if positive feedback dominates, then in saturation region. I think the condition \$V^+ = V^-\$, the virtual short principle, is valid only when the negative feedback dominates. So if you are not sure that negative feedback dominates, consider op-amp as a differential amplifier. To analyze the circuit, find \$V^+\$ and \$V^-\$ in terms of \$V_{in}\$ and \$V_{out}\$. Then substitute in the following formula,$$V_{out} = A_v(V^+-V^-)$$ calculate \$V_{out}/V_{in}\$ and then apply the limit \$A_v\rightarrow\infty\$ Now, net feedback is negative if \$V_{out}/V_{in}\$ is finite. Else if \$V_{out}/V_{in} \rightarrow \infty\$, then the net feedback is positive. Example: From the circuit given in the question,$$V^+ = V_{in}\ \text{and}\ V^- = V_{out}/2$$$$V_{out} = A_v(V_{in} - V_{out}/2)$$$$\lim_{A_v\rightarrow\infty}\frac{V_{out}}{V_{in}} = \lim_{A_v\rightarrow\infty}\frac{A_v}{1+A_v/2} = 2$$$$V_{out} = 2V_{in}$$\$V_{out}/V_{in}\$ is finite and net feedback is negative. \$\mathrm{\underline{Non-ideal\ source:}}\$ In the above analysis, \$V_{in}\$ is assumed to be an ideal voltage source. Considering the case when \$V_{in}\$ is not ideal and has an internal resistance \$R_s\$.$$V^+ = V_{out}+(V_{in}-V_{out})f_1\ \text{ and }\ V^- = V_{out}/2$$where, \$f_1 = \dfrac{R}{R+R_s}\$$$V_{out} = A_v(V_{out}/2+(V_{in}-V_{out})f_1)$$$$V_{out}(1-A_v/2+A_vf_1) = A_vf_1V_{in}$$$$\lim_{A_v\rightarrow\infty}\frac{V_{out}}{V_{in}} = \lim_{A_v\rightarrow\infty}\frac{f_1}{\frac{1}{A_v}-\frac{1}{2}+f_1}$$$$\frac{V_{out}}{V_{in}} = \frac{f_1}{f_1-\frac{1}{2}}$$ case1: \$R_s\rightarrow 0,\ f_1\rightarrow 1,\ V_{out}/V_{in}\rightarrow 2\$ case2: \$R_s\rightarrow R,\ f_1\rightarrow 0.5,\ V_{out}/V_{in}\rightarrow \infty\$ \$%case3: R_s \rightarrow \infty,\ f_1 \rightarrow 0,\ V_{out}/V_{in} \rightarrow 0\$ The output is finite in case1 and so net feedback is negative in these conditions (\$R_s < R\$). But at \$R_s = R\$, negative feedback fails to dominate. \$\mathrm{\underline{Application:}}\$ Case1 is the normal working of this circuit but it is not used as an amplifier with gain 2. If we connect this circuit as a load to any circuit, this circuit can act as a negative load (releases power instead of absorbing). Continuing with the analysis, the current through \$R\$ (from in to out) is,$$I_{in}=\frac{V_{in}-V_{out}}{R}=\frac{-V_{in}}{R}$$ calculating the equivalent resistance \$ R_{eq}\$$$R_{eq} = \frac{V_{in}}{I_{in}} = -R$$ This circuit can act as negative impedance load or it act as a negative impedance converter .
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/112472', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/30449/']}
jdg_372831
stackexchange
llm_judgeable_groundtruth_similarity
10434378
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 listview. I get data from an SQLite database. I get this error: It occurs when I go from line 20 to 21: I placed cursor.deactivate() and cursor.close() on line 50, with no result. Why I get this error and how to solve it? Now provide the response and nothing else.
You have to close the cursor before the database. Put your code in a try / catch block and in a finally block, close the cursor and then close the database: try { db = ...} catch(Exception ex) { // Log the exception's message or whatever you like} finally { try { if( cursor != null && !cursor.isClosed()) cursor.close(); if( db.isOpen() ) db.close(); } catch(Exception ex) {}} Closing sequence matters a lot while doing IO with DB or Content Providers.For more information refer this link
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10434378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1110599/']}
jdg_372832
stackexchange
llm_judgeable_groundtruth_similarity
36402646
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a real-world example from a 3rd party library API, but simplified. Compiled with Oracle JDK 8u72 Consider these two methods: <X extends CharSequence> X getCharSequence() { return (X) "hello";}<X extends String> X getString() { return (X) "hello";} Both report an "unchecked cast" warning - I get why. The thing that baffles me is why can I call Integer x = getCharSequence(); and it compiles? The compiler should know that Integer does not implement CharSequence . The call to Integer y = getString(); gives an error (as expected) incompatible types: inference variable X has incompatible upper bounds java.lang.Integer,java.lang.String Can someone explain why would this behaviour be considered valid? How would it be useful? The client does not know that this call is unsafe - the client's code compiles without warning. Why wouldn't the compile warn about that / issue an error? Also, how is it different from this example: <X extends CharSequence> void doCharSequence(List<X> l) {}List<CharSequence> chsL = new ArrayList<>();doCharSequence(chsL); // compilesList<Integer> intL = new ArrayList<>();doCharSequence(intL); // error Trying to pass List<Integer> gives an error, as expected: method doCharSequence in class generic.GenericTest cannot be applied to given types; required: java.util.List<X> found: java.util.List<java.lang.Integer> reason: inference variable X has incompatible bounds equality constraints: java.lang.Integer upper bounds: java.lang.CharSequence If that is reported as an error, why Integer x = getCharSequence(); isn't? Now provide the response and nothing else.
CharSequence is an interface . Therefore even if SomeClass does not implement CharSequence it would be perfectly possible to create a class class SubClass extends SomeClass implements CharSequence Therefore you can write SomeClass c = getCharSequence(); because the inferred type X is the intersection type SomeClass & CharSequence . This is a bit odd in the case of Integer because Integer is final, but final doesn't play any role in these rules. For example you can write <T extends Integer & CharSequence> On the other hand, String is not an interface , so it would be impossible to extend SomeClass to get a subtype of String , because java does not support multiple-inheritance for classes. With the List example, you need to remember that generics are neither covariant nor contravariant. This means that if X is a subtype of Y , List<X> is neither a subtype nor a supertype of List<Y> . Since Integer does not implement CharSequence , you cannot use List<Integer> in your doCharSequence method. You can, however get this to compile <T extends Integer & CharSequence> void foo(List<T> list) { doCharSequence(list);} If you have a method that returns a List<T> like this: static <T extends CharSequence> List<T> foo() you can do List<? extends Integer> list = foo(); Again, this is because the inferred type is Integer & CharSequence and this is a subtype of Integer . Intersection types occur implicitly when you specify multiple bounds (e.g. <T extends SomeClass & CharSequence> ). For further information, here is the part of the JLS where it explains how type bounds work. You can include multiple interfaces, e.g. <T extends String & CharSequence & List & Comparator> but only the first bound may be a non-interface.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/36402646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/466738/']}
jdg_372833
stackexchange
llm_judgeable_groundtruth_similarity
14420826
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 wondering if you can store items into a vector, using the emplace_back, a type that is derived from the class that vector expects. For example: struct fruit{ std::string name; std::string color;};struct apple : fruit{ apple() : fruit("Apple", "Red") { }}; Somewhere else: std::vector<fruit> fruits; I want to store an object of type apple inside the vector. Is this possible? Now provide the response and nothing else.
No. A vector only stores elements of a fixed type. You want a pointer to an object: #include <memory>#include <vector>typedef std::vector<std::unique_ptr<fruit>> fruit_vector;fruit_vector fruits;fruits.emplace_back(new apple);fruits.emplace_back(new lemon);fruits.emplace_back(new berry);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14420826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168313/']}
jdg_372834
stackexchange
llm_judgeable_groundtruth_similarity
12612414
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 learn ZF2. I have a page that uses Ajax to get some data. The ZF2 function should return an JSON string. <?phpnamespace Application\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\View\Model\ViewModel;use Zend\View\Model\JsonModel;class DocumentsController extends AbstractActionController { public function indexAction() { } public function getTreeDataAction() { $json = new JsonModel(array( 'title' => 'Some Title' )); return $json; }} But I keep getting this Fatal Error: ( ! ) Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "application/documents/get-tree-data"; resolver could not resolve to a file' in ../vendor/ZF2/library/Zend/View/Renderer/PhpRenderer.php on line 451 I have been searching around for this error and the best way to make ajax calls in ZF2, however results for ZF1 or ZF2 betas keep coming up and do not work. Thank you for any advice you can give. Now provide the response and nothing else.
Hmm, that error pretty much implies that it tries to access the default rendering strategy, which is quite weird... Have you added the JsonStrategy to your view_manager? //module.config.phpreturn array( 'view_manager' => array( 'strategies' => array( 'ViewJsonStrategy', ), ),) Furthermore it's a good idea to set the correct accept header for within you ajax calls to only accept application/json content type. With this set, it should actually work. Out of curiousity though, does modules/__NAMESPACE__/view/__namespace__/documents/get-tree-data.phtml exist?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12612414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830069/']}
jdg_372835
stackexchange
llm_judgeable_groundtruth_similarity
33525
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Accumulate can be used to compute the partial sums of a list. The partial sums can also be computed using a For loop but this method should not be used according to following answer . I have the following questions: Why is Accumulate much faster than using a For loop? Please give a more elaborate answer than the fact that Mathematica is inherently a functional programming language. What is the exact algorithm for Accumulate ? Can this algorithm be used in object-oriented languages (I am familiar with C++) to compute partial sums of an array faster than a for loop? If no, then why not? If yes, then how much will the performance gain (big- O notation is preferable) in C++ be compared to Mathematica? P.S. I am not very familiar with algorithm stability so if that is a part of your answer, please provide links/details on the same. Now provide the response and nothing else.
Using Accumulate for 20,000,000 size list. Time < 1 Hour Your timings seem way too high. On my PC, Accumulate on an 20.000.000-element packed array takes about 50ms. A For loop (not compiled!) needs about one minute for 20 million values. My PC may be fast, but not that fast. Make sure your array contains only machine-precision reals and is packed. Otherwise, any comparison with C or C++ doesn't make much sense, because values in a C++ double* array are always machine precision and "packed". Why is Accumulate much faster than using a For loop? Because your For loop is written in an interpreted language, while Accumulate is (presumably) written in a low-level language; It might even use special SIMD CPU instructions that process multiple values in a single instruction. The interpreted loop on the other hand needs more than one CPU instruction just for a single addition. What is the exact algorithm for Accumulate? As others said in the comments, we don't know. But the obvious algorithm (take each element from the input buffer, add it to an accumulator register, store it in the output buffer) needs n read operations, n-1 add operations and n write operations. And I don't see how you could get the right result without reading each input data, writing each output value and adding n-1 values. So my guess would be that Mathematica does something like that. Can this algorithm be used in object-oriented languages (I am familiar with C++) to compute partial sums of an array faster than a for loop? C++ has a library function partial_sum , and (at least in my implementation) that's exactly how it's implemented. If yes, then how much will the performance gain (big-O notation is preferable) in C++ be compared to Mathematica? Any decent algorithm will be O(n). Probably your For loop is O(n), too. If the question really was: Will a C++ implementation be faster, slower or just as fast as Mathematica's Accumulate, then the answer depends mostly on how smart your C++ compiler is. My guess is that any modern CPU can add numbers much faster than it can read/write them from and to main memory. So performance depends on things like whether the C++ compiler is smart enough to make the CPU prefetch values from main memory to cache before it needs them. If it is, and if Mathematica's implementation does the same, they might just be equally fast.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/33525', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9332/']}
jdg_372836
stackexchange
llm_judgeable_groundtruth_similarity
27736186
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Like many others, my website is using jQuery. When I open the developer tools, I see a warning that says that XMLHTTPRequest is deprecated because of its detrimental effects to the end user's experience. I went on and read part of the documentation , but it was fairly technical. Can someone explain the consequences of shifting from XMLHTTPRequest to WHATWG in simple terms? It says it happened in 2012. Also, the documentation says that Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform, when that happens, if a user agent had them in a service, do they need to modify their existing code? Now provide the response and nothing else.
To avoid this warning, do not use: async: false in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated. The default is async: true , so if you never use this option at all, your code should be safe if the feature is ever really removed. However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now. Notice that the Fetch API that's replacing XMLHttpRequest does not even offer a synchronous option.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27736186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2917873/']}
jdg_372837
stackexchange
llm_judgeable_groundtruth_similarity
48885256
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 MSSQL for storing data.When I tried to delete the data in a table, it shows an error The transaction log for database 'test' is full due to 'LOG_BACKUP'. Also, I have checked the size of C drive, and it almost full now, before doing this delete operation, the free space was 10GB. When I searched for the error, I found that backing up the transaction log will resolve the issue.I did the same and still, C drive remains full. What I can do to resolve the issue? Now provide the response and nothing else.
As per the comments, I have shrunk the transaction log file, it freed up around 13GB. Since the recovery model of my database is Full, first I have taken a backup of transaction logs and then change the recovery model of my database to Simple. After that, I have shrunk my log files and again set back to Full. ALTER DATABASE AdventureWorks2012 SET RECOVERY SIMPLE GO DBCC SHRINKFILE (AdventureWorks2012_log, 1) GO ALTER DATABASE AdventureWorks2012 SET RECOVERY FULL https://www.mssqltips.com/sqlservertutorial/3311/how-to-shrink-the-transaction-log/ Thanks, @sepupic, for the very accurate approach you have mentioned in the post. After cleaned up space, I have deleted the records in small batches as per the comments of @Pedro Martins.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48885256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6328851/']}
jdg_372838
stackexchange
llm_judgeable_groundtruth_similarity
45686477
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been on quite an adventure to get JWT working on DotNet core 2.0 (now reaching final release today). There is a ton of documentation, but all the sample code seems to be using deprecated APIs and coming in fresh to Core, It's positively dizzying to figure out how exactly it's supposed to be implemented. I tried using Jose, but app. UseJwtBearerAuthentication has been deprecated, and there is no documentation on what to do next. Does anyone have an open source project that uses dotnet core 2.0 that can simply parse a JWT from the authorization header and allow me to authorize requests for a HS256 encoded JWT token? The class below doesn't throw any exceptions, but no requests are authorized, and I get no indication why they are unauthorized. The responses are empty 401's, so to me that indicates there was no exception, but that the secret isn't matching. One odd thing is that my tokens are encrypted with the HS256 algorithm, but I see no indicator to tell it to force it to use that algorithm anywhere. Here is the class I have so far: using System;using System.Collections.Generic;using System.IO;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.JwtBearer;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Net.Http.Headers;using Newtonsoft.Json.Linq;using Microsoft.IdentityModel.Tokens;using System.Text;namespace Site.Authorization{ public static class SiteAuthorizationExtensions { public static IServiceCollection AddSiteAuthorization(this IServiceCollection services) { var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET_KEY")); var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, ValidateAudience = false, ValidateIssuer = false, IssuerSigningKeys = new List<SecurityKey>{ signingKey }, // Validate the token expiry ValidateLifetime = true, }; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(o => { o.IncludeErrorDetails = true; o.TokenValidationParameters = tokenValidationParameters; o.Events = new JwtBearerEvents() { OnAuthenticationFailed = c => { c.NoResult(); c.Response.StatusCode = 401; c.Response.ContentType = "text/plain"; return c.Response.WriteAsync(c.Exception.ToString()); } }; }); return services; } }} Now provide the response and nothing else.
Here is a full working minimal sample with a controller. I hope you can check it using Postman or JavaScript call. appsettings.json, appsettings.Development.json. Add a section. Note, Key should be rather long and Issuer is an address of the service: ...,"Tokens": { "Key": "Rather_very_long_key", "Issuer": "http://localhost:56268/"}... !!! In real project, don't keep Key in appsettings.json file. It should be kept in Environment variable and take it like this: Environment.GetEnvironmentVariable("JWT_KEY"); UPDATE : Seeing how .net core settings work, you don't need to take it exactly from Environment. You may use setting. However,instead we may write this variable to environment variables in production, then our code will prefer environment variables instead of configuration. AuthRequest.cs : Dto keeping values for passing login and password: public class AuthRequest{ public string UserName { get; set; } public string Password { get; set; }} Startup.cs in Configure() method BEFORE app.UseMvc() : app.UseAuthentication(); Startup.cs in ConfigureServices() : services.AddAuthentication() .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = Configuration["Tokens:Issuer"], ValidAudience = Configuration["Tokens:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])) }; }); Add a controller: [Route("api/[controller]")] public class TokenController : Controller { private readonly IConfiguration _config; private readonly IUserManager _userManager; public TokenController(IConfiguration configuration, IUserManager userManager) { _config = configuration; _userManager = userManager; } [HttpPost("")] [AllowAnonymous] public IActionResult Login([FromBody] AuthRequest authUserRequest) { var user = _userManager.FindByEmail(model.UserName); if (user != null) { var checkPwd = _signInManager.CheckPasswordSignIn(user, model.authUserRequest); if (checkPwd) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Tokens:Issuer"], _config["Tokens:Issuer"], claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } } return BadRequest("Could not create token"); }} That's all folks! Cheers! UPDATE: People ask how get Current User. Todo: In Startup.cs in ConfigureServices() add services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); In a controller add to constructor: private readonly int _currentUser;public MyController(IHttpContextAccessor httpContextAccessor){ _currentUser = httpContextAccessor.CurrentUser();} Add somewhere an extension and use it in your Controller (using ....) public static class IHttpContextAccessorExtension{ public static int CurrentUser(this IHttpContextAccessor httpContextAccessor) { var stringId = httpContextAccessor?.HttpContext?.User?.FindFirst(JwtRegisteredClaimNames.Jti)?.Value; int.TryParse(stringId ?? "0", out int userId); return userId; }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45686477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/899671/']}
jdg_372839
stackexchange
llm_judgeable_groundtruth_similarity
14321390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sorry, I do not know the protocol for re-asking a question if it doesn't get an answer. This question was asked a few months ago here: Numpy sum between pairs of indices in 2d array I have a 2-d numpy array (MxN) and two more 1-d arrays (Mx1) that represent starting and ending indices for each row of the 2-d array that I'd like to sum over. I'm looking for the most efficient way to do this in a large array (preferably without having to use a loop, which is what I'm currently doing). An example of what i'd like to do is the following. >>> random.seed(1234)>>> a = random.rand(4,4)>>> print a[[ 0.19151945 0.62210877 0.43772774 0.78535858] [ 0.77997581 0.27259261 0.27646426 0.80187218] [ 0.95813935 0.87593263 0.35781727 0.50099513] [ 0.68346294 0.71270203 0.37025075 0.56119619]]>>> b = array([1,0,2,1])>>> c = array([3,2,4,4])>>> d = empty(4)>>> for i in xrange(4): d[i] = sum(a[i, b[i]:c[i]]) >>> print d[ 1.05983651 1.05256841 0.8588124 1.64414897] My problem is similar to the following question, however, I don't think the solution presented there would be very efficient. Numpy sum of values in subarrays between pairs of indices In that question, they want to find the sum of multiple subsets for the same row, so cumsum() can be used. However, I will only be finding one sum per row, so I don't think this would be the most efficient means of computing the sum. Now provide the response and nothing else.
EDIT Added timing results for all answers so far, including the OP's code following @seberg's comment below, and the OP's method is the fastest: def sliced_sum_op(a, b, c) : d = np.empty(a.shape[0]) for i in xrange(a.shape[0]): d[i] = np.sum(a[i, b[i]:c[i]]) return d You can still get it done with np.cumsum with a big speed boost , although it will require storage equivalent to the size of your original array: def sliced_sum(a, b, c) : cum = np.cumsum(a, axis=1) cum = np.hstack((np.zeros((a.shape[0], 1), dtype=a.dtype), cum)) rows = np.arange(a.shape[0]) return cum[rows, c] - cum[rows, b] Timings are deceptive for your array, because your method is actually slightly faster than this one for small array sizes. But numpy soon wins it over, see the graph below for timings on random square arrays of size (n, n) : The above was generated with import timeitimport matplotlib.pyplot as pltn = np.arange(10, 1000, 10)op = np.zeros(n.shape[0])me = np.zeros(n.shape[0])th = np.zeros(n.shape[0])jp = np.zeros(n.shape[0])for j, size in enumerate(n) : a = np.random.rand(size, size) b, c = indices = np.sort(np.random.randint(size + 1, size=(2, size)), axis=0) np.testing.assert_almost_equal(sliced_sum_op(a, b, c), sliced_sum(a, b, c)) np.testing.assert_almost_equal(sliced_sum_op(a, b, c), sum_between2(a, b, c)) np.testing.assert_almost_equal(sliced_sum_op(a, b, c), sum_between_mmult(a, b, c)) op[j] = timeit.timeit('sliced_sum_op(a, b, c)', 'from __main__ import sliced_sum_op, a, b, c', number=10) me[j] = timeit.timeit('sliced_sum(a, b, c)', 'from __main__ import sliced_sum, a, b, c', number=10) th[j] = timeit.timeit('sum_between2(a, b, c)', 'from __main__ import sum_between2, a, b, c', number=10) jp[j] = timeit.timeit('sum_between_mmult(a, b, c)', 'from __main__ import sum_between_mmult, a, b, c', number=10)plt.subplot(211)plt.plot(n, op, label='op')plt.plot(n, me, label='jaime')plt.plot(n, th, label='thorsten')plt.plot(n, jp, label='japreiss')plt.xlabel('n')plt.legend(loc='best')plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14321390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1554752/']}
jdg_372840