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
6306431
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 search my whole project for a certain string, but I only want results which are uncommented. It would be great if there was just an option to not include comments in the search results, but I don't see how to do this. Is there a hidden option for this, or a trick? I could go back to the command line and use grep, but I prefer to have the results within eclipse so I can easily jump to the line number. Now provide the response and nothing else.
In "File Search", you can tick "Regular expressions" and use this regex to search for "some text" but exclude one-line (ie // ... ) java comments: ^(?!\s*//).*some text There's probably a better way to express this. It would be difficult (impossible?) to to write a regex for multi-line comments ie /* ...many lines... */ EDIT: This regex will also exclude all lines whose first character is * - ie javadoc comments: ^(?!\s*(//|\*)).*some text While lines that start with * are not necessarily comments, it is rare indeed for java code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6306431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300311/']}
jdg_84741
stackexchange
llm_judgeable_groundtruth_similarity
174599
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: Will it be possible to use diff on a specific columns in a file? file1 Something 123 item1Something 456 item2Something 768 item3Something 353 item4 file2 Another 123 stuff1Another 193 stuff2Another 783 stuff3Another 353 stuff4 output(Expected) Something 456 item2Something 768 item3Another 193 stuff2Another 783 stuff3 I want to diff the 2nd column of each file, then, the result will contain the diff-ed column but along with the whole line. Now provide the response and nothing else.
awk is a better tool for comparing columns of files. See, for example, the answer to: compare two columns of different files and print if it matches -- there are similar answers out there for printing lines for matching columns. Since you want to print lines that don't match, we can create an awk command that prints the lines in file2 for which column 2 has not been seen in file1: $ awk 'NR==FNR{c[$2]++;next};c[$2] == 0' file1 file2Another 193 stuff2Another 783 stuff3 As explained similarly by terdon in the above-mentioned question , NR==FNR : NR is the current input line number and FNR the current file's line number. The two will be equal only while the 1st file is being read. c[$2]++; next : if this is the 1st file, save the 2nd field in the c array. Then, skip to the next line so that this is only applied on the 1st file. c[$2] == 0 : the else block will only be executed if this is the second file so we check whether field 2 of this file has already been seen ( c[$2]==0 ) and if it has been, we print the line. In awk , the default action is to print the line so if c[$2]==0 is true, the line will be printed. But you also want the lines from file1 for which column 2 doesn't match in file2. This you can get by simply exchanging their position in the same command: $ awk 'NR==FNR{c[$2]++;next};c[$2] == 0' file2 file1Something 456 item2Something 768 item3 So now you can generate the output you want, by using awk twice. Perhaps someone with more awk expertise can get it done in one pass. You tagged your question with /ksh , so I'll assume you are using korn shell. In ksh you can define a function for your diff, say diffcol2 , to make your job easier: diffcol2(){ awk 'NR==FNR{c[$2]++;next};c[$2] == 0' $2 $1 awk 'NR==FNR{c[$2]++;next};c[$2] == 0' $1 $2 } This has the behavior you desire: $ diffcol2 file1 file2Something 456 item2Something 768 item3Another 193 stuff2Another 783 stuff3
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/174599', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/95190/']}
jdg_84742
stackexchange
llm_judgeable_groundtruth_similarity
467952
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 equilateral triangle ABC of side length d, if P is an internal point with PA = a, PB = b, and PC = c, the following pleasingly symmetrical relationship holds:$3(a^4 + b^4 + c^4 + d^4) = (a^2 + b^2 + c^2 + d^2)^2.$Please prove this identity.source: http://www.qbyte.org/puzzles/p117s.html Now provide the response and nothing else.
An explanation and derivation without calculations follows. That a relation exists can be inferred by a parameter count. (In an equilateral triangle there are two dimensions of freedom to select a point, and three distances to the vertices.) What the relation is, can be discovered by writing down Euler's formula for $288 V^2$ of a tetrahedron as a function of the squared edge lengths, and setting volume to zero. (The Cayley-Menger determinant is the $n$ dimensional generalization and organization of this formula.) The puzzle is to explain the $S_4$ symmetry of the relation, that allows exchange of $d$ with $a$,$b$ or $c$. The determinant is symmetric in $a,b,c$ only. A 60 degree rotation of the triangle around $A$ moves $P$ to $P'$ so that $APP'$ is an equilateral triangle with side $a$, whose vertices have distances $d,b,c$ to point $B$ (and $d,c,b$ to point $C$). Hence we also have symmetries that permute $d$ with the other variables. Conclusion: the degree $4$ polynomial relation from the Euler-Cayley-Menger determinant (which is a quadratic polynomial in the squares of $a,b,c,d$), is symmetric in all its variables. Any such relation can be written as $A(a^2+b^2+c^2+d^2)^2 + B(a^4+b^4+c^4+d^4) = 0$. In this problem, neither coefficient can be zero, and it is harmless to assume $A=1$. All that is left is to pin down $B$, and by moving $P$ toward $\infty$, the relation should be consistent with $a=b=c$ and $d=0$, so that $B=-3$. The same works in $n$ dimensions, with $(\sum a^2)^2 = (n+1)\sum a^4$. Another way to say all this is that looking at the formula, we know it must be homogeneous, symmetric in $a,b,c$, valid for $(1,1,1,0)$, and it is not so surprising that it be of degree $4$. The surprise is that the symmetry includes $d$, and this additional "hidden symmetry" then dictates the formula.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/467952', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44596/']}
jdg_84743
stackexchange
llm_judgeable_groundtruth_similarity
19691530
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 the answer to this question the user lists values for android:fontFamily and 12 variants (see below). Where do these values come from? The documentation for android:fontFamily does not list this information in any place (I checked here , and here ). The strings are listed in the Android styles.xml file in various places, but how do these map back to the Roboto font? From android 4.1 / 4.2, the following Roboto font families are available: android:fontFamily="sans-serif" // roboto regular android:fontFamily="sans-serif-light" // roboto light android:fontFamily="sans-serif-condensed" // roboto condensed android:fontFamily="sans-serif-thin" // roboto thin (android 4.2) android:fontFamily="sans-serif-medium" // roboto medium (android 5.0) in combination with this android:textStyle="normal|bold|italic" 12 variants are possible: Regular Italic Bold Bold-italic Light Light-italic Thin Thin-italic Condensed regular Condensed italic Condensed bold Condensed bold-italic In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong: <item name="android:fontFamily">Roboto-Regular.ttf</item> I'd like to get the theme for our app set up correctly (which includes using fontFamily correctly) and remove all the redundancy that is in some of the styles that were created before I had a look at the file. Now provide the response and nothing else.
Where do these values come from? The documentation for android:fontFamily does not list this information in any place These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1. In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong: Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this: <item name="android:fontFamily">sans-serif</item> Like the linked answer already stated, 12 variants are possible: Added in Android Jelly Bean (4.1) - API 16 : Regular (default): <item name="android:fontFamily">sans-serif</item><item name="android:textStyle">normal</item> Italic : <item name="android:fontFamily">sans-serif</item><item name="android:textStyle">italic</item> Bold : <item name="android:fontFamily">sans-serif</item><item name="android:textStyle">bold</item> Bold-italic : <item name="android:fontFamily">sans-serif</item><item name="android:textStyle">bold|italic</item> Light : <item name="android:fontFamily">sans-serif-light</item><item name="android:textStyle">normal</item> Light-italic : <item name="android:fontFamily">sans-serif-light</item><item name="android:textStyle">italic</item> Thin : <item name="android:fontFamily">sans-serif-thin</item><item name="android:textStyle">normal</item> Thin-italic : <item name="android:fontFamily">sans-serif-thin</item><item name="android:textStyle">italic</item> Condensed regular : <item name="android:fontFamily">sans-serif-condensed</item><item name="android:textStyle">normal</item> Condensed italic : <item name="android:fontFamily">sans-serif-condensed</item><item name="android:textStyle">italic</item> Condensed bold : <item name="android:fontFamily">sans-serif-condensed</item><item name="android:textStyle">bold</item> Condensed bold-italic : <item name="android:fontFamily">sans-serif-condensed</item><item name="android:textStyle">bold|italic</item> Added in Android Lollipop (v5.0) - API 21 : Medium : <item name="android:fontFamily">sans-serif-medium</item><item name="android:textStyle">normal</item> Medium-italic : <item name="android:fontFamily">sans-serif-medium</item><item name="android:textStyle">italic</item> Black : <item name="android:fontFamily">sans-serif-black</item><item name="android:textStyle">italic</item> For quick reference, this is how they all look like:
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/19691530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/413414/']}
jdg_84744
stackexchange
llm_judgeable_groundtruth_similarity
49990427
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 define a mutation using graphql. My mutation is getting an object as argument. So I defined the new Object in the schema and in the resolver using GraphQLObjectType. However I m getting this error : Error: Agreement.name defined in resolvers, but not in schema Any idea ? Here is my Schema definition const typeDefs = ` type Agreement { id: Int } type Mutation { agreementsPost(agreement: Agreement) : String }`; And Here is my resolver : const appResolvers = { Agreement: new GraphQLObjectType({ name: 'Agreement', fields: { id: { type: GraphQLInt }, } }),Mutation: { agreementsPost(root, args) { return axios.post("....").then(res => res.data); }, } Now provide the response and nothing else.
Couple of things to fix here. First, to use an object as an argument, you have to define it as an input (or GraphQLInputObjectType ) in your schema -- you cannot use a regular type (or GraphQLObjectType ) as an argument. So your type definitions need to look something like this: type Mutation { agreementsPost(agreement: Agreement): String}input Agreement { id: Int} If you already have an Agreement type, you'll need to name your input something else. It's a good convention to just append Input to whatever your type name is: type Mutation { agreementsPost(agreement: AgreementInput): String}type Agreement { id: Int}input AgreementInput { id: Int} This should be sufficient to allow you to pass in an AgreementInput object as an argument to your mutation. You don't need to add Agreement or AgreementInput to your resolvers (in fact, inputs are not "resolved" by GraphQL, so adding a resolver for an input is not possible). That said, your resolvers object should not need to incorporate any of the type constructors provided by the graphql package -- Apollo constructs a GraphQLSchema object from your resolvers and type definitions for you when you call makeExecutableSchema . If your type definitions include the types Foo and Bar , your resolvers object might look something like this: const resolvers = { Foo: { someFooProperty: (foo, args, context, info) => {} }, Bar: { someBarProperty: (bar, args, context, info) => {} someOtherBarProperty: (bar, args, context, info) => {} }, Query: { someQuery: (root, args, context, info) => {} }, Mutation: { someMutation: (root, args, context, info) => {} },} Notice how each property in the resolvers object matches one of the types defined in your schema (including Query and Mutation). The value of each of those properties is itself an object, with each property mapping to one of the fields defined for that particular type. Each field's value is your resolve function. The reason for the error you're seeing is that you've effectively told makeExecutableSchema to add resolvers to two fields on the Agreement type -- name and fields -- neither of which are actually in your schema according to your type definitions. You can read more about how to generate a schema using Apollo here . You may see examples out there of generating a schema "programatically" using just GraphQL.js by defining a GraphQLSchema object and passing that to your middleware instead. There's pros and cons to both approaches, but using makeExecutableSchema is generally easier and less error-prone. Either way, it's good to know how to generate a schema programatically, but you should not mix the two!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49990427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2272636/']}
jdg_84745
stackexchange
llm_judgeable_groundtruth_similarity
428669
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: The headline a generalization of what I want.Specific problem: given some command that outputs multiple timestamps, e.g: $ cat timestamps | sort -n15083492718201508349271821150834942522215083494252231508349454218150834947641915083495000181508349500020150834969882015083496988221508350047721150835004772415083516356211508351635623150835169961815083516996201508351699621150835169962215083516996231508352230120150835223012315083522301241508352230125150835223221915083522322201508352364919150835236492015083523876181508352387619 I want to compute each 2 diff.I ended up doing something like: $ wc -l timestamps29cat <(sort -n timestamps | head -28) <(sort -n timestamps | tail -28) | sort -n | xargs -n 2 sh 'calc $2 - $1' sh1153401128995222012359921988002348899315878972639952111530497311209411326991226981 So I managed to get by, but there's must be an easier way.The generalization is: given an output with multiple lines, how can I compute a sliding window of x args at once, with y args step size? Now provide the response and nothing else.
Awk is well suited for this: awk 'NR>1{print $1-last} {last=$1}' timestamps In the above, for each line after the first ( NR>1 ), we print the value on the current value, $1 , minus the value on the previous line, last . Next, we update the value of last . Example $ awk 'NR>1{print $1-last} {last=$1}' timestamps1153401128995222012359921988002348899315878972639952111530497311209411326991226981 More complex calculation The code below starts with the number in the current line, adds twice the number in the preceding line, and then subtracts three times the number on the line five lines previous: awk '{a[NR]=$1} NR>5{print a[NR]+2*a[NR-1]-3*a[NR-5]}' timestamps
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/428669', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/173099/']}
jdg_84746
stackexchange
llm_judgeable_groundtruth_similarity
22998183
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 dynamic list of items using ng-repeat. When something happens an item may disappear. I have handled smoothly animating the removal of these items using ng-animate, but after they are gone, the remaining items simply snap to their new position. How can I animate this movement smoothly? I've tried applying an "all" transition to the repeated class and using ng-move with no success. Now provide the response and nothing else.
You can achieve this by animating the max-height property. Check out this sample: http://jsfiddle.net/k4sR3/8/ You will need to pick a sufficiently high value for max-height (in my sample, I used 90px). When an item is initially being added, you want it to start off with 0 height (I'm also animating left to have the item slide in from the left, as well as opacity , but you can remove these if they don't jibe with what you're doing): .repeated-item.ng-enter { -webkit-transition:0.5s linear all; -moz-transition:0.5s linear all; -o-transition:0.5s linear all; transition:0.5s linear all; max-height: 0; opacity: 0; left: -50px;} Then, you set the final values for these properties in the ng-enter-active rule: .repeated-item.ng-enter.ng-enter-active { max-height: 90px; opacity: 1; left: 0;} Item removal is a bit trickier, as you will need to use keyframe-based animations. Again, you want to animate max-height , but this time you want to start off at 90px and decrease it down to 0. As the animation runs, the item will shrink, and all the following items will slide up smoothly. First, define the animation that you will be using: @keyframes my_animation { from { max-height: 90px; opacity: 1; left: 0; } to { max-height: 0; opacity: 0; left: -50px; }} (For brevity, I'm omitting the vendor-specific definitions here, @-webkit-keyframes , @-moz-keyframes , etc - check out the jsfiddle above for the full sample.) Then, declare that you will be using this animation for ng-leave as follows: .repeated-item.ng-leave { -webkit-animation:0.5s my_animation; -moz-animation:0.5s my_animation; -o-animation:0.5s my_animation; animation:0.5s my_animation;} Basics In case anyone is struggling with figuring out how to get AngularJS animations to work at all, here's an abbreviated guide. First, to enable animation support, you will need to include an additional file, angular-animate.js , after you load up angular.js . E.g.: <script type="text/javascript" src="angular-1.2/angular.js"></script><script type="text/javascript" src="angular-1.2/angular-animate.js"></script> Next, you will need to load ngAnimate by adding it to the list of your module's dependencies (in the 2nd parameter): var myApp = angular.module('myApp', ['ngAnimate']); Then, assign a class to your ng-repeat item. You will be using this class name to assign the animations. In my sample, I used repeated-item as the name: <li ng-repeat="item in items" class="repeated-item"> Then, you define your animations in the CSS using the repeated-item class, as well as the special classes ng-enter , ng-leave , and ng-move that Angular adds to the item when it is being added, removed, or moved around. The official documentation for AngularJS animations is here: http://docs.angularjs.org/guide/animations
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22998183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1828041/']}
jdg_84747
stackexchange
llm_judgeable_groundtruth_similarity
21747136
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following: let mut my_number = 32.90; How do I print the type of my_number ? Using type and type_of did not work. Is there another way I can print the number's type? Now provide the response and nothing else.
If you merely wish to find out the type of a variable and are willing to do it at compile time, you can cause an error and get the compiler to pick it up. For example, set the variable to a type which doesn't work : let mut my_number: () = 32.90;// let () = x; would work too error[E0308]: mismatched types --> src/main.rs:2:29 |2 | let mut my_number: () = 32.90; | ^^^^^ expected (), found floating-point number | = note: expected type `()` found type `{float}` Or call an invalid method : let mut my_number = 32.90;my_number.what_is_this(); error[E0599]: no method named `what_is_this` found for type `{float}` in the current scope --> src/main.rs:3:15 |3 | my_number.what_is_this(); | ^^^^^^^^^^^^ Or access an invalid field : let mut my_number = 32.90;my_number.what_is_this error[E0610]: `{float}` is a primitive type and therefore doesn't have fields --> src/main.rs:3:15 |3 | my_number.what_is_this | ^^^^^^^^^^^^ These reveal the type, which in this case is actually not fully resolved. It’s called “floating-point variable” in the first example, and “ {float} ” in all three examples; this is a partially resolved type which could end up f32 or f64 , depending on how you use it. “ {float} ” is not a legal type name, it’s a placeholder meaning “I’m not completely sure what this is”, but it is a floating-point number. In the case of floating-point variables, if you don't constrain it, it will default to f64 ¹. (An unqualified integer literal will default to i32 .) See also: What is the {integer} or {float} in a compiler error message? ¹ There may still be ways of baffling the compiler so that it can’t decide between f32 and f64 ; I’m not sure. It used to be as simple as 32.90.eq(&32.90) , but that treats both as f64 now and chugs along happily, so I don’t know.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21747136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2431012/']}
jdg_84748
stackexchange
llm_judgeable_groundtruth_similarity
78552
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Matt Strassler's recent post ( here ) he makes the statement that scale invariant (I assume he means conformally invariant, more generally) theories have no particles in them. What's the reason for this? What are the technical and heuristic explanations, apart from what he mentions in his post? Now provide the response and nothing else.
The precise statement should be that massless fields in conformal field theories in 3+1 dimensions are necessarily free. This result was first proved by Buchholz andFredenhagen . There are two modern proofs of this fact, one by Steven Weinberg (please see arXiv: hep-th/1210.3864v1 ) and the other by Yoh Tanimoto in the framework of algebraic quantum field theory. (Weinberg's proof is a generalization of an unpublished argument by Witten for the spin 0 fields). Weinberg proves that the massless fields neceaarily satisfy free field equations. The freeness of the massless fields should not be confused with the freeness of the whole theory, as conformal field theories contain massive fields also, where there is no known freeness restriction on the massive fields. The conformal group in 3+1 dimensions is $SU(2,2)/\mathbb{Z}_4$ . Itspositive energy representations have been classified by Mack in: All unitary ray representations of the conformal group SU(2,2) with positive energy . These representations are parameterized by two $SL_2$ quantum numbers $(j_1, j_2)$ and when restricted to the Poincaré subgroup, they reducibly or irreducibly decompose into representations of mass $m$ and spin $s$ .The massless representations are the two families $(j, 0)$ or $(0, j)$ which reduce to massless Poincaré multiplets. It should be emphasized that the existence of a mass parameter does not contradict conformal invariance, because the dilation parameter canshrink the energy to zero and these states are also gapless. As mentioned above, there is no known restriction on the freeness of the massive states, and there is a construction by Odzijewicz of a massive conformal particle and an attempt to describe its interaction with an external field. The mass of such a particle is not a constant of motion and can change as a consequence of the interaction. Odzijewicz works in the single particle level and uses the Orbit Method to describe the dynamics of the massive conformal particles. Weinberg and the others work on the field level for the same irreducible representations of the conformal group. It would be interesting to see a unified treatment of the two approaches.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/78552', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/26866/']}
jdg_84749
stackexchange
llm_judgeable_groundtruth_similarity
83614
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: For example I have 100 values sample. I'd like to build histogram in which every bin contains, for example, 10 values. How can i do that?Thanks. Now provide the response and nothing else.
You can use the values of the quantiles of your sample as bin delimiters for your histogram. You can think of $n$-quantiles as those threshold values that divide your data set into $n$ equal-sized subsets. Let's generate some sample data and set your requirements, i.e. number of points per bin: SeedRandom[10]sample = RandomVariate[NormalDistribution[], 200];datapointsperbin = 10;numberofbins = IntegerPart[Length[sample]/datapointsperbin]; This is what a regular histogram with evenly spaced bins would look like for that sample: Histogram[sample] Now we use Quantile to calculate numberofbins quantiles for your distribution, then we use those values as bin delimiters for your histogram. Histogram[ sample, {Table[Quantile[sample, i/numberofbins], {i, 1, numberofbins - 1}]}] You can see from the vertical axis of the histogram that each bin contains 10 samples, as specified by the value of datapointperbin . Having done this, however, I still wonder why you need such a histogram. Of course, if what you needed was to calculate the intervals that would accomplish such binning, given your sample, the magic is all in the Quantile function, so you can get those values directly as well: Table[Quantile[sample, i/numberofbins], {i, 1, numberofbins - 1}] {-1.8614, -1.42414, -1.21859, -0.971859, -0.905122, -0.707023, -0.470983, -0.274088, -0.163548, 0.0100698, 0.122639, 0.271601, 0.383704, 0.475579, 0.608299, 0.873699, 1.03975, 1.33463, 1.81741}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/83614', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/29456/']}
jdg_84750
stackexchange
llm_judgeable_groundtruth_similarity
190081
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to replace the common part in the equation by different value.Here is my equation -(3/(2*θ)) - (1/2)*Sqrt[9/θ^2 - (2*(-18 + θ))/(3*θ^2) + (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)) + (-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)/(3*θ^2)] + (1/2)*Sqrt[18/θ^2 - (4*(-18 + θ))/(3*θ^2) - (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)) - (-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)/(3*θ^2) - (-(216/θ^3) + (24*(-18 + θ))/θ^3 - 96/θ^2)/(4*Sqrt[9/θ^2 - (2*(-18 + θ))/(3*θ^2) + (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)) + (1/(3*θ^2))*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)])] which looks too complicate. However, this include the common part, (-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3) Thus, I replace this part by A using the command % /. (-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3) -> A However, the output shows that not all common parts are changed into A.I get the output, -(3/(2*θ)) - (1/2)*Sqrt[9/θ^2 + A/(3*θ^2) - (2*(-18 + θ))/(3*θ^2) + (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3))] + (1/2)*Sqrt[18/θ^2 - A/(3*θ^2) - (4*(-18 + θ))/(3*θ^2) - (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3)) - (-(216/θ^3) + (24*(-18 + θ))/θ^3 - 96/θ^2)/(4*Sqrt[9/θ^2 + A/(3*θ^2) - (2*(-18 + θ))/(3*θ^2) + (324 - 252*θ - 23*θ^2)/ (3*θ^2*(-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3))])] which still has the common part, (-5832 + 6804*θ - 702*θ^2 + 73*θ^3 + 54*Sqrt[6]*Sqrt[-324*θ^3 + 306*θ^4 + 17*θ^5 + θ^6])^(1/3) How can I chance all these common parts at the same time? Now provide the response and nothing else.
Keys@Select[Counts[list], # == 1 &] {m, n, p, r} Also: Select[list, Count[list, #] == 1 &]Select[list, Counts[list][#] == 1 &]Flatten[Cases[Split[Sort[list]], {_}]]Flatten[DeleteCases[Split[Sort[list]], {_, __}]]Flatten[Select[Split[Sort[list]], Length@# == 1 &]]SequenceReplace[list, {OrderlessPatternSequence[Repeated[b_, {2, Infinity}], a_]} :> a]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/190081', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/61379/']}
jdg_84751
stackexchange
llm_judgeable_groundtruth_similarity
370878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know how to get a service ticket from the Key Distribution Center (KDC) using the Java GSS-API? I have a thick-client-application that first authenticates via JAAS using the Krb5LoginModule to fetch the TGT from the ticket cache (background: Windows e.g. uses a kerberos implementation and stores the ticket granting ticket in a secure memory area). From the LoginManager I get the Subject object which contains the TGT. Now I hoped when I create a specific GSSCredential object for my service, the service ticket will be put into the Subject's private credentials as well (I've read so somewhere in the web). So I have tried the following: // Exception handling ommittedLoginContext lc = new LoginContext("HelloEjbClient", new DialogCallbackHandler());lc.login()Subject.doAs(lc.getSubject(), new PrivilegedAction() { public Object run() { GSSManager manager = GSSManager.getInstance(); GSSName clientName = manager.createName("clientUser", GSSName.NT_USER_NAME); GSSCredential clientCreds = manager.createCredential(clientName, 8 * 3600, createKerberosOid(), GSSCredential.INITIATE_ONLY); GSSName serverName = manager.createName("myService@localhost", GSSName.NT_HOSTBASED_SERVICE); manager.createCredential(serverName, GSSCredential.INDEFINITE_LIFETIME, createKerberosOid(), GSSCredential.INITIATE_ONLY); return null; } private Oid createKerberosOid() { return new Oid("1.2.840.113554.1.2.2"); }}); Unfortunately I get a GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt). Now provide the response and nothing else.
My understanding of getting the service ticket was wrong. I do not need to get the credentials from the service - this is not possible on the client, because the client really doesn't have a TGT for the server and therefore doesn't have the rights to get the service credentials.What's just missing here is to create a new GSSContext and to initialize it. The return value from this method contains the service ticket, if I have understood that correctly. Here is a working code example. It must be run in a PrivilegedAction on behalf of a logged in subject: GSSManager manager = GSSManager.getInstance(); GSSName clientName = manager.createName("clientUser", GSSName.NT_USER_NAME); GSSCredential clientCred = manager.createCredential(clientName, 8 * 3600, createKerberosOid(), GSSCredential.INITIATE_ONLY); GSSName serverName = manager.createName("http@server", GSSName.NT_HOSTBASED_SERVICE); GSSContext context = manager.createContext(serverName, createKerberosOid(), clientCred, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(true); context.requestConf(false); context.requestInteg(true); byte[] outToken = context.initSecContext(new byte[0], 0, 0); System.out.println(new BASE64Encoder().encode(outToken)); context.dispose(); The outToken contains then contains the Service Ticket. However this is not the way the GSS-API was meant to be used. Its goal was to hide those details to the code, so it is better to establish a GSSContext using the GSS-API on both sides. Otherwise you really should know what you are doing because of potential security holes.For more information read the Sun SSO tutorial with kerberos more carefully than I did. EDIT:Just forgot that I am using Windows XP with SP2. There is a new "feature" in this version of Windows that disallows using the TGT in the Windows RAM. You have to edit the registry to allow this. For more information have a look at the JGSS Troubleshooting page topic in case you experience a "KrbException: KDC has no support for encryption type (14)" like I did.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/370878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16515/']}
jdg_84752
stackexchange
llm_judgeable_groundtruth_similarity
38809580
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 JPARespository for all my CRUD operation.Recently I wanted to implement sorting, so I went ahead with Pagable . The problem is, I want the repository methods to return List objects, I use them in my service layer. How can I achieve this, is there a way to convert these Page objects to List ? Now provide the response and nothing else.
If you use pageable in a jpa repository method, spring will always return a Page not a List. I suggest you have a service method that calls the repository method and extracts the contents of the Page result into a list. So if your repository method is thus: import org.springframework.data.domain.Page;import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;@Repositorypublic interface RecordRepository extends JpaRepository<Record, Integer>{ Page<Record> findAll(Pageable pageable);} then you can have a service class which has a method that calls the repository method @Servicepublic class RecordService{ @Autowired RecordRepository recordRepository; public List<Record> findAll(PageRequest pageRequest){ Page<Record> recordsPage = recordRepository.findAll(pageRequest); return recordsPage.getContent(); }} so in your calling class instead of calling the repository directly you can just use the service. thus: public class MyRecordImpl{ @Autowired RecordService recordService; public void doSomething(){ int page = 0; int pageSize = 5; List<Record> recordList = recordService.findAll(new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "recordId"))); //do other implementations here }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38809580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4348925/']}
jdg_84753
stackexchange
llm_judgeable_groundtruth_similarity
9731126
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 a very basic question but I've searched all over and been unable to find an answer that explains well enough for me to get my head around it. What I want to do is create a method in one class of my iOS app and then call that method from other classes in my app. Could someone explain exactly what I need to do to achieve this? Any help would be greatly appreciated as all my attempts so far have failed! Thanks. Now provide the response and nothing else.
Objective-C: You have to import the header of the class that contains the method you want to use ( ClassYouWantToUse.h ) into the class you want to use it at ( TargetClass ). Inside the TargetClass.h or TargetClass.m (depending on the scope you want to give it): #import "ClassYouWantToUse.h" Then create an instance of the class you want to use inside the target class either as a property like this: @property (nonatomic,strong) ClassYouWantToUse *classObject; Or as an instance variable like this: ClassYouWantToUse *classObject; Make sure you initialize it! (usually inside ViewDidLoad): classObject = [[ClassYouWantToUse alloc] init]; Now you can call any public methods from that class like this: [classObject theClassMethodWithParam:param1 andSecondParam:param2]; Note: The ClassYouWantToUse class must have the methods that you want to make accessible to others by declaring them in the header file: - (void)theClassMethodWithParam:(UIImage*)someImage andSecondParam:(NSString*)someText; Otherwise you won't be able to see these methods. Swift: Theres really nothing special about it in swift, just adding this as a reference. In swift you simply create an instance of the class you want to use: let classObject = ClassYouWantToUse() And use it directly: classObject.theClassMethodWithParam(param1, andSecondParam:param2)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9731126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1255861/']}
jdg_84754
stackexchange
llm_judgeable_groundtruth_similarity
57560017
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 learn Data Science and so have used some really popular Python modules likes Pandas, Matplotlib, Numpy, etc. So I clean installed Anaconda and am now using it as my default Python interpreter and also using Conda for installing packages and making virtual environments. I use VS Code as my daily text editor. But I have run into some issues when using the integrated Git terminal in VS Code with the Anaconda Python interpreter. There are a couple of issues that I am facing. One of the first issues that I see is when I am using CMD to run Python. If I type and enter python in cmd, the Python interpreter provided by anaconda comes up. But I also get a warning: Warning: This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation I didn't expect to get this output. Anyway, there's another problem in VS code. But first I would like to mention that I have checked "Add to PATH" when installing Anaconda so no issues there. Now, when I open a new Terminal in VS Code, automatically C:/Users/User/Anaconda3/Scripts/activate is run and then conda activate base is run. But when conda activate base is run, automatically, as mentioned, I get a CommandNotFoundError. It states Your shell has not been properly configured to use 'conda activate'.If using 'conda activate' from a batch script, change yourinvocation to 'CALL conda.bat activate' And then I am told to initialize my shell, so I did conda init bash but still no luck. And this brings me to talk about .bash_profile . I think it has to do something with this bash profile. Anyway, this is what is in my bash profile # >>> conda initialize >>># !! Contents within this block are managed by 'conda init' !!eval "$('/C/Users/User/Anaconda3/Scripts/conda.exe' 'shell.bash' 'hook')"# <<< conda initialize <<< Just a summary of the problem: Unexpected warning in CMD when running Anaconda Python interpreter Automatically run Anaconda Scripts and conda activate base when opening new Terminal in VS Code Conda init bash not helping P.S I have tried using conda activate [env_name] in CMD and also in Git Bash and they work without any issues. In other words, Anaconda and Conda work perfectly outside of VS Code terminal. Now provide the response and nothing else.
I have figured out the answer myself and would like to share it here. First of all at the time of writing the question I was using Git Bash as my Terminal in VS Code (am still using it). So the issue was that when I ran the command conda init bash in Git Bash or the VS Code Terminal, Conda just basically put the command used for activating Conda environments in the .bash_profile since it is sourced during logging into Bash. But the integrated Terminal in VS Code is a subshell of a Git Bash session. That is why .bash_profile is NOT sourced in VS Code since .bash_profile is only sourced during the main Bash session. The .bashrc file is the file that is sourced when creating a Terminal session in VS Code. So what you actually need to do is take the code that is put into .bash_profile by conda init bash and paste it into your .bashrc file and make the .bash_profile source that .bashrc file automatically. So, to sum up, using conda init bash will put the conda command in the .bash_profile and it is usually sourced by Git Bash, but VS Code Git Bash terminal will use .bashrc . So you can just cut and paste the code from .bash_profile to .bashrc (as already mentioned) or if you want, just simply follow this: put this code in your .bash_profile : if [ -f ~/.bashrc ]; then source ~/.bashrcfi And in your .bashrc , put this code: # >>> conda initialize >>># !! Contents within this block are managed by 'conda init' !!eval "$('{path_to_your_conda.exe}' 'shell.bash' 'hook')"# <<< conda initialize <<<# You can get conda.exe path by using `which conda` in Git Bash Now, when you open up a Git Bash session in VS Code Terminal, you can use conda activate env_name to activate any environments you have. Everything is now supposed to work as expected in VS Code terminal but I would like to further elaborate about something. If you want, you can skip the conda init bash process (NOT recommended, just read on for additional knowledge but please follow the above steps only). This is a feature that was introduced in conda 4.4.0 . Till then the way of activating conda environments was by using source activate but that command was NOT cross-platform, meaning that the command could not be used in OSes like Windows.So they made this change by introducing commands like: conda activate env_name so that conda environments become much easier to use despite the OS platform. conda activate also has other advantages. This is directly from their release docs : conda activate: The logic and mechanisms underlying environment activation have been reworked. With conda 4.4, conda activate and conda deactivate are now the preferred commands for activating and deactivating environments. You'll find they are much more snappy than the source activate and source deactivate commands from previous conda versions. The conda activate command also has advantages of (1) being universal across all OSes, shells, and platforms, and (2) not having path collisions with scripts from other packages like Python virtualenv's activate script. I used this question as a reference. Check it out to learn more. Having said that, using source activate env_name will still work if you are using Git Bash, even in VS Code Git Bash terminal. source activate env_name requires no prior set up or config. But it is highly recommended that you only use conda init to set everything up and then use conda activate env_name . [NOTE] : Locating and modifying the said .bashrc and .bash_profile on Windows is usually not as simple as it is on Linux. But can be done fairly easily like this: It goes without saying but, you should have Git Bash installed. Having Git Bash installed should, as far as I know, automatically create .bashrc or .bash_profile or maybe both. These files are called "dotfiles" (since they start with a dot) and these are by default hidden on most OSes and definitely on Windows. If they were auto-created by Git Bash on your system, it is most likely that they are placed in your home directory. Home directory on Windows is C:\Users\<you>\ . With that said, follow this: Open Git Bash and go to your home directory with: cd . Just type this and you will be in your home directory Enter this command: ls -a and you will see all your files, even hidden ones. Look for .bash_profile and .bashrc . Both should be present. If they are, you are ready to follow the above instructions. But if one is not there or if both are missing create them using: touch .bashrc && touch .bash_profile . You should now see these files when you again type: ls -a That's it. Now that you have your .bashrc and .bash_profile , you can follow the above instructions. Also, to access these two files quicker, open them like this with VS Code: code ~/.bashrc or code ~/.bash_profile . Now, modify these two files as per the instructions. In the question, I have also talked about VS Code activating Conda environments automatically. There's no issue with VS Code doing that since this is the default behavior. I misinterpreted that as something that's an issue. But if anyone was looking to stop VS Code from automatically doing that, I would recommend trying to set this in the user settings: "python.terminal.activateEnvironment": false
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57560017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10910567/']}
jdg_84755
stackexchange
llm_judgeable_groundtruth_similarity
490046
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 want to prove that in the set$$ S = \{4k+1 : k\text{ is a positive integer}\}$$(i.e. $S = \{1, 5, 9, 16, \dots \}$) unique prime factorization holds. How do I do that? Edit: a prime in this universe is something that cannot be written as $ab$ where both $a$ and $b$ are in the set unless either $a=1$ or $b=1$. Now provide the response and nothing else.
If by a prime in this set you mean something that cannot be factored non-trivially in this set , the result is false. For we have $(9)(49)=(21)(21)$. The numbers $9$, $49$, and $21$ are prime in this set. You can produce an infinite family of examples by taking $4$ distinct ordinary primes of the form $4k+3$, say $s,t,u, v$ and considering the number $stuv$, which has three distinct "prime" (in the $4k+1$ sense) factorizations. Remark: This answers the question if we define prime as you did, as a number $p$ which has no non-trivial factorization in our set. It does not answer the question if by prime we mean a number $p$ which is not a unit, such that $p$ divides $ab$ implies that $p$ divides $a$ or $p$ divides $b$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/490046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94215/']}
jdg_84756
stackexchange
llm_judgeable_groundtruth_similarity
12150624
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 an application, which will have a view layer organized in three parts: Sidebar Toolbar-left Toolbar-right I have spent may last few hours with trying to find something helpful with google, but I had no luck. I would need a short and complete application example on how to do this using Router and connectOutlet, with named outlets. Thx ahead. Now provide the response and nothing else.
With the new Router you can do something like this: {{outlet "menu"}}{{outlet}} In your Route you can handle the content of the outlets: // application routeEmber.Route.extend({ renderTemplate: function() { // Render default outlet this.render(); // render extra outlets this.render("menu", { outlet: "menu", into: "application" // important when using at root level }); }}); You should have an menu -template though. You can read more about it here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12150624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/785548/']}
jdg_84757
stackexchange
llm_judgeable_groundtruth_similarity
18697533
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The problem is I import data into relational tables where the source of the data is a XML-file + XSD schema. The XML source has several outputs and the relationships between nodes is created by SSIS in columns as order_id (generated primary key value not in XML) and in lets say order details we get the foreign key order_id. The file gets imported and we have a correct referential integrity between lets say orders and order details but the key is only unique within each file so if same file is imported again the same id is generated/used by ssis. How can you ensure uniqueness / control how the id is generated. I have tried to use a identity column as order_id in the order table that works but then it does not propagate down to reference tables like order details... Example if we have <order some attributes ...> <orderdetails some attributes ...></orderdetails> <orderdetails some attributes ...></orderdetails> </order> if we just let ssis import the rows we will get something like : order table order_id = 4 , rest of data columns orderdetails table row 1 orderdetail columns , order_id=4row 2 orderdetail columns , order_id=4 Everything ok but I don't understand how the apparently semi-random id = 4 is generated If an incremental key is used I would get (assuming seed starts at 1) order table order_id = 1 , rest of data columns orderdetails table row 1 orderdetail columns , order_id=4 <--same as previously SSIS generated row 2 orderdetail columns , order_id=4 <--same as previously SSIS generated I would like the id be 1 for the foreign key in details so I guess there is some intermediary step / setting I have missed in order to maintain referential integrity when importing XML data. Any pointers would be highly appreciated. Now provide the response and nothing else.
in words: A Gaussian filter which ignores NaNs in a given array U can be easily obtained by applying a standard Gaussian filter to two auxiliary arrays V and W and by taking the ratio of the two to get the result Z . Here, V is copy of the original U with NaNs replaced by zeros and W is an array of ones with zeros indicating the positions of NaNs in the original U . The idea is that replacing the NaNs by zeros introduces an error in the filtered array which can, however, be compensated by applying the same Gaussian filter to another auxiliary array and combining the two. in Python: import numpy as npimport scipy as spimport scipy.ndimagesigma=2.0 # standard deviation for Gaussian kerneltruncate=4.0 # truncate filter at this many sigmasU=sp.randn(10,10) # random array...U[U>2]=np.nan # ...with NaNs for testingV=U.copy()V[np.isnan(U)]=0VV=sp.ndimage.gaussian_filter(V,sigma=sigma,truncate=truncate)W=0*U.copy()+1W[np.isnan(U)]=0WW=sp.ndimage.gaussian_filter(W,sigma=sigma,truncate=truncate)Z=VV/WW in numbers: Here coefficients of the Gaussian filter are set to [0.25,0.50,0.25] for demonstration purposes and they sum up to one 0.25+0.50+0.25=1, without loss of generality. After replacing the NaNs by zeros and applying the Gaussian filter (cf. VV below) it is clear that the zeros introduce an error, i.e., due to the "missing" data the coefficients 0.25+0.50=0.75 do not sum up to one anymore and therefore underestimate the "true" value. However, this can be compensated by using the second auxiliary array (cf. WW below) which, after filtering with the same Gaussian, just contains the sum of coefficients. Therefore, dividing the two filtered auxiliary arrays rescales the coefficients such that they sum up to one while the NaN positions are ignored. array U 1 2 NaN 1 2 auxiliary V 1 2 0 1 2 auxiliary W 1 1 0 1 1position a b c d efiltered VV_b = 0.25*V_a + 0.50*V_b + 0.25*V_c = 0.25*1 + 0.50*2 + 0 = 1.25filtered WW_b = 0.25*W_a + 0.50*W_b + 0.25*W_c = 0.25*1 + 0.50*1 + 0 = 0.75ratio Z = VV_b / WW_b = (0.25*1 + 0.50*2) / (0.25*1 + 0.50*1) = 0.333*1 + 0.666*2 = 1.666 update - division-by-zero : The following incorporates useful questions and answers by @AndyL and @amain from the comments below, thanks! Large areas of NaNs may lead to a zero denominator (WW=0) at some positions when there are only NaN entries within the support of the Gaussian kernel (in theory that support is infinite, but in practice the kernel is usually truncated, see 'truncate' parameter in code example above). In that situation, the nominator becomes zero as well (VV=0) so that numpy throws a 'RuntimeWarning: invalid value encountered in true_divide' and returns NaN at the corresponding positions. This is probably the most consistent/meaningful result and if you can live with a numpy warning, no further adjustments are required.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18697533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2749495/']}
jdg_84758
stackexchange
llm_judgeable_groundtruth_similarity
7320701
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 having trouble creating/replicating the google maps directions function. I am able to get it working fine when I have a From/To field but as soon as I try to add multiple destinations it does not work. I have looked on the we but I am not getting any really good example tutorials showing how this is done. Below is what I have done so far. But I am pretty sure this is done really badly. Any examples would be great. <linkhref=http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" /><script src=http://maps.google.com/maps/api/js?sensor=false&amp;key=xxxxx" type="text/javascript"></script><script type="text/javascript">var intTextBox = 0;//FUNCTION TO ADD TEXT BOX ELEMENTfunction addElement() {intTextBox = intTextBox + 1;var contentID = document.getElementById('content');var newTBDiv = document.createElement('div');newTBDiv.setAttribute('id', 'strText' + intTextBox);newTBDiv.innerHTML ="Text " + intTextBox + ": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";contentID.appendChild(newTBDiv);}//FUNCTION TO REMOVE TEXT BOX ELEMENTfunction removeElement() {if (intTextBox != 0) {var contentID = document.getElementById('content');contentID.removeChild(document.getElementById('strText' + intTextBox));intTextBox = intTextBox - 1;}}var address = '<%= hdnDefault.Value %>'; //Hidden field contains default city Londonvar rendererOptions = {draggable:true};var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); ;var directionsService = new google.maps.DirectionsService();var map;var mygc = new google.maps.Geocoder();mygc.geocode({'address': address },function(results, status) {var country1 = results[0].geometry.location.lat();var country2 = results[0].geometry.location.lng();var australia = new google.maps.LatLng(country1, country2);initialize(australia);});function initialize(australia) {var myOptions ={zoom: 7,mapTypeId: google.maps.MapTypeId.ROADMAP,center: australia};map =new google.maps.Map(document.getElementById("map_canvas"), myOptions);directionsDisplay.setMap(map);directionsDisplay.setPanel(document.getElementById("directionsPanel")); google.maps.event.addListener(directionsDisplay,'directions_changed', function() { computeTotalDistance(directionsDisplay.directions);});calcRoute();}function calcRoute(fromAddress, toAddress) {/*from and to text boxes*/var request = {origin: fromAddress,destination: toAddress,travelMode: google.maps.DirectionsTravelMode.DRIVING};directionsService.route(request,function(response, status) {if (status == google.maps.DirectionsStatus.OK) {directionsDisplay.setDirections(response);}});}function computeTotalDistance(result) {var total = 0;var myroute = result.routes[0];for (i = 0; i < myroute.legs.length; i++) {total += myroute.legs[i].distance.value;}}function setDirections(fromAddress, toAddress) {calcRoute(fromAddress, toAddress);}function showLocation() {geocoder.getLocations(document.forms[0].fromAddress.value,function(response) {if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the first address");}else {location1 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };geocoder.getLocations(document.forms[0].toAddress.value,function(response) {if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}else {location2 = { lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address };gDir.load('from: ' + location1.address + ' to: ' + location2.address);}});}});}</script><body onload="initialize()"><div><div id="map_canvas" style="width: 430px; height: 450px; margin-right: 10px;"></div></div></div>/*Contains texboxes and buttons*/</div><div id="directionsPanel" style="text-align: right; width: 900px; height: 100%;"><p>Total Distance:<span id="total"></span></p></div></body> Now provide the response and nothing else.
This is how I have handled multiple way point directions. var directionsService = new google.maps.DirectionsService();var renderOptions = { draggable: true };var directionDisplay = new google.maps.DirectionsRenderer(renderOptions);//set the directions display service to the mapdirectionDisplay.setMap(map);//set the directions display panel//panel is usually just and empty div. //This is where the turn by turn directions appear.directionDisplay.setPanel(directionsPanel); //build the waypoints//free api allows a max of 9 total stops including the start and end address//premier allows a total of 25 stops. var items = ["address 1", "address 2", "address 3"];var waypoints = [];for (var i = 0; i < items.length; i++) { var address = items[i]; if (address !== "") { waypoints.push({ location: address, stopover: true }); }}//set the starting address and destination addressvar originAddress = "starting address";var destinationAddress = "destination address";//build directions requestvar request = { origin: originAddress, destination: destinationAddress, waypoints: waypoints, //an array of waypoints optimizeWaypoints: true, //set to true if you want google to determine the shortest route or false to use the order specified. travelMode: google.maps.DirectionsTravelMode.DRIVING };//get the route from the directions servicedirectionsService.route(request, function (response, status) { if (status == google.maps.DirectionsStatus.OK) { directionDisplay.setDirections(response); } else { //handle error }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7320701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492201/']}
jdg_84759
stackexchange
llm_judgeable_groundtruth_similarity
207973
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've got STM32F030F4 chips from shop, made a small breadboard adapter for it and tried to connect to its built-in bootloader via USART1. I've failed and I'm somewhat bewildered about wiring. My current schematic is the following: pin 16 (VDD) to +3.3 pin 15 (GND) to GND pin 1 (BOOT0) to +3.3 pin 4 (RESET) to GND, temporarily pin 8 (USART1_TX) to RX of the FTDI-cable pin 9 (USART1_RX) to TX of the FTDI-cable The cable I use constantly with NXP chips, so I think it is using. It also provides +3.3 volts and has LEDS to indicate TX/RX activity. I've tried this tool http://sourceforge.net/projects/bootstm32/ after plugging the cable and temporarily applying RESET to GND. Magically, it could not connect, though I see the TX activity LED blink... I've rechecked datasheet and I am somewhat bewildered. There are also pins 17 and 18 for USART1 TX and RX. I've tried them also but to no avail. Another concern is that I think this chip do not have BOOT1 pin (many manuals write about driving it low). So I assume it is not needed? I also thought I can test with multimeter either one of pins is in strong HIGH state, which should be TX - but none is. Though probably TX is turned to output only after auto baud rate detection is completed? What else can be wrong? I think I need not quartz for simplest schematic, yes? Thanks in advance for your hints! UPD Solved! It appeared that VDDA should also be connected, otherwise chip is in reset state. Please see my own answer below for more details. Now provide the response and nothing else.
At last I've found what was missing. VDDA should be connected! e.g. to VDD. I believe if device has VSSA also, it also should be connected. Otherwise the chip is in reset mode "thanks" to functionality which monitors both VDD and VDDA and simply does not allow chip to start. So minimal connection is like this: 3.3 Volts to VDD, VDDA, BOOT0 GND to VSS (and VSSA if present) (at this point you can check that PA9 yields strong high level - seems it at once becomes TX output) PA9 (TX) to the RX of the cable (in my case no pull-up is needed as it is full-functional output) PA10 (RX) to the TX of the cable. By the way I use the cable with 5V levels and it is Ok as the pins are 5v-tolerant.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/207973', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/93820/']}
jdg_84760
stackexchange
llm_judgeable_groundtruth_similarity
2385221
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 $p$ be a prime number, and $n$ a positive integer such $$p\mid n^3+n^2-2n-1, \quad n\ge 2.$$ Show that $$7\mid p^3-p.$$ It maybe can use Fermat's little theorem? Now provide the response and nothing else.
Expanding my comments. I first give an answer using the machinery of algebraic-number-theory . That argument relies on the theory of splitting of primes in cyclotomic fields and their subfields, most notably to identifying the action of the Frobenius automorphism which is particularly easy in a cyclotomic fields. Following that answer I also give another answer using less technology - replacing the use of cyclotomic fields with a few basic facts about finite fields. Some readers may benefit from reading the second answer first, and then coming back to the first (provided they are at all familiar with algebraic number theory). The reason why I ordered the answers in this way is my way of handling Bill Dubuque's comment. Otherwise the key equation used in the second answer looks like it came out of a magic box. I actually believe that there may be a way of replacing the use of finite fields in my second answer with Little Fermat (or something close to that). I don't have a good way of doing that myself (I have made a little bit of progress and am still thinking...). On with the first answer: Let $\zeta=e^{2\pi i/7}$ be a primitive seventh root of unity, when $2\cos(2\pi/7)=\zeta+\zeta^{-1}$ .We know that $m(x)=(x^7-1)/(x-1)=x^6+x^5+x^4+x^3+x^2+x+1$ is the minimal polynomial of $\zeta$ . Denoting $f(x)=x^3+x^2-2x-1$ we then see that $$\begin{aligned}f(\zeta+\zeta^{-1})&=(\zeta+\zeta^{-1})^3+(\zeta+\zeta^{-1})^2-2(\zeta+\zeta^{-1})-1\\&=\sum_{j=-3}^3\zeta^j=\frac{m(\zeta)}{\zeta^3}=0.\end{aligned}$$ Therefore $f(x)$ is the minimal polynomial of $2\cos(2\pi/7)$ . Finally, let $L=\Bbb{Q}(\zeta)$ , $K=\Bbb{Q}(\zeta+\zeta^{-1})$ be the given field extensions. For a rational prime $p\neq7$ we know that the corresponding Frobenius automorphism $\sigma_p$ in $Gal(L/\Bbb{Q})$ is uniquely determined by the requirement $\sigma_p(\zeta)=\zeta^p$ . Assume that $n$ is an integer such that $p\mid f(n)$ . This means that the norm $N_K(z)$ of the algebraic integer $z:=n-(\zeta+\zeta^{-1})\in K$ is divisible by $p$ . Without loss of generality we can assume that $0<n<p$ implying that the norm has absolute value $<p^3$ . Because $K/\Bbb{Q}$ is a cubic cyclic extension, this forces the prime $p$ to split into a product of three distinct prime ideals of $\mathcal{O}_K$ , $p=\mathfrak{p}_1\mathfrak{p}_2\mathfrak{p}_3$ , each with inertia degree $f(\mathfrak{p}_i\mid p)=1$ . Without loss of generality we can assume that $\mathfrak{p}_1=(p,n-(\zeta+\zeta^{-1}))$ , $\mathfrak{p}_2=(p,n-(\zeta^2+\zeta^{-2}))$ , $\mathfrak{p}_3=(p,n-(\zeta^3+\zeta^{-3}))$ . The information about the inertia degree is important here. When $f=1$ we know that the Frobenius automorphism must map $\mathfrak{p}_1$ to itself. Also, it must induce the identity mapping on the residue class field $\mathcal{O}_K/\mathfrak{p}_1$ . In particular $z$ must be a fixed point of $\sigma_p$ . But $$z=\sigma_p(z)=n-(\zeta^p+\zeta^{-p})$$ if and only if $p\equiv\pm1\pmod7$ . This implies that $7\mid p^2-1$ . Taking into account the possibility $p=7=f(2)$ we see that we always have $7\mid p(p^2-1)$ . Then the same in the language of finite fields, and without a semester's worth of algebraic number theory. Assume that the prime $p\neq7$ and that $n$ is an integer such that $p\mid f(n)$ . Because $\gcd(n,f(n))=1$ it follows that $n$ is not divisible by $p$ . We can also conclude that $n$ is not congruent to $2$ modulo $p$ , because then $n^3+n^2-2n-1$ would be congruent to $2^3+2^2-2\cdot2-1=7$ modulo $p$ contradicting the assumption $p\neq7$ . Consider the equation $$x+\frac1x=n\qquad(*)$$ over the field $K=\Bbb{F}_p$ . Let $\alpha$ be a solution of $(*)$ in some extension field of $K$ . Because $n\not\equiv2\pmod p$ we can conclude that $\alpha\neq1_K$ . But $$\begin{aligned}&\alpha^3+\alpha^2+\alpha+1+\alpha^{-1}+\alpha^{-2}+\alpha^{-3}\\=&(\alpha+\alpha^{-1})^3+(\alpha+\alpha^{-1})^2-2(\alpha+\alpha^{-1})-1\\=&(n^3+n^2-2n-1)\cdot 1_K\\=&0_K.\end{aligned}$$ Multiplying this by $\alpha^3$ gives $$0=1+\alpha+\alpha^2+\cdots+\alpha^6=\frac{\alpha^7-1}{\alpha-1},$$ as $\alpha-1\neq0$ . Therefore $\alpha^7=1$ and $\alpha$ has multiplicative order $7$ . But $(*)$ is a quadratic equation so $\alpha$ belongs to the quadratic extension $\Bbb{F}_{p^2}$ . Its multiplicative group is known to be cyclic of order $p^2-1$ , so we can conclude that $7\mid p^2-1$ . Including the case $p=7$ we have, again, shown that in all the cases $7\mid p^3-p$ . Hopefully it is clear that in the second solution $n$ plays the role played by $2\cos(2\pi/7)$ in the first solution while $\alpha$ handles the duties of $\zeta$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2385221', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/465089/']}
jdg_84761
stackexchange
llm_judgeable_groundtruth_similarity
22385876
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can see that the log.d requires Log.d(String TAG, String). How do I print to the android debug logcat a List String instead of just a String? Now provide the response and nothing else.
Make use of toString() method which is available for most common data structures: Log.d("list", list.toString()); Above statement will give you the expected result if you declare your List / Collection using Generic type defined in Java. Such as String, Integer, Long etc. Cause, they all have implemented toString() method. Custome Generic Type: But if you declare the List using your own custom type then you will not get proper output by just calling list.toString() . You need to implement toString() method for your custom type to get expected output. For example: You have a model class named Dog as below public class Dog{ String breed; int ageC String color; } You declared a List using Dog type List<Dog> dogList = new ArrayList<Dog>(); Now, if you want to print this List in LogCat properly then you need to implement toString() method in Dog class. public class Dog{ String breed; int age String color; String toString(){ return "Breed : " + breed + "\nAge : " + age + "\nColor : " + color; } } Now, you will get proper result if you call list.toString() .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22385876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1936916/']}
jdg_84762
stackexchange
llm_judgeable_groundtruth_similarity
5294416
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 run the following code with the left and the right images and get the strange result. I'm not exactly sure what I'm doing wrong. First of all, why is it cropped and why is the disparity all one color? CvStereoBMState *BMState = cvCreateStereoBMState();assert(BMState != 0);BMState->preFilterSize=41;BMState->preFilterCap=31;BMState->SADWindowSize=41;BMState->minDisparity=-64;BMState->numberOfDisparities=128;BMState->textureThreshold=10;BMState->uniquenessRatio=5;CvMat* disp = cvCreateMat(image_pyramid[0][0]->height, image_pyramid[0][0]->width, CV_16S);CvMat* vdisp = cvCreateMat(image_pyramid[0][0]->height, image_pyramid[0][0]->width, CV_8U);cvFindStereoCorrespondenceBM(image_pyramid[0][0], image_pyramid[1][0], disp, BMState);cvNormalize(disp, vdisp, 0, 256, CV_MINMAX);cvSaveImage("wowicantbelieveitsnotbutter.jpg", vdisp); Now provide the response and nothing else.
You can use Array.prototype.findIndex method to find out the index of NaN in an array let index = [1,3,4,'hello',NaN,3].findIndex(Number.isNaN)console.log(index) You can use Array.prototype.includes to check if NaN is present in an array or not. It won't give you the index though !! It will return a boolean value. If NaN is present true will be returned, otherwise false will be returned let isNaNPresent = [1,2,NaN,'ball'].includes(NaN)console.log(isNaNPresent) Don't use Array.prototype.indexOf You can not use Array.Prototype.indexOf to find index of NaN inside an array.Because indexOf uses strict-equality-operator internally and NaN === NaN evaluates to false .So indexOf won't be able to detect NaN inside an array [1,NaN,2].indexOf(NaN) // -1 Use Number.isNaN instead of isNaN : Here i choose Number.isNaN over isNaN . Because isNaN treats string literal as NaN .On the other hand Number.isNaN treats only NaN literal as NaN isNaN('hello world') // trueNumber.isNaN('hello world') // false Or, Write your own logic : You can write your own logic to find NaN.As you already know that, NaN is the only value in javascript which is not equal to itself . That's the reason i suggested not to use Array.prototype.indexOf . NaN === NaN // false We can use this idea to write our own isNaN function. [1,2,'str',NaN,5].findIndex(e=>e!=e) // 3
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5294416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592667/']}
jdg_84763
stackexchange
llm_judgeable_groundtruth_similarity
30590903
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 add some constraints to a UIButton programmatically.I need it to have it centred horizontally to superview, centred vertically to superview, aspect ratio to its superview and aspect ratio to self. Can anyone help me please? Thank you. Now provide the response and nothing else.
I'll get the ball rolling for you so you can see the general idea, otherwise use the documentation as provided by Larme. Add the constraint in your superview (probably your view controller). NSLayoutConstraint *centreHorizontallyConstraint = [NSLayoutConstraint constraintWithItem:self.uiButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];[self.view addConstraint:centreHorizontallyConstraint]; So as you can see we are saying constraint the centre x attribute of UIButton too the centre x attribute of the View Controllers view with no additional offsets (multiplier set to 1.0 and constant 0). Make sure you add it to your view controller's view not the button because the button has not been laid out at this point and therefore you cannot add a constraint to it! (Please someone correct me if I'm wrong here). I add my constraints in the viewDidLoad method.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30590903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3783005/']}
jdg_84764
stackexchange
llm_judgeable_groundtruth_similarity
1179856
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do you calculate $$\sum_{i=0}^\infty {{2i \choose i}\over 4^i\cdot (2i+1)}$$ Wolfram gives ${\pi \over 2}$, but I have no idea how it got this. Now provide the response and nothing else.
Note \begin{align}\binom{2i}{i} &= \frac{2^i(2i - 1)(2i-3)\cdots 3\cdot 1}{i!}\\& = \frac{(-1)^i 4^i(1/2 - i)(3/2 - i)\cdots (-3/2)(-1/2)}{i!}\\& = (-1)^i4^i\binom{-1/2}{i}\end{align} and use the monotone convergence theorem to write \begin{align}\sum_{i = 0}^\infty \frac{\binom{2i}{i}}{4^i(2i+1)} &=\sum_{i = 0}^\infty 4^{-i}\binom{2i}{i}\int_0^1 x^{2i}\, dx \\&= \int_0^1 \sum_{i = 0}^\infty 4^{-i}\binom{2i}{i}x^{2i}\, dx \\&= \int_0^1 \sum_{i = 0}^\infty \binom{-1/2}{i}(-x^2)^i dx\\&= \int_0^1 \frac{1}{\sqrt{1 - x^2}}\, dx\\&= \arcsin(1) - \arcsin(0)\\&= \frac{\pi}{2}.\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1179856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/209892/']}
jdg_84765
stackexchange
llm_judgeable_groundtruth_similarity
50463636
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 use SoapClient . And i get message from API provider that my source requests wsdl at each request. But i see that after executing in /tmp appear file with wsdl data, i suppose this is cache. How can i check, is cache really used or not? API use https so i can't use something like tcpflow to check that. Of course i can use some pure php soap implementation and use debugger, but at this point i don't want do that. Cache should be used. APIs admin said that i don't use cache and create too much load. But i can't check on my side is this true or not. And my question - how can i check that? Now provide the response and nothing else.
You are looking at the status code of the response before response is actually generated. OnActionExecuting is called before the action is executed, so no status code is set yet. Default value for status code is 200, and that's what you see. To be able to see the actual status code other actions have assigned to the response, you need to look at OnActionExecuted , which runs after the action. Update. Another issue might be the fact that in Core framework action filter runs before and after the action is executed. So the response is not processed yet, and status code is not set in the http response object. The proper method for your use case seems to be IResultFilter.OnResultExecuted
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50463636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2103893/']}
jdg_84766
stackexchange
llm_judgeable_groundtruth_similarity
11658915
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it a bad practice to use a release version of 3rd party library in debug binary? I am using a 3rd party library and compiled a release .lib library. My exe is in debug mode development. Then I got: error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in test1.obj After some googling I found that is because I am trying to mix release with debug, and I should probably compile the library in debug mode or otherwise muddle with the _ITERATOR_DEBUG_LEVEL macro. But I am just curious if that is the recommanded way and why. It just seem cumbersome that I need to compile and keep a record of both release and debug binaries for every 3rd party library I intend to use, which will be many very soon, while having no intention to debug into these code. Now provide the response and nothing else.
Mixing debug and release code is bad practice. The problem is that the different versions can depend on different fundamental parts of the C++ runtime library, such as how memory is allocated, structures for things like iterators might be different, extra code could be generated to perform operations (e.g. checked iterators). It's the same as mixing library files built with any other different settings. Imagine a case where a header file contains a structure that is used by both application and library. The library is built with structure packing and alignment set to one value and the application built with another. There are no guarantees that passing the structure from the application into the library will work since they could vary in size and member positions. Is it possible to build your 3rd party libraries as DLLs? Assuming the interface to any functions is cleaner and does not try to pass any STL objects you will be able to mix a debug application with release DLLs without problems.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11658915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1400249/']}
jdg_84767
stackexchange
llm_judgeable_groundtruth_similarity
84030
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: In version 10 some built-in symbols are updated to support operator form like the Derivative . For example, Select , Cases , MatchQ , Map -related functions, and so on. These updates are handy (although it is not clear whether they are directly defined as SubValues for the symbols or defined as functions, see this answer .) In principle we can check all the new symbols listed here to see which of them have operator form. But this is tedious. Is there a way to automatically return such symbols from Names["System`*"] ? The difficulty is, neither DownValues nor SubValues can be used to built-in symbols to return useful information. Now provide the response and nothing else.
As Mr.Wizard already noted, it's not clear whether "operator form" occurs in the documentation of every command that has an operator form (or conversely, e.g., NDSolve* , which references the operator form of Inactive ). docdir = FileNameJoin[{$InstallationDirectory, "Documentation", "English", "System", "ReferencePages", "Symbols"}];docs = FileNames["*", docdir];ops = Count[Get[#], s_String /; StringMatchQ[s, ___ ~~ "operator form" ~~ ___], Infinity] & /@ docsToExpression @ Pick[StringDrop[#, -3] & /@ FileNameTake /@ docs, Unitize[ops], 1](*{AllTrue, AnyTrue, Append, Apply, AssociationMap, Cases, \CellularAutomaton, CountDistinctBy, Count, CountsBy, Dataset, \DeleteCases, DeleteDuplicatesBy, Delete, Extract, FirstCase, \FirstPosition, FreeQ, GroupBy, Insert, KeyDrop, KeyExistsQ, KeyMap, \KeySelect, KeySortBy, KeyTake, KeyValueMap, Lookup, MapAt, \MapIndexed, Map, MatchQ, MaximalBy, MemberQ, Merge, MinimalBy, \NDSolve, NDSolveValue, NoneTrue, Position, Prepend, Query, Replace, \ReplacePart, Scan, SelectFirst, Select, SortBy, StringCases, \StringContainsQ, StringDelete, StringEndsQ, StringStartsQ, \TakeLargestBy, TakeLargest, TakeSmallestBy, TakeSmallest}*) On a Unix system, you can do this: commandstring = "!cd " <> docdir <> "; fgrep -l \"operator form\" *";StringDrop[#, -3] & /@ Import[commandstring, "List"] // ToExpression
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/84030', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5943/']}
jdg_84768
stackexchange
llm_judgeable_groundtruth_similarity
25246435
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 currently finding ways to pass a string in java to a batch file where several commands will be running based on it. For example.. JFileChooser chooser = new JFileChooser(); JButton btnSelect = new JButton("SELECT"); btnSelect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent args) { //chooser.setMultiSelectionEnabled(true); //enable multiple selection of files int i = chooser.showOpenDialog(null); if (i == chooser.APPROVE_OPTION) { textField.setText(chooser.getSelectedFile().getAbsolutePath()); } //works. able to output file path. //System.out.println(chooser.getSelectedFile().getAbsolutePath()); } });//when start button is selected btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent args) { // image info code try { //System.out.println(chooser.getSelectedFile().getAbsolutePath()); //create new process String command = "cmd /c start /wait "+DetectDrive+"\\imageinfo.bat"; Process p = Runtime.getRuntime().exec(command); //cause this process to stop until process p is terminated p.waitFor(); } catch (IOException | InterruptedException e1) { e1.printStackTrace(); } } } So this is part of my java coding. But what I want is that when the user uses the "select" option to choose a file, this file path is System.out.println(chooser.getSelectedFile().getAbsolutePath()); . How can I pass this parameter to a batch file for other uses? Because my batch file will need the filepath chose by the user. I heard there's a way but I do not know how.. I tried researching but didn't seem to work. Any help will be greatly appreciated!!! EDITED I have written this to my java coding: String filePath = chooser.getSelectedFile().getAbsolutePath();//create new processString command = "cmd /c start /wait "+DetectDrive+"\\BatchFiles\\imageinfo.bat";Process p = Runtime.getRuntime().exec(new String[]{command,"\""+filePath+"\""});p.waitFor(); When a user selects a file (e.g. E:\jooo.txt), the filePath is able to store that file path.But when I run it, there's seems something wrong with the Process p = ... And I do not know what to write to my batch file so that the file path that the user has selected will be shown in the batch file. For example ( In my batch file ): echo %filePath% It doesn't seems to work. How should I code in the batch file so that it will show the file path that the user has selected in java? I'm new to this area so I need more help here. Any help will be greatly appreciated! EDITED2 java.io.IOException: Cannot run program "cmd /c start /wait E:\\imageinfo.bat": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at Volatility$3.actionPerformed(Volatility.java:187) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) ... This is my error. I am trying to debug now. Now provide the response and nothing else.
The final solution was to use regex and split it using groups. This resolved all issues and allowed me to get the file / directory name and whether it was a directory or file. string regex =@"^" + //# Start of line@"(?<dir>[\-ld])" + //# File size @"(?<permission>[\-rwx]{9})" + //# Whitespace \n@"\s+" + //# Whitespace \n@"(?<filecode>\d+)" +@"\s+" + //# Whitespace \n@"(?<owner>\w+)" +@"\s+" + //# Whitespace \n@"(?<group>\w+)" +@"\s+" + //# Whitespace \n@"(?<size>\d+)" +@"\s+" + //# Whitespace \n@"(?<month>\w{3})" + //# Month (3 letters) \n@"\s+" + //# Whitespace \n@"(?<day>\d{1,2})" + //# Day (1 or 2 digits) \n@"\s+" + //# Whitespace \n@"(?<timeyear>[\d:]{4,5})" + //# Time or year \n@"\s+" + //# Whitespace \n@"(?<filename>(.*))" + //# Filename \n@"$"; //# End of linevar split = new Regex(regex).Match(line);string dir = split.Groups["dir"].ToString();string filename = split.Groups["filename"].ToString();bool isDirectory = !string.IsNullOrWhiteSpace(dir) && dir.Equals("d", StringComparison.OrdinalIgnoreCase); Thanks to: http://blogs.msdn.com/b/adarshk/archive/2004/09/15/sample-code-for-parsing-ftpwebrequest-response-for-listdirectorydetails.aspx for providing the regex.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25246435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3843484/']}
jdg_84769
stackexchange
llm_judgeable_groundtruth_similarity
43061707
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 I have the string "UGGUGUUAUUAAUGGUUU" how to I turn it into a list split up by every 3 characters into ["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"] ? Now provide the response and nothing else.
If your string contains only ASCII characters and your string's byte_size is a multiple of 3, there's a really elegant solution using a lesser known Elixir feature: binary comprehensions: iex(1)> string = "UGGUGUUAUUAAUGGUUU""UGGUGUUAUUAAUGGUUU"iex(2)> for <<x::binary-3 <- string>>, do: x["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"] This splits the string into chunks of 3 bytes. This will be much faster than splitting on codepoints or graphemes but will not work correctly if your string contains non-ASCII characters. (In that case I'd go with @michalmuskala's answer.) Edit: Patrick Oscity's answer reminded me that this can also work for codepoints: iex(1)> string = "αβγδεζηθικλμνξοπρςστυφχψ""αβγδεζηθικλμνξοπρςστυφχψ"iex(2)> for <<a::utf8, b::utf8, c::utf8 <- string>>, do: <<a::utf8, b::utf8, c::utf8>>["αβγ", "δεζ", "ηθι", "κλμ", "νξο", "πρς", "στυ", "φχψ"]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43061707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4678727/']}
jdg_84770
stackexchange
llm_judgeable_groundtruth_similarity
51166035
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 looking for some tutorial or some reference which can help me to create some custom shapes like below-mentioned shape. Background Shape I have tried creating a shape using the standard shape in android xml, but I am not able to find an appropriate solution for it. It would be a good help if someone can explain how can I achieve this. Now provide the response and nothing else.
You can achieve this by adding the edit-config tag to the Android platform in your config.xml , this is supported by Cordova Android Plugin v7.0. You will need to create the Network Security Config file that you would create for a native Android application using the examples from Google . Next in the Cordova config.xml you can use the edit-config tag to add the networkSecurityConfig attribute to the Application tag. Then you just need to copy the Network Security Config file as a resource for your application to the res/xml directory. Here is an example of how this might look in your applications config.xml ...<platform name="android"> <edit-config xmlns:android="http://schemas.android.com/apk/res/android" file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application"> <application android:networkSecurityConfig="@xml/network_security_config" /> </edit-config> <resource-file src="network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" /></platform>...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51166035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84771
stackexchange
llm_judgeable_groundtruth_similarity
1647666
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 few developers who constantly put If null checks For example: Run(Order order){ if (order == null) return;} in their code as they think they are protecting their class if someone passes in a parameter that is null. I am trying to tell them the flaw in their logic because if someone is passing in null in this case, its most likely an issue with the consumer code and instead of this class throwing an exception and failing fast, it gracefully handles the bad behavior of the consumer and keep chugging away. another suggestion is to have precondition or guard class that fail fast and throw exceptions. any thing but ignoring that fact that the consumer probably has some other issue and i am help mask it. how do i get folks to appreciate the fact that your class shouldn't be so forgiving. if someone doesn't pass in good data, they should be told. any good articles or suggestions to help me get this point across? Now provide the response and nothing else.
If your class cannot accept null arguments, then the best thing to do is this: if (arg == null) throw new ArgumentNullException(); This is vastly preferable to getting a NullPointerException deeper down the stack. In the worst case scenario, you'll cache that null somewhere and won't actually trigger the exception until much later, and see how much fun you'll have debugging the problem then . And as others have stated, sometimes the contract says that null is okay. In that case, having a guard clause around some parts of the code is correct--although even then I'd say that the best design would be to add an overload without the optionally-null arguments.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1647666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653/']}
jdg_84772
stackexchange
llm_judgeable_groundtruth_similarity
23118341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]' The above command outputs only the values as below: "[email protected]""2323""test""02-03-2014-13:41""application" How can I get the key names instead like the below: emailversionIDcontextdateversionName Now provide the response and nothing else.
You can use: jq 'keys' file.json Complete example $ cat file.json{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }$ jq 'keys' file.json[ "Archiver-Version", "Build-Id", "Build-Jdk", "Build-Number", "Build-Tag", "Built-By", "Created-By", "Implementation-Title", "Implementation-Vendor-Id", "Implementation-Version", "Manifest-Version", "appname", "build-date", "version"] UPDATE: To create a BASH array using these keys: Using BASH 4+: mapfile -t arr < <(jq -r 'keys[]' ms.json) On older BASH you can do: arr=()while IFS='' read -r line; do arr+=("$line")done < <(jq 'keys[]' ms.json) Then print it: printf "%s\n" "${arr[@]}""Archiver-Version""Build-Id""Build-Jdk""Build-Number""Build-Tag""Built-By""Created-By""Implementation-Title""Implementation-Vendor-Id""Implementation-Version""Manifest-Version""appname""build-date""version" or use: declare -p arr You may also use sort for better visibility like this: jq 'keys | sort' file.json
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/23118341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476906/']}
jdg_84773
stackexchange
llm_judgeable_groundtruth_similarity
45478105
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 facing two problems: The scroll listener won't work The RecyclerView never recycles any views when it's attached to a NestedScrollView . It acts like a linear layout inside the ScrollView. It uses a lot of memory and creates lags. I am attaching a youtube player fragment on top of the recycler view since I can't put a fragment inside the recycler view. In my code you can see there is a frame layout. My layout looks like this: <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/nestedScroll" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#ffffff" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <FrameLayout android:layout_width="match_parent" android:layout_height="240dp" android:layout_alignParentTop="true"/> </LinearLayout> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/youtube_layout" android:visibility="visible"/> </LinearLayout></android.support.v4.widget.NestedScrollView> I want to use scroll listener to load more items so I have tried the following: @Overridepublic void onScrolled(RecyclerView recyclerView, int dx, int dy) { Log.i(TAG, "onScrolled: "); // bail out if scrolling upward or already loading data if (dy < 0 || dataLoading.isDataLoading()) return; final int visibleItemCount = recyclerView.getChildCount(); final int totalItemCount = layoutManager.getItemCount(); final int firstVisibleItem = layoutManager.findFirstVisibleItemPosition(); if ((totalItemCount - visibleItemCount) <= (firstVisibleItem )) { onLoadMore(); }} But layoutManager.findFirstVisibleItemPosition()==0 so it's not working, and more over onScrolled never called twice since I set recyclerview.setNestedScrollingEnabled(false) so I have tried in onBindView like this public void onBindViewHolder(RecyclerView.ViewHolder customViewHolder, int i) { Log.w("d","inside bind view"); if(i>=getItemCount()-1 && !datamanager.isDataLoading()){ datamanager.loadmoreData(); } but the recylerview binds the all the view at once time before I even start scrolling, so this method also does not work. Now provide the response and nothing else.
The recycler view never recycle any views when its attached to nested scroll view,its acts as set on linear layout inside scroll view.its create a huge memory and lags the screen. Exactly. You can't put a RecyclerView inside another scrolling view. It will not work, because the wrapping view needs to know the total height of the RecyclerView and the RecyclerView can only know its total height by measuring and layouting all of its items. How to fix this? Don't put a RecyclerView inside another scrolling view. If you need a header or footer you will have to add it to the RecyclerView and let the RecyclerView take care of displaying it. Get rid of your ScrollView and move your header inside of the RecyclerView. Technically it is possible to also load fragments inside a RecyclerView, but I have to admit getting this to work properly is a bit tricky. There are also a lot of libraries that facilitate the process, my personal favorite being Epoxy made by AirBnb, but there's also Groupie , and a lot of others.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45478105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2578800/']}
jdg_84774
stackexchange
llm_judgeable_groundtruth_similarity
17413001
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 Visual Studio 2013, Microsoft again presents the menu in UPPERCASE as the default. Can these be modified to be Sentence Case? Now provide the response and nothing else.
Yes - in the new Visual Studio 2013 (as in VS 2012), MS reinforced their design decision to make ALL CAPS MENU ITEMS the default. The methods for reverting the menu style are almost the same methods used for Visual Studio 2012, which has been discussed before . Update (after Visual Studio 2013 Update 4) As of Visual Studio 2013 Update 4 you can go into Tools > Options > Environment and uncheck Turn off upper case in the menu bar Before Visual Studio 2013 Update 4: You need to create a specific registry key if you want "old-style" menus back. First Variant : Since Package Manager Console is Powershell , select menu options TOOLS / Library Package Manager / Package Manager Console and enter and run Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\12.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1 (as a single line). Second Variant : Open up a Command Prompt ( win + r , cmd , enter ) and enter and run REG ADD HKCU\Software\Microsoft\VisualStudio\12.0\General /v SuppressUppercaseConversion /t REG_DWORD /d 1 (as a single line). Third Variant :Change registry values by hand, open regedit and navigate to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\General then, create (right click): DWORD value with the content of SuppressUppercaseConversion and set it to 1 Close regedit.exe and you're done. Fourth Variant : At least one VS Extension ( VSCommands for Visual Studio 2013 ) has been published that enables you (among other things) to switch menu style via config menu from within VS 2013. You may also set it to all-lower-case items (which is, imho, nice): switch to Sentence Case (subtly different from what you get with SuppressUppercaseConversion: the SQL menu gets renamed to Sql) or hide it completely (and have it appear on ALT key press or mouse over)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/17413001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170194/']}
jdg_84775
stackexchange
llm_judgeable_groundtruth_similarity
6120091
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Should I commit the project file (.xcodeproj)? When I commit this file from one system and update it on a second system, the project gets corrupted and Xcode won't open it. Is this expected behavior, or am I maybe doing something wrong? Here is my list of ignored files: *.o,*.lo,*.la,*.al,.libs,*.so,*.so.[0-9]*,*.a,*.pyc,*.pyo,*.rej,*~,#*#,.#*,.*.swp,.DS_Store,*.pbxuser,*.perspective,*.perspectivev3,*.project.xcworkspace,*.xcuserdata,*.mode1v3,*.mode2v3,build/,build,/build/ Should I add something to this list? Should I forget the SVN and switch to GIT? I am using Cornerstone as SVN client and using Xcode 3.2.5 Please help; I am stuck! Now provide the response and nothing else.
do commit and track it. specifically, there are a few bits in there which you want - the most important is project.pbxproj. it looks like you have already ignored the user-specific pieces (which is good). problem is, it will conflict often in distributed environments. break your projects and/or their definitions into smaller pieces to avoid this risk. the project file is a text format - it will merge without issue in some cases. i do not track these: *.xcbkptlist*.xcuserstate but you'll want to track some of the scheme and workspace files, new in Xc4. again, don't bother tracking the user defined bits, unless you really like them to be tracked, and you are the only person committing. another thing i recommend is to build to a central location which lies outside of your versioned source directories -- no build/ directories among the sources, even if they are ignored.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6120091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303073/']}
jdg_84776
stackexchange
llm_judgeable_groundtruth_similarity
14175992
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 table in PostgreSQL. I want to re-order the rows data physically according to a specific column (which is not primary key). In my case this column type is date . How can I do it? Now provide the response and nothing else.
If you have an index on that column, then the CLUSTER command will physically "order" the rows according to that index CLUSTER [VERBOSE] table_name [ USING index_name ] http://www.postgresql.org/docs/current/static/sql-cluster.html Note that this "order" isn't automatically maintained, you need to run that statement on a regular basis manually. This will however not guarantee any specific order when retrieving the rows. Not even when no joins or aggregates are involved. Even if all you do is select * from the_table the order in which the rows are returned is still not guaranteed. For example: Postgres has a feature called "synchronized seq scan", which means that if one session starts a seq scan ( select * from ... ) and another session is doing the same thing, the second one piggy-backs on the first seq scan (where ever that is) and then adds the "missed" rows at the end of the result. The only way to guarantee an order of a result set (really: the only ) is to supply an order by clause. This only makes sense (at least to me) if you have a single harddisk in your server (which is not a SSD). In that case a seq scan might be faster because all blocks might be right next to each other (which isn't guaranteed either because of the way a file system re-uses free space). On a SSD or a proper server which uses a RAID array with many, many hard disks I can't see how this could be beneficial in any way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14175992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1043898/']}
jdg_84777
stackexchange
llm_judgeable_groundtruth_similarity
3822162
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 $G$ be a group, $H$ a subgroup of infinite index (that is there exists a sequence $(x_n) \in G^\mathbb{N}$ of distinct elements such that $\forall i \neq j, x_i H \neq x_j H$ ), $H_1, \ldots, H_p$ subgroups of $G$ such that $G = H \cup H_1 \cup H_2 \cup \cdots \cup H_p$ , show that $G = H_1 \cup H_2 \cup \cdots \cup H_p$ . By posting this exercise, I am looking for different approches to this problem. What I've done so far (draft): The property verified by $(x_n)$ is equivalent to $\forall i\neq j, x_i^{-1} x_j \notin H$ . So if $x_0 \in H$ therefore $\forall n \ge 1, x_n \notin H$ . Let's say that if $\exists i, x_i \in H$ we take $i=0$ . I studied the case $p=1$ with $G= (\mathbb{R}, +), H = \mathbb{Z}, (x_n) = (\frac{2}{3})^n$ but my proof isn't generalizable. For $p=1$ , we have $G = H_1 \cup H$ . Suppose $H_1 \neq H \cup H_1$ ie. there exists $h \in H - H_1$ . We have $x_1 \notin H$ so $x_1 \in H_1$ , so $h x_1 \notin H_1$ , so $hx_1 \in H$ , so $x_1 \in H$ which is absurd. I tried to use the same method for $p=2$ but it's harder: suppose there exists $h \in H-H_1-H_2$ , we still have $x_1 \notin H$ so let's say $x_1 \in H_1$ , therefore $hx_1 \notin H_1$ so $hx_1 \in H_2-H_1-H$ ... Back to the general case: Using 1. we see that $\forall n \ge 1, \exists j, x_n \in H_j$ so there exists $i_1$ such that $H_{i_1}$ contains an infinite number of images of the sequence $(x_n)$ . Let's call $(x^{(i_1)}_n)$ a sequence of distinct terms such that $\forall n \ge 1,x^{(i_1)}_n \in H_{i_1}$ . Suppose there exists $h \in H-H_1 - \cdots - H_p$ , we see that $h x^{(i_1)}_n \in H-H_{i_1}$ so by induction we can find a sequence $(y_n)$ of distinct terms such that $\forall n, y_n \in H-H_1 - \cdots - H_p$ . Reference: Exercise 2.13 in Exercices de mathématiques: oraux X-ENS (Algèbre I) , by Francinou, Gianella, and Nicolas. Now provide the response and nothing else.
One of the subgroups $H_i$ , say $H_1$ , must contain infinitely many of the $x_i$ , which we can label as $y_1,y_2,\ldots,$ . Then, choosing $h \in H \setminus (H_1 \cup \cdots \cup H_p)$ , we have $hy_i \not\in H_1 \cup H$ for all $i$ , and so some other $H_i$ , say $H_2$ , must contain infinitely many of them, say $hz_1,hz_2,\ldots,$ Note that $z_i^{-1}z_j \in (H_1 \cap H_2) \setminus H$ for all $i \ne j$ , so $hz_1^{-1}z_j \not\in H_1 \cup H_2 \cup H$ for all $j>1$ , and hence some other $H_i$ , say $H_3$ contains infinitely many of them, say $hz_1^{-1}w_1, hz_1^{-1}w_2.\ldots$ . Then $w_i^{-1}w_j \in (H_1 \cap H_2 \cap H_3) \setminus H$ for all $i \ne j$ so $hw_1^{-1}w_j \not\in H_1 \cup H_2 \cup H_3 \cup H$ for all $j>1$ , and hence some other $H_i$ , say $H_4$ contains infinitely many of them, etc. etc.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3822162', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/718613/']}
jdg_84778
stackexchange
llm_judgeable_groundtruth_similarity
42988
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: While studying about Hückel theory, I got accustomed to the approximation of making the overlap matrix an identity matrix; that is making the off-diagonal elements zero as $S_{AB}= S_{BA}= 0\;;$ this implies the use of orthogonal base states of AOs. The off-diagonal elements of the Hamiltonian matrix are still taken as constants that may be non-zero: $H_{AB}= H_{BA}= \beta_{AB}$, where $\beta_{AB}$ is a negative quantity. Then I wondered why it isn't the case that $H_{AB}= H_{BA}= 0$ strictly, as it represents the expectation value - the average energy contribution of the overlapping region of AOs $A$ and $B$. But, it would seem that overlapping is not actually possible, as is evident from the fact that $S_{AB}$ is zero. In this question , when I asked about this, ifilot replied: Indeed, this seems rather counterintuitive, but it is not. Another way of looking at $S_{ij}=δ_{ij}$ is saying that all atomic orbitals are orthonormal to each other. So if you would evaluate the overlap integral of two different orbitals, it would result in zero. This does not necessarily mean that evaluating the Hamiltonian integral $\langle ϕ_i|\hat H|ϕ_j\rangle$ results in zero, because first applying the Hamiltonian operator on the wave function and then integrating might result in a non-zero outcome. I know he is right in this point; but I'm still having trouble seeing how this is possible. As Peter Atkins in his book Elements of Physical Chemistry wrote : [...] The integral $H_{AB}$ depends on both $\psi_A$ and $\psi_B$, and we can interpret it as the contribution to the energy due to the accumulation of electron density where the two atomic orbitals overlap , including, for instance, the Coulombic attraction between the extra accumulation of electron density and both nuclei. Evidently, this phrase makes clear that $H_{AB}$ is non-zero iff there is overlap between the AOs. So, how can $H_{AB}\ne 0$ and $S_{AB}= 0$ both be true at the same time? And, what are the physical implications? While the former means there is overlap, the latter means the opposite; it seems really contradictory . Now provide the response and nothing else.
I believe the confusion lies in some ambiguity in the use of the term overlap . For the $S_{AB}=0$ approximation of Hückel theory, overlap is used in the specific mathematical sense of the "overlap integral": $$S_{AB} = \left<\varphi_A|\varphi_B\right> = \int_{\vec r}{\varphi_A^*\!\left(\vec r\right)\varphi_B\!\left(\vec r\right)\mathrm{d}\vec r}$$ However, this does not mean that at each point in $\mathbb{R}^3$ only one of $\varphi_A$ or $\varphi_B$ is allowed to bear a non-zero value. In fact, at most points in $\mathbb R^3$, $\varphi_A$ and $\varphi_B$ will both bear non-zero values . Since $\varphi_A$ and $\varphi_B$ will in general have "co-located regions of non-zero values," the two functions can be described qualitatively as overlapping , in the same sense as in your second quote. It is the overlap of the functions in this more general, qualitative sense, that allows $H_{AB}=\left<\varphi_A^*\middle|\hat H\middle|\varphi_B\right>\neq0$. (To note, in order for Hückel's approximation to be exact, the orbitals would have to be selected such that the specific integral $S_{AB}$ over all $\mathbb R^3$ equals zero$^\ddagger$. I believe Hückel did not actually do this , but instead just coerced to zero any nonzero $S_{AB}$.) To help explain more explicitly why this is , I'll first write out the integral implied by the Dirac notation for $H_{AB}$: $$H_{AB}=\left<\varphi_A^*\middle|\hat H\middle|\varphi_B\right>=\int_{\vec r}{\varphi_A^*\!\left(\vec r\right)\hat H\!\left[\varphi_B\!\left(\vec r\right)\right]\mathrm{d}\vec r}$$ Then, I'll introduce two (real-valued) one-dimensional functions defined on the closed domain $x=[0,1]$ to use for demonstration purposes: $$\varphi_A\!\left(x\right) = \sin\!\left(2\pi x\right) \\\varphi_B\!\left(x\right) = \sin\!\left(3\pi x\right)$$ $\hspace{10mm}$ It is straightforward to show that $S_{AB}=0$ for these two functions. One way is to plug the overlap integral into Wolfram Alpha . Another option is to do it by hand. In the below figure, the green curve is a plot of the product $\varphi_A\!\left(x\right)\cdot\varphi_B\!\left(x\right)$, and the orange curve is a plot of the cumulative integral of this product: $$\int_0^x{\varphi_A\!\left(x'\right)\cdot\varphi_B\!\left(x'\right)\mathrm{d}x'}$$ $\hspace{10mm}$ As can be seen, the integral over the entire domain is zero, satisfying $S_{AB}=0$. Now , let's introduce a simple "Hamiltonian"$^\dagger$: $$\hat H = x$$ The next figure is a replicate of the first one above, with $\hat H\!\left[\varphi_B\right]$ also plotted as the dashed red curve: $\hspace{10mm}$ As in the second figure above, one last plot shows the local value of $\varphi_A\!\left(x\right)\hat H\!\left[\varphi_B\!\left(x\right)\right]$ along with the cumulative integral: $$\int_0^x{\varphi_A\!\left(x'\right)\cdot\left[x'\cdot\varphi_B\!\left(x'\right)\right]\mathrm{d}x'}$$ $\hspace{10mm}$ The value of $H_{AB}$ here is clearly not equal to zero. ( Wolfram Alpha concurs .) Thus, it is absolutely possible to have $H_{AB} \neq S_{AB} = 0$. To note , the principle exhibited here on a closed domain in $\mathbb R^1$ applies equally well to orbitals on an infinite domain in $\mathbb R^3$. Note also , if I were actually performing a quantum mechanical calculation here, I would have been a lot more careful about normalizing my wavefunctions (viz., ensuring $S_{ii}=1$). $^\ddagger$ Numerous methods are known for generating orthogonalized orbitals with $S_{AB}=0$ strictly, from a general set of orbitals where $S_{AB}\neq0$ occurs for some non-null subset of the $\left(\!A,\!B\right)$. To my knowledge, the most commonly used orthogonalization for atomic orbitals is Löwdin's method (see this PDF ). The Gram-Schmidt orthogonalization (usually in its " modified " form) is used in a variety of other areas of quantum chemistry. Wikipedia also has a pretty solid article on orthogonalization methods in general. $^\dagger$ You'd never use this as a Hamiltonian operator. Further, I'm not sure if it technically even is a Hamiltonian operator. (I think it'd work as a dipole moment operator ?) But, whatever, leave me alone, it's for purposes of illustration.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/42988', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/-1/']}
jdg_84779
stackexchange
llm_judgeable_groundtruth_similarity
54701255
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 use the victor.js library in a TypeScript project (3.0.1) and I'm having real heartache trying to import and use it. I've installed it from npm along with it's typings (victor @types/victor). I've tried to import it a myriad of ways but can't seem to get it to import along with type resolution in my IDE. I've tried these: import { Victor} from 'victor'; import * as v from 'victor'; (This module can only be referenced with ECMAScript imports/exports by turning on the 'allowSyntheticDefaultImports' flag and referencing its default export) import Victor = require('victor'); (works but not compatible when targeting ecmascript modules) const Victor = require("victor"); (Imports validly and I can construct objects but none of the typings are present) I'm sure someone out there has run into a similar situation to this before. If it helps the top of the index.js of victor has the line: exports = module.exports = Victor; Now provide the response and nothing else.
In Brief You're trying to use victor as if it were an es6 module, but it is not. I see two options: Let tsc convert your modules to a format like commonjs , in which case tsc will provide necessary glue logic between victor and your code Or you need to load your application through a module loader that provides the glue. Detailed Explanation When I run the latest tsc with the import that you show, the error I get is: This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export. When I turn on esModuleInterop , then it works just fine. Here is the test code I've used: import Victor from "victor";const foo = new Victor(1, 2);console.log(foo.y); And the tsconfig.json : { "compilerOptions": { "esModuleInterop": true }} The issue originates due to the fact that when you do import Victor from "victor" you are asking for the value that would be exported through an export default... statement, which is a syntax provided by es6 modules. However, victor does export anything that corresponds to export default... . So something has to bridge the gap. With what I've shown above, when you compile, tsc emits this: "use strict";var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod };};exports.__esModule = true;var victor_1 = __importDefault(require("victor"));var foo = new victor_1["default"](1, 2);console.log(foo.y); Note the __importDefault helper function. It is used whenever the TS code wants to access what a module exports as export default... What it does is check whether the module claims to be an es6 module. An es6 module that wants to export a default value is already correctly structured so there's nothing to do if the module is an es6 module. If the module is not an es6 module, then the helper creates a kind of fake module whose default exported value is the value of the original module. There's an important caveat since you mention "targeting ecmascript modules". If you use, this tsconfig.json : { "compilerOptions": { "esModuleInterop": true, "module": "es6" }} Then the emitted code is: import Victor from "victor";var foo = new Victor(1, 2);console.log(foo.y); Note that there is no longer any helper function. It is up to the module loader which will load the modules for your application to provide the same logic as provided by __importDefault . If I rename the file to have the mjs extension and run: $ node --experimental-modules test.mjs I get this output: (node:18394) ExperimentalWarning: The ESM module loader is experimental.2 When using Node with the experimental module support, it provides the same functionality as __importDefault . When you just use allowSyntheticDefaultImports without using esModuleInterop you are telling the compiler to assume that there will be something in your toolchain that will do the work of __importDefault . So the compiler does not provide a helper. It allows the compilation to proceed, but you are responsible later to use a module loader that will perform the same work as __importDefault .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54701255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341133/']}
jdg_84780
stackexchange
llm_judgeable_groundtruth_similarity
852122
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a nice geometric, intuitive or picture proof as to why the easily algebraically provable identity $\cos(3 \theta) = 4 \cos^3(\theta)-3\cos(\theta)$ is true? Note I'm not looking for a computational proof like the one linked to, more a proof without words or intuitive style proof, thanks. Now provide the response and nothing else.
Enhancing my diagram for the angle-sum formula (currently featured in Wikipedia ) to use three angles will get you pretty close ... Thus, $$\begin{align}\cos(\alpha+\beta+\gamma) &= \cos\alpha \cos\beta \cos\gamma - \sin\alpha \sin\beta \cos\gamma - \sin\alpha \cos\beta\sin\gamma - \cos\alpha \sin\beta\sin\gamma \\\sin(\alpha+\beta+\gamma) &= \sin\alpha \cos\beta \cos\gamma + \cos\alpha \sin\beta \cos\gamma + \cos\alpha \cos\beta \sin\gamma - \sin\alpha \sin\beta \sin\gamma\end{align}$$ With $\alpha = \beta = \gamma = \theta$, these become ...$$\begin{align}\cos 3\theta &= \cos^3\theta - 3 \sin^2\theta \cos\theta \\\sin 3\theta &= 3\cos^2\theta \sin\theta - \sin^3\theta\end{align}$$... which the Pythagorean identity helps us rewrite as ...$$\begin{align}\cos 3\theta &= \cos^3\theta - 3 (1-\cos^2\theta) \cos\theta = 4\cos^3\theta - 3 \cos\theta \\\sin 3\theta &= 3(1-\sin^2\theta) \sin\theta - \sin^3\theta = 3\sin\theta - 4\sin^3\theta\end{align}$$ Off-hand, I don't know of a diagram that goes directly from $\cos 3\theta$ to $4\cos^3\theta-3\cos\theta$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/852122', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/140929/']}
jdg_84781
stackexchange
llm_judgeable_groundtruth_similarity
36869134
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Input I have a column Parameters of type map of the form: from pyspark.sql import SQLContextsqlContext = SQLContext(sc)d = [{'Parameters': {'foo': '1', 'bar': '2', 'baz': 'aaa'}}]df = sqlContext.createDataFrame(d)df.collect()# [Row(Parameters={'foo': '1', 'bar': '2', 'baz': 'aaa'})]df.printSchema()# root# |-- Parameters: map (nullable = true)# | |-- key: string# | |-- value: string (valueContainsNull = true) Output I want to reshape it in PySpark so that all the keys ( foo , bar , etc.) would become columns, namely: [Row(foo='1', bar='2', baz='aaa')] Using withColumn works: (df .withColumn('foo', df.Parameters['foo']) .withColumn('bar', df.Parameters['bar']) .withColumn('baz', df.Parameters['baz']) .drop('Parameters')).collect() But I need a solution that doesn't explicitly mention the column names , as I have dozens of them. Now provide the response and nothing else.
Since keys of the MapType are not a part of the schema you'll have to collect these first for example like this: from pyspark.sql.functions import explodekeys = (df .select(explode("Parameters")) .select("key") .distinct() .rdd.flatMap(lambda x: x) .collect()) When you have this all what is left is simple select: from pyspark.sql.functions import colexprs = [col("Parameters").getItem(k).alias(k) for k in keys]df.select(*exprs)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36869134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/690430/']}
jdg_84782
stackexchange
llm_judgeable_groundtruth_similarity
1122067
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If a>0 and b>0, $ \lim_{x\rightarrow +\infty } \sqrt[x]{a^x+b^x} = ? $ What I was trying to do:Suppose a>b. Then, for sufficiently large values of x, $ a^x >> b^x $; so $\sqrt[x]{a^x+b^x} \rightarrow \sqrt[x]{a^x} \rightarrow a $ when $x \rightarrow +\infty$. Is that idea correct? How can I formalize it? Now provide the response and nothing else.
Assume $a>b$$$a^x\leq a^x+b^x\leq 2a^x$$ $$(a^x)^{\frac{1}{x}}\leq (a^x+b^x)^{\frac{1}{x}}\leq (2a^x)^{\frac{1}{x}}$$ $$a\leq (a^x+b^x)^{\frac{1}{x}}\leq 2^{\frac{1}{x}}a$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1122067', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/199011/']}
jdg_84783
stackexchange
llm_judgeable_groundtruth_similarity
29421343
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a cleaner or more pythonic way to do the following? try: error_prone_function(arg1)except MyError: try: error_prone_function(arg2) except MyError: try: another_error_prone_function(arg3) except MyError: try: last_error_prone_function(arg4) except MyError: raise MyError("All backup parameters failed.") Basically it's: If attempt #1 fails, try #2. If #2 fails, try #3. If #3 fails, try #4. If #4 fails, ... if #n fails, then finally raise some exception. Note that I'm not necessarily calling the same function every time, nor am I using the same function arguments every time. I am , however, expecting the same exception MyError on each function. Now provide the response and nothing else.
Thanks to John Kugelman's post here , I decided to go with this which utilizes the lesser-known else clause of a for loop to execute code when an entire list has been exhausted without a break happening. funcs_and_args = [(func1, "150mm"), (func1, "100mm", (func2, "50mm"), (func3, "50mm"), ]for func, arg in funcs_and_args : try: func(arg) # exit the loop on success break except MyError: # repeat the loop on failure continueelse: # List exhausted without break, so there must have always been an Error raise MyError("Error text") As Daniel Roseman commented below, be careful with indentation since the try statement also has an else clause.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29421343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1354930/']}
jdg_84784
stackexchange
llm_judgeable_groundtruth_similarity
30284695
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I've been researching this issue and found that this issue seems to occur when it can't reach something I'm referencing in my Activity. I think the issue might lie in me trying to reach the class Application but I'm not sure. I've tried commenting out the intents that relate to geocoding and still got the same error so I'm not really sure where its finding a null pointer. This is the error code I'm getting: 05-17 01:50:11.583: E/AndroidRuntime(23183): FATAL EXCEPTION: main05-17 01:50:11.583: E/AndroidRuntime(23183): Process: com.binarsunset.topic, PID: 2318305-17 01:50:11.583: E/AndroidRuntime(23183): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.binarsunset.topic/com.binarsunset.topic.CreateTopicActivity}: java.lang.NullPointerException05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread.access$800(ActivityThread.java:139)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.os.Handler.dispatchMessage(Handler.java:102)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.os.Looper.loop(Looper.java:136)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread.main(ActivityThread.java:5097)05-17 01:50:11.583: E/AndroidRuntime(23183): at java.lang.reflect.Method.invokeNative(Native Method)05-17 01:50:11.583: E/AndroidRuntime(23183): at java.lang.reflect.Method.invoke(Method.java:515)05-17 01:50:11.583: E/AndroidRuntime(23183): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)05-17 01:50:11.583: E/AndroidRuntime(23183): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)05-17 01:50:11.583: E/AndroidRuntime(23183): at dalvik.system.NativeStart.main(Native Method)05-17 01:50:11.583: E/AndroidRuntime(23183): Caused by: java.lang.NullPointerException05-17 01:50:11.583: E/AndroidRuntime(23183): at com.binarsunset.topic.CreateTopicActivity.updateCharacterCountTextViewText(CreateTopicActivity.java:118)05-17 01:50:11.583: E/AndroidRuntime(23183): at com.binarsunset.topic.CreateTopicActivity.onCreate(CreateTopicActivity.java:71)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.Activity.performCreate(Activity.java:5248)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)05-17 01:50:11.583: E/AndroidRuntime(23183): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)05-17 01:50:11.583: E/AndroidRuntime(23183): ... 11 more So I start in activity TopicActivity but it is not my main, here is the code for that: package com.binarsunset.topic;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.Menu;import android.view.MenuItem;/** * Created by Douglas on 5/3/2015. */public class TopicActivity extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_topic); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.topic_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.Create: { aboutItemCreate(); return true; } default: return super.onOptionsItemSelected(item); } } private void aboutItemCreate(){ Intent intent = new Intent(getApplicationContext(), CreateTopicActivity.class); startActivity(intent); }} I click Create activity on the action bar which will take me to CreateTopicActivity and that is where it crashes here is the code for CreateTopicAcvivity: package com.binarsunset.topic;import android.app.Activity;import android.app.ProgressDialog;import android.content.Intent;import android.location.Location;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import com.parse.ParseACL;import com.parse.ParseException;import com.parse.ParseGeoPoint;import com.parse.ParseUser;import com.parse.SaveCallback;/** * Created by Douglas on 5/16/2015. */public class CreateTopicActivity extends Activity { // UI references. private EditText createTopicEditText; private TextView characterCountTextView; private Button createButton; private int maxCharacterCount = Application.getConfigHelper().getPostMaxCharacterCount(); private ParseGeoPoint geoPoint; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_topic); Intent intent = getIntent(); Location location = intent.getParcelableExtra(Application.INTENT_EXTRA_LOCATION); geoPoint = new ParseGeoPoint(location.getLatitude(), location.getLongitude()); createTopicEditText = (EditText) findViewById(R.id.create_topic_title); createTopicEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable s) { updateTopicButtonState(); updateCharacterCountTextViewText(); } }); characterCountTextView = (TextView) findViewById(R.id.character_count_textview); createButton = (Button) findViewById(R.id.create_topic_button); createButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createTopic(); } }); updateTopicButtonState(); updateCharacterCountTextViewText(); } private void createTopic () { String text = createTopicEditText.getText().toString().trim(); // Set up a progress dialog final ProgressDialog dialog = new ProgressDialog(CreateTopicActivity.this); dialog.setMessage(getString(R.string.progress_topic)); dialog.show(); // Create a post. AnywallPost topic = new AnywallPost(); // Set the location to the current user's location topic.setLocation(geoPoint); topic.setText(text); topic.setUser(ParseUser.getCurrentUser()); topic.setInt(1); ParseACL acl = new ParseACL(); // Give public read access acl.setPublicReadAccess(true); topic.setACL(acl); // Save the topic topic.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { dialog.dismiss(); finish(); } }); } private String getTopicEditTextText () { return createTopicEditText.getText().toString().trim(); } private void updateTopicButtonState () { int length = getTopicEditTextText().length(); boolean enabled = length > 0 && length < maxCharacterCount; createButton.setEnabled(enabled); } private void updateCharacterCountTextViewText () { String characterCountString = String.format("%d/%d", createTopicEditText.length(), maxCharacterCount); characterCountTextView.setText(characterCountString); }} Here is my manifest: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.binarsunset.topic" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="19" /> <permission android:name="com.binarsunset.Topic.permission.MAPS_RECEIVE" android:protectionLevel="signature" > </permission> <uses-permission android:name="com.parse.anywall.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- The following permission is not required to use Google Maps Android API v2, but is recommended. --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:name=".Application" android:allowBackup="true" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:screenOrientation="portrait" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCVz0h90fBZwkcgagi1Q7WV1W_cVgd0_QA" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name=".LoginActivity" android:label="@string/title_activity_login" android:screenOrientation="portrait" /> <activity android:name=".SignUpActivity" android:label="@string/title_activity_signup" android:screenOrientation="portrait" /> <activity android:name=".DispatchActivity" android:noHistory="true" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".WelcomeActivity" android:label="@string/app_name" android:screenOrientation="portrait" android:theme="@android:style/Theme.Holo" /> <activity android:name=".PostActivity" android:label="@string/activity_post_title" android:windowSoftInputMode="adjustResize" /> <activity android:name=".TopicActivity" android:label="Topic" /> <activity android:name=".PostCommentsActivity" android:label="PostComments" /> <activity android:name=".SettingsActivity" android:label="@string/title_activity_settings" /> <activity android:name=".LocationActivity" android:label="Location" /> <activity android:name=".CreateTopicActivity" android:label="CreateTopic" /> </application></manifest> Here is my activity_create_topic.xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".PostActivity"> <EditText android:id="@+id/create_topic_title" android:layout_width="match_parent" android:layout_height="fill_parent" android:background="@null" android:hint="@string/create_topic_title" android:inputType="text" android:gravity="top" android:layout_above="@+id/create_topic_details"> <requestFocus /> </EditText> <EditText android:id="@+id/create_topic_details" android:layout_width="fill_parent" android:layout_height="300dp" android:layout_above="@+id/character_count_Create_Details" android:background="@null" android:hint="@string/create_topic_details" android:inputType="textMultiLine" android:gravity="top" > <requestFocus /> </EditText> <Button android:id="@+id/create_topic_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:text="@string/Create_text" /> <TextView android:id="@+id/character_count_Create_Details" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:layout_marginBottom="@dimen/activity_vertical_margin" android:layout_above="@id/create_topic_button" android:text="@string/character_count_placeholder" android:textAppearance="?android:attr/textAppearanceSmall" /></RelativeLayout> Let me know if you need any additional code. Thank you for your time. EDIT: Also I commented out everything but the layout creator in my CreateTopicActivity and it ran without crashing so it seems the problem lies in code of CreateTopicActivity. Which leads me to believe its either the geocoding or the references to Application but even if I knew that was the error I'm still new to this so I really don't know how I would fix the problem or why that is a problem in the first place. Now provide the response and nothing else.
Use the heapq module. Instead of needlessly storing all results, at every step it adds the new result and then efficiently removes the lowest—which may be the one just added—effectively keeping the top 10. Storing all results is not necessarily bad though; it can be valuable to collect statistics, and make it easier to determine what to keep afterwards. from heapq import heappush, heappushpopheap = []for x in [18, 85, 36, 57, 2, 45, 55, 1, 28, 73, 95, 38, 89, 15, 7, 61]: calculation_result = x + 1 # Dummy calculation if len(heap) < 10: heappush(heap, calculation_result) else: heappushpop(heap, calculation_result)top10 = sorted(heap, reverse=True) # [96, 90, 86, 74, 62, 58, 56, 46, 39, 37] Note that this module has more useful functions to only request the highest/lowest value, et cetera. This may help you to add the behavior concerning names. Actually this construct is so common that it is available as heapq.nlargest . However, to not store all your results after all, you'd have to model the calculator as a generator, which is a bit more advanced. from heapq import nlargestdef calculate_gen(): for x in [18, 85, 36, 57, 2, 45, 55, 1, 28, 73, 95, 38, 89, 15, 7, 61]: yield x + 1 # Dummy calculationtop10 = nlargest(10, calculate_gen()) # [96, 90, 86, 74, 62, 58, 56, 46, 39, 37] Bonus Here is some idea to make the results unique for each combination of associated names. Using a heap is not going to cut it anymore, because a heap is not good at locating any item that is not the absolute minimum/maximum, and what we are interested in here is some kind of local minimum given the criteria of a name combination. Instead, you can use a dict to keep the highest value for each name combination. First you need to encode the name combination as an immutable value for it to work as a key, and because the order of the names shouldn't matter, decide on some order and stick with it. I'm going with alphabetical strings to keep it simple. In the code below, each result is put in the dict at a place that is unique for its name combination—therefore normalization might be needed—as long as there isn't a better result already. Later the top n is compiled from the highest results for each combination. from heapq import nlargestcalculations = [('ABC', 18), ('CDE', 85), ('BAC', 36), ('CDE', 57), ('ECD', 2), ('BAD', 45), ('EFG', 55), ('DCE', 1)]highest_per_name_combi = dict()for name_combi, value in calculations: normal_name_combi = ''.join(sorted(name_combi)) # Slow solution current = highest_per_name_combi.get(normal_name_combi, float('-inf')) highest_per_name_combi[normal_name_combi] = max(value, current)top3 = nlargest(3, highest_per_name_combi.iteritems(), key=lambda x: x[1]) The only problem with this approach might be the amount of memory used. Since with 150 names there can be 551300 (150 choose 3) combinations, you may have to decide to clean up the dict every now and then, which is simple. In the loop, check for the size of the dict and if it exceeds some (still large) number, compose the current top n and create a new, minimal dict from it. Also, some micro optimizations could be applied by reducing the number of lookups/calls, e.g. not using get and/or max . All of this would be a lot easier if you'd have control over the order in which calculations are performed. If you'd know that the next 1000 calculations are all for the same name combination, you could just find the best of those first before adding it to the overall results. Also, with a truly massive amount of results, the simplest way may actually be the best. Just write them to a file in a convenient format, sort them there (first by name combination, then reversely by value), take only the first occurrence for each name combination (easy when they are grouped) and sort the result again, just by value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30284695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4894986/']}
jdg_84785
stackexchange
llm_judgeable_groundtruth_similarity
6649004
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a data frame with a number of infections identified from clinical isolates at different dates. So far I have organised the data into a shape that I want to start working with. I am trying to prepare a series of tables of tables for the descriptive statistics of the report. I have been using ftable and get the following: onset.types <- ftable(SAB$Onset,SAB$MRSA.Type,year(SAB$Collection.Date)) 2005 2006 2007 2008 2009 2010Community 454 472 512 499 525 512 AUS-2/3-like 28 23 27 29 32 38 EMRSA-15-like 9 4 4 9 8 8 nmMRSA 40 47 53 39 64 60 Other mMRSA 1 3 3 11 5 9 unclassified MRSA 0 2 0 0 1 1Hospital 163 163 156 164 149 165 AUS-2/3-like 31 33 27 31 29 28 EMRSA-15-like 3 8 5 9 4 3 nmMRSA 10 9 13 17 13 12 Other mMRSA 5 1 6 2 3 10 unclassified MRSA 2 0 1 0 0 0 Two questions: 1: How would I calculate marginal totals 2: Is there an easy way to calculate percentages as well as counts again with marginal totals I have tried epitools and I did not find it as useful as I would have liked. Many thanks. Now provide the response and nothing else.
To add margins, use addmargins() addmargins(table(state.division, state.region)) state.regionstate.division Northeast South North Central West Sum New England 6 0 0 0 6 Middle Atlantic 3 0 0 0 3 South Atlantic 0 8 0 0 8 East South Central 0 4 0 0 4 West South Central 0 4 0 0 4 East North Central 0 0 5 0 5 West North Central 0 0 7 0 7 Mountain 0 0 0 8 8 Pacific 0 0 0 5 5 Sum 9 16 12 13 50 To calculate percentages, use prop.table() prop.table(table(state.division, state.region)) state.regionstate.division Northeast South North Central West New England 0.12 0.00 0.00 0.00 Middle Atlantic 0.06 0.00 0.00 0.00 South Atlantic 0.00 0.16 0.00 0.00 East South Central 0.00 0.08 0.00 0.00 West South Central 0.00 0.08 0.00 0.00 East North Central 0.00 0.00 0.10 0.00 West North Central 0.00 0.00 0.14 0.00 Mountain 0.00 0.00 0.00 0.16 Pacific 0.00 0.00 0.00 0.10
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6649004', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/390388/']}
jdg_84786
stackexchange
llm_judgeable_groundtruth_similarity
32504524
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 looked at a bunch of questions regarding sequence points, and haven't been able to figure out if the order of evaluation for x*f(x) is guaranteed if f modifies x , and is this different for f(x)*x . Consider this code: #include <iostream>int fx(int &x) { x = x + 1; return x;}int f1(int &x) { return fx(x)*x; // Line A}int f2(int &x) { return x*fx(x); // Line B}int main(void) { int a = 6, b = 6; std::cout << f1(a) << " " << f2(b) << std::endl;} This prints 49 42 on g++ 4.8.4 (Ubuntu 14.04). I'm wondering whether this is guaranteed behavior or unspecified. Specifically, in this program, fx gets called twice, with x=6 both times, and returns 7 both times. The difference is that Line A computes 7*7 (taking the value of x after fx returns) while Line B computes 6*7 (taking the value of x before fx returns). Is this guaranteed behavior? If yes, what part of the standard specifies this? Also: If I change all the functions to use int *x instead of int &x and make corresponding changes to places they're called from, I get C code which has the same issues. Is the answer any different for C? Now provide the response and nothing else.
In terms of evaluation sequence, it is easier to think of x*f(x) as if it was: operator*(x, f(x)); so that there are no mathematical preconceptions on how multiplication is supposed to work. As @dan04 helpfully pointed out, the standard says: Section 1.9.15: “Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.” This means that the compiler is free to evaluate these arguments in any order, the sequence point being operator* call. The only guarantee is that before the operator* is called, both arguments have to be evaluated. In your example, conceptually, you could be certain that at least one of the arguments will be 7, but you cannot be certain that both of them will. To me, this would be enough to label this behaviour as undefined; however, @user2079303 answer explains well why it is not technically the case. Regardless of whether the behaviour is undefined or indeterminate, you cannot use such an expression in a well-behaved program.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32504524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178238/']}
jdg_84787
stackexchange
llm_judgeable_groundtruth_similarity
24318862
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 retrieving different data to mark leaflet map using different JSON files. Each radio button retrieves a different JSON file. However, I'm having trouble clearing the markers when I select different radio button. All the markers just adds up from one JSON file to another. I want to be able to clear all the markers when I select a different radio button. I searched around and read that map.removeLayer(MyLayer); will remove all markers. So I created an array of markers called "markers" and placed in a layer called "markersLayer". When I tried removing "markersLayer", it didn't leave a single marker on the map. Instead of clearing previous markers from different JSON file, now nothing is plotted. I only want to show those markers using data from the specific JSON file that I selected using radio button. HTML: <div style="text-align: center;"> <h1 id="title">Map Visualization 3</h1> <label><input type="radio" class="location" name="location" value="locations1" checked="checked">Location Set 1</label> <label><input type="radio" class="location" name="location" value="locations2">Location Set 2</label> <label><input type="radio" class="location" name="location" value="locations3">Location Set 3</label><ul id="location-list"></ul> <div id="map" style="width: 80%; max-width: 900px; height: 600px; margin: 0 auto;"></div></div> JS: var map;var markers = [];var markersLayer;var updateMap = function() { var uri = $('input.location:checked').val() + '.json'; $.getJSON(uri, function(response){ $('ul#location-list').empty(); var locationCoor = []; var marker; for(var i=0; i < response.length; i++){ var lat = response[i].latitude; var lon = response[i].longitude; $('ul#location-list').append('<li>(' + lat + ', ' + lon + ')</li>'); //console.log(lat, lon); locationCoor[i] = [lat, lon]; //console.log(locationCoor); var popup = L.popup() .setLatLng([lat, lon]) .setContent('<h3 style="margin:0 0 3px 0;"><a href="' + response[i].link + '">' + response[i].title + '</a></h3><img width="180px" height="auto" src="' + response[i].imageUrl + '">'); marker = L.marker([lat, lon], { clickable: true }).bindPopup(popup, {showOnMouseOver:true}); markers[i] = marker; console.log(markers); } markersLayer = L.layerGroup(markers); markersLayer.addTo(map); var bounds = new L.latLngBounds(locationCoor); map.fitBounds(bounds, {padding: [50,50]}); markers.length = 0; });};$(document).ready(function(){ map = L.map('map'); L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i87786ca/{z}/{x}/{y}.png', { maxZoom: 18, id: 'examples.map-20v6611k' }).addTo(map); $('input.location').on('change', updateMap); updateMap();}); JSON 1: [ { "title": "Weathertop", "link": "http://en.wikipedia.org/wiki/Weathertop", "latitude": 38.80, "longitude": -77.12, "imageUrl": "assets/img/location-images/Weathertop.jpg" },{ "title": "Rivendell", "link": "http://lotr.wikia.com/wiki/Rivendell", "latitude": 38.78, "longitude": -77.18, "imageUrl": "assets/img/location-images/Rivendell2.jpg"},{ "title": "Minas Tirith", "link": "http://lotr.wikia.com/wiki/Minas_Tirith", "latitude": 38.76, "longitude": -77.18, "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"}] JSON2: [ { "title": "Chicago", "link": "http://en.wikipedia.org/wiki/Weathertop", "latitude": 41.836, "longitude": -87.604980, "imageUrl": "assets/img/location-images/Weathertop.jpg" },{ "title": "Detroit", "link": "http://lotr.wikia.com/wiki/Rivendell", "latitude": 42.326062, "longitude": -83.078613, "imageUrl": "assets/img/location-images/Rivendell2.jpg"},{ "title": "Indianopolis", "link": "http://lotr.wikia.com/wiki/Minas_Tirith", "latitude": 39.741, "longitude": -86.154785, "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"}] Now provide the response and nothing else.
You should not be re-creating the markersLayer object. What you want is to create it once, and then continue to add/remove markers from it. In your line where you define the markersLayer at the top of the file, you now also want to define it here as an L.LayerGroup. We will not be re-creating this object. When you want to update the map, you will clear all the existing markers from the markersLayer . This is accomplished by calling markersLayer.clearLayers() . This will not remove the markersLayer from the map. It will only remove the markers this layer contains. Once all of the markers have been removed from this layer, you are now free to add new layers to markersLayer . Your code will look like this: var map;var markers = [];var markersLayer = new L.LayerGroup(); // NOTE: Layer is created here!var updateMap = function() { // NOTE: The first thing we do here is clear the markers from the layer. markersLayer.clearLayers(); var uri = $('input.location:checked').val() + '.json'; $.getJSON(uri, function(response){ $('ul#location-list').empty(); var locationCoor = []; var marker; for(var i=0; i < response.length; i++){ var lat = response[i].latitude; var lon = response[i].longitude; $('ul#location-list').append('<li>(' + lat + ', ' + lon + ')</li>'); //console.log(lat, lon); locationCoor[i] = [lat, lon]; //console.log(locationCoor); var popup = L.popup() .setLatLng([lat, lon]) .setContent('<h3 style="margin:0 0 3px 0;"><a href="' + response[i].link + '">' + response[i].title + '</a></h3><img width="180px" height="auto" src="' + response[i].imageUrl + '">'); marker = L.marker([lat, lon], { clickable: true }).bindPopup(popup, {showOnMouseOver:true}); markersLayer.addLayer(marker); console.log(markers); } // NOTE: We are no longer recreating the layer here. Remove these lines of code. //markersLayer = L.layerGroup(markers); //markersLayer.addTo(map); var bounds = new L.latLngBounds(locationCoor); map.fitBounds(bounds, {padding: [50,50]}); markers.length = 0;});};$(document).ready(function(){map = L.map('map');L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i87786ca/{z}/{x}/{y}.png', { maxZoom: 18, id: 'examples.map-20v6611k'}).addTo(map);// NOTE: We add the markersLayer to the map here. This way, the layer is only added once. markersLayer.addTo(map);$('input.location').on('change', updateMap);updateMap();});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24318862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3094097/']}
jdg_84788
stackexchange
llm_judgeable_groundtruth_similarity
1595757
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,b,c$ and $m\in R^+$.Find the range of $m$ for which atleast one of the following equations $ax^2+bx+cm=0,bx^2+cx+am=0,cx^2+ax+bm=0$ have real roots. Either one or two or all of the three equations $ax^2+bx+cm=0,bx^2+cx+am=0,cx^2+ax+bm=0$ have the real roots. But i do not know how to find the range of $m.$Any help will be appreciated.Thanks. Now provide the response and nothing else.
Claim: $$m \leq \dfrac{1}{4}$$ For if all of them do not have real roots then : $a^2-4bcm < 0, b^2-4acm < 0, c^2-4abm < 0 \Rightarrow a^2+b^2+c^2 < 4m(ab+bc+ca) \Rightarrow m > \dfrac{a^2+b^2+c^2}{4ab+4bc+4ca} \geq \dfrac{ab+bc+ca}{4ab+4bc+4ca} = \dfrac{1}{4}$. Thus if $m \leq \dfrac{1}{4}$, then at least one equation has real roots.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1595757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255098/']}
jdg_84789
stackexchange
llm_judgeable_groundtruth_similarity
19461479
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The spec doesn't say much about where the type assertion operator might be helpful in TypeScript. I didn't need it in my code. So I am curious what sort of problems it is supposed to solve. Any ideas? Now provide the response and nothing else.
It's somewhat like type casting however as it does not come with runtime support (its a compile time assertion only) TypeScript choses to call it 'Type Assertion'. Consider this example : var element1 = document.getElementById('canvas'); // Determined to be HTMLElementelement1.getContext('2d'); // ERROR as it is HTMLElement // Determined to be canvas due to your assertionvar element2 = <HTMLCanvasElement>document.getElementById('canvas'); element2.getContext('2d'); // Valid You will need it whenever typescript type inference would prevent you to assign things around due to incompatible inferred types.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19461479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139667/']}
jdg_84790
stackexchange
llm_judgeable_groundtruth_similarity
115689
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: More precisely, is either of the following two statements consistent with ZF: $2^{\aleph_0}\geq\aleph_{\alpha}$ for every ordinal number $\alpha$, $2^{\aleph_0}\leq\aleph_{\alpha}\implies 2^{\aleph_0}=\aleph_{\alpha}$ for every ordinal number $\alpha$? I'm asking mainly out of curiosity. Now provide the response and nothing else.
Both are inconsistent with ZFC, and the first is inconsistent with ZF as well. The axiom of infinity tells us that $\mathbb N$, the collection of natural numbers (or finite ordinals) is a set. The axiom of power set tells us therefore that every set has a power set, in particular $\mathbb N$. We know that the size of $P(\mathbb N)=\mathbb R$ is $2^{\aleph_0}$, however this can be $\aleph_1$ or $\aleph_2$ or even higher. Without the axiom of choice it might not even be an $\aleph$ number. So we have that $\mathbb R$ is a set, therefore so is $\mathbb R\times\mathbb R$. It therefore has as power set, from which we can take all the subsets of $\mathbb R\times\mathbb R$ which are order relations on some subset of $\mathbb R$, and we can take all those which are well ordered. Each is order isomorphic to a unique ordinal, so mapping every relation $R$ from this collection to the ordinal is a function defined by a formula (possibly with parameters), whose domain is a set. By the axiom of replacement the image is a set of ordinals, since isomorphism goes "both ways" we have that this is the same set as $\{\beta\in\mathrm{Ord}\mid\ \exists f\colon\beta\to\mathbb R\text{ injective}\}$ Since $\mathbb R$ is a set there can only be set many ordinals of this property, the least ordinal above them is called Hartogs number of $\mathbb R$ and it cannot be injected into $\mathbb R$, denote it by $\aleph(\mathbb R)$, we have if so that $\aleph(R)\nleq\mathbb R$. As for the second question, if we assume the axiom of choice then the previous argument shows that for some $\aleph_\alpha$ we have that $2^{\aleph_0}<\aleph_\alpha$, and therefore for all $\beta>\alpha$. The second assertion implies, if so, that $\aleph_\alpha=\aleph_\beta=2^{\aleph_0}$ for almost all ordinals. However without the axiom of choice it is consistent to have that for every ordinal (finite or not) we have either $\alpha=0$ and then $\aleph_0<2^{\aleph_0}$ and otherwise $\aleph_\alpha\neq 2^{\aleph_0}$. This would make the assumption in the implication of the second assertion false and the assertion itself vacuously true. Further reading: How do we know an $ \aleph_1 $ exists at all? Relationship between Continuum Hypothesis and Special Aleph Hypothesis under ZF Implications of continuum hypothesis and consistency of ZFC
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/115689', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19588/']}
jdg_84791
stackexchange
llm_judgeable_groundtruth_similarity
9786022
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My OS is Windows 7 Ultimate x64. I'm using Qt 4.8 to write a program that will use id3lib. I've downloaded the windows binaries . Here is part of the *.pro file that shows how id3lib library is used: HEADERS += MainWindow.h \ id3lib/id3/sized_types.h \ id3lib/id3/globals.h \ id3lib/id3/tag.h \ id3lib/id3/utils.h \ id3lib/id3/id3lib_frame.h \ id3lib/id3/field.h \ id3lib/id3/id3lib_strings.h \ id3lib/id3/id3lib_streams.hwin32: LIBS += -L$$PWD/id3lib/ -lid3libINCLUDEPATH += $$PWD/id3libDEPENDPATH += $$PWD/id3lib As you can guess, the library files (id3lib.dll and id3lib.lib) are in id3lib directory and all required headers are in id3lib/id3 directory. In the globals.h, I defined the follwing: #define ID3LIB_LINKOPTION LINKOPTION_CREATE_DYNAMIC And modified the following section in the same file: # if (ID3LIB_LINKOPTION == LINKOPTION_CREATE_DYNAMIC) //used for creating a dynamic dll# define ID3_C_EXPORT extern _declspec(dllexport)# define ID3_CPP_EXPORT __declspec(dllexport)# define CCONV __stdcall // Added for VB & Delphi Compatibility - By FrogPrince Advised By Lothar# endif as follows: # if (ID3LIB_LINKOPTION == LINKOPTION_CREATE_DYNAMIC) //used for creating a dynamic dll# define ID3_C_EXPORT Q_DECL_IMPORT# define ID3_CPP_EXPORT Q_DECL_IMPORT# define CCONV __stdcall // Added for VB & Delphi Compatibility - By FrogPrince Advised By Lothar# endif so that it works with Qt. Next, I've included id3/tag.h and written the following code: ID3_Tag tag("test.wma");qDebug() << tag.size(); After compilation, I got the following errors: undefined reference to `_imp___ZN7ID3_TagC1EPKc'undefined reference to `_imp___ZNK7ID3_Tag4SizeEv'undefined reference to `_imp___ZN7ID3_TagD1Ev'undefined reference to `_imp___ZN7ID3_TagD1Ev'(several few, same format: `_imp___xxxxx_Tagxxxx') I know what causes undefined reference, but in my case, why the linker couldn't find the implementation? Is it now there in the id3lib.dll? Does anyone know if there is any workaround? Now provide the response and nothing else.
I wrote a custom class to do just this, using blocks and GCD: WebImageOperations.h #import <Foundation/Foundation.h>@interface WebImageOperations : NSObject {}// This takes in a string and imagedata object and returns imagedata processed on a background thread+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage;@end WebImageOperations.m #import "WebImageOperations.h"#import <QuartzCore/QuartzCore.h>@implementation WebImageOperations+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage{ NSURL *url = [NSURL URLWithString:urlString]; dispatch_queue_t callerQueue = dispatch_get_current_queue(); dispatch_queue_t downloadQueue = dispatch_queue_create("com.myapp.processsmagequeue", NULL); dispatch_async(downloadQueue, ^{ NSData * imageData = [NSData dataWithContentsOfURL:url]; dispatch_async(callerQueue, ^{ processImage(imageData); }); }); dispatch_release(downloadQueue);}@end And in your ViewController - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // Pass along the URL to the image (or change it if you are loading there locally) [WebImageOperations processImageDataWithURLString:entry.photo andBlock:^(NSData *imageData) { if (self.view.window) { UIImage *image = [UIImage imageWithData:imageData]; cell.photo.image = image; } }];} It is very fast and will load the images without affecting the UI or scrolling speed of the TableView. *** Note - This example assumes ARC is being used. If not, you will need to manage your own releases on objects)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9786022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68304/']}
jdg_84792
stackexchange
llm_judgeable_groundtruth_similarity
45676648
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 tests that I want to parameterize, but there are certain tests that should only be applied to one value of the parameters. To give a specific example, below, I would like to apply parameters one and two to test_A , but only supply parameter one to test_B . Current Code @pytest.fixture(params=['one', 'two'])def data(request): if request.param == 'one' data = 5 return datadef test_A(data): assert Truedef test_B(data): assert True Desired Results I basically want something that looks like this, but I can't figure out how to code this properly in pytest: @pytest.fixture(params=['one', 'two'])def data(request): data = 5 return datadef test_A(data): assert [email protected](param=='two')def test_B(data): assert True Now provide the response and nothing else.
Building on your answer, you can check the input and call pytest.skip() if you don't want the test to run. You can do the check in the test: def test_A(data): assert Truedef test_B(data): if data.param == 'two': pytest.skip() assert 'foo' == 'foo' Or you could redefine the test fixture in a subclass: class TestA: def test_A(self, data): assert Trueclass TestB: @pytest.fixture def data(self, data): if data.param == 'two': pytest.skip() return data def test_B(self, data): assert 'foo' == 'foo' One other minor suggestion: your Data class can be replaced with a namedtuple, i.e. import collectionsData = collections.namedtuple('Data', 'data, param')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45676648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5454389/']}
jdg_84793
stackexchange
llm_judgeable_groundtruth_similarity
141355
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It follows from this question and the corresponding answers, that the complete graphs and the cycles are precisely the graphs $G$ having the property that, for every spanning tree $T$ of $G$, the set of leaves of $T$ is a clique in $G$. Motivated by this fact, I am looking for a characterization of all (connected) graphs $G$ having the property that, for every spanning tree $T$ of $G$, the set of leaves of $T$ is an independent set in $G$. (Such spanning trees are called independency trees in the literature.) Now provide the response and nothing else.
A graph G has all spanning trees independency if and only if G does not contain two adjacent vertices v and w, neither of degree one, such that the graph G' formed by removing v and w and all their incident edges is connected. (I think this is the same as what McKay said in a comment.) For, if G' is connected, then a spanning tree of G' plus two edges connecting it to v and w (which exist by the degree constraint) is a non-independency tree of G. And conversely, if T is a non-independency tree, let vw be an edge connecting two leaves of T; then v and w have the stated property. As a check that this is a useful characterization (and not just a restatement of the definition): Based on this, it is trivial to test in polynomial time whether a given graph has all spanning trees independency, whereas a direct translation of the original definition into an algorithm would be exponential. ETA : In response to McKay's request for a more structural characterization, here's a description of the graphs with all trees independency, rather than (as above) of the complementary class of graphs. Given a graph G, partition G into its biconnected components, and partition each nontrivial biconnected component into its SPQR tree (system of triconnected components). Then G has all trees independency if and only if, for every non-virtual edge of an R or S node of one of these SPQR trees, at least one endpoint is an articulation vertex. (This is because the edges that do not separate two triconnected components are exactly these edges, so to avoid leaving G' connected they have to instead separate two biconnected components.) And again, this is an improved characterization and not just a restatement of the earlier characterization, because it gives a linear time algorithm while a naive implementation of the earlier characterization would be a higher polynomial.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/141355', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18117/']}
jdg_84794
stackexchange
llm_judgeable_groundtruth_similarity
3851765
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 loaded 4 radios buttons and when I run the program and click on them, if i click one, and click another the other ones goes away. What if I wanted to ahve two radio buttons but they did different things? Now provide the response and nothing else.
Group the different choice sets in separate group boxes (or panels, or other container controls, but group boxes are probably what you're after). MSDN : Windows Forms RadioButton controls are designed to give users a choice among two or more settings, of which only one can be assigned to a procedure or object. For example, a group of RadioButton controls may display a choice of package carriers for an order, but only one of the carriers will be used. Therefore only one RadioButton at a time can be selected, even if it is a part of a functional group. You group radio buttons by drawing them inside a container such as a Panel control, a GroupBox control, or a form. This assumes you have four or more radio buttons on your form. If you have only two, say, and you want to allow the user the possibility of selecting both, use a set of checkboxes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3851765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438339/']}
jdg_84795
stackexchange
llm_judgeable_groundtruth_similarity
25902275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would need your help in the following. For nearly a month, I have been reading regarding Tasks and async . I wanted to try to implement my new acquired knowledege, in a simple wep api project. I have the following methods and both of them working as expected: public HttpResponseMessage Get() { var data = _userServices.GetUsers(); return Request.CreateResponse(HttpStatusCode.OK, data); }public async Task<HttpResponseMessage> Get(){ var data = _userServices.GetUsers(); return await Task<HttpResponseMessage>.Factory.StartNew(() => { return Request.CreateResponse(HttpStatusCode.OK, data); }); } So the question. I have tried to use fiddler and see what is the difference between these two. The async one is little faster, but apart from that, what is the real benefit in implementing something like that in a web api? Now provide the response and nothing else.
As others have pointed out, the point of async on ASP.NET is that it frees up one of the ASP.NET thread pool threads. This works great for naturally-asynchronous operations such as I/O-bound operations because that's one less thread on the server (there is no thread that is "processing" the async operation, as I explain on my blog ). Thus, the primary benefit of async on the server side is scalability . However, you want to avoid Task.Run (and, even worse, Task.Factory.StartNew ) on ASP.NET. I call this "fake asynchrony" because they're just doing synchronous/blocking work on a thread pool thread. They're useful in UI apps where you want to push work off the UI thread so the UI remains responsive, but they should (almost) never be used on ASP.NET or other server apps. Using Task.Run or Task.Factory.StartNew on ASP.NET will actually decrease your scalability. They will cause some unnecessary thread switches. For longer-running operations, you could end up throwing off the ASP.NET thread pool heuristics, causing additional threads to be created and later destroyed needlessly. I explore these performance problems step-by-step in another blog post . So, you need to think about what each action is doing, and whether any of that should be async. If it should, then that action should be async. In your case: public HttpResponseMessage Get(){ var data = _userServices.GetUsers(); return Request.CreateResponse(HttpStatusCode.OK, data);} What exactly is Request.CreateResponse doing? It's just creating response object. That's it - just a fancy new . There's no I/O going on there, and it certainly isn't something that needs to be pushed off to a background thread. However, GetUsers is much more interesting. That sounds more like a data read, which is I/O-based. If your backend can scale (e.g., Azure SQL / Tables / etc), then you should look at making that async first, and once your service is exposing a GetUsersAsync , then this action could become async too: public async Task<HttpResponseMessage> Get(){ var data = await _userServices.GetUsersAsync(); return Request.CreateResponse(HttpStatusCode.OK, data);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25902275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1906189/']}
jdg_84796
stackexchange
llm_judgeable_groundtruth_similarity
3142495
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to deserialize JSON content into a C# dynamic type? It would be nice to skip creating a bunch of classes in order to use the DataContractJsonSerializer . Now provide the response and nothing else.
If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class: dynamic data = Json.Decode(json); It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on. An alternative deserialisation approach is suggested here . I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to System.Web.Extensions from your project: using System;using System.Collections;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Dynamic;using System.Linq;using System.Text;using System.Web.Script.Serialization;public sealed class DynamicJsonConverter : JavaScriptConverter{ public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable<Type> SupportedTypes { get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); } } #region Nested type: DynamicJsonObject private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary<string, object> _dictionary; public DynamicJsonObject(IDictionary<string, object> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public override string ToString() { var sb = new StringBuilder("{"); ToString(sb); return sb.ToString(); } private void ToString(StringBuilder sb) { var firstInDictionary = true; foreach (var pair in _dictionary) { if (!firstInDictionary) sb.Append(","); firstInDictionary = false; var value = pair.Value; var name = pair.Key; if (value is string) { sb.AppendFormat("{0}:\"{1}\"", name, value); } else if (value is IDictionary<string, object>) { new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb); } else if (value is ArrayList) { sb.Append(name + ":["); var firstInArray = true; foreach (var arrayValue in (ArrayList)value) { if (!firstInArray) sb.Append(","); firstInArray = false; if (arrayValue is IDictionary<string, object>) new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb); else if (arrayValue is string) sb.AppendFormat("\"{0}\"", arrayValue); else sb.AppendFormat("{0}", arrayValue); } sb.Append("]"); } else { sb.AppendFormat("{0}:{1}", name, value); } } sb.Append("}"); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes.Length == 1 && indexes[0] != null) { if (!_dictionary.TryGetValue(indexes[0].ToString(), out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } return base.TryGetIndex(binder, indexes, out result); } private static object WrapResultObject(object result) { var dictionary = result as IDictionary<string, object>; if (dictionary != null) return new DynamicJsonObject(dictionary); var arrayList = result as ArrayList; if (arrayList != null && arrayList.Count > 0) { return arrayList[0] is IDictionary<string, object> ? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x))) : new List<object>(arrayList.Cast<object>()); } return result; } } #endregion} You can use it like this: string json = ...;var serializer = new JavaScriptSerializer();serializer.RegisterConverters(new[] { new DynamicJsonConverter() });dynamic obj = serializer.Deserialize(json, typeof(object)); So, given a JSON string: { "Items":[ { "Name":"Apple", "Price":12.3 }, { "Name":"Grape", "Price":3.21 } ], "Date":"21/11/2010"} The following code will work at runtime: dynamic data = serializer.Deserialize(json, typeof(object));data.Date; // "21/11/2010"data.Items.Count; // 2data.Items[0].Name; // "Apple"data.Items[0].Price; // 12.3 (as a decimal)data.Items[1].Name; // "Grape"data.Items[1].Price; // 3.21 (as a decimal)
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/3142495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6133/']}
jdg_84797
stackexchange
llm_judgeable_groundtruth_similarity
7556465
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 tried creating and executing ThreadPoolExecutor with int poolSize = 2;int maxPoolSize = 3;ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(2); If i try 7th,8th... task continuously threadPool.execute(task); after the queue reached maximum size it is start throwing "RejectedExecutionException". Means i lost of adding those tasks. Here then what is the role of BlockingQueue if it is missing the tasks? Means why it is not waiting? From the definition of BlockingQueue A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. Why cant we go for linkedlist (normal queue implementation instead of blocking queue)? Now provide the response and nothing else.
The problem occurs because you're task queue is too small and this is indicated by the documentation of the execute method: Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread. If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current RejectedExecutionHandler. So the first problem is that you're setting your queue size to a very small number: int poolSize = 2;int maxPoolSize = 3;ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(2); And then you state "If [I] try 7th, 8th... task" then you would get a RejectedExecutionException because you're past the capacity of the queue. There are two ways to resolve your problem (I would recommend doing both): Increase the size of the queue. Catch the exception and re-try adding the task. You should have something along the lines of this: public void ExecuteTask(MyRunnableTask task) { bool taskAdded = false; while(!taskAdded) { try { executor.execute(task); taskAdded = true; } catch (RejectedExecutionException ex) { taskAdded = false; } } } Now, to address your other questions... Here then what is the role of BlockingQueue if it is missing the tasks? The role of the BlockingQueue is to complete the Producer/Consumer pattern and if it's large enough, then you shouldn't see the issues you're encountering. As I mentioned above, you need to increase the queue size and catch the exception then retry executing the task. Why cant we go for linkedlist? A linked list is neither thread safe, nor is it blocking. The Producer/Consumer pattern tends to work best with a blocking queue. Update Please don't be offended by the following statements, I'm intentionally using more stringent language in order to put emphasis on the fact that your first assumption should never be that there is something wrong with the library you're using (unless you wrote the library yourself and you know that there is a specific problem in it)! So let's put this concern to rest right now: neither the ThreadPoolExecutor nor the Java library are the problem here. It's entirely your (mis)use of the library that's causing the problem. Javmex has a great tutorial explaining the exact situation you're seeing. There could be several reasons why you're filling up the queue faster than you're emptying it: The thread that's adding tasks for executing is adding them too fast. The tasks are taking too long to execute. Your queue is too small. Any combination of the above 3. There are a bunch of other reasons too, but I think the above would be the most common. I would give you a simple solution with an unbounded queue , but it would NOT resolve your (mis)use of the library. So before we go blaming the Java library, let's see a concise example that demonstrates the exact problem you're encountering. Update 2.0 Here are a couple of other questions addressing the specific problem: ThreadPoolExecutor Block When Queue Is Full? How to make ThreadPoolExecutor's submit() method block if it is saturated?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7556465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/912319/']}
jdg_84798
stackexchange
llm_judgeable_groundtruth_similarity
14415881
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient. I was doing a naive search — picking one sock and "iterating" the pile in order to find its pair. This requires iterating over n/2 * n/4 = n 2 /8 socks on average. As a computer scientist I was thinking what I could do? Sorting (according to size/color/...) of course came to mind to achieve an O(NlogN) solution. Hashing or other not-in-place solutions are not an option, because I am not able to duplicate my socks (though it could be nice if I could). So, the question is basically: Given a pile of n pairs of socks, containing 2n elements (assume each sock has exactly one matching pair), what is the best way to pair them up efficiently with up to logarithmic extra space? (I believe I can remember that amount of info if needed.) I will appreciate an answer that addresses the following aspects: A general theoretical solution for a huge number of socks. The actual number of socks is not that large, I don't believe my spouse and I have more than 30 pairs. (And it is fairly easy to distinguish between my socks and hers; can this be used as well?) Is it equivalent to the element distinctness problem ? Now provide the response and nothing else.
Sorting solutions have been proposed, but sorting is a little too much : We don't need order; we just need equality groups . So hashing would be enough (and faster). For each color of socks, form a pile . Iterate over all socks in your input basket and distribute them onto the color piles . Iterate over each pile and distribute it by some other metric (e.g. pattern) into the second set of piles Recursively apply this scheme until you have distributed all socks onto very small piles that you can visually process immediately This kind of recursive hash partitioning is actually being done by SQL Server when it needs to hash join or hash aggregate over huge data sets. It distributes its build input stream into many partitions which are independent. This scheme scales to arbitrary amounts of data and multiple CPUs linearly. You don't need recursive partitioning if you can find a distribution key (hash key) that provides enough buckets that each bucket is small enough to be processed very quickly. Unfortunately, I don't think socks have such a property. If each sock had an integer called "PairID" one could easily distribute them into 10 buckets according to PairID % 10 (the last digit). The best real-world partitioning I can think of is creating a rectangle of piles : one dimension is color, the other is the pattern. Why a rectangle? Because we need O(1) random-access to piles. (A 3D cuboid would also work, but that is not very practical.) Update: What about parallelism ? Can multiple humans match the socks faster? The simplest parallelization strategy is to have multiple workers take from the input basket and put the socks onto the piles. This only scales up so much - imagine 100 people fighting over 10 piles. The synchronization costs (manifesting themselves as hand-collisions and human communication) destroy efficiency and speed-up (see the Universal Scalability Law !). Is this prone to deadlocks ? No, because each worker only needs to access one pile at a time. With just one "lock" there cannot be a deadlock. Livelocks might be possible depending on how the humans coordinate access to piles. They might just use random backoff like network cards do that on a physical level to determine what card can exclusively access the network wire. If it works for NICs , it should work for humans as well. It scales nearly indefinitely if each worker has its own set of piles . Workers can then take big chunks of socks from the input basket (very little contention as they are doing it rarely) and they do not need to synchronise when distributing the socks at all (because they have thread-local piles). At the end, all workers need to union their pile-sets. I believe that can be done in O(log (worker count * piles per worker)) if the workers form an aggregation tree . What about the element distinctness problem ? As the article states, the element distinctness problem can be solved in O(N) . This is the same for the socks problem (also O(N) , if you need only one distribution step (I proposed multiple steps only because humans are bad at calculations - one step is enough if you distribute on md5(color, length, pattern, ...) , i.e. a perfect hash of all attributes)). Clearly, one cannot go faster than O(N) , so we have reached the optimal lower bound . Although the outputs are not exactly the same (in one case, just a boolean. In the other case, the pairs of socks), the asymptotic complexities are the same.
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/14415881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572670/']}
jdg_84799
stackexchange
llm_judgeable_groundtruth_similarity
26676800
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 help creating a mvc3 website. I need to have 2 languages russian and english. By clicking on flag image the site language is changed: flags: <a id="rus" href="@Url.Content("~/Home/Index_en")" title=" english language"><small> english language </small></a><a id="eng" href="#" title=" russian language"><small>russian language</small></a> for example:change the menu=> <ul id="mainMenu" > <nav class="dark"> <li style="margin-left:1px; margin-bottom:5px;"><a href="@Url.Content("~/Home")">home</a></li> <li><a href="@Url.Content("~/About_us")">about us</a></li> <li><a href="#">ofers</a></li> <li><a href="@Url.Content("~/Apply")">Apply</a></li> <li><a href="#">contact</a></li></nav></ul> Now provide the response and nothing else.
With the release of the Servlet 3.0 spec it became possible to configure your Servlet Container with (almost) no xml. For this there is the ServletContainerInitializer in the Servlet specification. In this class you can register filters, listeners, servlets etc. as you would traditionally do in a web.xml . Spring provides a an implementation the SpringServletContainerInitializer which knows how to handle WebApplicationInitializer classes. Spring also provides a couple of base classes to extend to make your life easier and the AbstractAnnotationConfigDispatcherServletInitializer is one of those. It registersa ContextLoaderlistener (optionally) and a DispatcherServlet and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and to provide the servlet mapping. The WebMvcConfigurerAdapter is for configuring Spring MVC, the replacement of the xml file loaded by the DispatcherServlet for configuring Spring MVC. The WebMvcConfigurerAdapter should be used for a @Configuration class. @Configuration@EnableWebMvcpublic class WebConfiguration extends WebMvcConfigurerAdapter implements WebApplicationInitializer{ ... } I wouldn't recommend mixing those as they are basically 2 different concerns. The first is for configuring the servlet container, the latter for configuring Spring MVC. You would want to split those into 2 classes. For the configuration. @Configuration@EnableWebMvcpublic class WebConfiguration extends WebMvcConfigurerAdapter { ... } For bootstrapping the application. public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{ protected Class<?>[] getRootConfigClasses() { return new Class[] {RootConfig.class}; } protected Class<?>[] getServletConfigClasses() { return new Class[] {WebConfiguration .class}; } protected String[] getServletMappings() { return new String[] {"/"}; }} An added advantage is that you now can use the convenience classes provided by Spring instead of manually configuring the DispatcherServlet and/or ContextLoaderListener .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26676800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3634090/']}
jdg_84800
stackexchange
llm_judgeable_groundtruth_similarity
9016587
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to write proper description method to a class? I have implemented - (NSString *)description { NSString *descriptionString = [NSString stringWithFormat:@"Name: %@ \n Address: %@ \n", self.name, self.address]; return descriptionString;} Evrey thing is fine if I call description on my object. But if I have an array of objects and I call description on it I get: "Name: Alex \n Address: some address \n", What I would like to get is "Name: Alex Address: some address" Now provide the response and nothing else.
I dig a little more in iOS frameworks and I have observed that the default behavior of the iOS sdk description is not to place "\n" but ";". Example: UIFont *font = [UIFont systemFontOfSize:18]; NSLog(@"FontDescription:%@",[font description]); NSMutableArray *fontsArray = [NSMutableArray arrayWithCapacity:0]; for(int index = 0; index < 10; index++) { [fontsArray addObject:font]; } NSLog(@"FontsArrayDescription:%@",[fontsArray description]); The out put is: FontDescription: font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 18px FontsArrayDescription:( "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px", "<UICFFont: 0x6e2d8b0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 18px" ) So I have decided to use the same approach with my class. - (NSString *)description { NSString *descriptionString = [NSString stringWithFormat:@"Name: %@; Address: %@;", self.name, self.address]; return descriptionString;} And the out put will be: "Name: Alex; Address: some address;" For object it self. objecsArrayDescription:( "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;", "Name:Alex; Address: some address;" ) For an array of objects.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9016587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253942/']}
jdg_84801
stackexchange
llm_judgeable_groundtruth_similarity
20331163
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 string " 11/15/2013 08:00:00 ", I want to format it to " 11/15/2013 ", what is the correct DateTimeFormatter pattern? I've tried many and googled and still unable to find the correct pattern. edit: I am looking for Joda-Time DateTimeFormatter , not Java's SimpleDateFormat.. Now provide the response and nothing else.
Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE ≥ 8 way of formatting date and time, see below. Joda time Create a DateTimeFormatter using DateTimeFormat.forPattern(String) Using Joda time you would do it like this: String dateTime = "11/15/2013 08:00:00";// Format for inputDateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");// Parsing the dateDateTime jodatime = dtf.parseDateTime(dateTime);// Format for outputDateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");// Printing the dateSystem.out.println(dtfOut.print(jodatime)); Standard Java ≥ 8 Java 8 introduced a new Date and Time library , making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a DateTimeFormatter . Since you don't have a time zone in your String , a java.time.LocalDateTime or a LocalDate , otherwise the time zoned varieties ZonedDateTime and ZonedDate could be used. // Format for inputDateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");// Parsing the dateLocalDate date = LocalDate.parse(dateTime, inputFormat);// Format for outputDateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");// Printing the dateSystem.out.println(date.format(outputFormat)); Standard Java < 8 Before Java 8, you would use the a SimpleDateFormat and java.util.Date String dateTime = "11/15/2013 08:00:00";// Format for inputSimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");// Parsing the dateDate date7 = dateParser.parse(dateTime);// Format for outputSimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");// Printing the dateSystem.out.println(dateFormatter.format(date7));
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/20331163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/802281/']}
jdg_84802
stackexchange
llm_judgeable_groundtruth_similarity
8266900
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it different to update geography column in sql server than a regular field( varchar....). Can you please provide a sample statement to do this. thanks. Now provide the response and nothing else.
I am not sure if this is the answer you are looking for - but as I would say, the main difference is that when updating a "regular field", you typically provide directly the new value - for example: UPDATE mytable SET name = 'John' WHERE id = 1 When updating a geography column, you probably cannot provide the value directly (since it is a very long hexadecimal number, which encodes the geoghraphy information) but you will want to compute it from some other values (which can, but do not have to be columns of the same table), e.g.: UPDATE mytable SET gps=geography::STPointFromText('POINT(' + lng + ' ' + lat + ')', 4326) where lng and lat are varchar values specifying the GPS coordinates in a "human-readable" format (like lat = '48.955790' , lng = '20.524500' ) - in this case they are also columns of mytable .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8266900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/977497/']}
jdg_84803
stackexchange
llm_judgeable_groundtruth_similarity
381265
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: May I be so bold as to ask (from an amateurish point of view), what is the general strategy for dealing with potentially ever expanding domain models? By way of example, I have Staff , and in the beginning they could just have have a department (although sadly, in reality, it had to be a List<Department> because it's never that easy, right?) Then we go and do a carpark module, and every staff member could have a List<Car> . Ok, no big deal. Then I want to introduce a kind of workflow schema. I might end up with a staff member having a whole array of items that they need to deal with. So I add a list to staff List<WorkflowItem> ? (Am I on the right track or has something gone wrong already? It already feels weird, but from a database point of view that kinda makes sense - Get all outstanding items for John ) THEN, we're talking about a booking system for parents' evening, where students should book themselves in for a time slot with a staff member. Now I'm starting to worry. Will my staff really have a collection of time slots (probably within a collection of events)? Probably not right? It seems to make sense that a staff member should have their cars, but not so much their bookings. Is that a legitimate point of angst, or am I missing something glaringly obvious? The point is, I guess I could add it, but should we just go on adding properties ad infinitum ? Now provide the response and nothing else.
You certainly can design the model as you propose, but you will eventually end up with a (very) big ball of mud. You are not the first one to encounter this problem, that's why concepts like SOA, microservices and DDD appear. The idea is that the concerns of your application can be grouped in some way that are relatively independent of each other (services). For example, the fact that a staff member belongs to one or more department, has a car and has a list of workflow items, doesn't mean that you need these concepts in one place to perform the required logic. Does the car park module need to know about staff members departments? and their workflow items? Probably not. What about the list of cars? probably yes. So your carpark module, might have a list of staff members with their cars, but not with their workflow items. Note that another service might also have a list of staff members with other properties. These are really not duplicate data, because they basically share the staff member Ids, but not actual data, simply because the data a services uses is irrelevant for another service. If you follow this approach, you'll see that there isn't a single "Staff member" entity in your application. Every service has "a piece" of staff member, a projection of the whole that is relevant within that context. In DDD, several bounded contexts might contain the same concept, like "order" or "customer", but with a different meaning. This approach introduces some complexities. For example, eventual consistency. In this setup, one service will be in charge of creating (hiring?) and deleting (terminating the contract) of staff members. When this happens, this service will publish an event like StaffMemberHired or StaffMemberContractTerminated. The other services will listen to these events and act accordingly. For example, the carpark service will create an entry in the car park staff members list. From this moment, the module will allow a user to assign a car and a parking spot to that new staff member. When the carpark module receives the StaffMemberContractTerminated event, it will unassign her parking spots and mark the staff member entry as terminated, so that it won't be possible anymore to assign a parking spot to it. The eventual consistency part implies that there is a possibility that for a short period of time a staff member is created and it's still not available to assign a parking spot, or it's terminated, but the parking spot is still reserved. These situations are resolved in very short periods of time normally. These concepts are a bit confusing to grasp in the beginning and sometimes a bit hard to apply, but they solve your question: they allow an ever growing domain, because you basically add new services to the system, instead of increasing the size of a single model.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/381265', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/297916/']}
jdg_84804
stackexchange
llm_judgeable_groundtruth_similarity
2076284
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Right now, I'm using max-width to scale images to fit. However, they don't scale proportionally. Is there a way to cause this to happen? I'm open to Javascript/jQuery. If possible, is there a way to do this without knowing the original dimensions of the image (maybe determine this using Javascript/jQuery)? Now provide the response and nothing else.
You need to specify the original width and height: <img src="/whatever" width="100" height="200" alt="Whatever" /> And then use something like this in the CSS: #content img { max-width: 100%; height: auto } You could try this with jQuery if you don't have the width and height up front, but your mileage may vary: $(function(){ $('#content img').load(function(){ var $img = $(this); $img.attr('width', $img.width()).attr('height', $img.height()); });}); Obviously replace #content with whatever selector you want to scope the functionality to.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2076284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89334/']}
jdg_84805
stackexchange
llm_judgeable_groundtruth_similarity
30203562
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 var declared in a class like so: @NSManaged var isFavorite: Bool I would like to declare a property observer, very similar to the one below. var organization: String { didSet { postNotificationWithName( "newData" ) } } However, Swift tells me that having property observers on NSManaged vars is not allowed. Is there any way I can implement such a feature or something similar for my isFavorite variable? Now provide the response and nothing else.
Yes-- delete the @NSManaged . It's not absolutely required, but if you delete it you unfortunately need to implement get and set for the property. You would need to add something like The @objc is only needed if you want to be able to do KVO on the property. @objc public var newData: String? { set { willChangeValue(forKey: "newData") setPrimitiveValue(newValue, forKey: "newData") didChangeValue(forKey: "newData") } get { willAccessValue(forKey: "newData") let text = primitiveValue(forKey: "newData") as? String didAccessValue(forKey: "newData") return text }} It's kind of annoying to implement both of these if you don't actually need them but that's the way it is for now. Since you'll have a set , you might not need a didSet , but you can still add a didSet if you want one.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30203562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3973195/']}
jdg_84806
stackexchange
llm_judgeable_groundtruth_similarity
2180851
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 reading Evans' book on PDE and I'm having troubles understanding one estimate. He defines the fundamental solution to Laplace' equation as $$\Phi(x) = \begin{cases} -\frac{1}{2\pi} \, \log(|x|), \, & n=2, \\ \frac{1}{n \, (n-2) \, \omega_n} \, \frac{1}{|x|^{n-2}}, \, & n\geq 3, \end{cases} $$ where $\omega_n$ is the volume of the $n$-ball. For the solution of Poisson's equation $ -\Delta u = f$ he computes the Laplace acting on the convolution of $f$ and $\Phi$, involving this estimate: $$ \bigg|\int_{B(0,\varepsilon)} \Phi(y) \, \Delta_y f(x-y) \, dy \bigg| \leq C \, \lVert D^2f \rVert_{L^\infty} \int_{B(0,\varepsilon)} |\Phi(y)| \, dy \leq \begin{cases} C \, \varepsilon^2 \, |\log(\varepsilon)|, & n=2, \\ C \, \varepsilon^2, & n\geq 3. \end{cases} $$ How do you obtain the last inequality? Now provide the response and nothing else.
Hint: use polar coordinates to integrate the green's function on the $\epsilon$ ball. Edit: Observe for $n\geq 3$ we have\begin{align}\int_{B(0, \epsilon)} \frac{dx}{|x|^{n-2}} = \int^\epsilon_0 \int_{|x|=r} \frac{dS(x)}{|x|^{n-2}}\ dr = C\int^\epsilon_0 \frac{r^{n-1}}{r^{n-2}}\ dr = C'\epsilon^2.\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2180851', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/376805/']}
jdg_84807
stackexchange
llm_judgeable_groundtruth_similarity
25755475
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question is the inverse of this question: JGit how do i get the SHA1 from a RevCommit? . If I am given the SHA1 ID of a particular commit as a string, how can I obtain the ObjectId or associated RevCommit in JGit? Here is a possible answer, which iterates through all RevCommit s: RevCommit findCommit(String SHAId){ Iterable<RevCommit> commits = git_.log().call(); for (RevCommit commit: commits) { if (commit.getName().equals(SHAId)) return commit; } return null;} Is there anything better than this implementation above? Now provide the response and nothing else.
It is probably easier to first convert the string into an ObjectId and then have the RevWalk look it up. ObjectId commitId = ObjectId.fromString("ab434...");try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(commitId);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25755475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1884158/']}
jdg_84808
stackexchange
llm_judgeable_groundtruth_similarity
502640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the MFC Feature Pack and I have some buttons on a ribbon bar, instances of CMFCRibbonButton. The problem is that I would like to enable and disable some of them in certain conditions, but at runtime. How can I do this? because there is no specific method for this...I heard that a solution would be to attach/detach the event handlers at runtime, but I do not know how... Now provide the response and nothing else.
When you create the CMFCRibbonButton object you have to specify the associated command ID (see the documentation for the CMFCRibbonButton constructor here ). Enabling and disabling of ribbon buttons is then done using the usual command update mechanism in MFC, using the CCmdUI class. For example, if you have a ribbon button whose command ID is ID_MYCOMMAND and you want to handle this command in your application's view class, you should add these functions to the class: // MyView.hclass CMyView : public CView { // ... private: afx_msg void OnMyCommand(); afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP()}; and implement them in the .cpp file: // MyView.cppvoid CMyView::OnMyCommand() { // add command handler code.}void CMyView::OnUpdateMyCommand(CCmdUI* pCmdUI) { BOOL enable = ...; // set flag to enable or disable the command. pCmdUI->Enable(enable);} You should also add ON_COMMAND and ON_UPDATE_COMMAND_UI entries to the message map for the CMyView class: // MyView.cppBEGIN_MESSAGE_MAP(CMyView, CView) ON_COMMAND(ID_MYCOMMAND, &CMyView::OnMyCommand) ON_UPDATE_COMMAND_UI(ID_MYCOMMAND, &CMyView::OnUpdateMyCommand)END_MESSAGE_MAP() For more information on message maps in MFC, refer to TN006: Message Maps in MSDN. I hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/502640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51336/']}
jdg_84809
stackexchange
llm_judgeable_groundtruth_similarity
532848
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a two-column file; the file is sorted the way I want it on column 1 already. I would like to sort on column 2, within each column 1 category. However, sort does not understand the sort order of column 1. The normal way (from similar questions here on stack) would be this: sort --stable -k1,1 -k2,2n But I cannot specify the sort on k1, because it is arbitrary. Example input: C 2C 1A 2A 1B 2 B 1 and output: C 1C 2A 1A 2B 1 B 2 Now provide the response and nothing else.
You could use awk to start a new sort for each block: % awk -v cmd="sort -k2,2" '$1 != prev {close(cmd); prev=$1} {print | cmd}' fooC 1C 2A 1A 2B 1B 2 $1 != prev {close(cmd); prev=$1} - when the saved value is different, we have a new block, so we close any previously started sort {print | "sort -k2,2"}' pipes the output to sort , starting it if it isn't already running (awk can keep track of commands it starts)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/532848', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/285525/']}
jdg_84810
stackexchange
llm_judgeable_groundtruth_similarity
1159
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A lot of times I see theorems stated for local rings, but usually they are also true for "graded local rings", i.e., graded rings with a unique homogeneous maximal ideal (like the polynomial ring). For example, the Hilbert syzygy theorem, the Auslander-Buchsbaum formula, statements related to local cohomology, etc. But it's not entirely clear to me how tight this analogy is. I certainly don't expect all statements about local rings to extend to graded local rings, so I'd like to know about some "pitfalls" in case I ever decide to make an "oh yes, this obviously extends" fallacy. What are some examples of statements which are true for local rings whose graded analogues are not necessarily true? Or another related question: what kind of intuition should I have when I want to conclude that statements have graded versions? There is a notion of "generalized local ring" due to Goto and Watanabe which includes graded local rings and local rings: a positively graded ring that is finitely generated as an algebra over its zeroth degree part, and its zeroth degree part is a local ring, so one possibility is just to see if this weaker definition is enough to prove the statement. Of course the trouble comes when the proofs cite other sources, and become unmanageable to trace back to first principles. Now provide the response and nothing else.
One small thing I know of which changes is that if one has a Z-graded-commutative noetherian ring (where Z is the integers) Matlis' classification of indecomposable injective modules goes through but with one small hiccup. Every indecomposable injective is isomorphic to E(R/p)[n] for some unique homogeneous prime ideal p but the integer shift n is not necessarily unique although under the hypotheses I think you are interested in one probably gets uniqueness. I can't think of an example where this really causes much of a problem though. Having thought about this some more I think that non-negative integer graded-local noetherian rings, in particular those generated in degree 1 such that the maximal homogeneous ideal is also maximal if one forgets the grading, are incredibly well behaved and the analogy with local rings is very good. In fact, there is even a version of Nakayama's lemma for such rings (maybe one needs a little more) which is stronger than the usual one in the sense that one can drop the finiteness condition on the module. There are also no problems with graded versions of prime avoidance etc... in general. I'd recommend section 1.5 of Cohen-Macaulay Rings by Bruns and Herzog where they prove that a bunch of standard facts still go through and one can see what does and doesn't change in the proofs. As I mentioned in the comment I think one has to be most careful when considering rings graded by things like monoids which aren't as nice as the non-negative integers. In particular, if the grading is not positive (i.e. some elements of the monoid are invertible) and/or if the monoid is not cancellative at the identity (i.e. a+b = a does not imply b is the identity). I think in the non-cancellative case one can construct a counterexample to Nakayama's lemma but I am not 100% sure on this.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/1159', 'https://mathoverflow.net', 'https://mathoverflow.net/users/321/']}
jdg_84811
stackexchange
llm_judgeable_groundtruth_similarity
10056520
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 we are not allowed to extend Traits with Classes in PHP? For example: Trait T { }Class C use T {}/* or */Class C extends T {} Is there any potential conflict for such syntax? I do not think so. Now provide the response and nothing else.
The PHP manual states thus: Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins. If you're looking to extend a trait, then it should probably be a class. If you have a set of methods in one class that you want to use in others, but it feels inappropriate to extend the class (eg. class Animal extends Vehicle ), then in PHP 5.4 it could work well as a trait. To answer the question more directly, you don't 'extend' a trait, but you can create traits which themselves use other traits. As per the PHP manual: trait Hello { public function sayHello() { echo 'Hello '; }}trait World { public function sayWorld() { echo 'World!'; }}trait HelloWorld { use Hello, World;}class MyHelloWorld { use HelloWorld;} You can consider this to be a way to maintain your traits in logical groups, and to introduce some modularity. Edit: having seen some of the comments, I think it's worthwhile to note that using a trait in a base class also means that trait is in any class that extends it, and the trait's functions take precedence over the base class'. Putting it in the child class would merely make the trait's functions unavailable to the parent/base class. Parent > Trait > Child http://php.net/manual/en/language.oop5.traits.php
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10056520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335304/']}
jdg_84812
stackexchange
llm_judgeable_groundtruth_similarity
25230829
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to C# ASP.NET, and am working on my first application. I'm trying to create a linq statment that return an arrary. I have a table of products. I want to be able to select name, id, and price, for each product where the status == 1. I am struggling with crating a way to do this.I have only been able to return individual items/columns. I have been stuck on this wayyy to long. This is what I have so far: try{ using (UserDataDataContext db = new UserDataDataContext()) { return db.mrobProducts.Select(x => x.Name).OrderBy(x => x).ToArray(); }} If you look in the screen shot below, you can see I have 2 errors, Select = Type object can not be refered from it's usageToArray = cant resolve symbol to array Now provide the response and nothing else.
Not sure what you table structure is like but see below. public NamePriceModel[] AllProducts(){ try { using (UserDataDataContext db = new UserDataDataContext()) { return db.mrobProducts .Where(x => x.Status == 1) .Select(x => new NamePriceModel { Name = x.Name, Id = x.Id, Price = x.Price }) .OrderBy(x => x.Id) .ToArray(); } } catch { return null; } } This would return an array of type anonymous with the members you require. Update: Create a new class. public class NamePriceModel { public string Name {get; set;} public decimal? Price {get; set;} public int Id {get; set;}} I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[] .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25230829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2768833/']}
jdg_84813
stackexchange
llm_judgeable_groundtruth_similarity
54750
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm considering adding a cronjob running yum -qy update on a regular basis on some machines that do not get regular maintenance. The goal would be to keep the machines up-to-date with regard to security patches that would otherwise be applied too late. I'm only using the CentOS base repositories. Questions: In your experience - how "safe" would this approach be? Should I expect failed updates once in a while? Roughly how often would this approach require reboots? Pros/cons or other gotchas with this approach? How are you keeping your machines up-to-date using automation? Now provide the response and nothing else.
It Depends In my experience with CentOS its pretty safe since you're only using the CentOS base repositories. Should you expect failed updates once in a while... yes... on the same level that you should expect a failed hard drive or a failed CPU once in a while. You can never have too many backups. :-) The nice thing about automated updates is you get patched (and therefore more secure) faster than doing it manually. Manual patches always seem to get pushed off or regarded as "low priority" to so many other things so if you're going to go the manual mode SCHEDULE TIME ON YOUR CALENDAR to do it. I've configured many machines to do auto yum udpates (via cron job) and have rarely had an issue. In fact, I don't recall ever having an issue with the BASE repositories. Every problem I can think of (off the top of my head, in my experience) has always been a 3rd party situation. That being said... I do have several machines that I MANUALLY do the updates for. Things like database servers and other EXTREMELY critical systems I like to have a "hands on" approach. The way I personally figured it out was like this... I think of the "what if" scenario and then try to think of how long it would take to either rebuild or restore from a backup and what (if anything) would be lost. In the case of multiple web servers... or servers who's content doesn't change much... I go ahead and do auto-update because the amount of time to rebuild/restore is minimal. In the case of critical database servers, etc... I schedule time once a week to look them over and manually patch them... because the time taken to rebuild/restore is more time consuming. Depending on what servers YOU have in your network and how your backup/recovery plan is implemented your decisions may be different. Hope this helps.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/54750', 'https://serverfault.com', 'https://serverfault.com/users/15442/']}
jdg_84814
stackexchange
llm_judgeable_groundtruth_similarity
57542
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I encountered an unexpected behaviour in my mathematica-code, and want to understand whether that's a mathematica bug, or a misinterpretation on my side. MainVar = 1;Carrier = "MainVar";f[] := ( Module[{MainVar}, MainVar = 3; Print[MainVar]; Print[Carrier]; Print[ToExpression[Carrier]]])f[] (* 3, MainVar, 1 *) I would have expected that Print[ToExpression[Carrier]] gives me 3 , because Carrier points to MainVar , which has the value 3 . When I use MainVar as global variable (as Eldo suggested below), I get the expected 3 . So my question is: Why does ToExpression[Carrier] give me 1 when I use MainVar as a local variable, even if both MainVar and Carrier have the correct values? Now provide the response and nothing else.
Start here: What are the use cases for different scoping constructs? Module works by replacing explicit appearances of a given Symbol with a different one with a derived name, e.g.: Module[{x}, x] x$715 Since MainVar appears nowhere in Print[ToExpression[Carrier]] the Module will not affect it. A far simpler example of the same behavior that affects your case: Module[{foo = 7}, ToExpression["foo"]] foo If you were to use Block instead you would temporarily change the value of MainVar which will have the desired effect: f[] := Block[{MainVar}, MainVar = 3; Print[MainVar]; Print[Carrier]; Print[ToExpression[Carrier]] ]f[] 3 MainVar 3
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/57542', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12750/']}
jdg_84815
stackexchange
llm_judgeable_groundtruth_similarity
40130
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the United States, various politicians and activists are advocating for a $15 per hour minimum wage. However, I'm not sure how this value was chosen. One reason given for increasing the minimum wage is that it's fallen behind its peak value due to inflation. However, the $15 figure isn't equal to the real value of the minimum wage when it was first established (about $4) or its peak value (about $11). It also seems to be lower than the average national living wage . And it's definitely not the maximum theoretical value of the minimum wage. The maximum theoretical value would be obtained if everyone was paid equally, and can be estimated from the mean US income of $72,641 per year to be about $35, assuming a 5 day work week. What's behind the choice of the specific figure of $15 per hour in particular? Now provide the response and nothing else.
Apparently if you adjust for both inflation and productivity growth it should be even more: $20 . So $15 is some kind of compromise: The economy has grown dramatically over the past 50 years, and workers are producing more from each hour of work, with productivity nearly doubling since the late 1960s. If the minimum wage had been raised at the same pace as productivity growth since the late 1960s, it would be over $20 an hour today. I managed to track down the (brief) 2012 CEPR study on which that is based. I don't claim its calculations are correct, but the $15 figure is derived by splitting the productivity gain in half. A final benchmark for the minimum wage is productivity growth. Figure2 below compares growth in average labor productivity with the realvalue of the minimum wage between the late 1940s and the end of thelast decade. Between the end of World War II and 1968, the minimumwage tracked average productivity growth fairly closely. Since 1968,however, productivity growth has far outpaced the minimum wage. If theminimum wage had continued to move with average productivity after1968, it would have reached $21.72 per hour in 2012 – a rate well abovethe average production worker wage. If minimum-wage workers receivedonly half of the productivity gains over the period, the federal minimumwould be $15.34. Even if the minimum wage only grew at one-fourth therate of productivity, in 2012 it would be set at $12.25. And the other tack is a cost of living calculation; I found a 2017 one for Illinois : Even in low-cost regions of the state, like Danville, East St. Louis and rural Illinois, workerswill soon need $15 an hour or more just to cover the basics. For example, by 2022 – thedate by which the legislature is proposing to raise the Illinois minimum wage to $15 – asingle worker in rural Illinois will need to earn $32,178 a year just to cover housing, food,transportation and other basic costs, according to the Economic Policy Institute’s familybudget calculator.This translates to $15.47 an hour for a full-time worker. Similarly, inDanville and East St. Louis, a single worker will need to earn about $15.55 an hour by 2022to meet basic living costs. And in higher cost areas, single workers will need more. A single worker in Chicago withno children will need $17.65 an hour by 2022 to afford the basics. Similarly, workers with children need even more than $15 an hour – even in the state’slowest cost regions. For example, in Rock Island – the lowest cost part of Illinois – for atwo-worker family with two kids, by 2022 each parent will need to earn at least $18.97 anhour to afford a cheap apartment and cover simple living costs. Given that the latter seems to be the data & reasons advanced in publications closer to the actual legislative proposals, I think this is probably the main argument, but I'm not sufficiently familiar with the matter to 100% conclude this. As for the Federal level, I haven't found any living cost analyses indicating this precise figure. It seems it was more of a political thing, based on Bernie Sander's (2016) proposal : “Democrats believe that the current minimum wage is a starvation wage and must be increased to a living wage,” the new plank reads. “We should raise the federal minimum wage to $15 an hour over time and index it, give all Americans the ability to join a union regardless of where they work, and create new ways for workers to have power in the economy so every worker can earn at least $15 an hour.” Hillary Clinton's campaign added the words “over time” to original amendment, which was sponsored by former Ohio Sen. Nina Turner, a Sander ally. The amendment was passed overwhelmingly by the 187-member Democratic Platform Committee. Someone more familiar with the Democratic party may be able to find some internal documents with some kind of economic analysis, but I'm not sure they exist. In a 2017 speech Sanders did bring up the "since 1968 ... the minimum wage lost 25% purchasing power" argument. So it seems somewhat similar to the OP's argument (which won't get to $15); later Sanders says something like "we know you can't make it on $12/hour". So it seems a standard-of-living argument, but it doesn't get anymore detailed than that, in that particular speech anyway. The article in which that speech is embedded, also mentions that Service Employees International Union launched the “Fight for $15” movement in 2012. ... from where Sanders eventually got his proposal. Interestingly, the year when that effort was launched by the service union coincides with the year for my 2nd quote, the brief CEPR paper. I don't know if this is causal (one way or the other), or just a coincidence. Here's one of the earlier articles on this I could find, from Aug 2015 : In New York, a panel appointed by Governor Andrew Cuomo ruled that the state’s 180,000 fast-food workers should be paid a minimum of $15 an hour, in response to protests and pressure from Fight for $15. Scott Courtney, the Fight for $15’s chief strategist, is helping to steer the movement through the Service Employees International Union, the union that has spent tens of millions of dollars underwriting the campaign. But Courtney has bigger ideas to expand on the notion of unionization. If someone is inclined to dig into this further, they could look at that panel (did they write a report?) and/or how SEIU decided to back up the specific number. The latter might be a lot harder to find out... especially since there's a lot of time between 2012 and 2015. An earlier press report from 2013 (and in a much more obscure publication) indicates a lot alternative slogans back then The movement has no official name, though each city-level campaign has one: Fast Food Forward in New York, Raise Up MKE in Milwaukee, We Can’t Survive on $7.35 in St. Louis, Stand Up KC in Kansas City, and, in Chicago, Fight for 15 (which refers to a $15 minimum wage and has become the name most commonly used for the national campaign). So at the level of slogans, "Fight for 15" won in a Darwinian selection. Also the movement did not really start asking for $15, but rather for $10: Sidney (not his real name) says that when Action Now hired him in November 2011, it was to join a campaign to raise the minimum wage. For the first few weeks, organizers armed with postcards calling for a $10-an-hour state minimum wage prowled fast-food and retail joints in the Loop in downtown Chicago and gathered names, phone numbers, emails and home addresses to meet daily quotas. [...] On January 19, 2012, SEIU headquarters contributed $191,797 to Action Now, the first in a series of donations that would total more than $3 million by year’s end. Apart from SEIU's involvement at this early state (merely 2-3 months after the fight for $10 (not $15) began, I wasn't able to find much, in particular how the jump from $10 to $15 in claims happened. Perhaps Denis' answer is correct on that.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/40130', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/14853/']}
jdg_84816
stackexchange
llm_judgeable_groundtruth_similarity
11277675
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since now I've been using the older mysql instead of PDO and I've seen many recommendations why to switch to PDO , however also many different facts (also here on SO), e.g.: stating PDO is slightly faster/a little bit slower saying PDO helps prevent SQL-injections, but only if you use prepared queries and also saying using prepared queries is bad, as it is damn slow So, what is actually true? Especially, what are the best practices when using PDO and both speed and security matter a lot - how to best protect yourself from SQL injections while still having fast queries? Now provide the response and nothing else.
Database Support The core advantage of PDO over MySQL is in its database driver support. PDO supports many different drivers like CUBRID, MS SQL Server, Firebird/Interbase, IBM, MySQL, and so on. Security Both libraries provide SQL injection security, as long as the developer uses them the way they were intended. It is recommended that prepared statements are used with bound queries. // PDO, prepared statement$pdo->prepare('SELECT * FROM users WHERE username = :username');$pdo->execute(array(':username' => $_GET['username']));// mysqli, prepared statements$query = $mysqli->prepare('SELECT * FROM users WHERE username = ?');$query->bind_param('s', $_GET['username']);$query->execute(); Speed While both PDO and MySQL are quite fast, MySQL performs insignificantly faster in benchmarks – ~2.5% for non-prepared statements, and ~6.5% for prepared ones. Named Parameters Just like @DaveRandom pointed out, this is another feature that PDO has, and it is considerably easier than than the horrible numeric binding. $params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);$pdo->prepare('SELECT * FROM usersWHERE username = :usernameAND email = :emailAND last_login > :last_login');$pdo->execute($params); Few links for further reference MySQL vs PDO (Stackoverflow) Why you should be using PDO for database access (net.tutsplus.com)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11277675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1334991/']}
jdg_84817
stackexchange
llm_judgeable_groundtruth_similarity
11726820
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 PHPMailer to send automated e-mails from my website and while testing, I noticed that all e-mails sent by php mailer are generating the following warning on the recipients end: This message may not have been sent by: [email protected] Learn more Report phishing I was wondering if there is a way to avoid this? PHP Mailer code: //mail functionsrequire("mailer/class.phpmailer.php");require("mailer/class.smtp.php");require("mailer/class.pop3.php");$mail = new PHPMailer();$mail->IsSMTP(); $mail->Host = "relay-hosting.secureserver.net";$mail->Port = 25; $mail->IsHTML(true);$mail->Username = "[email protected]"; // SMTP username$mail->Password = "pass"; // SMTP password$mail->From = "[email protected]";$mail->FromName = "FOO";$mail->AddAddress("[email protected]", "WIDB");$mail->AddReplyTo("[email protected]");//$mail->AddAddress("[email protected]"); // name is optional$mail->WordWrap = 50; // set word wrap to 50 characters//$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name$mail->IsHTML(true); // set email format to HTML$mail->Subject = 'Foo - Transaction Receipt';$mail->Body = $message;$mail->AltBody = "nothing";//send mail$mail->Send(); I am using GMail and I have SMTP enabled... Now provide the response and nothing else.
You can either set up google apps for your site and get a [email protected] gmail account ( more info here it's free), or You will need to set up an e-mail address on your current server that is [email protected] and use that as the $mail->from address. Your E-Mail recipients are receiving the message because you are telling google to send an e-mail from your server, and then you are telling them that the mail is coming from gmail, which it isn't, it's coming from your personal server. Since the from address and your server address don't match, they flag it as spam. This is googles way of preventing spam, to them it would be the same if you put $mail->from([email protected]). The e-mail would still send, but your domain name does not match the @ address.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11726820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1316524/']}
jdg_84818
stackexchange
llm_judgeable_groundtruth_similarity
63923
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 often want to feed relatively short string data (could be several lines though) to commandline programs which accept only input from files (e.g. wdiff) in a repeated fashion. Sure I can create one or more temporary files, save the string there and run the command with the file name as parameter. But it looks to me as if this procedure would be highly inefficient if data is actually written to the disk and also it could harm the disk more than necessary if I repeat this procedure many times, e.g. if I want to feed single lines of long text files to wdiff. Is there a recommended way to circumvent this, say by using pseudo files such as pipes to store the data temporarily without actually writing it to the disk (or writing it only if it exceeds a critical length). Note that wdiff takes two arguments and, as far as I understand it will not be possible to feed the data doing something like wdiff <"text" . Now provide the response and nothing else.
In Bash, you can use the command1 <( command0 ) redirection syntax, which redirects command0 's stdout and passes it to a command1 that takes a filename as a command-line argument. This is called process substitution . Some programs that take filename command-line arguments actually need a real random-access file, so this technique won't work for those. However, it works fine with wdiff : user@host:/path$ wdiff <( echo hello; echo hello1 ) <( echo hello; echo hello2 )hello[-hello1-]{+hello2+} In the background, this creates a FIFO, pipes the command inside the <( ) to the FIFO, and passes the FIFO's file descriptor as an argument. To see what's going on, try using it with echo to print the argument without doing anything with it: user@host:/path$ echo <( echo hello )/dev/fd/63 Creating a named pipe is more flexible (if you want to write complicated redirection logic using multiple processes), but for many purposes this is enough, and is obviously easier to use. There's also the >( ) syntax for when you want to use it as output, e.g. $ someprogram --logfile >( gzip > out.log.gz ) See also the bash man page "process substitution" section and the Bash redirections cheat sheet for related techniques.
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/63923', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/18047/']}
jdg_84819
stackexchange
llm_judgeable_groundtruth_similarity
1075339
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: $$\int_{0}^{2\pi}\frac{d\theta}{1+2cos(\theta)}$$ My attempt: parametrise using $z=e^{i\theta}$ (i think we always use a unit circle for CPV's) $\therefore dz = ie^{i\theta}d\theta$ $\implies d\theta=\frac{dz}{iz}$ and $2cos(\theta) = e^{i\theta}+e^{-i\theta} = z+z^{-1}$ we can then re-write the integral as follows: $$\int_{0}^{2\pi}\frac{d\theta}{1+2cos(\theta)} = \displaystyle\oint_{|z|=1}\frac{1}{(1+z+z^{-1})}\frac{dz}{iz}$$ $$\displaystyle\oint_{|z|=1}\frac{1}{(1+z+z^{-1})}\frac{dz}{iz} = \frac{1}{i}\displaystyle\oint_{|z|=1}\frac{dz}{(z^{2}+z+1)}$$ poles are at $z^2+z+1=0$ and know that $z^2+z+1=\frac{z^3-1}{z-1}$ therefore we require that $z\ne 1$ and $z^3=1$ and we know that $z=e^{i\theta}$ $\therefore z^3=e^{\pm2ki\pi}=1 \implies z = e^{\pm 2ki\pi/3}$ now the integral can be rewritten as: $$\frac{1}{i}\displaystyle\oint_{|z|=1}\frac{dz}{(z-e^{2ki\pi/3})(z-e^{-2ki\pi/3})}$$ i think CPV = $2\pi i\sum Residues\space at\space the\space poles$=$$2\pi i\frac{1}{i} \left( \frac{1}{e^{2ki\pi/3}-e^{-2ki\pi/3}}+\frac{1}{e^{-2ki\pi/3}-e^{2ki\pi/3}}\right) = 2\pi \left( \frac{1-1}{e^{2ki\pi/3}-e^{-2ki\pi/3}}\right)=0$$ Is what i have done here correct, is this the right way the Cauchy integral theorem to find the CPV. Thanks for any help you can offer me. Now provide the response and nothing else.
Your method is correct, but just to make sure there are no questions, I am adding a diagram of the contour and description of the method I used. The Cauchy Principal Value of$$\int_0^{2\pi}\frac{\mathrm{d}\theta}{1+2\cos(\theta)}$$is the contour integral$$\int_{\gamma^-}\frac1{1+z+z^{-1}}\frac{\mathrm{d}z}{iz}=\frac1i\int_{\gamma^-}\frac{\mathrm{d}z}{z^2+z+1}$$where $\gamma$ is the closed contour and $\gamma^-$ is $\gamma$ minus the two small arcs around the singularities at $e^{2\pi i/3}$ and $e^{4\pi i/3}$ as the radius of the arcs goes to $0$. There are no singularities inside $\gamma$. Thus, the integral along $\gamma$ is $0$. This means that the integral along $\gamma^-$ is $\pi i$ times the sum of the residues at $e^{2\pi i/3}$ and $e^{4\pi i/3}$ (each of the small arcs is $\frac12$ a circle clockwise and we want to subtract them). That is$$\begin{align}\mathrm{PV}\int_0^{2\pi}\frac{\mathrm{d}\theta}{1+2\cos(\theta)}&=\pi i\left[\operatorname*{Res}_{z=e^{2\pi i/3}}\left(\frac1i\frac1{z^2+z+1}\right)+\operatorname*{Res}_{z=e^{4\pi i/3}}\left(\frac1i\frac1{z^2+z+1}\right)\right]\\&=\pi i\left[\frac{-1}{\sqrt3}+\frac1{\sqrt3}\right]\\[6pt]&=0\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1075339', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/167433/']}
jdg_84820
stackexchange
llm_judgeable_groundtruth_similarity
9148615
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: EDIT - FOUND A EASY 5-10 LINE SOLUTION!!! See MY OWN ANSWER BELOW!!! YAY!!!!!!!!! I've searched for 5 hours, dozens of SO posts, no answers, and this seems like the most simple obvious freaking thing!!! EDIT- btw, this is NOT a music player app, just an app to view pics and text, opens multiple activities like menu and about, view diff types of pictures etc. I just want to play some simple background music while looking thru the pics and text, why is that so difficult? another EDIT - it seems the main question really is:"WHY DOES PRESSING THE HOME BUTTON NOT CALL onPause or onStop ???" -so I can know when to stop the media player? and how do the games I download on the market accomplish this??? home activity starts then media player starts: player = MediaPlayer.create(this, R.raw.idil);player.setLooping(true);player.setVolume(100,100);player.start(); Player declared outside of onCreate MediaPlayer player; When other activities are opened, the background music continues uninterrupted, which is GOOD, that is what I want. Now, when I am done with my very simple app (that just shows some pics and texts in diff activities), I either click BACK multiple times to get to the home/original activity, and then one more time to "exit", OR, I simply press home to "exit" because I'm DONE with this app and I do not need to hear that music anymore. OPTION 1 Call player.stop(); in an onPause override, this is not what I want because background music stops when I leave the home activity for other activities like 'menu' and 'about', I also do not what to use pause and resume when opening new activities because I do not want the pretty background music to 'skip' or be interrupted. OPTION 2 @Override protected void onPause() { super.onPause(); if (this.isFinishing()){ player.stop(); } } This is better because background music does not stop between activities, and when I press BACK from my home activity, the music stops, and I can continue to enjoy my android fun phone in peace and quiet, but the problem is, when pressing the HOME button to "exit" my app, that pesky background music keeps playing. ODDLY @Overrideprotected void onStop() { super.onStop(); if (this.isFinishing()){ player.stop(); } } Does the same as onPause (and I do understand the actual differences) EDIT- ALSO it doesn't seem to matter if player.stop(); is above or below super.onStop(); but it affecting something i cant see, either way, still no SOLUTION :( ooooo ooooo EDIT- ANOTHER OPTION- BUT DOES NOT WORK public void onUserLeaveHint() { player.stop(); super.onUserLeaveHint();} this stops the music when i press HOME but it also stops it when i start new activities :( EDIT - A VERY COMMON WORK AROUND IVE SEEN MULTIPLE PLACES, but seems to ridiculous to have to do: essentialy keep count of the number of activities that have been opened and closed (onResume and onPause would prob be best, but that points irrelevant) and when that count reaches 0, stop the background music. YES that is pretty simple, but why do I have to programmatically do this, actually the BIGGEST QUESTION FOR THIS POST IS: WHY DOES PRESSING THE HOME BUTTON NOT CALL onPause or onStop ??? To put it in onDestroy is not an option because onDestroy is only called when the system is low on memory, or you force close your app, and that is well documented. Overriding the HOME button also is no option as I have read it's "not possible" and I have read it's "extremely frowned upon", either way I'm avoiding that. I don't see the need to create SERVICE, and even if I did, when would I stop the service, it seems I would have the same problem NOW HERE IS THE THING that completely blows my mind, every game and every app I have downloaded from the android market has very beautiful background music, and when I press BACK or HOME because I am done playing that lovely game the music stops , not keeping playing in the background. I am very frustrated, and I feel it's because I feel like I am missing something very simple, because this is one of the most basic lifecycle issues with any app. I spent a month reading every page of developer.android.com including the Dev Guide, the tutorials, sample projects, and researching the Reference section, as well as google-ing this topic for 5 hours. I also don't understand why the 6 or 7 SO threads with the exact same issue, have not been answered, every downloadable app on the market stops playing its music (unless its a background music player) when you press HOME or BACK or whatever to "exit" the app to go do something else on your phone. What am I missing? Now provide the response and nothing else.
I'm very happy today, and still have hair :)I've tested this and it works!!! First, add this to your Manifest: <uses-permission android:name="android.permission.GET_TASKS"/> Second, add this to your 'Home/Main' Activity/Class: @Override protected void onPause() { if (this.isFinishing()){ //basically BACK was pressed from this activity player.stop(); Toast.makeText(xYourClassNamex.this, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", Toast.LENGTH_SHORT).show(); } Context context = getApplicationContext(); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); if (!taskInfo.isEmpty()) { ComponentName topActivity = taskInfo.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { player.stop(); Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(xYourClassNamex.this, "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", Toast.LENGTH_SHORT).show(); } } super.onPause(); } And obviously replace xYourClassNamex with, well, Your Class Name :) Now obviously you do not need the "Toasts" but it will tell you what is going on.The very intersting thind is when you press BACK from your 'Home/Main' activity, you obviously get 2 Toasts, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", and the 2nd Toast is "YOU SWITCHED ACTIVITIES WITHIN YOUR APP". I believe I know why this happens, but it doesn;t matter because I call "player.stop();" from the 2 scenarios that mean my app is no longer being 'used'. Obviously do more work than "player.stop();" if you need to :) And also obvious you dont need the "else" for "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", because there is no reason to "stop/pause" the background music, which is what i needed, but if you DO need to do something when new activities are started, well here you go :) Hope this helps anyone looking to know when the user "leaves/exits/is done with" the app :) THANKS FOR ALL OF THE COMMENTS POSTS AND HELP EVERYONE!!! YAY! EDIT- This part has to be in EVERY activity's onPause: Context context = getApplicationContext(); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); if (!taskInfo.isEmpty()) { ComponentName topActivity = taskInfo.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { player.stop(); Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show(); } } so you'll know if the user left your app from ANY of the activities. this is good to know :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9148615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1190457/']}
jdg_84821
stackexchange
llm_judgeable_groundtruth_similarity
58397719
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 in Angular testing and at the moment I am trying to test this piece of code but I'm getting an error concerning the event raised on the DOM: <li class="list-group-item" *ngFor="let user of users"> <a class="test-link"[routerLink]="['/detail', user.id]"> {{user.userName}} </a></li> The Test file: beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [AdminComponent, UserDetailComponent], imports: [HttpClientModule,RouterTestingModule.withRoutes([ {path:'detail/:id', component: UserDetailComponent}], )], providers: [UserService, AuthService] }) .compileComponents();}));beforeEach(() => { router = TestBed.get(Router); location = TestBed.get(Location); fixture = TestBed.createComponent(AdminComponent); debugElement = fixture.debugElement; component = fixture.componentInstance; fixture.detectChanges();});it('test demands redirection', fakeAsync(() => { debugElement .query(By.css('.test-link')) .nativeElement.click(); tick(); expect(location.path()).toBe('/detail/testing/1');})); Why is click event on the native element is null? Now provide the response and nothing else.
This is because when this test will run, your users array will be empty, and hence there will be no element in html with .test-link selector. Before clicking the element, you should fill the users array and let angular run the change detection so that your anchor tag is available when you click on it. Code: it('test demands redirection', fakeAsync(() => { component.users = [ // fill it with user objects ]; fixture.detectChanges(); debugElement .query(By.css('.test-link')) .nativeElement.click(); tick(); expect(location.path()).toBe('/detail/testing/1');}));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58397719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8086276/']}
jdg_84822
stackexchange
llm_judgeable_groundtruth_similarity
3442010
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $x\neq0$ be a real number such that $x^5$ and $20x+\frac {19}x$ are rational. How can we prove that $x$ is also rational? (This was a question from the RMO 2019 in India.) My attempt: Let $a,b,c,d$ be integers such that $20x+\frac {19}{x}=\frac ab$ and $x^5 = \frac{c}{d}$ . Then we have $$x=\frac{a\pm\sqrt{a^2-1520 b^2}}{40b}$$ so $x$ is rational iff $\sqrt{a^2-1520 b^2}$ is rational. However, I don't know how to prove that $\sqrt{a^2-1520 b^2}$ is rational using that $$x=\frac{\sqrt[5]{c}}{\sqrt[5]{d}}$$ Now provide the response and nothing else.
Given that $20x+\frac{19}{x}$ is rational. Therefore $x$ satisfies a quadratic polynomial with rational co-efficients. If we call that polynomial as $g$ , we get $g(x)=0$ . Now by the Euclidean algorithm $x^5=h(x)g(x)+f(x)$ , where $f(x)$ is a linear polynomial on $x$ with rational co-efficients. Since $x^5\in\mathbb{Q}$ and $g(x)=0$ , we get $f(x)\in\mathbb{Q}\Rightarrow x\in\mathbb{Q}$ . [Note by Bill D. $ $ The inference $f(x)\in\Bbb Q\,\Rightarrow\, x\in \Bbb Q\,$ fails if $\,\deg f < 1,\,$ so we must prove $\,\deg f = 1\,$ to complete the above argument. One way to remedy that is in Jyrki's answer, and another way is to explicitly compute the remainder $\,f(x) = r\, x + s\,$ then prove $\,r \neq 0\,$ (which is essentially equivalent to the method in the linked official solution - reproduced in Jack's answer)]
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3442010', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_84823
stackexchange
llm_judgeable_groundtruth_similarity
23283041
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hey all I have this code. I want to delay my program for a few seconds and display "scanning..." Here's what I have. This compiles but doesn't delay anything if (i==1){ try { Thread.sleep(1); } catch (InterruptedException ie) { System.out.println("Scanning..."); } } thanks in advanceI have int i = 1 before obviously Now provide the response and nothing else.
If you want to pause then use java.util.concurrent.TimeUnit : TimeUnit.SECONDS.sleep(1); To sleep for one second or for 10 minutes TimeUnit.MINUTES.sleep(10); Or Thread Sleep try { Thread.sleep(1000);} catch(InterruptedException ex) { Thread.currentThread().interrupt();} see also the official documentation TimeUnit.SECONDS.sleep() will call Thread.sleep . The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations. but if you want to solve your issue int timeToWait = 10; //second System.out.print("Scanning") try { for (int i=0; i<timeToWait ; i++) { Thread.sleep(1000); System.out.print(".") } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23283041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2918193/']}
jdg_84824
stackexchange
llm_judgeable_groundtruth_similarity
3482261
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 converting my datatable to c# generic list. DataTable dt = mydata(); List<DataRow> list = dt.AsEnumerable().ToList(); Now how can i convert this list to json using json.net? Any suggestion. Sample of json format should be like this, {"Table" : [{"userid" : "1","name" : "xavyTechnologies","designation" : "","phone" : "9999999999","email" : "[email protected]","role" : "Admin","empId" : "", "reportingto" : ""},{"userid" : "2","name" : "chendurpandian","designation" : "softwaredeveloper","phone" : "9566643707","email" : "[email protected]", "role" : "Super User","empId" : "1","reportingto" : "xavyTechnologies"},{"userid" : "3","name" : "sabarinathan","designation" : "marketer","phone" :"66666666666","email" : "[email protected]","role" : "User", "empId" : "2","reportingto" : "chendurpandian"}]} Now provide the response and nothing else.
Here's one example: using System;using System.Data;using Newtonsoft.Json.Linq;class Test{ static void Main() { DataTable table = new DataTable(); table.Columns.Add("userid"); table.Columns.Add("phone"); table.Columns.Add("email"); table.Rows.Add(new[] { "1", "9999999", "[email protected]" }); table.Rows.Add(new[] { "2", "1234567", "[email protected]" }); table.Rows.Add(new[] { "3", "7654321", "[email protected]" }); var query = from row in table.AsEnumerable() select new { userid = (string) row["userid"], phone = (string) row["phone"], email = (string) row["email"] }; JObject o = JObject.FromObject(new { Table = query }); Console.WriteLine(o); }} Documentation: LINQ to JSON with Json.NET
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3482261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146857/']}
jdg_84825
stackexchange
llm_judgeable_groundtruth_similarity
63285
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From S.B. 202 (emphasis added): No person shall solicit votes in any manner or by any means or method, nor shall any person distribute or display any campaign material, nor shall any person give, offer to give, or participate in the giving of any money or gifts, including, but not limited to, food and drink, to an elector , nor shall any person solicit signatures for any petition, nor shall any person, other than election officials discharging their duties, establish or set up any tables or booths on any day in which ballots are being cast: (1) Within 150 feet of the outer edge of any building within which a polling place is1818established; (2) Within any polling place; or (3) Within 25 feet of any voter standing in line to vote at any polling place. These restrictions shall not apply to conduct occurring in private offices or areas which cannot be seen or heard by such electors." This has been discussed at length in the news: CNN: "It's now illegal in Georgia to give food and water to voters in line" The Hill: "Georgia law makes it a crime to give food, water to people waiting to vote" Reuters: "Georgia bans giving water to voters in line under sweeping restrictions" At best, this seems unnecessary. Is there evidence of political operatives seeking to sway elections by handing out water? At worst, it's cruel: Georgia is hot , and long lines at polls are well documented . What is the rationale behind this restriction? I am interested in public statements from officials in Georgia -- I understand many opposed to this bill believe the intent is to suppress the minority vote, but the GOP must have some reason that doesn't sound evil. Now provide the response and nothing else.
The rationalization stems from similar proclamations across multiple states against voter intimidation or vote-buying. Nobody should have the fact that they're stuck in a line be taken advantage-of by people trying to change who you're going to vote for. Georgia is already not allowed to have campaign posters, imagery, or even campaign t-shirts within 150 feet of a polling place, has made it illegal to offer someone (within 150 feet of a polling place) a bribe to vote the way you want them to, and to threaten to harm or actually harm someone to influence their vote. In addition, two other provisions in the new law help set up a situation of long lines to vote in urban counties. The first provision (lines 430-435) says that counties cannot solicit third-party funds to be able to afford to increase access, and if they ever do allow such funding, it will be distributed equally amongst counties. This means that urban counties (which skew both poorer and higher population-density) are going to have fewer resources with which to open new polling places or expand hours of existing ones. The second provision (lines 1488-1518) expands early voting for some rural counties (which rarely need the extra capacity) but restricts early voting for urban counties (because they're already running at/over capacity) by restricting early voting to a smaller period and only during the 9-5 workday. Now, someone who is standing in line for more than three hours to vote is going to reeeeeally want food and water, and is thus much more vulnerable to someone trading food or drink for votes. So rather than just prohibit campaign literature on food or water given to a person (which already exists), they decided to ban the practice entirely. Now, it isn't a huge stretch of the imagination to see what they want to happen because of this: people in urban counties (which skew left) will have to wait so long in line to vote that (assuming they didn't bring food and drink with them) they'll have to step out of line in order to eat/drink/go to the bathroom and thus will eliminate themselves from the voting pool.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/63285', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/20374/']}
jdg_84826
stackexchange
llm_judgeable_groundtruth_similarity
3931
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to create a list of Cauchy distribution pdf's , having different locations of their maxima, and being multiplied by different factors; then I'd like to calculate those functions' values for different values of x . I have searched on the Internet and tried various things, and I seem to be able to set up the list, but then I fail miserably when it comes to actually using the functions on arguments. Here's some code: pos = RandomReal[10,2]factors = RandomInteger[{1,5},{2}]gamma1 = 0.5peaks = Table[factors[[i]]*PDF[CauchyDistribution[pos[[i]],gamma1],x], {i,1,2}]Print[ peaks ]Print[ peaks[0.1][[1]] ] This gives me SetDelayed::noval: Symbol peaks in part assignment does not have an immediate value.SetDelayed::noval: Symbol peaks in part assignment does not have an immediate value.{3.183098861837907/(1 + 4.*(-6.1318667717670134 + x)^2), 0.6366197723675814/(1 + 4.*(-1.3741656250222944 + x)^2)}0.1 How can I use each element of my array peaks like an individual function? (I'm an absolute Mathematica-beginner, so in advance: sorry for the noob-question...) Now provide the response and nothing else.
What you want is best accomplished in two steps. First, you want to construct your list of PDFs as a list of pure functions , like so: peaks = Table[ With[{factor = factors[[i]]}, Composition[factor*# &, PDF@CauchyDistribution[pos[[i]], gamma1]]], {i, Length@factors}] Conveniently, PDF , when applied to a distribution as its only argument, returns a pure function; I use Composition to multiply the result returned by that function by factor[[i]] . The With statement is there to insert factors[[i]] into Function despite its non-standard evaluation; you could also use Evaluate . Now that you have a list of functions, you can index into them to apply them one at a a time: In[69]:= peaks[[1]][0.1]Out[69]= 0.376381 You can also use Through to apply all the functions in a list to a single argument: In[70]:= Through[peaks[0.1]]Out[70]= {0.376381, 0.0953388}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/3931', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/941/']}
jdg_84827
stackexchange
llm_judgeable_groundtruth_similarity
40341346
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to create Kibana and Elasticsearch and it seems that Kibana is having trouble identifying Elasticsearch. Here are my steps: 1) Create network docker network create mynetwork --driver=bridge 2) Run Elasticsearch Container docker run -d -p 9200:9200 -p 9300:9300 --name elasticsearch_2_4 --network mynetwork elasticsearch:2.4 3) Run Kibana Container docker run -i --network mynetwork -p 5601:5601 kibana:4.6 I get a JSON output when I connect to Elasticsearch via http://localhost:9200/ through my browser. But when I open http://localhost:5601/ I get Unable to connect to Elasticsearch at http://elasticsearch:9200. Alternate Approach, I still get a similar error when I try docker run -d -e ELASTICSEARCH_URL=http://127.0.0.1:9200 -p 5601:5601 kibana:4.6 where I get the error Unable to connect to Elasticsearch at http://127.0.0.1:9200. My blog post based on the accepted answer: https://gunith.github.io/docker-kibana-elasticsearch/ Now provide the response and nothing else.
There is some misunderstanding about what localhost or 127.0.0.1 means when running a command inside a container. Because every container has its own networking, localhost is not your real host system but either the container itself. So when you are running kibana and pointing the ELASTICSEARCH_URL variable to localhost:9200 the kibana process will look for elasticsearch inside the kibana container which of course isn't running there. You already introduced some custom network that you referenced when starting the containers. All containers running in the same network can reference each other via name on their expose d ports (see Dockerfiles). As you named your elasticsearch container elasticsearch_2_4 , you can reference the http endpoint of elasticsearch as http://elasticsearch_2_4:9200 . docker run -d --network mynetwork -e ELASTICSEARCH_URL=http://elasticsearch_2_4:9200 -p 5601:5601 kibana:4.6 As long as you don't need to access the elasticsearch instance directly, you can even omit mapping the ports 9200 and 9300 to your host. Instead of starting all containers on their own, I would also suggest to use docker-compose to manage all services and parameters. You should also consider mounting a local folder as volume to have the data persisted. This could be your compose file. Add the networks , if you need to have the external network, otherwise this setup just creates a network for you. version: "2"services: elasticsearch: image: elasticsearch:2.4 ports: - "9200:9200" volumes: - ./esdata/:/usr/share/elasticsearch/data/ kibana: image: kibana:4.6 ports: - "5601:5601" environment: - ELASTICSEARCH_URL=http://elasticsearch:9200
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40341346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264069/']}
jdg_84828
stackexchange
llm_judgeable_groundtruth_similarity
26657398
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 select attribute value by giving attribute name (only starts with)For instance if we have html tag <div class = "slide" data-confirmID = "46" confirmID = "54"/> I want to select the value from the attribute starts with data- Thanks in advance for the help. Now provide the response and nothing else.
If you want all data-* attributes, you can iterate through jq data object: $('.slide').each(function(){ for(data in $(this).data()) console.log(data); // returns confirmID so element as an attribute `data-confirmID`}); But this data object can contains other keys which aren't attribute, setted for example by some plugins. EDIT To get all kinds of attribute to "starts with", you can customize your own jQuery selector: jQuery.extend(jQuery.expr[':'], { attrStartsWith: function (el, _, b) { for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) { if(atts[i].nodeName.toLowerCase().indexOf(b[3].toLowerCase()) === 0) { return true; } } return false; }});//e.g:$('.slide:attrStartsWith("data-")').css('color', 'red');$('.slide:attrStartsWith("conf")').css('color', 'blue'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div class="slide" data-confirmID="46" data-testID="666">1</div><div class="slide" confirmID="54" >2</div> If on the opposite side, you want to check for attribute ends with specific string, you can use: jQuery.extend(jQuery.expr[':'], { attrEndsWith: function (el, _, b) { for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++) { var att = atts[i].nodeName.toLowerCase(), str = b[3].toLowerCase(); if(att.length >= str.length && att.substr(att.length - str.length) === str) { return true; } } return false; }});$('.slide:attrEndsWith("testID")').css('color', 'red'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div class="slide" data-confirmID="46" data-testID="666">1</div><div class="slide" confirmID="54" >2</div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26657398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3111581/']}
jdg_84829
stackexchange
llm_judgeable_groundtruth_similarity
31539804
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unbuffered channels block receivers until data is available on the channel. It's not clear to me how this blocking behaves with multiple receivers on the same channel (say when using goroutines). I am sure they would all block as long as there is no data sent on that channel. But what happens once I send a single value to that channel? Which receiver/goroutine will get the data and therefore unblock? All of them? The first in line? Random? Now provide the response and nothing else.
A single random (non-deterministic) one will receive it. See the language spec : Execution of a "select" statement proceeds in several steps: For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated. If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed. Unless the selected case is the default case, the respective communication operation is executed. If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned. The statement list of the selected case is executed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31539804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2800522/']}
jdg_84830
stackexchange
llm_judgeable_groundtruth_similarity
24791625
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 wondering what should be done when poll set these bits? Close socket, ignore it or what? Now provide the response and nothing else.
A POLLHUP means the socket is no longer connected. In TCP, this means FIN has been received and sent. A POLLERR means the socket got an asynchronous error. In TCP, this typically means a RST has been received or sent. If the file descriptor is not a socket, POLLERR might mean the device does not support polling. For both of the conditions above, the socket file descriptor is still open, and has not yet been closed (but shutdown() may have already been called). A close() on the file descriptor will release resources that are still being reserved on behalf of the socket. In theory, it should be possible to reuse the socket immediately (e.g., with another connect() call). A POLLNVAL means the socket file descriptor is not open. It would be an error to close() it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24791625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3790882/']}
jdg_84831
stackexchange
llm_judgeable_groundtruth_similarity
2436555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two traits, one extending the other, each with an inner class, one extending the other, with the same names: trait A { class X { def x() = doSomething() }}trait B extends A { class X extends super.X { override def x() = doSomethingElse() }}class C extends B { val x = new X() // here B.X is instantiated val y = new A.X() // does not compile val z = new A.this.X() // does not compile} How do I access A.X class in the C class's body? Renaming B.X not to hide A.X is not a preferred way. To make things a bit complicated, in the situation I have encountered this problem the traits have type parameters (not shown in this example). Now provide the response and nothing else.
trait A { class X { def x() = "A.X" }}trait B extends A { class X extends super.X { override def x() = "B.X" }}class C extends B { val self = this:A val x = new this.X() val y = new self.X()}scala> val c = new Cc: C = C@1ef4bscala> c.x.x res0: java.lang.String = B.Xscala> c.y.xres1: java.lang.String = A.X
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2436555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288315/']}
jdg_84832
stackexchange
llm_judgeable_groundtruth_similarity
37606581
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 implement DbContext for couple of tables called ' Employee ' and ' Department 'Relationship between Employee and Department is many to one. i.e. department can have many employees. Below are the EntityFramework classes I designed ( CodeFirst approach ) [Table("Employee")] public class Employee { [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Column("Name")] public string Name { get; set; } [Column("Department_ID")] public int Department_ID { get; set; } public virtual Department Department { get; set; } }[Table("Department")] public class Department { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } [Column("Name")] public string Name { get; set; } public virtual ICollection<Employee> Employees { get; set; } } While adding Employee record I am getting below exception "Invalid column name 'Department_ID1'." I am not sure why EF is referring to Department_ID1 . Do I need to add configuration in OnModelCreating method of DbContext ? I am using EF version 6.1.1 Now provide the response and nothing else.
Hi After spending some time I could fix this problem by using ForeignKey attribute on public virtual Department Department { get; set; } property of Employee class. Please see below code. [Table("Employee")]public class Employee{ [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Column("Name")] public string Name { get; set; } [Column("Department_ID")] public int Department_ID { get; set; } [ForeignKey("Department_ID")] public virtual Department Department { get; set; }} This fixed my problem. Are there any other solution to fix this? Using fluent API?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37606581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2243747/']}
jdg_84833
stackexchange
llm_judgeable_groundtruth_similarity
5317642
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 been designing a program using Visual C# and have came across an issue with making my program interact with web browsers. Basically what I need is to retrieve the URL address from a web browser (Internet Explorer, Firefox, Chrome etc...). I figured this wouldn't be too difficult of a task, but after days and days of research and tests, it seems almost impossible! Thus far, I have come across this... Get Firefox URL? Which has the code below: using NDde.Client;Class Test{ public static string GetFirefoxURL() { DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo"); dde.Connect(); string url = dde.Request("URL", int.MaxValue); dde.Disconnect(); return url; }} Which is perfect for Firefox, but for some reason I cannot get it to work with anything else. I have changed the portion of the code that says "Firefox" to "Iexplore" like I found all over the internet, along with trying other forms of expressing Internet Explorer, and I get the following error: "Client failed to connect to "IExplorer|WWW_GetWindowInfo", Make sure the server application is running and that it supports the specified service name and topic name pair" Any help on the issue would be much appreciated as it has become quite a task to figure out. Now provide the response and nothing else.
Here is a code based on Microsoft UI Automation : public static string GetChromeUrl(Process process){ if (process == null) throw new ArgumentNullException("process"); if (process.MainWindowHandle == IntPtr.Zero) return null; AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle); if (element == null) return null; AutomationElement edit = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;}public static string GetInternetExplorerUrl(Process process){ if (process == null) throw new ArgumentNullException("process"); if (process.MainWindowHandle == IntPtr.Zero) return null; AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle); if (element == null) return null; AutomationElement rebar = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "ReBarWindow32")); if (rebar == null) return null; AutomationElement edit = rebar.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); return ((ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;}public static string GetFirefoxUrl(Process process){ if (process == null) throw new ArgumentNullException("process"); if (process.MainWindowHandle == IntPtr.Zero) return null; AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle); if (element == null) return null; AutomationElement doc = element.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)); if (doc == null) return null; return ((ValuePattern)doc.GetCurrentPattern(ValuePattern.Pattern)).Current.Value as string;} You can use the UI Spy tool to understand the visual hierarchy for all 3 browsers. You may need to adapt things to make sure it really work in your specific cases, but you should get the general idea with these samples. And an example that dumps all urls for all the 3 types of process (IE, FF, CH) currently running in the system: static void Main(string[] args){ foreach (Process process in Process.GetProcessesByName("firefox")) { string url = GetFirefoxUrl(process); if (url == null) continue; Console.WriteLine("FF Url for '" + process.MainWindowTitle + "' is " + url); } foreach (Process process in Process.GetProcessesByName("iexplore")) { string url = GetInternetExplorerUrl(process); if (url == null) continue; Console.WriteLine("IE Url for '" + process.MainWindowTitle + "' is " + url); } foreach (Process process in Process.GetProcessesByName("chrome")) { string url = GetChromeUrl(process); if (url == null) continue; Console.WriteLine("CH Url for '" + process.MainWindowTitle + "' is " + url); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5317642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661346/']}
jdg_84834
stackexchange
llm_judgeable_groundtruth_similarity
34499875
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 more cost effective ways to deploy my Rails apps, and went through the Ruby Starter Projects to get a feel for Google Cloud Platform. It's almost perfect, and certainly competitive on price, but I can't figure out how to automatically delete old deployed version instances after redeploying. ie: let's say I have one version of each instance running: And then I make a change to my app and redeploy with: $ gcloud preview app deploy app.yaml worker.yaml --promote So now I have two versions of each instance deployed (as Google switches between them intelligently, I'd assume): But now what? Will these instances ever turn off by themselves? The best way I've found of getting rid of them so far is from the tutorial's Deleting the project page : Deleting app versions You can find the list of your app versions in the Versions page . To delete the non-default versions, select the check boxes and then click Delete . Is everyone on Google App Engine just manually deleting the old deployments of their apps? Now provide the response and nothing else.
To stop all instances of all non-default versions of all modules (independently of what languages those modules are in), you could add a small control module, written in Python, using the modules API: from google.appengine.api.modules import modules# core logic (inside a cron or other handler)for m in modules.get_modules(): dv = modules.get_default_version(m) for v in modules.get_versions(m): if v != dv: modules.stop_version(m, v) This doesn't delete the non-default versions (the modules API does not appear to currently support deletion), but does ensure that none of their instances are running (so no charges would be incurred for them). This core logic is meant for you to wrap it inside a handler, so you can trigger it as required, for example in a cron job, or in a "regular" handler that you trigger from the outside (with appropriate auth) e.g. via wget or curl within your bash scripts. I don't believe there's a Ruby version of Python's google.appengine.api.modules.modules , but, I could be wrong... I just couldn't find one. However, a simple Python-coded module should let you control modules coded in whatever other App Engine language (since App Engine lets you mix and match modules coded in different languages).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34499875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1298553/']}
jdg_84835
stackexchange
llm_judgeable_groundtruth_similarity
34519435
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 script which is uploading and saving video's correctly but I want to rename the video before saving. The page upload-video.php ends in .php?video_id=556 , in this example I want to save the video as 556 $video_id=$_GET["video_id"]; $target_dir = "video_uploads/"; And the move script: move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file Can anyone advise? Now provide the response and nothing else.
Thanks for sharing your code as a Gist. There are two changes that are necessary to make the shapes agree: The line: fc1 = tf.reshape(pool5, [-1, wd1Shape[0]]) ...is responsible for the erroneous 49 in the batch dimension. The input is 1 x 7 x 7 x 256, and it is reshaped to be 49 x 256, because wd1Shape[0] is 256. One possible replacement is the following: pool5Shape = pool5.get_shape().as_list()fc1 = tf.reshape(pool5, [-1, pool5Shape[1] * pool5Shape[2] * pool5Shape[3]]) ...which will give fc1 the shape 1 x 12544. After making this change, the size of the 'wd1' weight matrix (256 x 4096) doesn't match the number of nodes in fc1 . You could change the definition of this matrix as follows: 'wd1': tf.Variable(tf.random_normal([12544, 4096])), ...although you may want to modify the other weights, or perform additional pooling to reduce the size of this matrix.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34519435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_84836
stackexchange
llm_judgeable_groundtruth_similarity
18975746
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 developing a web application and I use JSF and PrimeFaces frameworks and external Geo Map API. The Map API gives me POI_id when I clicked on a POI on the map. But it's not enough for me, I want to get information about POI from a servlet and display it in a pop-up window. (fields like address, name, phone number, etc.). So, I need to send an HTTP request to the servlet in my managed bean when I click the POI on the map. I can get poi_id , but I cannot send this id to the backend managed bean, so getting the POI information does not seem possible. How can I send poi_id to my managed bean and handle the response to display in a popup window? Now provide the response and nothing else.
Just to add to Kishor's (halfway) answer, you need to have a to-be-updated component in your view (popup window as you call it) and ajax-update it after the request has been successfully completed. You can use remote command to send the AJAX request with an extra parameter attached and ajax-update the JSF component responsible to be a popup window. Like so (for PrimeFaces 3.x): <p:remoteCommand name="myRemote" actionListener="#{myBean.listen}" update="dialog" oncomplete="dlg.show()" />...<div onclick="myremote([{name:'poi_id', value:poi_id}]);">...</div>...<p:dialog id="dialog" widgetVar="dlg"> <h:outputText value="#{myBean.address}" /> ...(display other information)</p:dialog> with String address;public void listen(){ String poi_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("poi_id"); address = getAddress(poi_id);} The alternative to using a remote command is to have a hidden form with a hidden input that will be used to transmit the parameter to the backing bean, that could be separated from other beans to handle the retrieval of necessary information based on your poi_id : <h:form id="poi-form" styleClass="invisible"> <h:inputHidden id="poi" value="#{poiBean.poi}" /> <p:commandButton id="info" action="#{poiBean.info}" update="dialog" oncomplete="dlg.show()" /></h:form><div onclick="document.getElementById('poi-form:poi').value = poi_id; document.getElementById('poi-form:info').click();">...</div>...<p:dialog id="dialog" widgetVar="dlg"> <h:outputText value="#{poiBean.address}" /> ...(display other information)</p:dialog> with @ManagedBean@RequestScopedpublic class PoiBean { private String poi;//getter+setter private String address;//getter //other properties public void listen(){ address = getAddress(poi); //other properties }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18975746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1172945/']}
jdg_84837
stackexchange
llm_judgeable_groundtruth_similarity
5120914
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 text file that I read into a data table and then perform a bulk insert into a SQL Server table. It's quite fast and it works great when all the imported values are treated as strings (dates, strings, ints, etc are all imported into string fields). Now that I have the concept worked out, I'm going back to assign real datatypes in the database and my code. The database has the correct types assigned to the fields. I'm working on the code now. I'm having a problem with dates. As I mentioned, everything is a string and gets converted to the correct type. In the following code, I want to test if the string value representing a date is null or whitespace. If it isn't null, then use the existing value. Otherwise, set it to null. row[i] = !string.IsNullOrWhiteSpace(data[i]) ? data[i] : DBNull.Value; I tried using null but get an error telling me to use DBNull instead. When I use DBNull , I get a message telling me there is no implicit conversion between string and System.DBNull . The columns in the datatable have datatypes specified (in this case, DataType = Type.GetType("System.DateTime") ) and I set AllowDBNull = true for this column How do I handle this? Thanks! Now provide the response and nothing else.
The problem is because of the operation you are using. Since DBNull.Value is not a string, you can't use the conditional operator. This is because, from the conditional operator docs : Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other. Try doing this: if (!string.IsNullOrWhiteSpace(data[i])) row[i] = data[i];else row[i] = DBNull.Value; This bypasses the conversion requirements for both sides to be the same. Alternatively, you can cast both to a System.Object explicitly, and still use the conditional operator.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5120914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98215/']}
jdg_84838
stackexchange
llm_judgeable_groundtruth_similarity
897740
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 fact that $$\lim_{h\to 0} \frac{\sin(h)}{h}=1,$$compute the following limit: $$\lim_{h\to 0}\frac{\sin(x+h) - \sin(x)}{h}\ $$ How would I go about solving this problem? I have attempted to use trig identities (addition of angles) to try to simplify the problem, but it only seemed to make it worse... Now provide the response and nothing else.
\begin{align*}\lim_{h \rightarrow 0} \frac{\sin(x+h)-\sin x}h &=\lim_{h \rightarrow 0} \frac{(\sin x \cos h + \cos x \sin h)-\sin x}h & \text{trigonometric sum formula} \\&=\lim_{h \rightarrow 0} \frac{\sin x(\cos h-1) + \cos x \sin h}h &\text{shuffle terms in numerator} \\&=\lim_{h \rightarrow 0} \left(\frac{\sin x(\cos h-1)}h + \frac{\cos x \sin h}h \right) & \text{break the fraction} \\&=\lim_{h \rightarrow 0} \frac{\sin x(\cos h-1)}h +\lim_{h \rightarrow 0} \frac{\cos x \sin h}h \\&=\sin x \lim_{h \rightarrow 0} \frac{\cos h-1}h + \cos x \lim_{h \rightarrow 0} \frac{\sin h}h \\&= \sin x \cdot 0 + \cos x \cdot 1 & \text{apply limit indentities}\\&= \cos x. & \text{simplify}\end{align*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/897740', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169763/']}
jdg_84839
stackexchange
llm_judgeable_groundtruth_similarity
25466718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Previous to iOS8 we used the UIActionSheet for showing alert and now we need to use the UIAlertController. When we used the UIActionSheet we could easily handle situations where the user clicked outside the pop up (which means he want to cancel the operation) by comparing the clickedButtonAtIndex to the cancelButtonIndex - if the user indeed pressed outside the popup we got the cancel button index in this function. How can we handle these situations with the new UIAlertController? I tried to use the "completion" block but it doesn't have any context. Is there an easy way to handle this? (other than "saving" the actions states in some general variable). Now provide the response and nothing else.
You can add an action with style:UIAlertActionStyleCancel and the handler for this action is called when the user taps outside the popup. if ([UIAlertController class]) { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet]; [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"User clicked button called %@ or tapped elsewhere",action.title); }]]; [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { NSLog(@"User clicked button called %@",action.title); }]]; [alertController addAction:[UIAlertAction actionWithTitle:@"Other" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { NSLog(@"User clicked button called %@",action.title); }]]; UIControl *aControl = (UIControl *) sender; CGRect frameInView = [aControl convertRect:aControl.bounds toView:self.view]; alertController.popoverPresentationController.sourceRect = frameInView; alertController.popoverPresentationController.sourceView = self.view; alertController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny; [self presentViewController:alertController animated:YES completion:nil];}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25466718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1619554/']}
jdg_84840