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
13235559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: class Foo{ public static void main(String args[]){ final int x=101; int y; if(x>100){ y=-1; } System.out.println(y); }} Java compiler understands the condition of the if statement is always true and therefore y will always be initialized. No compile error, as expected. class Bar{ public static void main(String args[]){ final int x; x=101; int y; if(x>100){ y=-1; } System.out.println(y); }} But when I break the declaration and initialization of x into two lines, the compiler does not seem to get that the condition is always true and y will always be initialized. final int x;x=101;byte b;b=x;System.out.println(b); Same thing happens here and the compiler gives a loss of precision error. final int x=101;byte b;b=x;System.out.println(b); Again, the compiler can understand that x is inside the range of b. Now provide the response and nothing else.
As part of aiming for portability, there is a very specific set of rules for what a compiler should accept and what it should reject. Those rules both permit and require only a limited form of flow analysis when determining whether a variable is definitely assigned at its use. See the Java Language Specification Chapter 16. Definite Assignment The critical rule is the one in 16.2.7. if Statements , "if (e) S" case. The rule for being definitely assigned expands to: V is assigned after if (e) S if, and only if, V is assigned after S and V is assigned after e when false. y is the relevant V . It is unassigned before the if statement. It is indeed assigned after S , y = {y=-1;} but there is nothing making it assigned when x>100 is false. Thus y is not definitely assigned after the if statement. A more complete flow analysis would determine that the condition x>100 is always true, but the compiler is required by the JLS to reject the program based on these specific rules. The final variable is fine. The rule is actually: - "It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment." The declaration leaves it definitely unassigned, and even the limited flow analysis can determine that x is still definitely unassigned at the assignment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13235559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1800515/']}
jdg_78941
stackexchange
llm_judgeable_groundtruth_similarity
2286212
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 many solutions does the equation $x^2-y^2=5^{29}$ have, given that $x$ and $y$ are positive integers? Someone told me that it has $(29+1)/2=15$ solutions. How come? Any other method to solve this? Now provide the response and nothing else.
First, factorise :$$x^2-y^2=(x-y)(x+y)=5^{29}.$$Then by the Fundamental Theorem of Arithmetics, both factors must be powers of $5$, i.e.$$\left\{\begin{array}{}x+y & = & 5^a \\ x-y & = & 5^b,\end{array}\right.$$with $a+b=29$. Since $x+y>x-y$, we must have $a>b$; hence you will have one system for every $15\leq a\leq 29$. Since every system as above has a unique integer solution $$x=\frac{5^{a}+5^b}{2},\quad y=\frac{5^{a}-5^b}{2},$$we obtain the $15$ solutions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2286212', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114097/']}
jdg_78942
stackexchange
llm_judgeable_groundtruth_similarity
33653946
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't seem to figure out why: let a = Box::new(5i32);let _:() = *a; tells me that the assigned type on the second line is i32 and not &i32 since Deref.deref() (which I assume is being called at *a ), returns &T . Also, if I were to call deref() myself: let _:() = <Box<i32> as Deref>::deref(&a); I get the expected &i32 . Now provide the response and nothing else.
*foo is not the same as calling foo.deref() . If it were, you'd never be able to actually dereference a value. ^_^ * is syntactic sugar for "call Deref::deref and then go into the address provided". This is just what people expect from that operator. Deref exists to make it extensible. That last bit glosses over some details that bluss' answer covers much better . See also: How do I get an owned value out of a `Box`?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33653946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/319954/']}
jdg_78943
stackexchange
llm_judgeable_groundtruth_similarity
193931
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: Does anyone of you know how to specify the simulation when a deformable body is affected by contact with some rigid body? I think it should be possible, but I am unable to find it in the manual. Now provide the response and nothing else.
Since I want to perform the simulation of indentation with spherical tip, I have found more suitable answer thanks to prof. Stanisław Stupkiewicz from IPPT. Actually, there is much simpler way to implement contact with rigid obstacle. The point is to generate a contact element which has in itself implemented the contact with a surface. In case of a sphere, we calculate the normal gap by calculating the distance from the integration point to the center of a sphere and subtract the sphere's radius. Then the solution can be obtained either using penalty method or augmented Lagrangian. In case you apply this solution to your contact problem and publish the results somewhere, please cite the paper: Stupkiewicz, Stanisław, Jakub Lengiewicz, and Jože Korelc. "Sensitivity analysis for frictional contact problems in the augmented Lagrangian formulation." Computer Methods in Applied Mechanics and Engineering 199.33-36 (2010): 2165-2176. It is also recommended to read and understand section 3 of the paper before running anything. So first, you need to generate the contact element. << AceGen`;SMSInitialize["COR2S1ALFLsphere", "Environment" -> "AceFEM", "Mode" -> "Optimal"];SMSTemplate[ "SMSTopology" -> "S1", "SMSNoNodes" -> 8, "SMSDOFGlobal" -> {3, 3, 3, 3, 1, 1, 1, 1}, "SMSDefaultIntegrationCode" -> 5, "SMSAdditionalNodes" -> "{#1,#2,#3,#4}&", "SMSNodeID" -> {"D", "D", "D", "D", "Lagr", "Lagr", "Lagr", "Lagr"}, "SMSReferenceNodes" -> { {-1, -1, 0}, {1, -1, 0}, {1, 1, 0}, {-1, 1, 0}, {-1, -1, 0}, {1, -1, 0}, {1, 1, 0}, {-1, 1, 0}}, "SMSSymmetricTangent" -> True, "SMSGroupDataNames" -> { "X0 -sphere center", "Y0 -sphere center", "Z0 -sphere center", "R -sphere radius", "ρ -regularization parameter"}, "SMSDefaultData" -> {0., 0., 0., 1., 1.} ];SMSStandardModule["Tangent and residual"];SMSDo[IpIndex, 1, SMSInteger[es$$["id", "NoIntPoints"]]];initializataion[] := ( (* Element data *) {X0, Y0, Z0, R, ρ} ⊨ SMSReal[Array[es $$["Data", #1] &, 5]]; {Xi, Yi, Zi} ⊨ Array[SMSReal[nd$$ [#2, "X", #1]] &, {3, 4}]; {ui, vi, wi} ⊨ Array[SMSReal[nd $$[#2, "at", #1]] &, {3, 4}]; λNi ⊨ Array[SMSReal[nd$$ [4 + #1, "at", 1]] &, 4]; at = Join[ Transpose[{ui, vi, wi}], λNi ] // Flatten; (* Numerical integration *) {ξ, η, ζ, wGauss} ⊢ Array[SMSReal[es$$["IntPoints", #1, IpIndex]] &, 4]; (* Shape functions *) Ni ⊨ 1/4*{(1 - ξ)(1 - η), (1 + ξ)(1 - η), (1 + ξ)(1 + η), (1 - ξ) (1 + η)}; {X, Y, Z, u, v, w, λN} ⊨ {Xi, Yi, Zi, ui, vi, wi, λNi}.Ni; rξ ⊨ SMSD[{X, Y, Z}, ξ]; rη ⊨ SMSD[{X, Y, Z}, η]; dA ⊨ Cross[rξ, rη]; Jd ⊨ SMSSqrt[dA.dA]; (* Normal gap *) xS ⊨ {X, Y, Z} + {u, v, w}; x0 ⊨ {X0, Y0, Z0}; gN ⊨ SMSSqrt[(xS - x0).(xS - x0)] - R; ); initializataion[]; (* Augmented Lagrangian of contact *) λNaug ⊨ λN + ρ gN; Lagr ⊨ SMSIf[ λNaug < -10^-10 , (λN + ρ/2 gN) gN , -1/(2 ρ) λN^2 ];(* Tangent and residual *)SMSDo[i, 1, SMSNoDOFGlobal]; dLagr ⊨ Jd wGauss SMSD[Lagr, at, i]; SMSExport[dLagr, p $$[i], "AddIn" -> True]; SMSDo[j, i, SMSNoDOFGlobal]; ddLagr ⊨ SMSD[dLagr, at, j]; SMSExport[ddLagr, s$$ [i, j], "AddIn" -> True]; SMSEndDo[];SMSEndDo[];SMSEndDo[];(* Postprocessing *)SMSStandardModule["Postprocessing"];SMSGPostNames = {"Contact pressure", "Normal gap"};SMSDo[IpIndex, 1, SMSInteger[es $$["id", "NoIntPoints"]]]; initializataion[]; SMSExport[{λN, gN}, gpost$$ [IpIndex, #1] &];SMSEndDo[];SMSNPostNames = {"DeformedMeshX", "DeformedMeshY", "DeformedMeshZ"};{ut, vt, wt} ⊨ Array[SMSReal[nd $$[#2, "at", #1]] &, {3, 4}];SMSExport[{ut, vt, wt} // Transpose, npost$$ ];SMSWrite[];SMTMakeDll[] Then you can perform the simulation: << AceFEM`;wx = 1; wy = 1; wz = 1; r = 0.5;{Nx, Ny, Nz} = 20 {1, 1, 1};SMTInputData["CDriver"];SMTAddDomain["body", "BI:SED3H1DFHYH1NeoHooke", {"E *" -> 1, "ν *" -> 0.4}];SMTAddDomain["contact", "COR2S1ALFLsphere", {"X0 *" -> 0, "Y0 *" -> 0, "Z0 *" -> wz + r, "R *" -> r, "ρ *" -> 1}, "IntegrationCode" -> 5];SMTAddMesh[Hexahedron[ {{-wx/2, -wy/2, 0}, {wx/2, -wy/2, 0}, {wx/2, wy/2, 0}, {-wx/2, wy/2, 0}, {-wx/2, -wy/2, wz}, {wx/2, -wy/2, wz}, {wx/2, wy/2, wz}, {-wx/2, wy/2, wz}} ], "body", "H1", {Nx, Ny, Nz}];SMTAddMesh[ Polygon[{{-wx/2, -wy/2, wz}, {wx/2, -wy/2, wz}, {wx/2, wy/2, wz}, {-wx/2, wy/2, wz}}], "contact", "S1", {Nx, Ny}];SMTAddEssentialBoundary[{"Z" == 0 && "ID" == "D" &, 1 -> 0, 2 -> 0, 3 -> wz}];SMTAnalysis["Output" -> "temp.out"];SMTNextStep[1, 0.0025];SMTNewtonIteration[];While[ While[ (step = SMTConvergence[10^-8, 10, {"Adaptive", 8, 0.00001, 0.005, .2}]), SMTNewtonIteration[]; ]; (* SMTStatusReport[]; *) If[step[[4]] === "MinBound", SMTStatusReport["Δλ < Δλmin"];]; step[[3]] , If[step[[1]], SMTStepBack[];]; SMTNextStep[1, step[[2]]]];SMTStatusReport[];SMTShowMesh[ "DeformedMesh" -> True, "User" -> {Opacity[.2], (Sphere[{0, 0, wz + r}, r])}, ImageSize -> 250]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/193931', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/49493/']}
jdg_78944
stackexchange
llm_judgeable_groundtruth_similarity
209805
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: One of the fun tidbits that gets bandied around in physics departments is that the Mississippi River actually flows away from the center of the Earth. Due to the Earth's oblateness, the source of the Mississippi is actually significantly closer to the Earth's center than the mouth is, and it's only because of the Earth's rotation (and the centrifugal force present in a reference frame rotating with the Earth) that the water in the Mississippi ends up in the Gulf of Mexico. My questions are two: Does this mean that the Mississippi would flow north if the rotation of the Earth stopped? I'm leery of just looking at the distance to the center of the Earth, since the oblateness of the Earth also causes a distortion of its gravity field (i.e., the equipotential surfaces are no longer perfect spheres), and this distortion would seem to be on the same order of magnitude as the small differences in elevation we're considering. In other words, if one uses the actual gravitational potential for a non-rotating oblate spheroid, is the Gulf of Mexico at a higher gravitational potential than Minnesota? Are there any other rivers in the world for which this is true? Obviously these would need to be rivers that flow towards the equator with a very shallow gradient (elevations measured relative to "sea level", which would be one of the equipotentials measured above.) EDIT: For clarity's sake, assume that the Earth would remain the same shape if it wasn't rotating. (In reality, hydrostatic forces would eventually pull a non-rotating Earth into sphericity, but for this question I'm interested in the difference between an oblate, rotating Earth and an oblate, non-rotating Earth.) Now provide the response and nothing else.
Are there any other rivers in the world for which this is true? The Mekong, at least after it has left the Tibetan plateau. Location Latitude Elevation (m) Radial distance (km)Source 33° 42' 30" 5224 6376.8Manwan Reservoir 24° 45' 15.5" 997 6375.4Ruak River mouth 20° 21' 16" 336 6375.9Mekong delta 9° 27' 30" 0 6377.6 While the Mekong does flow "downhill" (toward the center of the Earth) at the start thanks to that four kilometer drop in altitude across the Tibetan plateau, it's pretty much all uphill from the Manwan Reservoir on. If one uses the actual gravitational potential for a non-rotating oblate spheroid, is the Gulf of Mexico at a higher gravitational potential than Minnesota? There's a nice what-if scenario at esri, the Environmental Systems Research Institute, that asks and answers this question: If the Earth Stood Still: Modeling the absence of centrifugal force . The scenario investigates what would happen to the Earth's waters if the Earth somehow stopped rotating over the course of a few decades. That's a long enough span of time that the waters would have a chance to adjust, but far too short a span of time for isostasy to readjust the shape of the Earth. Not only would the Mississippi stop flowing southward, the waters of the oceans would flow away from the equator. This would leave a globe-spanning equatorial bulge of land surrounded by two polar oceans. The end result: Source: https://www.esri.com/news/arcuser/0610/nospin.html
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/209805', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/81133/']}
jdg_78945
stackexchange
llm_judgeable_groundtruth_similarity
16885
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have code like below that applies a bandpass filter onto a signal. I am quite a noob at DSP and I want to understand what is going on behind the scenes before I proceed. To do this, I want to know how to plot the frequency response of the filter without using freqz . [b, a] = butter(order, [flo fhi]);filtered_signal = filter(b, a, unfiltered_signal) Given the outputs [b, a] how would I do this? This seems like it would be a simple task, but I'm having a hard time finding what I need in the documentation or online. I'd also like to understand how to do this as quickly as possible, e.g. using an fft or other fast algorithm. Now provide the response and nothing else.
We know that in general transfer function of a filter is given by: $$H(z)=\dfrac{\sum_{k=0}^{M}b_kz^{-k}}{\sum_{k=0}^{N}a_kz^{-k}} $$ Now substitute $z=e^{j\omega}$ to evaluate the transfer function on the unit circle: $$H(e^{j\omega})=\dfrac{\sum_{k=0}^{M}b_ke^{-j\omega k}}{\sum_{k=0}^{N}a_ke^{-j\omega k}} $$ Thus this becomes only a problem of polynomial evaluation at a given $\omega$ . Here are the steps: Create a vector of angular frequencies $\omega = [0, \ldots,\pi]$ for the first half of spectrum (no need to go up to $2\pi$ ) and save it in w . Pre-compute exponent $e^{-j\omega}$ at all of them and store it in variable ze . Use the polyval function to calculate the values of numerator and denominator by calling: polyval(b, ze) , divide them and store in H . Because we are interested in amplitude, then take the absolute value of the result. Convert to dB scale by using: $H_{dB}=20\log_{10} H $ - in this case $1$ is the reference value. Putting all of that in code: %% Filter definitiona = [1 -0.5 -0.25]; % Some filter with lot's of static gainb = [1 3 2];%% My freqz calculationN = 1024; % Number of points to evaluate atupp = pi; % Evaluate only up to fs/2% Create the vector of angular frequencies at one more point.% After that remove the last element (Nyquist frequency)w = linspace(0, pi, N+1); w(end) = [];ze = exp(-1j*w); % Pre-compute exponentH = polyval(b, ze)./polyval(a, ze); % Evaluate transfer function and take the amplitudeHa = abs(H);Hdb = 20*log10(Ha); % Convert to dB scalewn = w/pi;% Plot and set axis limitsxlim = ([0 1]);plot(wn, Hdb)grid on%% MATLAB freqzfigurefreqz(b,a) Original output of freqz : And the output of my script: And quick comparison in linear scale - looks great! [h_f, w_f] = freqz(b,a);figurexlim = ([0 1]);plot(w, Ha) % minegrid onhold onplot(w_f, abs(h_f), '--r') % MATLABlegend({'my freqz','MATLAB freqz'}) Now you can rewrite it into some function and add few conditions to make it more useful. Another way (previously proposed is more reliable) would be to use the fundamental property, that frequency response of a filter is a Fourier Transform of its impulse response: $$H(\omega)=\mathcal{F}\{h(t)\} $$ Therefore you must feed into your system $\delta(t)$ signal, calculate the response of your filter and take the FFT of it: d = [zeros(1,length(w_f)) 1 zeros(1,length(w_f)-1)];h = filter(b, a, d);HH = abs(fft(h));HH = HH(1:length(w_f)); In comparison this will produce the following:
{}
{'log_upvote_score': 6, 'links': ['https://dsp.stackexchange.com/questions/16885', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/10228/']}
jdg_78946
stackexchange
llm_judgeable_groundtruth_similarity
13332833
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 a previous question , I set Equal heights on individual <li> tags from UL groups on a page. But now I realize for better theming, I'd like to take the tallest height set on a group of <li> tags within a UL group and set that to its respective parent <ul> itself specifically for better theming of my page. I have a new fiddle here where I try to find the tallest height of an <li> within a UL group and set it to the UL. The issue still is specificity. The tallest height of the the <li> from the first UL group is being set to all <ul> tags on the page. The height of the tallest <li> in UL group (row 1) is 260px and the height from Row 2 is 156px. However, 260px is still being set to both UL tags on the page. The ULs will grow upon the page so I'd like the code to be extensible without having to specify each row in JQuery. So far I have tried this: // get the height of the tallest LI within each UL group var max = Math.max.apply(Math, $(".item-list ul li").map( function(){ return $(this).height(); } ));// now render the height in each parent UL $(".item-list ul").each(function() { $(this).find(".item-list ul").height(max); }); ... but the second part does not work. This works but... $(".item-list ul").height(max); ... it puts the height of the tallest <li> on the pages for all UL tags. Ideally the final HTML should be: <div class="item-list row-1"><ul style="height: 260px;">etc...<div class="item-list row-2"><ul style="height: 156px;">etc... Working version based on this one below Now provide the response and nothing else.
If I understand you correctly, you should do the max operation in the .each() loop. function thisHeight(){ return $(this).height();}$(".item-list ul").each(function() { var thisULMax = Math.max.apply(Math, $(this).find("li").map(thisHeight)); $(this).height(thisULMax);}); I also made the map function a named function so you can reuse it. Here are a couple more solutions that are a little cleaner. This one passes a function to height() to use it as the iterator. Shortens things a bit. function thisHeight(){ return $(this).height();}$(".item-list ul").height(function() { return Math.max.apply(Math, $(this).find("li").map(thisHeight));}); Here's another way using .reduce() , though it needs a shim for IE8 and lower. function maxHeight(max, elem) { var h = $(this).height(); return max > h ? max : h;}$(".item-list ul").height(function() { return $(this).find("li").toArray().reduce(maxHeight, 0);});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13332833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/819276/']}
jdg_78947
stackexchange
llm_judgeable_groundtruth_similarity
49680040
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 does Kotlin allow variable declarations with the same name as a parameter inside a method? Then also, is there any way to access the 'hidden' parameter? For example: fun main(args: Array<String>) { val args = Any()} Now provide the response and nothing else.
This is called shadowing and it is useful for decoupling your code from other parts of the system. It is possible because names are bound to the current scope. Consider this: You subclass a class Foo from someone else, let's say an API. In your code you introduce a variable bar . The author of Foo also updates his code and also adds a variable bar . Without the local scope, you would get a conflict. By the way, this is also possible in other JVM bases languages including Java and commonly used within constructors or setters: public TestClass(int value, String test) { this.value = value; this.test = test;}public void setFoo(String foo) { this.foo = foo;} Shadowing does not only apply to parameters, other things can be shadowed too: fields, methods and even classes. Most IDEs will warn you about shadowing as it can be confusing. Recommendation for our own code: try to avoid shadowing for two reasons: your code becomes hard to read as two different things have the same name, which leads to confusion. once shadowed, you can no longer access the original variable within a scope.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49680040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3641245/']}
jdg_78948
stackexchange
llm_judgeable_groundtruth_similarity
30424394
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 a form I have certain fields, that are not validated correctly. I wish to override the django validation and put my own instead. When I override the clean() method, the field self.errors is already filled with errors from the wrongly validated fields. Which method should I override, where are these errors generated? With overriding clean() and similar methods, one can achieve only extension to the django default validation. I want to prevent this default validation from happening. Edit: tried validators Here is what I tried: 253 def validate_gallery(value):254 print 'validate galley'255 return True256 257 def validate_cover_photo(value):258 print 'validate_cf'259 return True260 261 cover_photo_widget = SelectWithDefaultOptions(attrs={262 'class': 'chosen-select-no-single',263 'id': 'select-cover-photo',264 'data-placeholder': 'Select Cover Photo',265 'style': 'width: 200px;',266 'tabindex': '-1',267 });268 269 gallery_widget = SelectWithDefaultOptions(attrs={270 'class': 'chosen-select-no-single',271 'id': 'select-galley',272 'data-placeholder': 'Select Gallery',273 'style': 'width: 200px;',274 'gallery-select': '',275 'tabindex': '-1',276 'organisator-profile-specific': '',277 });278 279 gallery = forms.ChoiceField(widget = gallery_widget, validators = [validate_gallery])280 cover_photo = forms.ChoiceField(widget = cover_photo_widget, validators = [validate_cover_photo]) Those validators are not even called. Seems like the error-seeking process ends at the validate() function call, which happens before any validators are called. Edit: posting the whole class 240 def validate_gallery(value):241 print 'validate galley'242 return True243 244 def validate_cover_photo(value):245 print 'validate_cf'246 return True247 248 class EventDetailForm(NgFormValidationMixin, NgModelForm):249 def __init__(self, *args, **kwargs):250 super(EventDetailForm, self).__init__(*args, **kwargs)251 self.fields['end_date'].required = False252 self.fields['description'].required = False253 self.fields['start_date'].input_formats = DATE_TIME_INPUT_FORMATS254 self.fields['end_date'].input_formats = DATE_TIME_INPUT_FORMATS255 256 arguments_length = len(args)257 if arguments_length > 0:258 post_data = args[0]259 self.old_title = post_data.get('old_title', None)260 261 cover_photo_widget = SelectWithDefaultOptions(attrs={262 'class': 'chosen-select-no-single',263 'id': 'select-cover-photo',264 'data-placeholder': 'Select Cover Photo',265 'style': 'width: 200px;',266 'tabindex': '-1',267 });268 269 gallery_widget = SelectWithDefaultOptions(attrs={270 'class': 'chosen-select-no-single',271 'id': 'select-galley',272 'data-placeholder': 'Select Gallery',273 'style': 'width: 200px;',274 'gallery-select': '',275 'tabindex': '-1',276 'organisator-profile-specific': '',277 });278 279 gallery = forms.ChoiceField(widget = gallery_widget, validators = [validate_gallery])280 cover_photo = forms.ChoiceField(widget = cover_photo_widget, validators = [validate_cover_photo])281 282 class Meta:283 model = Event284 fields = ('title', 'description', 'end_date', 'start_date')285 widgets = {286 'title': forms.TextInput(attrs={287 'editable-detail': '',288 }),289 'description': forms.TextInput(attrs={290 'class': 'panel-body',291 'id': 'event-description-editable',292 'editable-detail': '',293 }),294 'start_date': DateTimeWidget(attrs = {295 'class': 'datetimepicker col-xs-6',296 'id': 'event-start-date-editable',297 'editable-detail': '',298 }),299 'end_date': DateTimeWidget(attrs = {300 'class': 'datetimepicker col-xs-6',301 'id': 'event-end-date-editable',302 'editable-detail': '',303 }),304 }305 306 def clean(self):307 cleaned_data = self.cleaned_data308 309 print self.errors310 311 return cleaned_data312 313 def save(self, commit=True):314 old_title = self.old_title315 event = Event()316 317 cover_photo_title = self.cleaned_data['cover_photo']318 cover_photo = Photo.objects.filter(title=cover_photo_title)319 320 gallery_title = self.cleaned_data['gallery']321 gallery = Gallery.objects.filter(title=gallery_title)322 323 event.title = self.cleaned_data['title']324 event.description = self.cleaned_data['desription']325 event.start_date = self.cleaned_date['start_date']326 event.end_date = self.cleaned_data['end_date']327 event.cover_photo = cover_photo328 event.gallery = gallery329 330 if commit:331 event.save()332 333 return event334 In clean() I can see that the errors are there, save() is never executed. Now provide the response and nothing else.
Why not write your own Field class, that has its own validate method, as this is called before the validator itself: class MyCustomChoiceField(ChoiceField): def validate(self, value): <do something to validate your field> then use it: gallery = MyCustomChoiceField(widget = gallery_widget)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30424394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1945458/']}
jdg_78949
stackexchange
llm_judgeable_groundtruth_similarity
573275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use the new and delete operators for creating and destroying my objects. The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delete which destructs and deallocates the object. Which of the python tp_* methods do I need to provide and what must they do? Also I want to be able to create the object directly in c++ eg "PyObject *obj = new MyExtensionObject(args);" Will I also need to overload the new operator in some way to support this? I also would like to be able to subclass my extension types in python, is there anything special I need to do to support this? I'm using python 3.0.1. EDIT:ok, tp_init seems to make objects a bit too mutable for what I'm doing (eg take a Texture object, changing the contents after creation is fine, but change fundamental aspects of it such as, size, bitdept, etc will break lots of existing c++ stuff that assumes those sort of things are fixed). If I dont implement it will it simply stop people calling __init__ AFTER its constructed (or at least ignore the call, like tuple does). Or should I have some flag that throws an exception or somthing if tp_init is called more than once on the same object? Apart from that I think ive got most of the rest sorted. extern "C"{ //creation + destruction PyObject* global_alloc(PyTypeObject *type, Py_ssize_t items) { return (PyObject*)new char[type->tp_basicsize + items*type->tp_itemsize]; } void global_free(void *mem) { delete[] (char*)mem; }}template<class T> class ExtensionType{ PyTypeObject *t; ExtensionType() { t = new PyTypeObject();//not sure on this one, what is the "correct" way to create an empty type object memset((void*)t, 0, sizeof(PyTypeObject)); static PyVarObject init = {PyObject_HEAD_INIT, 0}; *((PyObject*)t) = init; t->tp_basicsize = sizeof(T); t->tp_itemsize = 0; t->tp_name = "unknown"; t->tp_alloc = (allocfunc) global_alloc; t->tp_free = (freefunc) global_free; t->tp_new = (newfunc) T::obj_new; t->tp_dealloc = (destructor)T::obj_dealloc; ... } ...bunch of methods for changing stuff... PyObject *Finalise() { ... }};template <class T> PyObjectExtension : public PyObject{... extern "C" static PyObject* obj_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { void *mem = (void*)subtype->tp_alloc(subtype, 0); return (PyObject*)new(mem) T(args, kwds) } extern "C" static void obj_dealloc(PyObject *obj) { ~T(); obj->ob_type->tp_free(obj);//most of the time this is global_free(obj) }...};class MyObject : PyObjectExtension<MyObject>{public: static PyObject* InitType() { ExtensionType<MyObject> extType(); ...sets other stuff... return extType.Finalise(); } ...}; Now provide the response and nothing else.
The documentation for these is at http://docs.python.org/3.0/c-api/typeobj.html and http://docs.python.org/3.0/extending/newtypes.html describes how to make your own type. tp_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has it's own allocator, PyType_GenericAlloc, but a type can implement a specialized allocator. tp_new is the same as Python's __new__. It's usually used for immutable objects where the data is stored in the instance itself, as compared to a pointer to data. For example, strings and tuples store their data in the instance, instead of using a char * or a PyTuple *. For this case, tp_new figures out how much memory is needed, based on the input parameters, and calls tp_alloc to get the memory, then initializes the essential fields. tp_new does not need to call tp_alloc. It can for example return a cached object. tp_init is the same as Python's __init__. Most of your initialization should be in this function. The distinction between __new__ and __init__ is called two-stage initialization , or two-phase initialization . You say " c++ just has new " but that's not correct. tp_alloc corresponds a custom arena allocator in C++, __new__ corresponds to a custom type allocator (a factory function), and __init__ is more like the constructor. That last link discusses more about the parallels between C++ and Python style. Also read http://www.python.org/download/releases/2.2/descrintro/ for details about how __new__ and __init__ interact. You write that you want to "create the object directly in c++". That's rather difficult because at the least you'll have to convert any Python exceptions that occurred during object instantiation into a C++ exception. You might try looking at Boost::Python for some help with this task. Or you can use a two-phase initialization. ;)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/573275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6266/']}
jdg_78950
stackexchange
llm_judgeable_groundtruth_similarity
537629
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 at a loss. My guess is no, but I'm new to doing these problems. It can not be solved with cross multiplication but there are other ways of solving these problems I'm sure. Thank you for any help. Now provide the response and nothing else.
No. There is no way to manipulate this ODE so that the method of separation of variables can be used. This is a first-order linear differential equation since it has the form ${dy\over dx}+P(x)y=Q(x)$. We must use an integrating factor $I(x)=e^{\int P(x)dx}$ in order to solve this ODE. $${dy\over dx}-y=x$$ Let $I(x)=e^{-x}$. We now multiply both sides of the above equation by $e^{-x}$ and obtain $$e^{-x}{dy\over dx}-e^{-x}y=e^{-x}x$$ which becomes $${d\over dx}(e^{-x}y)=e^{-x}x.$$ Now we must integrate both sides with respect to x. $$(e^{-x}y)=\int e^{-x}x dx.$$ Using integration by parts on the right-hand side integral we obtain $$(e^{-x}y)=-e^{-x}x-e^{-x}+C$$ where $C$ is a constant. So multiplying both sides of the equation by $e^x$ we obtain $$y=-x-1+Ce^{x}.$$ Thus this is the desired solution of the ODE $${dy\over dx}-y=x.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/537629', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94404/']}
jdg_78951
stackexchange
llm_judgeable_groundtruth_similarity
17690713
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I keep getting an error when I try to commit my project files using Xcode. File -> Source Control -> Commit "The operation could not be performed because no valid working copies were found.""Please verify that your files are under source control and try again." This is an existing project that is NOT under source control. How do I get my project files under source control, using Xcode? EDIT: Answered my own question. Step 1) Restart Xcode Step 2) Choose connect to repo Step 3) Enter repo address Step 4) Choose existing project folder you wish to place under version control Step 5) Voila! :) Now provide the response and nothing else.
Since a lot of folks land here when they google "Add existing project to BitBucket using Xcode" and then click through to the link that goes to my blog post on the subject, I thought I would put the information here (in the spirit of SO which discourages link only answers.) NOTE: These instructions assume you have already made a local git repository for the project. You may have done this at project creation. If not, you will need to create the local git now. See this StackOverflow post for how to do that: https://stackoverflow.com/questions/19495141/add-local-repo-for-existing-xcode-5-project For Xcode 9 and the new Beta UI for Bitbucket: Log into your BitBucket Account on their web site. Click the Create button (plus sign + in the newest version of the web UI). And click Repository. Give your new repository a name. Additional features for the repo can be configured under the Advanced menu. Make sure the check mark for Private is on if you desire that. Verify that the repository type is Git. If desired, add issue tracking, and a Wiki. Select Objective C or Swift from the language drop down. Then Create Repository. Next, you will want to add your code. On the top of the Overview page is a field with the HTTPS URL of your project. It will look something like this: https://[email protected]/xyzteam/xyzapp.git . Highlight and copy that URL text. Run Xcode and load your project. From the left pane in Xcode, select the Source Control Navigator. Expand the project node. Right click the Remotes node under your project. Select “Add Existing Remote…” Give it a remote name, such as Bitbucket. Paste the URL from step 4 into the Location. Click Add. It should now appear as a Remote location in the Source Control navigator. Once your remote has been added, you should now be able to push to the remote. Select Source Control/Push… It should show your Bitbucket remote as the destination and will show (Create) as this is the first push. Click Push. If this is the first time you are pushing this project to BitBucket, you will be asked for login credentials. The User Name will be prefilled from the URL, so enter the password. Click Okay and after some seconds, it should complete. If all goes well, you now have the repositories linked up. Go to the BitBucket site, select your repo and you should see the code. For Xcode older than version 9 and the old Bitbucket UI: Log into your BitBucket Account on their web site. Click the Create button. Give your new repository a name, a description, and make sure the check mark for Private is on if you desire that. Verify that the repository type is Git. If desired, add issue tracking, and a Wiki. Select Objective C or Swift from the language drop down. Then Create it. Next, you will want to add your code. I am assuming you have an existing project. On the page, you will select “I have an existing project” link from the Command line section. You will see instructions for linking your local git repository to the remote. There is no need to follow those instructions. However, you will see an https url listed. It will look something like this: https://[email protected]/xyzteam/xyzapp.git . Highlight and copy that URL text. Run Xcode and load your project. From the main menu, select Source Control. Under the gray “Working Copy” item, you will see a menu with your local git repo name and the currently active branch. Expand this menu and you will see an option to Configure [Your project]…. Select this. Select the Remotes pane from this screen. At the bottom, click the plus +. Select Add Remote… Now you need a name and a URL. For the name, typically just use your project name, then paste the URL copied earlier in step 5. Some people have found that they must remove the user name portion of the URL. Per the example, remove “johndoe@”. This may have to do with whether your project is set up as a team project, or an individual project. Click Add Remote. Click Done. Once your remote has been added, you should now be able to push to the remote. Select Source Control/Push…. If this is the first time you are pushing this project to BitBucket, you may be asked about keychain access and/or login credentials. Enter the appropriate responses, such as Allow for keychain. If you have already done this before, it will simply use the keychain data without further prompting. If all goes well, you now have the repositories linked up. Go to the BitBucket site, select your repo and you should see the code. If you want to see a version of this information with screen shots, see my blog post .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17690713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2580303/']}
jdg_78952
stackexchange
llm_judgeable_groundtruth_similarity
143808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time? Most of the projects compile to static libraries, this makes testing easier since each one also has a set of associated unit tests. It seems the use of static libraries prevents VS2005 from using incremental linking, so even with incremental linking turned on it does a full link every time. Would using DLLs for the sub projects make any difference? I don't really want to go through all the headers and add macros to export the symbols (even using a script) but if it would do something to reduce the 7 minute link time I will certainly consider it. For some reason using nmake from the command line is slightly faster and linking the same application on Linux (with GCC) is much faster. Visual Studio IDE 7 minutes Visual C++ using nmake from the command line - 5 minutes GCC on Linux 34 seconds Now provide the response and nothing else.
If you're using the /GL flag to enable Whole Program Optimization (WPO) or the /LTCG flag to enable Link Time Code Generation, turning them off will improve link times significantly, at the expense of some optimizations. Also, if you're using the /Z7 flag to put debug symbols in the .obj files, your static libraries are probably huge. Using /Zi to create separate .pdb files might help if it prevents the linker from reading all of the debug symbols from disk. I'm not sure if it actually does help because I have not benchmarked it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/143808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5022/']}
jdg_78953
stackexchange
llm_judgeable_groundtruth_similarity
1036929
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: Consider the interval $[0,1]$. What is the probability that a number chosen at random in $[0,1]$ is transcendental? Please give me some points on how to start this problem. Now provide the response and nothing else.
I realize this question is old but I wanted to give my explanation: The measure of the unit interval $[0,1]$ is $1$. Cantor proved that the algebraic numbers are countable, and thus the measure of the set of algebraics on $[0,1]$ is the countable union of the measures of the singletons. Since each singleton has measure zero, the set of algebraic numbers on $[0,1]$ has measure zero. Since the algebraic numbers and the transcendental numbers both partition $[0,1]$, and the set of algebraic numbers has measure zero, the set of transcendental numbers on $[0,1]$ must be of measure $1$. So the probability of picking a transcendental number on the unit interval is $1$. Measure of a subset of $[0,1]$ more or less translates to "probability".
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1036929', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294365/']}
jdg_78954
stackexchange
llm_judgeable_groundtruth_similarity
385810
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I cook frequently with aluminum foil as a cover in the oven. When it's time to remove the foil and cook uncovered, I find I can handle it with my bare hands, and it's barely warm. What are the physics for this? Does it have something to do with the thickness and storing energy? Now provide the response and nothing else.
You get burned because energy is transferred from the hot object to your hand until they are both at the same temperature. The more energy transferred, the more damage done to you. Aluminium, like most metals, has a lower heat capacity than water (ie you) so transferring a small amount of energy lowers the temperature of aluminium more than it heats you (about 5x as much). Next the mass of the aluminium foil is very low - there isn't much metal to hold the heat, and finally the foil is probably crinkled so although it is a good conductor of heat you are only touching a very small part of the surface area so the heat flow to you is low. If you put your hand flat on an aluminium engine block at the same temperature you would get burned. The same thing applies to the sparks from a grinder or firework "sparkler", the sparks are hot enough to be molten iron - but are so small they contain very little energy.
{}
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/385810', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/85056/']}
jdg_78955
stackexchange
llm_judgeable_groundtruth_similarity
17456915
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 really stumped by the logcat stacktrace (i'm not really familiar with android) whilst creating this basic method to check my device's network bandwidth. The code loads a webpage, times how long it takes, and measures the content downloaded. This value is then divided by the milliseconds that was required to load the webpage to calculate the approximate bandwidth. Code: public class MainActivity extends Activity {private int linkSpeed;private TextView textView;/** Called when the activity is created. */@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); textView = new TextView(this); textView.setTextSize(25); //Download your image Thread thread = new Thread(new Runnable() { public void run() { try { String urlString = "http://www.google.com"; long startTime = System.currentTimeMillis(); HttpGet httpRequest = new HttpGet(new URL(urlString).toURI()); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpClient.execute(httpRequest); long endTime = System.currentTimeMillis(); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity; bufHttpEntity = new BufferedHttpEntity(entity); //You can re-check the size of your file final long contentLength = bufHttpEntity.getContentLength(); // Log String TAG = "tag"; Log.d(TAG, "[BENCHMARK] Dowload time :"+(endTime-startTime)+" ms"); // Bandwidth : size(KB)/time(s) float bandwidth = contentLength / ((endTime-startTime) *1000); textView.setText("bandwidth = " + bandwidth); setContentView(textView); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); thread.start();} I'm confused about LOGCAT complaining about being incapable of creating handlers, because I never used one in this class. LOGCAT TRACE: 07-03 14:42:18.214: D/dalvikvm(2401): Late-enabling CheckJNI07-03 14:42:18.474: D/tag(2401): [BENCHMARK] Dowload time :166 ms07-03 14:42:18.474: W/dalvikvm(2401): threadid=11: thread exiting with uncaught exception (group=0x4162e930)07-03 14:42:18.474: E/AndroidRuntime(2401): FATAL EXCEPTION: Thread-20107-03 14:42:18.474: E/AndroidRuntime(2401): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()07-03 14:42:18.474: E/AndroidRuntime(2401): at android.os.Handler.<init>(Handler.java:197)07-03 14:42:18.474: E/AndroidRuntime(2401): at android.os.Handler.<init>(Handler.java:111)07-03 14:42:18.474: E/AndroidRuntime(2401): at com.android.internal.app.ActionBarImpl.<init>(ActionBarImpl.java:108)07-03 14:42:18.474: E/AndroidRuntime(2401): at android.app.Activity.initActionBar(Activity.java:1867)07-03 14:42:18.474: E/AndroidRuntime(2401): at android.app.Activity.setContentView(Activity.java:1902)07-03 14:42:18.474: E/AndroidRuntime(2401): at com.example.networkinfo.MainActivity$1.run(MainActivity.java:69)07-03 14:42:18.474: E/AndroidRuntime(2401): at java.lang.Thread.run(Thread.java:856)07-03 14:42:18.524: D/dalvikvm(2401): GC_CONCURRENT freed 232K, 5% free 7525K/7912K, paused 9ms+2ms, total 50ms07-03 14:42:18.894: D/libEGL(2401): loaded /system/lib/egl/libEGL_tegra.so07-03 14:42:18.914: D/libEGL(2401): loaded /system/lib/egl/libGLESv1_CM_tegra.so07-03 14:42:18.924: D/libEGL(2401): loaded /system/lib/egl/libGLESv2_tegra.so07-03 14:42:18.944: D/OpenGLRenderer(2401): Enabling debug mode 0 Now provide the response and nothing else.
Here's a very rough draft to illustrate the principle. program.go package mainimport ( "fmt" "os")// input gets an array from the user.func input(in *os.File) (m int, array []int) { if in == nil { in = os.Stdin } fmt.Print("Enter the size of the array, n, and the difference, m: ") var n int _, err := fmt.Fscanf(in, "%d %d", &n, &m) if err != nil { panic(err) } fmt.Print("Enter the array as a space seperated string: ") array = make([]int, n) for i := 0; i < n; i++ { _, _ = fmt.Fscan(in, &array[i]) } return m, array}func main() { m, array := input(nil) fmt.Println(m, array)} program_test.go package mainimport ( "fmt" "io" "io/ioutil" "os" "testing")func TestInput(t *testing.T) { var ( n, m int array []int ) in, err := ioutil.TempFile("", "") if err != nil { t.Fatal(err) } defer in.Close() _, err = io.WriteString(in, "4 5\n"+"1 2 3 4\n") if err != nil { t.Fatal(err) } _, err = in.Seek(0, os.SEEK_SET) if err != nil { t.Fatal(err) } n, array = input(in) if n != 5 || fmt.Sprintf("%v", array) != fmt.Sprintf("%v", []int{1, 2, 3, 4}) { t.Error("unexpected results:", n, m, array) }} Output: $ go testok command-line-arguments 0.010s
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17456915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2525501/']}
jdg_78956
stackexchange
llm_judgeable_groundtruth_similarity
744952
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 it true that a map between ${\bf T1}$ topological spaces $f:X \to Y$ is surjective iff the induced geometric morphism $f:Sh(Y) \to Sh(X)$ is a surjection (i.e. its inverse image part $f^*$ is faithful)? In "Sheaves in Geometry and Logic" a proof is given, but the the "if" part leaves me a bit unsatisfied (and, btw, the "only if" part holds for any topological space). Thanks in advance! Now provide the response and nothing else.
I'm not really sure that there is a simple solution for that. In some sense, this limit is equivalent to the theorem about the inverse Fourier transform, so there will be no simple solutions. But use Parseval/Plancherel (I never remember which one is about the Fourier series). Or proceeding more elementary: Consider for simplicity the symmetric extension of $f$, so that the integral is over $(-∞,∞)$, resulting in twice the required value. Then, using$$\frac{\sin(ax)}{x}=\frac{e^{iax}-e^{-iax}}{2ix}=\frac12\int_{-a}^a e^{ixv}dv$$one gets$$\int_{-∞}^∞ \frac{\sin(ax)}{x}f(x)\,dx = \frac12\int_{-∞}^∞\int_{-a}^a e^{ixv} f(x)\,dv\,dx$$Now we only need to apply Fubini to exchange the order of integration, so that$$...=\frac12\int_{-a}^a \sqrt{2\pi} \hat f(v) \,dv$$and by dominated convergence, this converges to$$\frac{\sqrt{2\pi}}2\int_{-∞}^∞\hat f(v) \,dv=\pi\,\widehat{\widehat{f}}(0)=\pi\,f(0)$$There still are some assumptions that need to be added so that the used Fourier integrals, especially the last one, actually exist. $L^1$ and at least quadratic decay at infinity should be sufficient. The test functions, tempered or with compact support, all satisfy these conditions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/744952', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77181/']}
jdg_78957
stackexchange
llm_judgeable_groundtruth_similarity
547167
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a certain group we can find many representations of it. And If I'm not wrong a representation is a group itself. For example, given the group of the unitary 2x2 matrices with determinant 1 $SU(2)$ , its three-dimensional representation is a subsets of 3x3 matrices that is a group itself. Since a representation is a homomorphism I expect that the group and its representation can be different groups.So it looks like there exist many groups that are related to a certain group because they are its representation. Why is it important to know the representation of a group? is there a physically important property that the representation group inherit from the group it represents? If I'm wrong feel free to correct me (I'm pretty new to the topic) I've recently wrote a related post but there were too many questions inside, maybe it's useful somehow Some clarifications about the ideas of representation of a group Now provide the response and nothing else.
One can give many examples of where specific aspects of representation theory are useful in physics (see the current other answers to this question) but the fact of the matter is simply that you cannot do physics without having representations, whether you call them that or not: Don't think about representations as "a group and a different group". Even faithful (but different) representations are relevant. A representation is a pair - it consists of both a vector space $V_\rho$ and a representation map $\rho : G \to \mathrm{GL}(V_\rho)$ that represerves the group structure, i.e. is a group homomorphism . Without a representation, the group $G$ remains abstract and acts on nothing . Whenever we ask a question like "How does X transform under rotations?" (or with "rotations" replaced by any other transformation), this is - if X lives in a vector space, as it often does, e.g. when it is any sort of number or array of numbers - the same as asking "In which representation of $\mathrm{SO}(3)$ (the rotation group) does $X$ transform?". You cannot have transformations that form a group acting on vectors without having representations. Most of physics is literally impossible to do without having a representation somewhere, since the ideas of transformations and symmetries are fundamental to all fields of physics. And questions like "If I multiply X and Y, how does their product transform?" are so natural that it is mostly unavoidable to have more than one representation. You might as well ask "Why are groups important?", because without their representations, groups aren't very interesting from a physical perspective at all (this, coincidentally, is why you'll often hear physicists say "group theory" to what mathematicians would consider "representation theory")!
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/547167', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/206319/']}
jdg_78958
stackexchange
llm_judgeable_groundtruth_similarity
15032497
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 layer objects on a Fabric.js canvas via the official API? Right now the only way I have found to do it is to manually iterate through the canvas._objects and reorder them so that they get drawn in a specific order. Is there a better way to do this that doesn't (potentially) break the object? Now provide the response and nothing else.
[Edit]I've corrected my info below (my bad, I was originally thinking of the KineticJs api). FabricJS has these API methods that change the z-index of objects: canvas.sendBackwards(myObject)canvas.sendToBack(myObject)canvas.bringForward(myObject)canvas.bringToFront(myObject) Under the covers, FabricJs changes the z-index by removing the object from the getObjects() array and splicing it back in the desired position. It has a nice optimization that checks for intersecting objects. bringForward: function (object) { var objects = this.getObjects(), idx = objects.indexOf(object), nextIntersectingIdx = idx; // if object is not on top of stack (last item in an array) if (idx !== objects.length-1) { // traverse up the stack looking for the nearest intersecting object for (var i = idx + 1, l = this._objects.length; i < l; ++i) { var isIntersecting = object.intersectsWithObject(objects[i]) || object.isContainedWithinObject(this._objects[i]) || this._objects[i].isContainedWithinObject(object); if (isIntersecting) { nextIntersectingIdx = i; break; } } removeFromArray(objects, object); objects.splice(nextIntersectingIdx, 0, object); } this.renderAll(); },
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15032497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1092323/']}
jdg_78959
stackexchange
llm_judgeable_groundtruth_similarity
34009789
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 web2py's DAL and trying to do the equivalent of this MySQL query. SELECT header.tag, detail.siteFROM header LEFT OUTER JOIN detail ON header.id= detail.headerWHERE header.tag IN ('abc', 'def', 'xyz') I presumed that the DAL equivalent was as follows, but this code is giving me a cross product. tags = ['abc', 'def', 'xyz']query = (db.header.tag.belongs(tags) & db.header.id==db.detail.header)raw_data = db(query).select( db.header.tag, db.detail.site,)SELECT header.tag, detail.site FROM header, detail; If I omit the belongs clause from my query, all works fine. query = (db.header.id==db.detail.header)raw_data = db(query).select( db.header.tag, db.detail.site,)SELECT header.tag, detail.site FROM header, detail WHERE (header.id = detail.header); I am using this version: 2.12.3-stable+timestamp.2015.08.18.19.14.07 Now provide the response and nothing else.
To check whether two wildcard patterns could match the same filename, you can look at this problem as creating a grid of comparisons between pairs of characters, and then checking whether there exists a diagonal path. The illustration below shows how wildcard patterns ab?.c?? and a*bc.* can be checked for possible conflict: When a match between two identical literal characters is found, you move diagonally to the next characters to check. (indicated with green arrow) When a literal character and a single-character wild card ? are encountered, there are two possibilities: either the wild card matches the character (move diagonally), or the wildcard matches empty space, and you skip over it. (indicated with purple arrows) When a multi-character wild card * is encountered, three possibilities need to be taken into account: the wild card matches an empty space before the other character, the wild card matches the other character, or the wild card matches multiple characters. (indicated with blue arrows) code example 1 (iterative) Below is a simple javascript implementation which iterates over the grid diagonally, marks cells which can be reached from the current cell, and then checks whether the bottom right cell is reachable. Run the code snippet to see a few examples. (update: top-to-bottom left-to-right will do fine instead of diagonally) function wildConflict(wild1, wild2) { var grid = [[true]], width = wild1.length, height = wild2.length; for (var x = 1; x <= width; x++) grid[x] = []; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { if (grid[x][y]) { var a = wild1.charAt(x), b = wild2.charAt(y); if (a == '*' || b == '*' || a == '?' || b == '?' || a == b) grid[x + 1][y + 1] = true; if (a == '*' || b == '*' || a == '?') grid[x + 1][y] = true; if (a == '*' || b == '*' || b == '?') grid[x][y + 1] = true; } } } return grid[width][height] == true;}var a = ["a", "a", "a*", "abc", "a*", "*.x.y", "*.x.y", "a*b*", "a*bc.*", "a?c.de"];var b = ["a", "b", "abc", "a?", "*b", "*.y", "*.x", "a*c*", "ab?.c??", "ac.d??"];for (var i in a) document.write("&quot;" + a[i] + "&quot; &harr; &quot;" + b[i] + "&quot; &rarr; " + wildConflict(a[i], b[i]) + "<BR>"); code example 2 (recursive) A simple recursive implementation has the drawback of potentially checking some character pairs more than once. It doesn't need the 2D-array, but the recursions obviously use memory too. Note that when a multi-character wild card * is encountered, the algorithm recurses with only two possibilities: jump over the one character, or jump over the other character; jumping over both characters (i.e. the wild card matches exactly one character) is taken care of in the next step, when the wild card is compared to the next character. function wildConflict(wild1, wild2) { var w1 = wild1.split(''), w2 = wild2.split(''); return conflict(0, 0); function conflict(p1, p2) { if (p1 == w1.length || p2 == w2.length) { if ((p1 == w1.length && p2 == w2.length) || (p1 == w1.length - 1 && (w1[p1] == '*' || w1[p1] == '?')) || (p2 == w2.length - 1 && (w2[p2] == '*' || w2[p2] == '?'))) { return true; } else return false; // premature end } else if (w1[p1] == '*' || w2[p2] == '*' || (w1[p1] == '?' && w2[p2] == '?')) { return conflict(p1 + 1, p2) || conflict(p1, p2 + 1); } else if (w1[p1] == '?') { return conflict(p1 + 1, p2) || conflict(p1 + 1, p2 + 1); } else if (w2[p2] == '?') { return conflict(p1, p2 + 1) || conflict(p1 + 1, p2 + 1); } else if (w1[p1] == w2[p2]) { return conflict(p1 + 1, p2 + 1); } else return false; // unequal literals }}var x = ["a", "a", "a*", "abc", "a*", "*.x.y", "*.x.y", "a*b*", "a*bc.*", "a?c.de"];var y = ["a", "b", "abc", "a?", "*b", "*.y", "*.x", "a*c*", "ab?.c??", "ac.d??"];for (var i in x) document.write("&quot;" + x[i] + "&quot; &harr; &quot;" + y[i] + "&quot; &rarr; " + wildConflict(x[i], y[i]) + "<BR>");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34009789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/403043/']}
jdg_78960
stackexchange
llm_judgeable_groundtruth_similarity
678514
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: Where did the CMB originate from? I get that at the beginning of the universe, by the Big Bang theory temperatures and pressures were too high for matter to exist, and even if it did, it would just get annihilated from its antimatter equivalent, thereby releasing electromagnetic radiation (EMR). However, is this the origin of the CMB? From what I know, before the whole nucleosynthesis and decoupling event, the photons would constantly get scattered and hence the universe was opaque. However, after the temperatures cooled such that neutral atoms could exist, the EMR could propagate out and not get scattered. However, I read somewhere that it was actually the decoupling event itself which was what originated the CMB. Much like flame tests, or by Bohr's second postulate , when electrons relax into the ground state or just lower energy states, EMR is released. Hence, would the relaxation of these electrons be the source of the CMB? Now provide the response and nothing else.
Once recombination occurred, the black-body radiation , which was in thermal equilibrium with matter (hydrogen plasma), became decoupled from it and was free to propagate. The temperature at which this occurred was about 3000 degrees kelvin. This means that the CMB is composed of the radiation which existed right before the decoupling i.e., what was flying around inside the 3000 K hydrogen plasma right before the plasma cooled down enough to be quenched. (Cosmic expansion then stretched out the radiation so much that its spectrum now corresponds to a very cold 2.7 degrees kelvin.)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/678514', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/314843/']}
jdg_78961
stackexchange
llm_judgeable_groundtruth_similarity
234473
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I read that virtual calls make the code slower than calling non-virtual ones in C#.However, the IL instruction for both are the same callvirt except in cases where base.somemethod() is called. So how does virtual method hurt performance? Now provide the response and nothing else.
As pointed out here , calling callvirt is slower, but by a very small margin. I'm not sure how you're getting the CIL code, but as Eric Gunnerson points out , .NET never uses call for instance classes. It always uses callvirt , and he even states in a follow-up post that the difference in performance impact is minimum. Just a very quick test, where all classes have a void PrintTest() method (which only prints a message to the console)... BaseVirtual is a base class with the method defined as virtual . DerivedVirtual and DerivedVirtual2 use override to redefine the virtual method, inheriting from BaseVirtual . Base is a regular class with a regular instance method (no virtual or sealed ). Seal is a sealed class, just for the kicks. Stat is a class with the method defined as static . Here's the main code: using System;namespace CSharp{ class Program { static void Main(string[] args) { BaseVirtual baseVirtual = new BaseVirtual(); DerivedVirtual derivedVirtual = new DerivedVirtual(); DerivedVirtual2 derivedVirtual2 = new DerivedVirtual2(); Base regularBase = new Base(); Seal seal = new Seal(); baseVirtual.PrintTest(); derivedVirtual.PrintTest(); derivedVirtual2.PrintTest(); regularBase.PrintTest(); seal.PrintTest(); Stat.PrintTest(); } }} And, here's the CIL code: .method private hidebysig static void Main(string[] args) cil managed{ .entrypoint // Code size 68 (0x44) .maxstack 1 .locals init ([0] class CSharp.BaseVirtual baseVirtual, [1] class CSharp.DerivedVirtual derivedVirtual, [2] class CSharp.DerivedVirtual2 derivedVirtual2, [3] class CSharp.Base regularBase, [4] class CSharp.Seal seal) IL_0000: newobj instance void CSharp.BaseVirtual::.ctor() IL_0005: stloc.0 IL_0006: newobj instance void CSharp.DerivedVirtual::.ctor() IL_000b: stloc.1 IL_000c: newobj instance void CSharp.DerivedVirtual2::.ctor() IL_0011: stloc.2 IL_0012: newobj instance void CSharp.Base::.ctor() IL_0017: stloc.3 IL_0018: newobj instance void CSharp.Seal::.ctor() IL_001d: stloc.s seal IL_001f: ldloc.0 IL_0020: callvirt instance void CSharp.BaseVirtual::PrintTest() IL_0025: ldloc.1 IL_0026: callvirt instance void CSharp.BaseVirtual::PrintTest() IL_002b: ldloc.2 IL_002c: callvirt instance void CSharp.BaseVirtual::PrintTest() IL_0031: ldloc.3 IL_0032: callvirt instance void CSharp.Base::PrintTest() IL_0037: ldloc.s seal IL_0039: callvirt instance void CSharp.Seal::PrintTest() IL_003e: call void CSharp.Stat::PrintTest() IL_0043: ret} // end of method Program::Main Nothing too fancy, but this shows that only the static method used call .Even so, I don't think this will really make a difference for most applications, so we shouldn't sweat on the small stuff and worry about this. So, in conclusion, as the SO post states, you may get a performance hit because of the lookup the runtime needs to call the virtual methods. Compared to static methods, you get the overhead of callvirt . ... Well, that was fun...
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/234473', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/110328/']}
jdg_78962
stackexchange
llm_judgeable_groundtruth_similarity
3579044
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that if $f:[0,1] \to \mathbb{R}$ is a continuously differentiable function with $\int_0^1 f(x)\,dx=0$ , then $$\int_0^1 \big(1-x^2\big) \big(f'(x)\big)^2\,dx \ge 24 \left(\int_0^1 xf(x)\,dx\right)^{\!2}.$$ I think that I should somehow use the Cauchy-Schwarz inequality, but I wasn't succesful in doing this. I know that $$\left(\int_0^1 xf(x)\,dx\right)^2\le \int_0^1 x^2\,dx \cdot \int _0^1 f^2(x)\,dx=\frac{1}{3}\int _0^1 f^2(x)\,dx,$$ but this is clearly not enough. Now provide the response and nothing else.
(The following is inspired by Integral inequality with a function twice differentiable : Integrating by parts transforms the integral with $f$ to an integral with $f'$ . The condition $\int_0^1 f(x) \, dx = 0$ is used to add a term to the first integral so that the $u(b)v(b)-u(a)v(a)$ term vanishes. Cauchy-Schwarz then helps to estimate the integral containing $f'$ by an integral containing $f'^2$ .) Integrating by parts we get $$ \int_0^1 xf(x) \, dx = \frac 12 \int_0^1 (2x-1)f(x) \, dx = \frac 12 \int_0^1 x(1-x) f'(x) \,dx \\= \frac 12 \int_0^1 \frac{x \sqrt{1-x}}{\sqrt{1+x}} \sqrt{1-x^2} f'(x) \, dx \, .$$ Now apply Cauchy-Schwarz: $$ \left( \int_0^1 xf(x) \, dx \right)^2 \le \frac 14 \int_0^1 \frac{x^2(1-x)}{1+x} \, dx \int_0^1 (1-x^2) (f'(x))^2 \, dx \\\le \frac 14 \int_0^1 x^2(1-x) \, dx \int_0^1 (1-x^2) (f'(x))^2 \, dx \\= \frac{1}{48 }\int_0^1 (1-x^2) (f'(x))^2 \, dx$$ which is better than the desired estimate by a factor of $2$ . Using the exact value $\int_0^1 \frac{x^2(1-x)}{1+x}\, dx = 2 \ln(2) - 4/3$ we get the sharp estimate $$ \int_0^1 (1-x^2) (f'(x))^2 \, dx \ge C \left( \int_0^1 xf(x) \, dx \right)^2 $$ with $$C = \frac{2}{\ln(2)-2/3} \approx 75.53 \, .$$ Equality holds if equality holds in the Cauchy-Schwarz inequality, and that is if $$ f'(x) = \text{const} \cdot \frac{x}{x+1}$$ so that the integrands are linearly dependent. Together with the condition $\int_0^1 f(x) \, dx = 0$ this gives (up to a multiplicative constant) $$ f(x) = x - \ln(x) + 2 \ln(2) - \frac 23 \, .$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3579044', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/600843/']}
jdg_78963
stackexchange
llm_judgeable_groundtruth_similarity
2803637
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 $K>0$ be a constant. Suppose $\{z_n\}_{n=1}^\infty$ is a non-decreasing positive sequence. Then the series $$\sum_{n=1}^\infty\frac{z_n}{(K+z_1)(K+z_2)\cdots(K+z_n)}K^n=K$$ This is a quite interesting result as the series is convergent and the limit doesn't depend on the choice of $\{z_n\}_{n=1}^\infty$, as long as it is non-decreasing and positive I have run computer simulations and this result seems to hold. However, I am not sure how to prove it. Now provide the response and nothing else.
Consider $S_n - K$: $$ -K + \dfrac{z_1}{z_1 + K}K + \dfrac{z_2}{(z_1 + K)(z_2 + K)} K^2 + ... + \dfrac{z_n}{(z_1 + K)(z_2 + K)...(z_n + K)}K^n = $$ $$-\dfrac{1}{z_1 + K}K^2 + \dfrac{z_2}{(z_1 + K)(z_2 + K)} K^2 + ... + \dfrac{z_n}{(z_1 + K)(z_2 + K)...(z_n+K)}K^n = $$ $$- \dfrac{1}{(z_1 + K)(z_2 + K)} K^3 + ... + \dfrac{z_n}{(z_1 + K)(z_2 + K)...(z_n+K)}K^n$$ and keep telescoping until you reach $$S_n - K = -\dfrac{1}{(z_1 + K)(z_2 + K)...(z_n+K)}K^n$$ Edit Sorry, I was interrupted and omit the most important part. This delta could be rewritten as $- \prod\dfrac{1}{1 + \frac{z_i}{K}}$, which vanishes as long as $\prod (1+ \dfrac{z_i}{K})$ diverges to infinity. This is equivalent to $\sum z_i$ to diverge; you don't really need the non-decreasing sequence. As long as its sum diverges, your observation holds. Try $z_i = \dfrac{1}{i}$, for example.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2803637', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/464241/']}
jdg_78964
stackexchange
llm_judgeable_groundtruth_similarity
3278860
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 user defined function which is used in many stored procedures which will return me some value. If it possible for me to add a new optional parameter to the same. If I don't pass any value it should be null and if I pass some value it should take it. I don't want to go and change all the stored procedures to do so. Example code dbo.CalculateAverageForUser(userid int) Can I use dbo.CalculateAverageForUser(userid int, type NVARCHAR(10) = NULL) Now provide the response and nothing else.
If you don't want to go adjusting all of your existing stored procedures that reference the function then I think you would need to create a new function with the code from your existing one CREATE FUNCTION CalculateAverageForUser2( @userid int, @param2 nvarchar(10) = NULL)RETURNS floatAS/*Code from existing function goes here*/ Then just change the existing function to the following ALTER FUNCTION CalculateAverageForUser ( @userid int)RETURNS floatASBEGINRETURN dbo.CalculateAverageForUser2(@userid, DEFAULT)END
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3278860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_78965
stackexchange
llm_judgeable_groundtruth_similarity
5374908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone tell me what is the difference between a primary key and index key. And when to use which? Now provide the response and nothing else.
A primary key is a special kind of index in that: there can be only one; it cannot be nullable; and it must be unique. You tend to use the primary key as the most natural unique identifier for a row (such as social security number, employee ID and so forth, although there is a school of thought that you should always use an artificial surrogate key for this). Indexes, on the other hand, can be used for fast retrieval based on other columns. For example, an employee database may have your employee number as the primary key but it may also have an index on your last name or your department. Both of these indexes (last name and department) would disallow NULLs (probably) and allow duplicates (almost certainly), and they would be useful to speed up queries looking for anyone with (for example) the last name 'Corleone' or working in the 'HitMan' department.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5374908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/658358/']}
jdg_78966
stackexchange
llm_judgeable_groundtruth_similarity
20258994
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 following form: <form name="frmInput"> <input type="hidden" ng-model="record.usersId" value="{{user.userId}}"/> <input type="hidden" ng-model="record.userNameId" value="{{user.userNameId}}"/> <label for="fileNo">AccountId</label> <input id="fileNo" ng-model="record.fileNo" required/> <label for="madeSad">MadeSad</label> <input id="madeSad" ng-model="record.madeSadNo" required/> <button ng-disabled="!frmInput.$valid" ng-click="SaveRecord(record)">Accept</button></form> I get record.fileNo and record.madeSadNo in SaveRecord function but i don't get record.usersId and record.userNameId in SaveRecord function. Where am i making mistake? values of hidden inputs are correct. Now provide the response and nothing else.
Having hidden form fields is not the Angular way. You don't need hidden fields at all, as the all the scope variables (which are not in the form) can be taken as hidden variables. As for the solution, while submitting the form, just populate the object 'record' with 'user': function SaveRecord(){ $scope.record.usersId = $scope.user.userId; $scope.record.userNameId = $scope.user.userNameId; http.post(url, $scope.record);} As a side note, you do not need to mention your variable while calling the function: <button ng-disabled="!frmInput.$valid" ng-click="saveRecord()">Accept</button>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20258994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2279977/']}
jdg_78967
stackexchange
llm_judgeable_groundtruth_similarity
270354
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: If you increase the number of photons leaving a light source you increase the brightness/intensity, so it could be said that intensity is directly proportional to number of photons. However intensity is directly proportional to amplitude squared, so this leads me to wonder that if you increase the amplitude of a light wave, are you just creating more photons rather than affecting each individual photon in some way? Now provide the response and nothing else.
Yeah, pretty much. When you increase the amplitude of a light wave, you are essentially just sending more photons of the same kind. The energy of each photon is $hf$ (though with some allowance for wavepackets, where each photon will come with as a probability distribution over a range of frequencies), so if you increase the energy flux you need to increase the photon flux. When you actually dig down on it things are not quite as simple, of course, because the exact value of the electric field is a quantum mechanical variable analogous to the position variable of a quantum harmonic oscillator, and you can't really describe it as a variable with a well-defined oscillation. (In particular, for example, if you know precisely the intensity of the light, then you lose all information about the phase of the oscillations, and vice versa.) However, the electric field is essentially confined to a region that grows as the square root of the number of photons in the mode.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/270354', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/124247/']}
jdg_78968
stackexchange
llm_judgeable_groundtruth_similarity
9386979
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 understand that hardware will limit the amount of memory allocated during program execution. However, my question is without regard to hardware. Assuming that there was no limit to the amount of memory, would there be no limit to the array? Now provide the response and nothing else.
There is no fixed limit to the size of an array in C. The size of any single object, including of any array object, is limited by SIZE_MAX , the maximum value of type size_t , which is the result of the sizeof operator. (It's not entirely clear whether the C standard permits objects larger than SIZE_MAX bytes, but in practice such objects are not supported; see footnote.) Since SIZE_MAX is determined by the implementation, and cannot be modified by any program, that imposes an upper bound of SIZE_MAX bytes for any single object. (That's an upper bound, not a least upper bound; implementations may, and typically do, impose smaller limits.) The width of the type void* , a generic pointer type, imposes an upper bound on the total size of all objects in an executing program (which may be larger than the maximum size of a single object). The C standard imposes lower bounds, but not upper bounds, on these fixed sizes. No conforming C implementation can support infinite-sized objects, but it can in principle support objects of any finite size. Upper bounds are imposed by individual C implementations, by the environments in which they operate, and by physics, not by the language. For example, a conforming implementation could have SIZE_MAX equal to 2 1024 -1, which means it could in principle have objects up to 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137215 bytes. Good luck finding hardware that actually supports such objects. Footnote : There is no explicit rule that no object can be bigger than SIZE_MAX bytes. You couldn't usefully apply the sizeof operator to such an object, but like any other operator, sizeof can overflow; that doesn't mean you couldn't perform operations on such an object. But in practice, any sane implementation will make size_t big enough to represent the size of any object it supports.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9386979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177087/']}
jdg_78969
stackexchange
llm_judgeable_groundtruth_similarity
164
Below is a question asked on the forum skeptics.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've recently noticed a spate of answers submitted that are chock full of block quotes. Now, I think it's a very admirable quality and mark of how seriously this community is taking its mission that it feels that important points need be referenced, but to be honest with you, when my eyes come across a vast chunk of text that requires me to parse content its written in the obscuring language of scientific discourse, my eyes just glaze over, and I find myself skipping the meat of the post and coming away with little. These answers are mitigating one of the great strengths of the Q/A format here on StackExchange: That you can get your answers addressed to you at your skill level, in conversational language. There are "answers" to be found all over the Internet, but little understanding. I suspect this is coming from what I foresaw to a possible problem for a Skepticism Stack Exchange, in that for many different questions most users will not be familiar with the jargon and language of the topic they're investigating. E.g., a physics student on Physics SE will be able to post sensibly using jargony terms like "D-Brane" and "Kaluza-Klein theory", but here, users will be continually stumbling into fields whose ontology and vocabulary they are unfamiliar with. Thus comes the understandable tendency to block-quote because it's tough to translate a field is one unfamiliar with. It's a kind of laziness, unfortunately. My suggestion to this community? Specialization. Choose questions to answer that you have studied at length beforehand, whose language you at least partially familiar with, and don't go undertaking research to answer every single disparate question that comes your way. Can you explain your answer and the jargony terms in it to a sixth-grader in Simple English? If not, you probably shouldn't be answering that question. If that sounds like a recipe for slower growth for this site, it is, but the converse, and ultimately worse result is unsatisfied questioners and thus an unengaged community. It's best to translate block quotes to something written in your words. Now provide the response and nothing else.
Too much block quoting? Not nearly enough block quoting, I'd say! The point of block quoting is not to dazzle with information and lull your readers into a stupor. A block quote should: Summarize your source (as opposed to merely referencing it with a link). Mitigate the effects of link rot. Consider the following example answers to the (admittedly silly) hypothetical question "Do hairdryers cause earthquakes?" . Answer 1 No. Earthquakes are a well-known phenomenon which can be chalked up to plate tectonics. You can find an explanation of plate tectonics at <third-party website> . Answer 2 No. Earthquakes are a well-known phenomenon which can be chalked up to plate tectonics. This excerpt from [third-party website] explains plate tectonics very well: Insert succinct quotation(s) from source here. (Make any clarifications or explanations of the quote here, after the quote. Either define the jargon in the quote, if present, or replace the jargon with equivalent terms using brackets.) For further reading, please refer to this [third-party website] . The second answer is better , because: It does the heavy lifting for the reader by distilling a vast amount of information into an easily-readable chunk of block quote. As you said: One of the great strengths of the Q/A format here on StackExchange [is that] you can get your answers addressed to you at your skill level, in conversational language. A link should not be the meat of your answer-- your words should. If the reader wants more details, the link is there for them. It is much less prone to decay over time. If in the future, the link changes (as links do), or the website goes away, we won't have a totally broken answer, because the relevant information is still here . In summary , block quotes are a good thing when used properly (i.e. short, to the point, and alongside a link to the original source).
{}
{'log_upvote_score': 4, 'links': ['https://skeptics.meta.stackexchange.com/questions/164', 'https://skeptics.meta.stackexchange.com', 'https://skeptics.meta.stackexchange.com/users/200/']}
jdg_78970
stackexchange
llm_judgeable_groundtruth_similarity
1440957
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I seem to be running into a peculiar problem on Android 1.5 when a library I'm using (signpost 1.1-SNAPSHOT), makes two consecutive connections to a remote server. The second connection always fails with a HttpURLConnection.getResponseCode() of -1 Here's a testcase that exposes the problem: // BROKENpublic void testDefaultOAuthConsumerAndroidBug() throws Exception { for (int i = 0; i < 2; ++i) { final HttpURLConnection c = (HttpURLConnection) new URL("https://api.tripit.com/oauth/request_token").openConnection(); final DefaultOAuthConsumer consumer = new DefaultOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1); consumer.sign(c); // This line... final InputStream is = c.getInputStream(); while( is.read() >= 0 ) ; // ... in combination with this line causes responseCode -1 for i==1 when using api.tripit.com but not mail.google.com assertTrue(c.getResponseCode() > 0); }} Basically, if I sign the request and then consume the entire input stream, the next request will fail with a resultcode of -1. The failure doesn't seem to happen if I just read one character from the input stream. Note that this doesn't happen for any url -- just specific urls such as the one above. Also, if I switch to using HttpClient instead of HttpURLConnection, everything works fine: // WORKSpublic void testCommonsHttpOAuthConsumerAndroidBug() throws Exception { for (int i = 0; i < 2; ++i) { final HttpGet c = new HttpGet("https://api.tripit.com/oauth/request_token"); final CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1); consumer.sign(c); final HttpResponse response = new DefaultHttpClient().execute(c); final InputStream is = response.getEntity().getContent(); while( is.read() >= 0 ) ; assertTrue( response.getStatusLine().getStatusCode() == 200); }} I've found references to what seems to be a similar problem elsewhere, but so far no solutions. If they're truly the same problem, then the problem probably isn't with signpost since the other references make no reference to it. Any ideas? Now provide the response and nothing else.
Try set this property to see if it helps, http.keepAlive=false I saw similar problems when server response is not understood by UrlConnection and client/server gets out of sync. If this solves your problem, you have to get a HTTP trace to see exactly what's special about the response. EDIT: This change just confirms my suspicion. It doesn't solve your problem. It just hides the symptom. If the response from first request is 200, we need a trace. I normally use Ethereal/Wireshark to get the TCP trace. If your first response is not 200, I do see a problem in your code. With OAuth, the error response (401) actually returns data, which includes ProblemAdvice, Signature Base String etc to help you debug. You need to read everything from error stream. Otherwise, it's going to confuse next connection and that's the cause of -1. Following example shows you how to handle errors correctly, public static String get(String url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); URLConnection conn=null; byte[] buf = new byte[4096]; try { URL a = new URL(url); conn = a.openConnection(); InputStream is = conn.getInputStream(); int ret = 0; while ((ret = is.read(buf)) > 0) { os.write(buf, 0, ret); } // close the inputstream is.close(); return new String(os.toByteArray()); } catch (IOException e) { try { int respCode = ((HttpURLConnection)conn).getResponseCode(); InputStream es = ((HttpURLConnection)conn).getErrorStream(); int ret = 0; // read the response body while ((ret = es.read(buf)) > 0) { os.write(buf, 0, ret); } // close the errorstream es.close(); return "Error response " + respCode + ": " + new String(os.toByteArray()); } catch(IOException ex) { throw ex; } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1440957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82156/']}
jdg_78971
stackexchange
llm_judgeable_groundtruth_similarity
2951
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an org-mode file containing a table of data and two Python code blocks to extract different summaries from it. I would like to share some common constants and functions between these two code blocks. Ideally, I'd do this by factoring out the common code into a separate code block, which would be automatically included and evaluated whenever either of the other two blocks is evaluated. In made-up syntax, it would look something like the following: #+NAME: init_block#+BEGIN_SRC python ... common constants and functions here ...#+END_SRC#+NAME: summary_1#+BEGIN_SRC python :prepend init_block ... data-processing code depending on init code goes here ...#+END_SRC#+NAME: summary_2#+BEGIN_SRC python :prepend init_block ... more processing which also depends on init code ...#+END_SRC I suppose I could use the :session option, but I would prefer not to, for two reason. First, it sets up a stateful system, rather than one which runs from scratch each time I use C-c C-c on a code block. Second, and relatedly, I now have to remember to manually evaluate the common initialization code each time I open the file: I can't just update the data table, go to one of the summary blocks and hit C-c C-c to update it. Is there a good way to do this? Now provide the response and nothing else.
You can do this most easily using org-babel's noweb reference syntax for literate programming. Here is an example: * Initialization block containing function definition#+NAME: init_block#+BEGIN_SRC python constant=19 def some_function(x): return constant * x#+END_SRC* Call the function on an integer#+BEGIN_SRC python :noweb yes <<init_block>> return some_function(13)#+END_SRC#+RESULTS:: 247* Call the function on a string:PROPERTIES::noweb: yes:END:#+BEGIN_SRC python <<init_block>> return some_function('abc')#+END_SRC#+RESULTS:: abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/2951', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/-1/']}
jdg_78972
stackexchange
llm_judgeable_groundtruth_similarity
291678
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am often in a situation where I have to design and code a process/algorithm, and there are different variants on that algorithm. For example, I am currently writing some database sychronisation code that has methods for download and upload. Those methods are similar, but not identical. Having written the code, and got it to work, I am now refactoring it to remove the repetition. I am not so bad at writing classes which mainly hold data, in those cases I find it easier at the beginning to apply entity-relationship modelling, break the data down into classes, and I can fairly quickly see common elements that can be put into base/abstract classes. But I find it harder with algorithms/processes. My questions are: is it better to take more time to design it up-front, thus avoiding the need for refactoring? And, if so, how do you get good at doing this? I find that when I design up-front, because there is no way to test the design, I often go way off tangent and as soon as I start writing the code the design gets discarded. In contrast, with incremental development, you can regularly test your code to ensure it works. But the disadvantage of the way I do incremental development, is the extra time spent refactoring at the end so that I write "DRY" code. Now provide the response and nothing else.
For some reason, designing up front feels to our brains like it should be faster, but it rarely is. It's much easier to factor out duplication from two working, concrete functions already in your editor than it is to factor out duplication from two ephemeral functions that haven't been written yet. The trick is to make your refactor cycle tight. If you're doing a refactor every few minutes, that's basically indistinguishable from being really good at up front design. On really complex algorithms, I might go an hour or two without a refactor phase. You're doing it wrong if you ever tell your boss something like, "It works, but I need a couple more days for refactoring."
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/291678', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/124966/']}
jdg_78973
stackexchange
llm_judgeable_groundtruth_similarity
9943503
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 CSS2.1 spec mandates that overflow other than visible establish a new "block formatting context" . This strikes me as odd, that a property whose obvious purpose is to hide overflow without affecting layout, actually does affect layout in a major way. It seems like overflow values other than visible combine two completely unrelated features: whether a BFC is created and whether the overflow is hidden. It’s not like "overflow:hidden" is completely meaningless without a BFC, because floats historically can overflow their parent element, hiding the overflow without changing the layout seems sensible. What are the reasons behind this decision, assuming they are known? Have the people who worked on the spec described why this was decided to be the case? Now provide the response and nothing else.
I asked about this on the mailing list on your behalf; the thread can be found here . In summary, this has to do with scrolling content for the most part : Fundamentally, because if the spec didn't say this, then having floats intersect with something that's scrollable would require the browser to rewrap (around intruding floats) the contents of the scrollable element every time it scrolls. This is technically what CSS 2.0 required, but it was never implemented, and it would have been a huge problem for speed of scrolling. -David Most likely, it refers to scrollable content in a box that may occur outside of the float's parent but would intersect with the float. I don't think this is related to rewrapping content around a float within a scrollable container, as that already happens naturally, plus the float would clip into the container and scroll along with the rest of its content anyway . Finally this makes sense to me. In fact, I'm going to provide an example here so hopefully it makes sense to you and anyone else who may be wondering. Consider a scenario involving two boxes with the same fixed height and overflow: visible (the default), of which the first contains a float that stretches beyond its parent's height: <div> <p>...</p></div><div> <p>...</p> <p>...</p></div> /* Presentational properties omitted */div { height: 80px;}div:first-child:before { float: left; height: 100px; margin: 10px; content: 'Float';} Notice the similarity to one of the examples given in section 9.5 . The second box here is simply shown to have overflowing content for the purposes of this answer. This is fine since the content will never be scrolled, but when overflow is set to something other than visible , that causes the content to not only be clipped by the bounds of the box, but also to become scrollable. If the second box has overflow: auto , this is what it would look like had a browser implemented the original CSS2 spec: Because of the float, attempting to scroll the content would cause the browser to have to rewrap it so it doesn't become obscured by the float (and what should happen to the part that scrolls out of the top edge?). It would probably look something like this when scrolled to the bottom: The catch here is that the browser has to rewrap the content every time it repaints it during scrolling . For browsers that are capable of pixel-based smooth scrolling — which is to say, all of them — I can see why it would be a performance disaster! (And a user experience one, too.) But that's for when the user can scroll the content, right? This would make sense for overflow: auto and overflow: scroll , but what about overflow: hidden ? Well, a common misconception is that a container with overflow: hidden simply hides content by clipping and cannot be scrolled. This is not completely true : While scrolling UI is not provided, the content is still scrollable programmatically, and a number of pages perform just such scrolling (e.g. by setting scrollTop on the relevant element). -Boris Indeed, this is what it'd look like if the second box was set to overflow: hidden and then scrolled to the bottom with the following JavaScript: var div = document.getElementsByTagName('div')[1];div.scrollTop = div.scrollHeight; Again, notice that the content would have to be rewrapped to avoid being obscured by the float. Even though this wouldn't be as painful for performance as had scrolling UI been available, my best guess is that they made boxes with any overflow value other than visible generate a new BFC mainly for the sake of consistency. And so, this change was brought about in CSS2.1, documented here . Now if you apply an overflow value other than visible only to the second box, what a browser does is push the entire box aside to make way for the float, because the box now creates a new block formatting context that encloses its contents, instead of flowing around the float. This particular behavior is specified in the following paragraph : The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin box of any floats in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space. They may even make the border box of said element narrower than defined by section 10.3.3. CSS2 does not define when a UA may put said element next to the float or by how much said element may become narrower. Here's what it looks like with overflow: auto for example: Note that there is no clearance; if the second box had clear: left or clear: both it would be pushed down , not to the side, regardless of whether it established its own BFC. If you apply overflow: auto to the first box instead, the float is clipped into its containing box with the rest of the content due to its fixed height, which is set to 80px in the example code given above: If you revert the first box to height: auto (the default value), either by overriding or removing the height: 80px declaration from above, it then stretches to the height of the float: This happens to be new in CSS2.1 as well , in that an element with height: auto that generates a new block formatting context (i.e. a block formatting context root ) will stretch vertically to the height of its floats, and not just enough to contain its in-flow content unlike a regular box. The changes are documented here and here . The change leading to the side-effect of shrinking the box so that it does not intersect the float is documented here . In both of these cases, no matter what you do to the second box, it will never be affected by the float because it has been restricted by the bounds of its container.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9943503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33080/']}
jdg_78974
stackexchange
llm_judgeable_groundtruth_similarity
5117127
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 PHP you can do amazing/horrendous things like this: $a = 1;$b = 2;$c = 3;$name = 'a';echo $$name;// prints 1 Is there any way of doing something like this with Javascript? E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name ? Now provide the response and nothing else.
Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object ). So if you create variables like this: var a = 1, b = 2, c = 3; In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser). Those can get accessed by using the "dot" or "bracket" notation: var name = window.a; or var name = window['a']; This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object . For instance: function foobar() { this.a = 1; this.b = 2; var name = window['a']; // === undefined console.log(name); name = this['a']; // === 1 console.log(name);}new foobar(); new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with: var a = 1, b = 2; Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar , which we cannot access (of course we could access those directly by calling a and b ).
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5117127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/282706/']}
jdg_78975
stackexchange
llm_judgeable_groundtruth_similarity
6738896
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: domain.com testing.domain.com I want domain.com to be crawled and indexed by search engines, but not testing.domain.com The testing domain and main domain share the same SVN repository, so I'm not sure if separate robots.txt files would work... Now provide the response and nothing else.
1) Create separate robots.txt file (name it robots_testing.txt , for example). 2) Add this rule into your .htaccess in website root folder: RewriteCond %{HTTP_HOST} =testing.example.comRewriteRule ^robots\.txt$ /robots_testing.txt [L] It will rewrite (internal redirect) any request for robots.txt to robots_testing.txt IF domain name = testing.example.com . Alternatively, do opposite -- rewrite all requests for robots.txt to robots_disabled.txt for all domains except example.com : RewriteCond %{HTTP_HOST} !=example.comRewriteRule ^robots\.txt$ /robots_disabled.txt [L]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6738896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/843815/']}
jdg_78976
stackexchange
llm_judgeable_groundtruth_similarity
54782701
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 show a list which shows the rows matching the user entered value in the text box.List must keep changing dynamically as user keeps inputting values.that's why I tried using (change) event listener on the input text box.but list changes only after I press 'Enter' button.Here's the code. <tr> <td><input type = "text" [(ngModel)] = "writerSuggest" (change) = "getWriterList($event)" /></td></tr><tr *ngFor="let writers of writerListShow"> <td style="cursor: pointer;" (click) = "onWriterClick(writers.name)">{{writers.name}}</td></tr><tr> <td *ngIf = 'writerErr' >No writers with given name</td></tr> Now provide the response and nothing else.
Finally I could able to call Table values parameter Stored procedure from my .net core service which uses EF core I have created fake Response Domain Model public class MyResponse { public int Id { get; set; } public int Col1{ get; set; } public int Col2 { get; set; } } I called it Fake Domain Model because Domain model is generally table representation in CLR class but I dont have such Table in SQL Server. Then I have Added property for this under Context class as below public class MyQueryDbContext : DbContext{ public virtual DbSet<MyResponse> Data { get; set; } . . .} Then Need to create Data Table for Request parameter list, I have added like below DataTable table = new DataTable(); table.Columns.Add("Id", typeof(int)); table.Columns.Add("Col1", typeof(int)); table.Columns.Add("Col2", typeof(int)); Then I have called Stored procedure from .net core API using EF and passed datatable as parameter like below var parameter = new SqlParameter("@MyRequest", SqlDbType.Structured); parameter.Value = table; parameter.TypeName = "[dbo].[MyRequestType]" // My Table valued user defined typevar response=_context.Data .FromSql("EXEC [dbo].[GetMyData] @MyRequest", parameter) .ToList() You will get response in you response variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54782701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11016275/']}
jdg_78977
stackexchange
llm_judgeable_groundtruth_similarity
90254
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have created a New Trusted certification authority which issues certificate to the end entity and the end entity will use this certificate as trusted one for all their PKI operations. Some how the Root CA Key got compromised. Now my question here is how can I revoke the ROOT CA as its a self -signed ? Now provide the response and nothing else.
Revocation really is cancelling the certificate issuance -- the CA which has signed the certificate announces that it now denies it. A root CA being self-issued, it cannot be revoked. A root CA, by definition, is trusted a priori , not because its certificate was signed by some higher-placed CA in the hierarchy. Thus, there is nobody to emit revocation information that would be authoritative on that CA. Some extra comments must be made, though: You do not revoke a CA; you revoke a certificate . Any entity that has a name and owns a key pair, in particular a CA, may own several certificates. Each certificate is an assertion of that key ownership. What you think as a "root CA" may also be an intermediate CA in the following sense: besides its self-issued (traditionally self-signed) certificate, it may also have obtained another certificate that contains its name and its public key, and issued (signed) by another CA. The latter certificate, being issued by a distinct CA, can be revoked. This kind of situation is common in case of "root CA renewal" (a new root CA is created, and "cross-certificates" are issued so that the transition is smooth). What certificates cannot do, maybe other systems can. For instance, a Web browser may contain a list of a priori trusted root CA (for validation of SSL server certificates); then, any update of the browser executable may add or remove root CA. There is no CRL involved, but it sure looks like a revocation mechanism, especially since modern browsers update themselves automatically. Windows has a similar system with a "disallowed" certificate store that acts like an OS-enforced, super-CRL which can make any certificate untrusted, even root CA certificates explicitly added to the store of trusted roots. Trying to make a CRL containing the serial number of the compromised root, as was suggested in another answer, will not have the intended effect, for two reasons: Systems that validate certificates (e.g. SSL clients when trying to verify the server's certificate) download CRL only for certificates where it makes sense, i.e. not for root CA, since they cannot verify the signature on the CRL save relatively to the public-key of the CA higher in the chain, since there is no such CA. You can write what you want in any CRL; if clients don't look at it, it won't get you far. Even if you could somehow convince a client to download that "suicide CRL", where the root CA kills itself, remember that the private key have been compromised, thus the key thief may produce and sign a counter-CRL that says that everything is fine and nobody is revoked. Since the CRL download cannot be otherwise protected, the attacker can prevent that self-destruction mechanism to happen, even assuming that it would have worked with existing clients (and it does not).
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/90254', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/45475/']}
jdg_78978
stackexchange
llm_judgeable_groundtruth_similarity
8864405
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 play a video stream from the internet on the iPhone by pressing a button.I used many code samples but nothing worked. With this code it opens a black view without any video stream or controls in it. (The stream itself works.) NSURL *url = [NSURL URLWithString:@"http://MyStreamURL.com"];MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];moviePlayer.controlStyle = MPMovieControlStyleDefault;moviePlayer.shouldAutoplay = YES;[self.view addSubview:moviePlayer.view];[moviePlayer setFullscreen:YES animated:YES]; Now provide the response and nothing else.
Instead of creating a MPMoviePlayerController and adding that to your view, it is probably simpler to create a MPMoviePlayerViewController and present that view controller modally (since you are trying to show your video full screen anyway). Then the MPMoviePlayerViewController can manage the presentation of your video for you. MPMoviePlayerViewController *mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; mpvc.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;[self presentMoviePlayerViewControllerAnimated:mpvc];[mpvc release]; In your moviePlayBackDidFinish delegate method you can then dismiss the model view controller.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8864405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1149512/']}
jdg_78979
stackexchange
llm_judgeable_groundtruth_similarity
36171656
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 token, a file containing public key and I want to verify the signature.I tried to verify signature based on this . However, decodedCrypto and decodedSignature don't match. Here is my code: public static string Decode(string token, string key, bool verify) { var parts = token.Split('.'); var header = parts[0]; var payload = parts[1]; byte[] crypto = Base64UrlDecode(parts[2]); var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header)); var headerData = JObject.Parse(headerJson); var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload)); var payloadData = JObject.Parse(payloadJson); if (verify) { var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload)); var keyBytes = Encoding.UTF8.GetBytes(key); var algorithm = (string)headerData["alg"]; var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](keyBytes, bytesToSign); var decodedCrypto = Convert.ToBase64String(crypto); var decodedSignature = Convert.ToBase64String(signature); if (decodedCrypto != decodedSignature) { throw new ApplicationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature)); } } return payloadData.ToString(); } I'm sure that the signature of token is valid. I try to verify on https://jwt.io/ and it showed that Signature verified.So the problem is the algorithm to encode, decode. Is there anyone can solve this problem? The algorithm is RS256 Now provide the response and nothing else.
I finally got a solution from my colleague. For those who have the same problem, try my code: public static string Decode(string token, string key, bool verify = true){ string[] parts = token.Split('.'); string header = parts[0]; string payload = parts[1]; byte[] crypto = Base64UrlDecode(parts[2]); string headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header)); JObject headerData = JObject.Parse(headerJson); string payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload)); JObject payloadData = JObject.Parse(payloadJson); if (verify) { var keyBytes = Convert.FromBase64String(key); // your key here AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes); RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter; RSAParameters rsaParameters = new RSAParameters(); rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(); rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParameters); SHA256 sha256 = SHA256.Create(); byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(parts[0] + '.' + parts[1])); RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); if (!rsaDeformatter.VerifySignature(hash, FromBase64Url(parts[2]))) throw new ApplicationException(string.Format("Invalid signature")); } return payloadData.ToString();} It works for me. The algorithm is RS256.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36171656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4489400/']}
jdg_78980
stackexchange
llm_judgeable_groundtruth_similarity
7604966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE . Now provide the response and nothing else.
Python 3 In Python 3, this question doesn't apply. The plain int type is unbound. However, you might actually be looking for information about the current interpreter's word size , which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize , which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence . Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1 , and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2) . See this answer for more information. Python 2 In Python 2, the maximum value for plain int values is available as sys.maxint : >>> sys.maxint9223372036854775807 You can calculate the minimum value with -sys.maxint - 1 as shown here . Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/7604966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139909/']}
jdg_78981
stackexchange
llm_judgeable_groundtruth_similarity
287376
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_n=\sum_{k=1}^{n^2}\frac{1}{\sqrt{n^4+k}}$$ Is $\{x_n\}$ convergent? If it is convergent then find its limit. Here n- th term of the series $\frac{1}{\sqrt{n^4+n^2}} \to 0$ as $n \to \infty$. Can I conclude from here that $\{x_n\}$ is convergent? Again $$\lim_{n\to \infty }x_n=\lim_{n\to \infty }\sum_{k=1}^{n^2}\frac{1}{\sqrt{n^4+k}}=\lim_{m\to \infty }\frac{1}{m} \sum_{k=1}^{m}\frac{1}{\sqrt{1+\frac{k}{m^2}}}$$Then I am stuck .Please help. Now provide the response and nothing else.
For each term of the sum, we have$$\frac{1}{\sqrt{n^4+n^2}} \leq \frac{1}{\sqrt{n^4+k}}\leq \frac{1}{\sqrt{n^4+1}}.$$Summing these inequalities from $k=1$ to $k=n^2$ yields$$\frac{1}{\sqrt{1+1/n^2}}=\frac{n^2}{\sqrt{n^4+n^2}} \leq x_n \leq \frac{n^2}{\sqrt{n^4+1}}=\frac{1}{\sqrt{1+1/n^4}} .$$Now both ends converge to $1$. Therefore, by the Squeeze Theorem, $\lim_{n\rightarrow +\infty} x_n=1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/287376', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37459/']}
jdg_78982
stackexchange
llm_judgeable_groundtruth_similarity
765521
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 configuring an OpenVPN (version 2.3.10) server on a Windows 2012 server but I cannot make it to work. The server is behind a router and I opened the 1194 port and created a rule to forward traffic on this port to the server. Here is the log I see on the server when I try to connect from a client: Mon Mar 21 11:11:47 2016 XX.XX.XX.XX:57804 TLS: Initial packet from [AF_INET]XX.XX.XX.XX:57804, sid=fdf7a7ac 0264c7f3Mon Mar 21 11:12:38 2016 XX.XX.XX.XX:55938 TLS: Initial packet from [AF_INET]XX.XX.XX.XX:55938, sid=1f242a3f e454a525Mon Mar 21 11:12:48 2016 XX.XX.XX.XX:57804 TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)Mon Mar 21 11:12:48 2016 XX.XX.XX.XX:57804 TLS Error: TLS handshake failedMon Mar 21 11:12:48 2016 XX.XX.XX.XX:57804 SIGUSR1[soft,tls-error] received, client-instance restarting Where XX.XX.XX.XX is the ip of the client. So I understand from this that the client at least is able to arrive at the server, so there's no routing or firewall issues. I followed the description provided here Easy Windows Guide Any ideas? Now provide the response and nothing else.
What's interesting is how the port number changes mid-stream: Mon Mar 21 11:11:47 2016 XX.XX.XX.XX: 57804 TLS: Initial packet from [AF_INET]XX.XX.XX.XX:57804, sid=fdf7a7ac 0264c7f3 Mon Mar 21 11:12:38 2016 XX.XX.XX.XX: 55938 TLS: Initial packet from [AF_INET]XX.XX.XX.XX:55938, sid=1f242a3f e454a525 This makes me think that, somewhere between client and server, there is a misbehaving NAT device, a device with very short-lived state table entries, which is changing the source port number that it applies to the client's established stream, causing the server to think that two short-lived communications are in progress, instead of one continuous one. Such devices generally only do this with UDP, so I have advised you to confirm that you are using UDP, and try TCP instead. This you have done, and found that it fixes the problem. The next step is to identify the misbehaving NAT device, hit it with a club hammer, and replace it with one that doesn't make the cardinal mistake of assuming that all UDP communications are ephemeral; but you have indicated that you're happy with changing to TCP as a workaround, and so the matter is concluded.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/765521', 'https://serverfault.com', 'https://serverfault.com/users/345096/']}
jdg_78983
stackexchange
llm_judgeable_groundtruth_similarity
6041596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to output the list of items in a folder in the folowing way: "filename1" "filename2" "file name with spaces" "foldername" "folder name with spaces" In other words, item names must be in a single line, surrounded with quotes (single or double) and divided by spaces. I know that find . | xargs echo prints output in a single line, but I do not know how to add quotes around each item name. This code is part of a bsh script.The solution can therefore be a set of commands and use temporary files for storing intermediate output. Thank you very much for any suggestion. Cheers, Ana Now provide the response and nothing else.
this should work find $PWD | sed 's/^/"/g' | sed 's/$/"/g' | tr '\n' ' ' EDIT: This should be more efficient than the previous one. find $PWD | sed -e 's/^/"/g' -e 's/$/"/g' | tr '\n' ' ' @Timofey's solution would work with a tr in the end, and should be the most efficient. find $PWD -exec echo -n '"{}" ' \; | tr '\n' ' '
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6041596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758769/']}
jdg_78984
stackexchange
llm_judgeable_groundtruth_similarity
2728646
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am failing to understand why the integral is defined as: $$\int_a^b f(x) dx = \lim_{n\to\infty}\sum_{i=1}^n f(x_i^*)\Delta x$$ instead of: $$\int_a^b f(x)dx=\sum_{i=1}^\infty f(x_i^*)\Delta x$$ Is the former just popular preference or is there something I am not conceptually understanding here? Now provide the response and nothing else.
Let's cut $[a, b]$ up into infinitely many equally spaced slices. So $x_1 = a$, obviously. What's $x_2$? What's $\Delta x$, if not zero? In general, there isn't a "nice" way to cut a finite interval into infinitely many sampling intervals. Ultimately, the Riemann integral samples a bunch of function values in a fairly uniform way (meaning one from each interval of length $\Delta x$) and averages them. It doesn't make sense to make an infinite uniform sampling of a bounded interval.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2728646', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/311401/']}
jdg_78985
stackexchange
llm_judgeable_groundtruth_similarity
34034267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a pandas dataframe holding more than million records. One of its columns is datetime. The sample of my data is like the following: time,x,y,z2015-05-01 10:00:00,111,222,3332015-05-01 10:00:03,112,223,334... I need to effectively get the record during the specific period. The following naive way is very time consuming. new_df = df[(df["time"] > start_time) & (df["time"] < end_time)] I know that on DBMS like MySQL the indexing by the time field is effective for getting records by specifying the time period. My question is Does the indexing of pandas such as df.index = df.time makes the slicing process faster? If the answer of Q1 is 'No', what is the common effective way to get a record during the specific time period in pandas? Now provide the response and nothing else.
Let's create a dataframe with 1 million rows and time performance. The index is a Pandas Timestamp. df = pd.DataFrame(np.random.randn(1000000, 3), columns=list('ABC'), index=pd.DatetimeIndex(start='2015-1-1', freq='10s', periods=1000000)) Here are the results sorted from fastest to slowest (tested on the same machine with both v. 0.14.1 (don't ask...) and the most recent version 0.17.1): %timeit df2 = df['2015-2-1':'2015-3-1']1000 loops, best of 3: 459 µs per loop (v. 0.14.1)1000 loops, best of 3: 664 µs per loop (v. 0.17.1)%timeit df2 = df.ix['2015-2-1':'2015-3-1']1000 loops, best of 3: 469 µs per loop (v. 0.14.1)1000 loops, best of 3: 662 µs per loop (v. 0.17.1)%timeit df2 = df.loc[(df.index >= '2015-2-1') & (df.index <= '2015-3-1'), :]100 loops, best of 3: 8.86 ms per loop (v. 0.14.1)100 loops, best of 3: 9.28 ms per loop (v. 0.17.1)%timeit df2 = df.loc['2015-2-1':'2015-3-1', :]1 loops, best of 3: 341 ms per loop (v. 0.14.1)1000 loops, best of 3: 677 µs per loop (v. 0.17.1) Here are the timings with the Datetime index as a column: df.reset_index(inplace=True)%timeit df2 = df.loc[(df['index'] >= '2015-2-1') & (df['index'] <= '2015-3-1')]100 loops, best of 3: 12.6 ms per loop (v. 0.14.1)100 loops, best of 3: 13 ms per loop (v. 0.17.1)%timeit df2 = df.loc[(df['index'] >= '2015-2-1') & (df['index'] <= '2015-3-1'), :]100 loops, best of 3: 12.8 ms per loop (v. 0.14.1)100 loops, best of 3: 12.7 ms per loop (v. 0.17.1) All of the above indexing techniques produce the same dataframe: >>> df2.shape(250560, 3) It appears that either of the first two methods are the best in this situation, and the fourth method also works just as fine using the latest version of Pandas.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34034267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590847/']}
jdg_78986
stackexchange
llm_judgeable_groundtruth_similarity
714025
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that Newton's universal law of gravitation can be used, along with his laws of motion, to derive Kepler's laws. But what about the other way around? Can Kepler's laws be used to derive Newton's universal law of gravitation? Now provide the response and nothing else.
Yes, but it is somewhat contrived. You need to have defined angular momentum in the Newtonian way, too. The fact that planets orbit in ellipses with the sun at one of the foci (Kepler's first law) can be made mathematical by just geometry, $$r(\theta) = \frac{p}{1+\varepsilon \cos\theta}$$ where $p$ is the semi-latus rectum, $\varepsilon$ is the eccentricity, $\theta$ is the angle from perihelion, and $r$ the radial distance from planet to star. Just as you go from Newton's law to deriving the elliptic orbit in the usual way, you could now do this backwards to see what kinetic energy and potential could produce this path under assumption of Newton's 2nd law. Instead of integrating a differential equation, differentiate this ellipse equation twice wrt $\theta$ . This shows $$\ddot{r} + r = 1$$ Now somehow knowing to make a substitution like $u = \frac{1}{r}$ , you could work backwards to an expression for the total energy and hence infer a law for the gravitational potential, and finally Newton's law of gravitation. But note understanding which part of the total energy expression is due to gravity would require an understanding of angular momentum.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/714025', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/50612/']}
jdg_78987
stackexchange
llm_judgeable_groundtruth_similarity
2826559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to create a hash of string at compile time using the C /C++ preprocessor (or even template-metaprogramming)? e.g. UNIQUE_SALT("HelloWord", 3DES); The idea is that HelloWorld will not be present in the compiled binary, just a hash. Edit: There are many of these declarations spread over a large codebase. Now provide the response and nothing else.
With C++0x, this is possible as covered by answers in #1 and #2 . In C++03 there was no compile time string processing. With the preprocessor you can't seperate the string into tokens, with templates you can't access single characters. There was however a discussion on the speculated approach using C++0x . What you could do for C++03 is to pass the string character-wise (possible using multi-character literals): foo = hash<3DES, str<'a','b','c'> >::result;// or:foo = hash<3DES, str<'abc','def'> >::result; ... or simply do it as a pre-build step.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2826559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240837/']}
jdg_78988
stackexchange
llm_judgeable_groundtruth_similarity
45620436
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 input string is something like He#108##108#o and the output should be Hello . Basically I want to replace each #[0-9]+# with the relevant ASCII characters of the number inside the ## . Now provide the response and nothing else.
Use a replacement function in your regex, which extracts the digits, converts them to integer, and then to character: import res = "He#108##108#o"print(re.sub("#(\d+)#", lambda x : chr(int(x.group(1))), s)) Result: Hello
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45620436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_78989
stackexchange
llm_judgeable_groundtruth_similarity
581970
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The situation I have a windows SBS 2008 box running as DC/DNS/DHCP/Exchange/File Server to a network on 192.168.1.0/24. Suffice it to say that the IP of the SBS box is immutable. At some point in the past my predecessor here attempted to get 2 NICs running with 2 IPs on it (which is so very unsupported) and since then, attempting to change any of the network properties causes it to bluescreen on the prompted-for restart - we have had to restore from snapshots when this happens, there doesn't seem to be a way around it. We have recently started a project to get rid of SBS and build a real 2008/2012 (tbd) domain with 2 DCs, a seperate VM for Exchange, one for fileshares etc etc (yay!) but the prerequisite is that we transition to a new IP Scope (we will be getting onto a VPN with Head Office, allowing us to offload many of these services onto their network). This leaves me in kind of a sticky situation - I need to get the routers, workstations, terminals... pretty much everything on the network EXCEPT DC/DNS/DHCP/Exchange/File server onto a different scope, while maintaining connection to those services running on SBS which has to stay on 192.168.1.0/24 . One further complication on the issue is - we have 2 gateways here. One is used by SBS, the other... pretty much everything else - This is to allow SMTP and HTTPS traffic from outside to hit it. The Plan OK so here is what I plan to do - I have set up a VM with a minimal install of Ubuntu 12.04 and a NIC on each network scope. It has static routes set up to reach each network on it's respective interface, and I plan to push out another route via DHCP allowing client on the different scopes to contact each other by routing through the linux box. So for example I have routes: Client at 10.0.0.20 destination 192.168.1.0 mask 255.255.255.0 gateway 10.0.0.10 interface 10.0.0.20 Linux Router at 10.0.0.10 & 192.168.1.10 destination 192.168.1.0 mask 255.255.255.0 gateway 0.0.0.0 interface 192.168.1.10 destination 10.0.0.0 mask 255.255.255.0 gateway 0.0.0.0 interface 10.0.0.10 DC at 192.168.1.200 destination 10.0.0.0 mask 255.255.255.0 gateway 192.168.1.10 interface 192.168.1.200 At the same time I will move the internet gateway currently being used by everyone (not the one set up for DC) to the 10.0.0.0/24 network, so the 10.0.0.0/24 clients have a default gateway in their scope and the 192.168.1.0/24 clients (just the DC really) have a default gateway in it's scope (at this point the only remaining things in the 192.168.1.0/24 network are the DC and it's gateway). The Question Yes I am getting around to asking something! I want to confirm whether the DC can serve DHCP to these clients while being in a different scope. Research has led me here , which seems to suggest it is not possible without a DHCP Relay server in one case (Assuming I am correctly parsing a "network segment" as fairly analogous to a subnet), but also mentions Super Scope, which sounds like it MIGHT answer the issue (as it assigns address to any devices outside the other scopes... I think). It seems to me that when a client is requesting an address it doesn't yet have an address anyway, so how can it determine whether it is in the same "network segment" as the DC anyway? To clarify in a TL;DR kind of format - Can I serve 10.0.0.0/24 addresses as well as other network properties like static routes, DNS and default gateways to clients from a DHCP server sitting at 192.168.1.200/24 ? Do I need to use a Superscope to do so? Also if you see any other problems with my plan, please don't keep quiet! The Addendum using the DHCP-helper tool suggested by @HopelessN00b I was able to get this actioned fairly smoothly! A few things were problematic - The clients are all in the same network segment, there is no need to go through a layer 3 switch to reach the DHCP server. This resulted in all my clients grabbing 192 addresses because they were communicating directly to the server. I wanted to keep the 192 scope listed because a) if I had gotten in this morning to discovered I had screwed up, it would be easy to rollback; and b) As a handy listing of those services still on the 192 subnet; but I was able to get around this dodgily by creating an exclusion range for the scope that matched the full range of scoped addresses (ie, the scope went from 192.168.1.20 to 192.168.1.200, I created an exclusion range from 192.168.1.20 - 192.168.1.200). It makes me feel a little dirty, but it works, and the 192 subnet only needs to survive a few weeks for us to migrate services. There were a few devices which I discovered this morning do not support receiving a static route through the DHCP option 121 (namely: WYSE terminals). They were happily taking 10.61.73.x addresses but had no way to route to terminal server on 192.168.1.x. As the terminal server itself happily took the routes, I set them up statically in the 192 subnet for now, which has resolved their issues. @us10610 wanted to know the config I used on linux for DHCP-Helper - it was scarily simple - /etc/default/dhcp-helper contains a single line I modified from default: DHCPHELPER_OPTS="-b eth1" eth1 being the NIC that shares a subnet with the DHCP server. It then happily accepted DHCP UDP from it's other NIC and broadcast them on eth1 Now provide the response and nothing else.
You can absolutely use a DHCP server to serve a scope it's not a part of, so long as the traffic can flow between the two subnets. The trick is that DHCP requests are generally only served out to the broadcast domain the client is on, to so get around that, you place an IP-helper address on the piece of network gear the client is connecting through so that it will forward UDP traffic (such as your clients' DHCP requests) on to the specified IP address (the IP address of your DHCP server). And I did check before I answered; this is possible on Linux (and Ubuntu) boxes being used as switches or routers, though I'm not sure on the precise syntax and/or what additional packages you might need to do so. I did, however, find this page, which suggests a program to use and how to use it, so that might be a good place for you to start.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/581970', 'https://serverfault.com', 'https://serverfault.com/users/153274/']}
jdg_78990
stackexchange
llm_judgeable_groundtruth_similarity
6219141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question has been asked many times. After spending some time reading the answers, I did some quick profiling to try out the various methods mentioned previously... I have a 600 MB file with 6 million lines of strings (Category paths from DMOZ project). The entry on each line is unique. I want to load the file once & keep searching for matches in the data The three methods that I tried below list the time taken to load the file, search time for a negative match & memory usage in the task manager 1) set : (i) data = set(f.read().splitlines()) (ii) result = search_str in data Load time ~ 10s, Search time ~ 0.0s, Memory usage ~ 1.2GB 2) list : (i) data = f.read().splitlines() (ii) result = search_str in data Load time ~ 6s, Search time ~ 0.36s, Memory usage ~ 1.2GB 3) mmap : (i) data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) (ii) result = data.find(search_str) Load time ~ 0s, Search time ~ 5.4s, Memory usage ~ NA 4) Hash lookup (using code from @alienhard below): Load time ~ 65s, Search time ~ 0.0s, Memory usage ~ 250MB 5) File search (using code from @EOL below): with open('input.txt') as f: print search_str in f #search_str ends with the ('\n' or '\r\n') as in the file Load time ~ 0s, Search time ~ 3.2s, Memory usage ~ NA 6) sqlite (with primary index on url): Load time ~ 0s, Search time ~ 0.0s, Memory usage ~ NA For my use case, it seems like going with the set is the best option as long as I have sufficient memory available. I was hoping to get some comments on these questions : A better alternative e.g. sqlite ? Ways to improve the search time using mmap . I have a 64-bit setup. [edit] e.g. bloom filters As the file size grows to a couple of GB, is there any way I can keep using 'set' e.g. split it in batches .. [edit 1] P.S. I need to search frequently, add/remove values and cannot use a hash table alone because I need to retrieve the modified values later. Any comments/suggestions are welcome ! [edit 2] Update with results from methods suggested in answers[edit 3] Update with sqlite results Solution : Based on all the profiling & feeback, I think I'll go with sqlite. Second alternative being method 4. One downside of sqlite is that the database size is more than double of the original csv file with urls. This is due to the primary index on url Now provide the response and nothing else.
Variant 1 is great if you need to launch many sequential searches. Since set is internally a hash table, it's rather good at search. It takes time to build, though, and only works well if your data fit into RAM. Variant 3 is good for very big files, because you have plenty of address space to map them and OS caches enough data. You do a full scan; it can become rather slow once your data stop to fit into RAM. SQLite is definitely a nice idea if you need several searches in row and you can't fit the data into RAM. Load your strings into a table, build an index, and SQLite builds a nice b-tree for you. The tree can fit into RAM even if data don't (it's a bit like what @alienhard proposed), and even if it doesn't, the amount if I/O needed is dramatically lower. Of course, you need to create a disk-based SQLite database. I doubt that memory-based SQLite will beat Variant 1 significantly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6219141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781695/']}
jdg_78991
stackexchange
llm_judgeable_groundtruth_similarity
349612
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 would one compute the following improper integral: $$\int_0^\infty \sin\left(\frac{1}{x^2}\right) \, \operatorname{d}\!x$$ without any knowledge of Fresnel equations? I was thinking of using the comparison theorem since $\sin x$ is never greater than 1. However, I can't find a function always greater than 1 between 0 and infinity such that its integral from 0 to infinity converges. Thanks. Now provide the response and nothing else.
By "Fresnel equations," I assume you mean stuff like $$\mathcal{F}(z) = \int_0^z dt \: e^{i \frac{\pi}{2} t^2}$$ Have no fear: I will produce everything from scratch without reference to anyone named Fresnel. That said, I will produce integrals with quadratic phase, but I will show you how to deal with them. Begin with a substitution $u=1/x^2$: $$\begin{align}\int_0^{\infty} dx \: \sin{\left ( \frac{1}{x^2}\right)} &= \frac{1}{2} \underbrace{\int_0^{\infty} du \: u^{-3/2} \, \sin{u}}_{\text{integrate by parts}} \\ &= \frac{1}{2} \underbrace{\left [ -2 u^{-1/2} \sin{u} \right]_0^{\infty}}_{\text{this is zero}} + \underbrace{\int_0^{\infty} du \: u^{-1/2} \, \cos{u}}_{u=v^2}\\ &= 2 \int_{0}^{\infty} dv \: \cos{v^2} \\ &= \Re{\left[\int_{-\infty}^{\infty} dv \: e^{i v^2} \right ]} \end{align}$$ Now, let's focus on this last integral. It is far from obvious that this even converges; I will show below that it does. I hope you are familiar with Cauchy's integral theorem, though. Consider the integral in the complex plane $$\oint_C dz \: e^{-z^2}$$ where $C$ is the following contour: That is, a $45^{\circ}$ wedge of radius $R$, where we will set $R \rightarrow \infty$. Because there are no poles inside the contour, the above integral is zero. We then write the integral around this contour as $$\oint_C dz \: e^{-z^2}=\int_0^R dx \: e^{-x^2} + R \int_0^{-\pi/4} d\theta \: e^{-R^2 \cos{2 \theta}} e^{-i R^2 \sin{2 \theta}} + e^{-i \pi/4} \int_R^0 dv \: e^{i v^2}=0$$ I hope you see that the second integral, that about the arc, vanishes as $R \rightarrow \infty$. It vanishes because of the exponential term in the integrand which vanishes very quickly in this limit. Because this integral vanishes, we are then left with the following relation: $$\int_0^{\infty} dx \: e^{-x^2} - e^{-i \pi/4} \int_0^{\infty} dv \: e^{i v^2} = 0$$ Thus $$\int_0^{\infty} dv \: e^{i v^2} = e^{i \pi/4} \int_0^{\infty} dx \: e^{-x^2} $$ Using the fact that the integral on the RHS is equal to $\sqrt{\pi}$ and that we are only interested in the real part of the integral on the LHS, we finally get $$\int_0^{\infty} dx \: \sin{\left ( \frac{1}{x^2}\right)} = \sqrt{\frac{\pi}{2}}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/349612', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70701/']}
jdg_78992
stackexchange
llm_judgeable_groundtruth_similarity
11589816
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to implement vertical carousel sliding widh Twitter Bootstrap?In bootstrap.js I find this , slide: function (type, next) { var $active = this.$element.find('.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this I tried to change direction to "up" and "down" but sliding not working. Now provide the response and nothing else.
Yes. Below is a hacky way to do it, which does everything by simply overriding the CSS. If you add a class vertical to your carousel, then adding the following CSS to the page will override the sliding to be vertical: .vertical .carousel-inner { height: 100%;}.carousel.vertical .item { -webkit-transition: 0.6s ease-in-out top; -moz-transition: 0.6s ease-in-out top; -ms-transition: 0.6s ease-in-out top; -o-transition: 0.6s ease-in-out top; transition: 0.6s ease-in-out top;}.carousel.vertical .active { top: 0;}.carousel.vertical .next { top: 100%;}.carousel.vertical .prev { top: -100%;}.carousel.vertical .next.left,.carousel.vertical .prev.right { top: 0;}.carousel.vertical .active.left { top: -100%;}.carousel.vertical .active.right { top: 100%;}.carousel.vertical .item { left: 0;} This is basically taking everything in carousel.less and changing left to top . JSFiddle This at least indicates what you need to do to get it to slide vertically. However, in practice, one really should add up and down classes to the carousel.less and add a new option to bootstrap-carousel.js to switch between them.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11589816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1542184/']}
jdg_78993
stackexchange
llm_judgeable_groundtruth_similarity
3352377
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 a physics student starting grad school, and I figured I'd read up on manifolds since they pop up so much. However, one thing that continues to elude me is why tangent spaces have such involved definitions. Given that the tangent space of an $n$ dimensional manifold at any point is diffeomorphic to $\mathbb{R}^n$ , why do we bother with all the long definitions involving derivations and equivalence classes of curves in the first place? Now provide the response and nothing else.
We don't just want to have a vector space to call the "tangent space". We want to do geometric things with the tangent space, and we can't do those things if it's just an arbitrary vector space of the right dimension. We need it to more specifically be a vector space that encodes the parts of the geometry of our manifold that we care about. For instance, here's one geometric thing we'd like to be able to do: given a smooth curve $\gamma:\mathbb{R}\to M$ on a manifold $M$ , we'd like to define a "tangent vector" at each point of the curve. For each $t\in\mathbb{R}$ , this should give us a vector " $\gamma'(t)$ " which is in the tangent space of $M$ at the point $\gamma(t)$ . If the tangent space is just defined as some arbitrary $n$ -dimensional vector space, there isn't going to be any natural way to define $\gamma'(t)$ . But for the usual definition, there is: we just take the equivalence class of the curve $\gamma$ . Another very useful thing we like to do is differentiate functions between manifolds: if $f:M\to N$ is a smooth function between manifolds and $p\in M$ , there should be a "derivative" $df$ which is a linear map from $T_pM\to T_{f(p)}N$ . Again, there's not any natural way to get such a map if the tangent spaces are just some arbitrary vector spaces. To put it another way, the tangent space to a manifold at a point is not merely a vector space. It is a vector space together with a bunch of extra structure relating it to other geometric features of the manifold. So we care about it not just as a vector space up to isomorphism, but as a "vector space plus extra structure" up to isomorphism. It's possible to axiomatize this extra structure, and then you could define the tangent space as just any abstract gadget satisfying those axioms, rather than restricting yourself to the usual definition by equivalence classes of curves. This isn't commonly done though because (as far as I know) there isn't any nice axiomatization that isn't essentially just saying "a vector space equipped with an isomorphism to this particular concrete construction", so you might as well just use the concrete construction itself.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3352377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/450907/']}
jdg_78994
stackexchange
llm_judgeable_groundtruth_similarity
54578294
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 local files in my app which I read like this: <Image source={require("../../img/pic1.jpg") /> How to read this file using RNFS.readFile(filepath, "base64"); using RNFS.readFile("../../img/pic1.jpg", "base64"); gives me error "no such file" Now provide the response and nothing else.
react-native-fs will only access the files from device storage. So this problem poses a quandary. These files are bundled at build time so how can we access them in development vs production? My project structure ├── android├── app│   └── assets│   └── images└── ios I store my images inside ./app/assets/images/ Development When in Development or debug the files are served to the device via the metro bundler so they are not actually stored on the device. So accessing them from the devices storage would not be possible. You would have to provide some sort of mocked functionality for when you are developing. It is possible to use __DEV__ to allow different functions to run depending on the environment https://facebook.github.io/react-native/docs/javascript-environment if (__DEV__) { // do something in development} else { // do something in production} Production From some research it does seem like it is possible to access the files in production. iOS What I have discovered is that the files reside in a folder called assets that are in the MainBundlePath . So if you want to access the following file in my local directory ./app/assets/images/image.png you would need the following file path: RNFS.MainBundlePath + /assets/app/assets/images/image.png to access it on the device. You can check to see the file path by looking at the Packaging.log that is generated with your ipa . Android Android doesn't have a folder called MainBundlePath that is only on iOS . I have spent some time researching and looking at the different folders on the device but I was unable to access the images that are bundled. It would seem that they not accessible in the way that we would hope using react-native-fs . Possible solutions rn-fetch-blob rn-fetch-blob has functionality for both ios and Android to read from the assets directory To access the files for iOS you would do something like this: RNFetchBlob.fs.stat(fs.dirs.MainBundleDir + '/whatever/files/you/added.mp3').then( stats => {...}); And for Android you would do something like this: RNFetchBlob.fs.stat(fs.asset('/whatever/files/you/added.mp3').then( stats => {...}); It does give this warning about the assets being compressed by Gradle. Gradle will compress bundled assets by default. In order to interact with asset files with this module, compression must be disabled. Please see How to access files from assets for more detail. This could explain why I was unable to find any assets in Android when looking using react-native-fs You can read more about using rn-fetch-blob and its filesystem here https://github.com/joltup/rn-fetch-blob#user-content-file-system Storing the files in the native projects Rather than relying on the bundler to package up the images for you and put them on the device. You could store copies of them already in the iOS and Android projects. This has the bonus that the images would be available in development, however you would storing the images multiple times and it could lead to larger application sizes. Storing the images as base64 You could store the images as base64 strings in json files and then require these by your application. That would then mean that you would have them already in base64 (so the app doesn't have to do any conversion) but again you would be increasing the size of your application. If it is only a small number of images it may be the easiest option.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54578294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160059/']}
jdg_78995
stackexchange
llm_judgeable_groundtruth_similarity
64096953
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 Yolo format bounding box annotations of objects saved in a .txt files. Now I want to load those coordinates and draw it on the image using OpenCV , but I don’t know how to convert those float values into OpenCV format coordinates values I tried this post but it didn’t help, below is a sample example of what I am trying to do Code and output import matplotlib.pyplot as pltimport cv2img = cv2.imread(<image_path>)dh, dw, _ = img.shape fl = open(<label_path>, 'r')data = fl.readlines()fl.close() for dt in data: _, x, y, w, h = dt.split(' ') nx = int(float(x)*dw) ny = int(float(y)*dh) nw = int(float(w)*dw) nh = int(float(h)*dh) cv2.rectangle(img, (nx,ny), (nx+nw,ny+nh), (0,0,255), 1) plt.imshow(img) Actual Annotations and Image 0 0.286972 0.647157 0.404930 0.371237 0 0.681338 0.366221 0.454225 0.418060 Now provide the response and nothing else.
There's another Q&A on this topic, and there's this 1 interesting comment below the accepted answer. The bottom line is, that the YOLO coordinates have a different centering w.r.t. to the image. Unfortunately, the commentator didn't provide the Python port, so I did that here: import cv2import matplotlib.pyplot as pltimg = cv2.imread(<image_path>)dh, dw, _ = img.shapefl = open(<label_path>, 'r')data = fl.readlines()fl.close()for dt in data: # Split string to float _, x, y, w, h = map(float, dt.split(' ')) # Taken from https://github.com/pjreddie/darknet/blob/810d7f797bdb2f021dbe65d2524c2ff6b8ab5c8b/src/image.c#L283-L291 # via https://stackoverflow.com/questions/44544471/how-to-get-the-coordinates-of-the-bounding-box-in-yolo-object-detection#comment102178409_44592380 l = int((x - w / 2) * dw) r = int((x + w / 2) * dw) t = int((y - h / 2) * dh) b = int((y + h / 2) * dh) if l < 0: l = 0 if r > dw - 1: r = dw - 1 if t < 0: t = 0 if b > dh - 1: b = dh - 1 cv2.rectangle(img, (l, t), (r, b), (0, 0, 255), 1)plt.imshow(img)plt.show() So, for some Lenna image, that'd be the output, which I think shows the correct coordinates w.r.t. your image: ----------------------------------------System information----------------------------------------Platform: Windows-10-10.0.16299-SP0Python: 3.8.5Matplotlib: 3.3.2OpenCV: 4.4.0---------------------------------------- 1 Please upvote the linked answers and comments.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/64096953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9483941/']}
jdg_78996
stackexchange
llm_judgeable_groundtruth_similarity
3667714
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What kind of problems on graphs is faster (in terms of big-O) to solve using incidence matrix data structures instead of more widespread adjacency matrices? Now provide the response and nothing else.
The space complexities of the structures are: Adjacency: O(V^2)Incidence: O(VE) With the consequence that an incidence structure saves space if there are many more vertices than edges. You can look at the time complexity of some typical graph operations: Find all vertices adjacent to a vertex:Adj: O(V)Inc: O(VE) Check if two vertices are adjacent:Adj: O(1)Inc: O(E) Count the valence of a vertex:Adj: O(V)Inc: O(E) And so on. For any given algorithm, you can use building blocks like the above to calculate which representation gives you better overall time complexity. As a final note, using a matrix of any kind is extremely space-inefficient for all but the most dense of graphs, and I recommend against using either unless you've consciously dismissed alternatives like adjacency lists.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3667714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215571/']}
jdg_78997
stackexchange
llm_judgeable_groundtruth_similarity
4479928
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: Differentiating the integral w.r.t. $a$ yields $$\begin{aligned}\frac{\partial}{\partial a} \int_{0}^{1} \frac{x^{a}-1}{\ln x} d x =\int_{0}^{1} \frac{x^{a} \ln x}{\ln x} d x =\left[\frac{x^{a+1}}{a+1}\right]_{0}^{1}&=\frac{1}{a+1}\end{aligned}$$ Integrating both sides from $a=0$ to $a=t$ yields the result $$\boxed{\int_{0}^{1} \frac{x^{t}-1}{\ln x}dx=\ln (t+1)}$$ where $Re(t)>-1.$ Question : Can it be evaluated without Feynman? Now provide the response and nothing else.
Sure, we can use the dual to Feynman - turning the integral into a double integral: $$\int_0^1\frac{x^t-1}{\log x}\:dx = \int_0^1\int_0^tx^y\:dy\:dx = \int_0^t \frac{1}{y+1}\:dy = \log(t+1)$$ by Fubini's theorem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4479928', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/732917/']}
jdg_78998
stackexchange
llm_judgeable_groundtruth_similarity
2553566
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 not sure if its possible but I would like to create some sort of function where you pass in a string such as "yellow" or "green" and it returns its hex code or the range of hex codes that greens or yellows fit into. Is this possible in PHP? If not possible, I am willing to try anything else that can do this! Thanks all Now provide the response and nothing else.
// converts an html color name to a hex color value// if the input is not a color name, the original value is returned// http://wpCodeSnippets.infofunction color_name_to_hex($color_name){ // standard 147 HTML color names $colors = array( 'aliceblue'=>'F0F8FF', 'antiquewhite'=>'FAEBD7', 'aqua'=>'00FFFF', 'aquamarine'=>'7FFFD4', 'azure'=>'F0FFFF', 'beige'=>'F5F5DC', 'bisque'=>'FFE4C4', 'black'=>'000000', 'blanchedalmond '=>'FFEBCD', 'blue'=>'0000FF', 'blueviolet'=>'8A2BE2', 'brown'=>'A52A2A', 'burlywood'=>'DEB887', 'cadetblue'=>'5F9EA0', 'chartreuse'=>'7FFF00', 'chocolate'=>'D2691E', 'coral'=>'FF7F50', 'cornflowerblue'=>'6495ED', 'cornsilk'=>'FFF8DC', 'crimson'=>'DC143C', 'cyan'=>'00FFFF', 'darkblue'=>'00008B', 'darkcyan'=>'008B8B', 'darkgoldenrod'=>'B8860B', 'darkgray'=>'A9A9A9', 'darkgreen'=>'006400', 'darkgrey'=>'A9A9A9', 'darkkhaki'=>'BDB76B', 'darkmagenta'=>'8B008B', 'darkolivegreen'=>'556B2F', 'darkorange'=>'FF8C00', 'darkorchid'=>'9932CC', 'darkred'=>'8B0000', 'darksalmon'=>'E9967A', 'darkseagreen'=>'8FBC8F', 'darkslateblue'=>'483D8B', 'darkslategray'=>'2F4F4F', 'darkslategrey'=>'2F4F4F', 'darkturquoise'=>'00CED1', 'darkviolet'=>'9400D3', 'deeppink'=>'FF1493', 'deepskyblue'=>'00BFFF', 'dimgray'=>'696969', 'dimgrey'=>'696969', 'dodgerblue'=>'1E90FF', 'firebrick'=>'B22222', 'floralwhite'=>'FFFAF0', 'forestgreen'=>'228B22', 'fuchsia'=>'FF00FF', 'gainsboro'=>'DCDCDC', 'ghostwhite'=>'F8F8FF', 'gold'=>'FFD700', 'goldenrod'=>'DAA520', 'gray'=>'808080', 'green'=>'008000', 'greenyellow'=>'ADFF2F', 'grey'=>'808080', 'honeydew'=>'F0FFF0', 'hotpink'=>'FF69B4', 'indianred'=>'CD5C5C', 'indigo'=>'4B0082', 'ivory'=>'FFFFF0', 'khaki'=>'F0E68C', 'lavender'=>'E6E6FA', 'lavenderblush'=>'FFF0F5', 'lawngreen'=>'7CFC00', 'lemonchiffon'=>'FFFACD', 'lightblue'=>'ADD8E6', 'lightcoral'=>'F08080', 'lightcyan'=>'E0FFFF', 'lightgoldenrodyellow'=>'FAFAD2', 'lightgray'=>'D3D3D3', 'lightgreen'=>'90EE90', 'lightgrey'=>'D3D3D3', 'lightpink'=>'FFB6C1', 'lightsalmon'=>'FFA07A', 'lightseagreen'=>'20B2AA', 'lightskyblue'=>'87CEFA', 'lightslategray'=>'778899', 'lightslategrey'=>'778899', 'lightsteelblue'=>'B0C4DE', 'lightyellow'=>'FFFFE0', 'lime'=>'00FF00', 'limegreen'=>'32CD32', 'linen'=>'FAF0E6', 'magenta'=>'FF00FF', 'maroon'=>'800000', 'mediumaquamarine'=>'66CDAA', 'mediumblue'=>'0000CD', 'mediumorchid'=>'BA55D3', 'mediumpurple'=>'9370D0', 'mediumseagreen'=>'3CB371', 'mediumslateblue'=>'7B68EE', 'mediumspringgreen'=>'00FA9A', 'mediumturquoise'=>'48D1CC', 'mediumvioletred'=>'C71585', 'midnightblue'=>'191970', 'mintcream'=>'F5FFFA', 'mistyrose'=>'FFE4E1', 'moccasin'=>'FFE4B5', 'navajowhite'=>'FFDEAD', 'navy'=>'000080', 'oldlace'=>'FDF5E6', 'olive'=>'808000', 'olivedrab'=>'6B8E23', 'orange'=>'FFA500', 'orangered'=>'FF4500', 'orchid'=>'DA70D6', 'palegoldenrod'=>'EEE8AA', 'palegreen'=>'98FB98', 'paleturquoise'=>'AFEEEE', 'palevioletred'=>'DB7093', 'papayawhip'=>'FFEFD5', 'peachpuff'=>'FFDAB9', 'peru'=>'CD853F', 'pink'=>'FFC0CB', 'plum'=>'DDA0DD', 'powderblue'=>'B0E0E6', 'purple'=>'800080', 'red'=>'FF0000', 'rosybrown'=>'BC8F8F', 'royalblue'=>'4169E1', 'saddlebrown'=>'8B4513', 'salmon'=>'FA8072', 'sandybrown'=>'F4A460', 'seagreen'=>'2E8B57', 'seashell'=>'FFF5EE', 'sienna'=>'A0522D', 'silver'=>'C0C0C0', 'skyblue'=>'87CEEB', 'slateblue'=>'6A5ACD', 'slategray'=>'708090', 'slategrey'=>'708090', 'snow'=>'FFFAFA', 'springgreen'=>'00FF7F', 'steelblue'=>'4682B4', 'tan'=>'D2B48C', 'teal'=>'008080', 'thistle'=>'D8BFD8', 'tomato'=>'FF6347', 'turquoise'=>'40E0D0', 'violet'=>'EE82EE', 'wheat'=>'F5DEB3', 'white'=>'FFFFFF', 'whitesmoke'=>'F5F5F5', 'yellow'=>'FFFF00', 'yellowgreen'=>'9ACD32'); $color_name = strtolower($color_name); if (isset($colors[$color_name])) { return ('#' . $colors[$color_name]); } else { return ($color_name); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2553566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']}
jdg_78999
stackexchange
llm_judgeable_groundtruth_similarity
34803855
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 do some NLP text clean up of some Unicode columns in a PySpark DataFrame. I've tried in Spark 1.3, 1.5 and 1.6 and can't seem to get things to work for the life of me. I've also tried using Python 2.7 and Python 3.4. I've created an extremely simple udf as seen below that should just return a string back for each record in a new column. Other functions will manipulate the text and then return the changed text back in a new column. import pysparkfrom pyspark.sql import SQLContextfrom pyspark.sql.types import *from pyspark.sql import SQLContextfrom pyspark.sql.functions import udfdef dummy_function(data_str): cleaned_str = 'dummyData' return cleaned_strdummy_function_udf = udf(dummy_function, StringType()) Some sample data can be unzipped from here. Here is the code I use to import the data and then apply the udf on. # Load a text file and convert each line to a Row.lines = sc.textFile("classified_tweets.txt")parts = lines.map(lambda l: l.split("\t"))training = parts.map(lambda p: (p[0], p[1]))# Create dataframetraining_df = sqlContext.createDataFrame(training, ["tweet", "classification"])training_df.show(5)+--------------------+--------------+| tweet|classification|+--------------------+--------------+|rt @jiffyclub: wi...| python||rt @arnicas: ipyt...| python||rt @treycausey: i...| python||what's my best op...| python||rt @raymondh: #py...| python|+--------------------+--------------+# Apply UDF functiondf = training_df.withColumn("dummy", dummy_function_udf(training_df['tweet']))df.show(5) When I run the df.show(5) I get the following error. I understand that the problem most likely doesn't stem from the show() but the trace doesn't give me much help. ---------------------------------------------------------------------------Py4JJavaError Traceback (most recent call last)<ipython-input-19-0b21c233c724> in <module>() 1 df = training_df.withColumn("dummy", dummy_function_udf(training_df['tweet']))----> 2 df.show(5)/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/pyspark/sql/dataframe.py in show(self, n, truncate) 255 +---+-----+ 256 """--> 257 print(self._jdf.showString(n, truncate)) 258 259 def __repr__(self):/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args) 811 answer = self.gateway_client.send_command(command) 812 return_value = get_return_value(--> 813 answer, self.gateway_client, self.target_id, self.name) 814 815 for temp_arg in temp_args:/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/pyspark/sql/utils.py in deco(*a, **kw) 43 def deco(*a, **kw): 44 try:---> 45 return f(*a, **kw) 46 except py4j.protocol.Py4JJavaError as e: 47 s = e.java_exception.toString()/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 306 raise Py4JJavaError( 307 "An error occurred while calling {0}{1}{2}.\n".--> 308 format(target_id, ".", name), value) 309 else: 310 raise Py4JError(Py4JJavaError: An error occurred while calling o474.showString.: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 10.0 failed 1 times, most recent failure: Lost task 0.0 in stage 10.0 (TID 10, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main process() File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream vs = list(itertools.islice(iterator, batch)) File "<ipython-input-12-4bc30395aac5>", line 4, in <lambda>IndexError: list index out of range at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166) at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:129) at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:125) at org.apache.spark.InterruptibleIterator.next(InterruptibleIterator.scala:43) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$GroupedIterator.takeDestructively(Iterator.scala:913) at scala.collection.Iterator$GroupedIterator.go(Iterator.scala:929) at scala.collection.Iterator$GroupedIterator.fill(Iterator.scala:968) at scala.collection.Iterator$GroupedIterator.hasNext(Iterator.scala:972) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at org.apache.spark.api.python.PythonRDD$.writeIteratorToStream(PythonRDD.scala:452) at org.apache.spark.api.python.PythonRunner$WriterThread$$anonfun$run$3.apply(PythonRDD.scala:280) at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1741) at org.apache.spark.api.python.PythonRunner$WriterThread.run(PythonRDD.scala:239)Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1431) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1419) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1418) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1418) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:799) at scala.Option.foreach(Option.scala:236) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:799) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1640) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1599) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1588) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:620) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1832) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1845) at org.apache.spark.SparkContext.runJob(SparkContext.scala:1858) at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:212) at org.apache.spark.sql.execution.Limit.executeCollect(basicOperators.scala:165) at org.apache.spark.sql.execution.SparkPlan.executeCollectPublic(SparkPlan.scala:174) at org.apache.spark.sql.DataFrame$$anonfun$org$apache$spark$sql$DataFrame$$execute$1$1.apply(DataFrame.scala:1538) at org.apache.spark.sql.DataFrame$$anonfun$org$apache$spark$sql$DataFrame$$execute$1$1.apply(DataFrame.scala:1538) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:56) at org.apache.spark.sql.DataFrame.withNewExecutionId(DataFrame.scala:2125) at org.apache.spark.sql.DataFrame.org$apache$spark$sql$DataFrame$$execute$1(DataFrame.scala:1537) at org.apache.spark.sql.DataFrame.org$apache$spark$sql$DataFrame$$collect(DataFrame.scala:1544) at org.apache.spark.sql.DataFrame$$anonfun$head$1.apply(DataFrame.scala:1414) at org.apache.spark.sql.DataFrame$$anonfun$head$1.apply(DataFrame.scala:1413) at org.apache.spark.sql.DataFrame.withCallback(DataFrame.scala:2138) at org.apache.spark.sql.DataFrame.head(DataFrame.scala:1413) at org.apache.spark.sql.DataFrame.take(DataFrame.scala:1495) at org.apache.spark.sql.DataFrame.showString(DataFrame.scala:171) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381) at py4j.Gateway.invoke(Gateway.java:259) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:209) at java.lang.Thread.run(Thread.java:745)Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 111, in main process() File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/Users/dreyco676/spark-1.6.0-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream vs = list(itertools.islice(iterator, batch)) File "<ipython-input-12-4bc30395aac5>", line 4, in <lambda>IndexError: list index out of range at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166) at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:129) at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:125) at org.apache.spark.InterruptibleIterator.next(InterruptibleIterator.scala:43) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$GroupedIterator.takeDestructively(Iterator.scala:913) at scala.collection.Iterator$GroupedIterator.go(Iterator.scala:929) at scala.collection.Iterator$GroupedIterator.fill(Iterator.scala:968) at scala.collection.Iterator$GroupedIterator.hasNext(Iterator.scala:972) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at org.apache.spark.api.python.PythonRDD$.writeIteratorToStream(PythonRDD.scala:452) at org.apache.spark.api.python.PythonRunner$WriterThread$$anonfun$run$3.apply(PythonRDD.scala:280) at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1741) at org.apache.spark.api.python.PythonRunner$WriterThread.run(PythonRDD.scala:239) Actual function I'm trying: def tag_and_remove(data_str): cleaned_str = ' ' # noun tags nn_tags = ['NN', 'NNP', 'NNP', 'NNPS', 'NNS'] # adjectives jj_tags = ['JJ', 'JJR', 'JJS'] # verbs vb_tags = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] nltk_tags = nn_tags + jj_tags + vb_tags # break string into 'words' text = data_str.split() # tag the text and keep only those with the right tags tagged_text = pos_tag(text) for tagged_word in tagged_text: if tagged_word[1] in nltk_tags: cleaned_str += tagged_word[0] + ' ' return cleaned_strtag_and_remove_udf = udf(tag_and_remove, StringType()) Now provide the response and nothing else.
Your dataset isn't clean. 985 lines split('\t') to only one value: >>> from operator import add>>> lines = sc.textFile("classified_tweets.txt")>>> parts = lines.map(lambda l: l.split("\t"))>>> parts.map(lambda l: (len(l), 1)).reduceByKey(add).collect()[(2, 149195), (1, 985)]>>> parts.filter(lambda l: len(l) == 1).take(5)[['"show me the money!” at what point do you start trying to monetize your #startup? tweet us with #startuplife.'], ['a good pitch can mean money in the bank for your #startup. see how body language plays a key role: (via: ajalumnify)'], ['100+ apps in five years? @2359media did it using microsoft #azure: #azureapps'], ['does buying better coffee make you a better leader? little things can make a big difference: (via: @jmbrandonbb)'], ['.@msftventures graduates pitched\xa0#homeautomation #startups to #vcs! check out how they celebrated: ']] So changing your code to: >>> training = parts.filter(lambda l: len(l) == 2).map(lambda p: (p[0], p[1].strip()))>>> training_df = sqlContext.createDataFrame(training, ["tweet", "classification"])>>> df = training_df.withColumn("dummy", dummy_function_udf(training_df['tweet']))>>> df.show(5)+--------------------+--------------+---------+| tweet|classification| dummy|+--------------------+--------------+---------+|rt @jiffyclub: wi...| python|dummyData||rt @arnicas: ipyt...| python|dummyData||rt @treycausey: i...| python|dummyData||what's my best op...| python|dummyData||rt @raymondh: #py...| python|dummyData|+--------------------+--------------+---------+only showing top 5 rows
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34803855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3016037/']}
jdg_79000
stackexchange
llm_judgeable_groundtruth_similarity
18912699
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 kendo grid customosed and I want to format some cells to have decimal type, to calculate a sum in the footer of the grid. After all I want to format numbers with spaces for each 000s. Does anybody have any idea what is the best way of doing that? This is already done, but I want to make it using kendo framework functionality, if exist.. Now provide the response and nothing else.
Since DescriptionAttribute is not available for portable class libraries you need to use another attribute. The namespace System.ComponentModel.DataAnnotations which is available for portable class libraries provides the attribute DisplayAttribute that you can use instead. public enum InstallationType{ [Display(Description="Forward of Bulk Head")] FORWARD = 0, [Display(Description="Rear of Bulk Head")] REAR = 1, [Display(Description="Roof Mounted")] ROOF = 2,} Your method needs to be changed to public static string GetDescriptionFromEnumValue(Enum value) { DisplayAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof(DisplayAttribute ), false) .SingleOrDefault() as DisplayAttribute ; return attribute == null ? value.ToString() : attribute.Description; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18912699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2609787/']}
jdg_79001
stackexchange
llm_judgeable_groundtruth_similarity
26430259
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to do a "BETWEEN ? AND ?" where condition LIKE in cakephp 2.5?In cakephp 2.5 I write something like 'conditions' => ['start_date BETWEEN ? AND ?' => ['2014-01-01', '2014-12-32']] how can I migrate that? additionally I would write something like 'conditions' => [ '? BETWEEN start_date AND end_date'] => '2014-03-31'] Now provide the response and nothing else.
Expressions Between expression are supported out of the box, however they only support the first case without additional fiddling: $Query = $Table ->find() ->where(function($exp) { return $exp->between('start_date', '2014-01-01', '2014-12-32', 'date'); }); If you'd wanted to handle the second case via the between method, then you'd have to pass all values as expressions, which can easily go wrong, as they will not be subject to escaping/parameter binding in that case, you'd have to do that on your own (which is anything but recommended! See the security notes in the manual for PDO::quote() ), something along the lines of: use Cake\Database\Expression\IdentifierExpression;use Cake\Database\Expression\QueryExpression;use Cake\ORM\Query;// ...$Query = $Table ->find() ->where(function(QueryExpression $exp, Query $query) { return $exp->between( $query->newExpr( $query->connection()->driver()->quote( '2014-03-31', \PDO::PARAM_STR ) ), new IdentifierExpression('start_date'), new IdentifierExpression('end_date') ); }); That might feel a little inconvenient for such a basic SQL expression that is supported by all SQL dialects that CakePHP ships with, so you may have a reason here to use a raw SQL snippet with value bindig instead. It should be noted however that expressions are often the better choice when it comes to for example cross dialect support, as they can be (more or less) easily transformed at compile time, see the implementations of SqlDialectTrait::_expressionTranslators() . Also expressions usually support automatic identifier quoting. Value binding Via manual value binding you can pretty much create anything you like. It should however be noted that whenever possible, you should use expressions instead, as they are easier to port, which happens out of the box for quite a few expressions already. $Query = $Table ->find() ->where([ 'start_date BETWEEN :start AND :end' ]) ->bind(':start', '2014-01-01', 'date') ->bind(':end', '2014-12-31', 'date'); That way the second case can also be solved very easily, like: $Query = $Table ->find() ->where([ ':date BETWEEN start_date AND end_date' ]) ->bind(':date', '2014-03-31', 'date'); A mixture of both (safest and most compatible approach) It's also possible to mix both, ie use an expression that makes use of custom bindings, something along the lines of this: use Cake\Database\Expression\IdentifierExpression;use Cake\Database\Expression\QueryExpression;use Cake\ORM\Query;// ...$Query = $Table ->find() ->where(function(QueryExpression $exp, Query $query) { return $exp->between( $query->newExpr(':date'), new IdentifierExpression('start_date'), new IdentifierExpression('end_date') ); }) ->bind(':date', '2014-03-31', 'date'); That way you could handle the second case using possibly portable expressions, and don't have to worry about quoting/escaping input data and identifiers manually. Regular comparison using array syntax All that being said, in the end BETWEEN is just the same as using two separate simple conditions like this: $Query = $Table ->find() ->where([ 'start_date >=' => '2014-01-01', 'start_date <=' => '2014-12-32', ]); $Query = $Table ->find() ->where([ 'start_date >=' => '2014-03-31', 'end_date <=' => '2014-03-31', ]); But don't be mad, if you read all the way down to here, at least you learned something about the ins and outs of the query builder. See also Cookbook > Database Access & ORM > Query Builder > Advanced Conditions API > \Cake\Database\Query::bind() Currently there seems to be only two options. The core now supports this out of the box, the following is just kept for reference. Value binding (via the database query builder) For now the ORM query builder ( Cake\ORM\Query ), the one that is being retrived when invoking for example find() on a table object, doesn't support value binding https://github.com/cakephp/cakephp/issues/4926 So, for being able to use bindings you'd have to use the underlying database query builder ( Cake\Database\Query ), which can for example be retrived via Connection::newQuery() . Here's an example: $conn = ConnectionManager::get('default');$Query = $conn->newQuery(); $Query ->select('*') ->from('table_name') ->where([ 'start_date BETWEEN :start AND :end' ]) ->bind(':start', new \DateTime('2014-01-01'), 'date') ->bind(':end', new \DateTime('2014-12-31'), 'date');debug($Query->execute()->fetchAll()); This would result in a query similar to this SELECT *FROM table_nameWHERE start_date BETWEEN '2014-01-01' AND '2014-12-31' A custom expression class Another option would be a custom expression class that generates appropriate SQL snippets. Here's an example. Column names should be wrapped into identifier expression objects in order to them be auto quoted (in case auto quoting is enabled), the key > value array syntax is for binding values, where the array key is the actual value, and the array value is the datatype. Please note that it's not safe to directly pass user input for column names, as they are not being escaped! Use a whitelist or similar to make sure the column name is safe to use! Field between values use App\Database\Expression\BetweenComparison;use Cake\Database\Expression\IdentifierExpression;// ...$between = new BetweenComparison( new IdentifierExpression('created'), ['2014-01-01' => 'date'], ['2014-12-31' => 'date']);$TableName = TableRegistry::get('TableName');$Query = $TableName ->find() ->where($between);debug($Query->execute()->fetchAll()); This would generate a query similar to the one above. Value between fields use App\Database\Expression\BetweenComparison;use Cake\Database\Expression\IdentifierExpression;// ...$between = new BetweenComparison( ['2014-03-31' => 'date'], new IdentifierExpression('start_date'), new IdentifierExpression('end_date'));$TableName = TableRegistry::get('TableName');$Query = $TableName ->find() ->where($between);debug($Query->execute()->fetchAll()); This on the other hand would result in a query similar to this SELECT *FROM table_nameWHERE '2014-03-31' BETWEEN start_date AND end_date The expression class namespace App\Database\Expression;use Cake\Database\ExpressionInterface;use Cake\Database\ValueBinder;class BetweenComparison implements ExpressionInterface { protected $_field; protected $_valueA; protected $_valueB; public function __construct($field, $valueA, $valueB) { $this->_field = $field; $this->_valueA = $valueA; $this->_valueB = $valueB; } public function sql(ValueBinder $generator) { $field = $this->_compilePart($this->_field, $generator); $valueA = $this->_compilePart($this->_valueA, $generator); $valueB = $this->_compilePart($this->_valueB, $generator); return sprintf('%s BETWEEN %s AND %s', $field, $valueA, $valueB); } public function traverse(callable $callable) { $this->_traversePart($this->_field, $callable); $this->_traversePart($this->_valueA, $callable); $this->_traversePart($this->_valueB, $callable); } protected function _bindValue($value, $generator, $type) { $placeholder = $generator->placeholder('c'); $generator->bind($placeholder, $value, $type); return $placeholder; } protected function _compilePart($value, $generator) { if ($value instanceof ExpressionInterface) { return $value->sql($generator); } else if(is_array($value)) { return $this->_bindValue(key($value), $generator, current($value)); } return $value; } protected function _traversePart($value, callable $callable) { if ($value instanceof ExpressionInterface) { $callable($value); $value->traverse($callable); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26430259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4154577/']}
jdg_79002
stackexchange
llm_judgeable_groundtruth_similarity
2933857
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The axiom of infinity in ZFC (see this wikipedia link ) allows us to construct the natural numbers. But I think we can drop that axiom and replace it with this one: Axiom of Infinity: There exists a set $M$ and a non-surjective injective mapping $\sigma: M \to M$ . We can use this to construct the natural numbers. Select a function $\sigma$ that injects a set $M$ into itself but does not hit all the elements of $M$ . Assume $0 \in M$ is not in the range of $\sigma$ . Consider the family of all subsets of $R$ of $M$ with the following properties: $\tag 1 0 \in R$ $\tag 2 \text{The image of } R \text{ under } \sigma \text{ is contained in } R$ So if we restrict $\sigma$ to $R$ and change the target to $R$ , we have another function with the properties we are examining. One can easily check that the intersection of two 'restriction sets' $R$ and $S$ in this family also satisfies both (1) and (2). In fact, we can intersect all of the subsets satisfying (1) and (2) and the result is a minimal such set So assume that our function $\sigma: M \to M$ has no viable restrictions to any proper subsets. It is easy to see that the only element not in the range of $\sigma$ is $0$ . Now let $S \subset M$ have the following properties: $\tag 3 0 \in S$ $\tag 4 \text{If } n \in S \text{ Then } \sigma(n) \in S$ Then, since $M$ is minimal, $S$ must be equal to $S$ . But we have shown that $\sigma$ is a 'successor' function (hello Peano!) and (3) and (4) is the induction scheme. We have shown that $M$ is the set of natural numbers, $\mathbb N$ . Question 1: Does this work indeed make sense in the ZFC setting? Question 2: If yes, has this already been examined? Question 3: If 1=yes/2=no, does it change anything in ZFC? Now provide the response and nothing else.
The answer is that it makes sense and doesn't change anything. Precisely, over ZF-Inf (= ZF without the axiom of infinity), your statement (call it " $(*)$ ") is equivalent to the usual axiom of infinity. One direction is immediate: obviously the axiom of infinity implies $(*)$ . Here's a sketch of the other direction. Fix $m\in M\setminus ran(\sigma)$ . For an ordinal $\alpha$ say that a map $e:\alpha\rightarrow M$ is a good embedding if: $e(0)=m$ (or $\alpha=0$ ) . If $\beta+1<\alpha$ , then $e(\beta+1)=\sigma(e(\beta))$ . Now call an ordinal $\alpha$ finitary (avoiding the word "finite" for obvious reasons) if it has a maximal element and no limit elements: that is, if $(i)$ $\alpha=\beta\cup\{\beta\}$ for some ordinal $\beta$ (unless $\alpha$ is empty), and $(ii)$ for every nonempty $\gamma\in\alpha$ we have that $\gamma=\theta\cup\{\theta\}$ for some ordinal $\theta$ . The key point is this: we can show that for every $k\in M$ there is at most one finitary ordinal $\alpha$ such that $k$ is the image of the maximal element of $\alpha$ under some good embedding, and conversely every finitary ordinal admits exactly one good embedding into $M$ . This lets us apply Replacement to get the set of all finitary ordinals; but we can show that this is exactly $\omega$ . So why use the axiom of infinity as it's written? Well, note the use of Replacement above. There are very good reasons to want to be able to drop Replacement from time to time, so an axiom which requires Replacement to use in the obvious ways is immediately suspicious. Basically, by being so explicit the axiom of infinity can save us unnecessary axiomatic overhead, while apparently-reasonable alternatives may not do so.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2933857', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/432081/']}
jdg_79003
stackexchange
llm_judgeable_groundtruth_similarity
1046057
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if the following integral is able to be evaluated using the Gamma Function.$$\int_0^{\infty}t^{-\frac{1}{2}}\mathrm{exp}\left[-a\left(t+t^{-1}\right)\right]\,dt$$I already have a tedious solution that doesn't exceed the scope of the first few semesters of calculus, but I want to tackle this with the Gamma Function. I just don't know how or if it's even possible. If anyone can give a hint, I'd really like to finish it on my own. EDIT:You are allowed to use the fact that $$\int_{-\infty}^{\infty}\exp(-x^2)\,dx = \sqrt{\pi}$$ Now provide the response and nothing else.
Let $t=u^2$, and the integral becomes $$2 \int_0^{\infty} du \, e^{-a \left (u^2 + \frac1{u^2} \right)} = 2 e^{2 a} \int_0^{\infty} du \, e^{-a \left ( u+\frac1{u} \right )^2}$$ Let $v=u+1/u$, then $$u = \frac12 \left (v \pm \sqrt{v^2-4} \right ) $$ $$du = \frac12 \left (1 \pm \frac{v}{\sqrt{v^2-4}} \right ) dv $$ Now, it should be understood that as $u$ traverses from $0$ to $\infty$, $v$ traverses from $\infty$ down to a min of $2$ (corresponding to $u \in [0,1]$), then from $2$ back to $\infty$ (corresponding to $u \in [1,\infty)$). Therefore the integral is $$e^{2 a} \int_{\infty}^{2} dv \left (1 - \frac{v}{\sqrt{v^2-4}}\right ) e^{-a v^2} + e^{2 a} \int_{2}^{\infty} du \left (1 + \frac{v}{\sqrt{v^2-4}}\right ) e^{-a v^2} $$ which is $$\begin{align}2 e^{2 a}\int_2^{\infty} dv \frac{v}{\sqrt{v^2-4}} e^{-a v^2} &= e^{2 a} \int_4^{\infty} \frac{dy}{\sqrt{y-4}} e^{-a y}\\ &= e^{-2 a} \int_0^{\infty} dq \, q^{-1/2} \, e^{-a q} \end{align}$$ I guess the gamma function comes from this integral, but I find it easier to refer to gaussian integrals.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1046057', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80630/']}
jdg_79004
stackexchange
llm_judgeable_groundtruth_similarity
36156741
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 building a series of linked classes whose instances I want to be able to marshall to XML so I can save them to a file and read them in again later. At present I'm using the following code as a test case: import javax.xml.bind.annotation.*;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import java.time.LocalDate;public class LocalDateExample{ @XmlRootElement private static class WrapperTest { public LocalDate startDate; } public static void main(String[] args) throws JAXBException { WrapperTest wt = new WrapperTest(); LocalDate ld = LocalDate.of(2016, 3, 1); wt.startDate = ld; marshall(wt); } public static void marshall(Object jaxbObject) throws JAXBException { JAXBContext context = JAXBContext.newInstance(jaxbObject.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(jaxbObject, System.out); }} The XML output is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?><wrapperTest> <startDate/></wrapperTest> Is there a reason why the startDate element is empty? I would like it to contain the string representation of the date (i.e. toString() ). Do I need to write some code of my own in order to do this? The output of java -version is: openjdk version "1.8.0_66-internal"OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode) Now provide the response and nothing else.
You will have to create an XmlAdapter like this: public class LocalDateAdapter extends XmlAdapter<String, LocalDate> { public LocalDate unmarshal(String v) throws Exception { return LocalDate.parse(v); } public String marshal(LocalDate v) throws Exception { return v.toString(); }} And annotate your field using @XmlJavaTypeAdapter(value = LocalDateAdapter.class) See also javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters if you want to define your adapters on a package level.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36156741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/452880/']}
jdg_79005
stackexchange
llm_judgeable_groundtruth_similarity
7355187
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I received this error message: Error in if (condition) { : missing value where TRUE/FALSE needed or Error in while (condition) { : missing value where TRUE/FALSE needed What does it mean, and how do I prevent it? Now provide the response and nothing else.
The evaluation of condition resulted in an NA . The if conditional must have either a TRUE or FALSE result. if (NA) {}## Error in if (NA) { : missing value where TRUE/FALSE needed This can happen accidentally as the results of calculations: if(TRUE && sqrt(-1)) {}## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed To test whether an object is missing use is.na(x) rather than x == NA . See also the related errors: Error in if/while (condition) { : argument is of length zero Error in if/while (condition) : argument is not interpretable as logical if (NULL) {}## Error in if (NULL) { : argument is of length zeroif ("not logical") {}## Error: argument is not interpretable as logicalif (c(TRUE, FALSE)) {}## Warning message:## the condition has length > 1 and only the first element will be used
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7355187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633426/']}
jdg_79006
stackexchange
llm_judgeable_groundtruth_similarity
24623023
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok I know this must be simpler than I am making it out to be, but I can't seem to figure it out. I have menu. the user selects a number which calls a certain method. I want the menu to repeat if they do not select a valid option. and then I want to give them the option to select another option or end the program. Can anyone help me out? import java.util.Scanner;public class TestStringManip { //=================MAIN=============== public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String input = in.nextLine(); StringManipulation newString = new StringManipulation(input); String menu = "\n Please select an option to perform" + "\n1 (1) Get all uppercase letters." + "\n2 (2) Get every second letter." + "\n3 (3) Replace vowels with _ " + "\n4 (4) Get a count of all vowels." + "\n5 (5) Get position of all vowels."; System.out.println(menu); int option = in.nextInt(); do { if (option == 1) { newString.getUpperCase(input); } else if (option == 2) { newString.getEverySecond(input); } else { System.out.println("Error must select 1-5"); System.out.println(menu); option = in.nextInt(); } }while (option < 1 || option > 5); }} I have updated my code to try some of the suggested answers. It works for the first two options but that is it. I am also trying to get it to repeat after each option is chosen unless 0 is chosen which should end the program. Here is my updated code. import java.util.Scanner;public class TestStringManip { //=================MAIN=============== public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String input = in.nextLine(); StringManipulation newString = new StringManipulation(input); String menu = "\n Please select an option to perform" + "\n1 (1) Get all uppercase letters." + "\n2 (2) Get every second letter." + "\n3 (3) Replace vowels with _ " + "\n4 (4) Get a count of all vowels." + "\n5 (5) Get position of all vowels." + "\n0 (0) Exit Program"; System.out.println(menu); int option = in.nextInt(); int i = 0; do { if (option == 1) { newString.getUpperCase(input); i = 1; } else if (option == 2) { newString.getEverySecond(input); i = 1; } else if (option == 3) { newString.replaceVowels(input); i = 1; } else if (option == 4) { newString.getNumberOfVowels(input); i = 1; } else if (option == 5) { newString.getVowelPosition(input); i = 1; } else if (option == 0) { break; } else { System.out.println("Error must select 0-5"); System.out.println("Enter your option: "); option = in.nextInt(); } }while (i == 0); }} Now provide the response and nothing else.
I got the exact same problem when I included the following line on my ~/.bashrc : stty -ixon The purpose of this line was to allow the use of Ctrl-s in reverse search of bash . This gmane link has a solution: (original link dead) => Web Archive version of gmane link 'stty' applies to ttys, which you have for interactive login sessions..kshrc is executed for all sessions, including ones where stdin isn'ta tty. The solution, other than moving it to your .profile, is tomake execution conditional on it being an interactive shell. There are several ways to check for interecative shell . The following solves the problem for bash: [[ $- == *i* ]] && stty -ixon
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24623023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3769297/']}
jdg_79007
stackexchange
llm_judgeable_groundtruth_similarity
3980049
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 the set $A = [0,1]\setminus\mathbb{Q}$ countable or not? What I am thinking is $A$ consist of irrational numbers in the interval $[0,1]$ hence it is subset of irrational numbers. As set of irrational numbers is uncountable so I think set $A$ is also uncountable. Now provide the response and nothing else.
Yes, it is uncountable, but not for that reason. For instance, $\left\{\sqrt2+n\,\middle|\, n\in\Bbb N\right\}$ is also a set of irrational numbers, but it is countable. However, if $[0,1]\setminus\Bbb Q$ was countable, then, since $\Bbb Q\cap[0,1]$ is countable, $[0,1]$ would be countable too, since it's the union of them.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3980049', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/655531/']}
jdg_79008
stackexchange
llm_judgeable_groundtruth_similarity
6215523
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found. So long story short, count how many times each UUID appears in the log file.At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value. for i, logLine in enumerate(logHandle): #start matching UUID entries in log file to UUID from rulebase if logFunc.progress(lineCount, logSize): #check progress print logFunc.progress(lineCount, logSize) #print progress in 10% intervals for uid in uidHits: if logLine.count(uid) == 1: #for each UUID, check the current line of the log for a match in the UUID list uidHits[uid] += 1 #if matched, increment the relevant value in the uidHits list break #as we've already found the match, don't process the rest lineCount += 1 It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :) Now provide the response and nothing else.
Think functionally! Write a function which will take a line of the log file and return the uuid. Call it uuid , say. Apply this function to every line of the log file. If you are using Python 3 you can use the built-in function map; otherwise, you need to use itertools.imap. Pass this iterator to a collections.Counter. collections.Counter(map(uuid, open("log.txt"))) This will be pretty much optimally efficient. A couple comments: This completely ignores the list of UUIDs and just counts the ones that appear in the log file. You will need to modify the program somewhat if you don't want this. Your code is slow because you are using the wrong data structures. A dict is what you want here.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6215523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781242/']}
jdg_79009
stackexchange
llm_judgeable_groundtruth_similarity
1132422
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 saw the other topic and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong? System.Diagnostics.Process.Start("explorer.exe", @"c:\teste"); Now provide the response and nothing else.
Have you made sure that the folder " c:\teste " exists? If it doesn't, explorer will open showing some default folder (in my case " C:\Users\[user name]\Documents "). Update I have tried the following variations: // opens the folder in explorerProcess.Start(@"c:\temp");// opens the folder in explorerProcess.Start("explorer.exe", @"c:\temp");// throws exceptionProcess.Start(@"c:\does_not_exist");// opens explorer, showing some other folder)Process.Start("explorer.exe", @"c:\does_not_exist"); If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following: Open the Run dialog, enter "explorer.exe" and hit enter Open a command prompt, type "explorer.exe" and hit enter
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1132422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75975/']}
jdg_79010
stackexchange
llm_judgeable_groundtruth_similarity
9323329
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 worked on a C++ project using a regular text editor. Later, I imported all the files to Eclipse to make it debugging easier. In Eclipse a weird thing happens. It complains "Member declaration not found" even if I have included the header file. The header file has the function definition. How do I fix this problem? Now provide the response and nothing else.
"Member declaration not found" is an error produced by the Eclipse static analysis tool ( codan ). If you get this error, but the compilation succeeds this is a false positive. Older versions of this tool are known to give some false positives, see for example this bug report . So I recommend updating Eclipse CDT to the most recent version. Another thing that may cause this error is an unresolved include that prevents Eclipse from parsing a portion of your code correctly. Selecting Index -> Search For Unresolved Includes in the context menu of the project will give you the list of unresolved includes. See this answer for the details of how to fix it. Here's an example: class C { void f(std::vector<int>&);};void C::f(std::vector<int>&) {} // Member declaration not found The above example causes "Member declaration not found" error in Eclipse CDT even if you have <vector> included but unresolved (due to misconfigured include paths).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9323329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/615780/']}
jdg_79011
stackexchange
llm_judgeable_groundtruth_similarity
65640
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 $P$, the vector space of all polynomials (over reals), I am supposed to come out with a hyperplane of $P$, and show that it is indeed a hyperplane. Since a hyperplane is the same as a flat, I gave myself such example $p+M=\{p+q: q \text{ is in } M \}$ where $M$ is a subspace of dimension $n-1$, so $M$ is spanned by basis elements say $(1,x,x^2,...,x^n-2)$. I am now supposed to show that indeed it is a hyperplane. I am thinking of showing that the vectors $1-x^{n-1}, x-x^{n-1},\ldots, x^{n-2}-x^{n-1}$ are linearly independent? Does this solve the question? Or you think I have to do something different? Now provide the response and nothing else.
The OP is in the correct direction. By Cayley's formula, the number of labeled trees on $n$ vertices is $n^{n-2}$. We will count the number of labelled trees in a different way and get the equality. Take a tree $T$ and an edge $e \in T$. Then $T \setminus \{ e \}$ contains two components, say of sizes $k$ and $n-k$. Also, each of the components is a tree by itself. With this in mind, we build the tree $T$ as follows. Partition the vertices into two parts, of sizes $k$ and $n-k$ respectively. Draw trees $T_1$ and $T_2$ on the two parts. Then pick an arbitrary vertex from each of the parts and join the pair by an edge. The number of ways of doing this procedure is:$$\sum_{k=1}^{n-1} \binom{n}{k} \times k^{k-2} (n-k)^{n-k-2} \times (k (n-k)) = R,$$the right hand side of the purported equation. The binomial coefficient arises from choosing $k$ vertices. The second factor is by applying the Cayley's formula for the number of trees on $k$ and $n-k$ vertices. The $k(n-k)$ factor is the number of ways to connect these components by a single edge. Now, this procedure overcounts the number of trees. Specifically, each tree can be cut in any of its $n-1$ edges to give a pair of components. (That's a factor of $n-1$.) Further, in selecting $k$ vertices to make two components of sizes $k$ and $n-k$, we distinguish the two components (one that is selected, and one that is not). So we should further divide the number we got by $2$. Thus the number of labelled trees on $n$ vertices is $$\frac{R}{2(n-1)}.$$Equating it to $n^{n-2}$, we get the claim.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/65640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15973/']}
jdg_79012
stackexchange
llm_judgeable_groundtruth_similarity
13975058
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my activity, I have a editText field. When the user taps on it, the editText gains the focus and the keyboard appears. Now, when the user presses the hardware back button on the phone, the keyboard disappears but the cursor remains in the Edittext, i. e., it still has the focus. Is it possible to make the EditText lose focus when back button is pressed? I tried using the following code but it didn't work: @Overridepublic void onBackPressed() { vibrator.vibrate(Constants.DEFAULT_VIBRATE_TIME); myEditText.clearFocus(); super.onBackPressed();} Now provide the response and nothing else.
Just extend EditText: public class EditTextV2 extends EditText{ public EditTextV2( Context context ) { super( context ); } public EditTextV2( Context context, AttributeSet attribute_set ) { super( context, attribute_set ); } public EditTextV2( Context context, AttributeSet attribute_set, int def_style_attribute ) { super( context, attribute_set, def_style_attribute ); } @Override public boolean onKeyPreIme( int key_code, KeyEvent event ) { if ( key_code == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP ) this.clearFocus(); return super.onKeyPreIme( key_code, event ); }} And in the xml just use <yourPackage.EditTextV2> instead of <EditText> . Note: You may need to add/remove constructors to this class depending on the min API you're supporting. I suggest just adding them all and removing the ones whose super() calls get underlined in red.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13975058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773416/']}
jdg_79013
stackexchange
llm_judgeable_groundtruth_similarity
48204141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Java 9 deprecated six modules that contain Java EE APIs and they are going to be removed soon: java.activation with javax.activation package java.corba with javax.activity , javax.rmi , javax.rmi.CORBA , and org.omg.* packages java.transaction with javax.transaction package java.xml.bind with all javax.xml.bind.* packages java.xml.ws with javax.jws , javax.jws.soap , javax.xml.soap , and all javax.xml.ws.* packages java.xml.ws.annotation with javax.annotation package Which maintained third-party artifacts provide those APIs? It doesn't matter how well they provide those APIs or which other features they have to offer - all that matters is, are they a drop-in replacement for these modules/packages? To make it easier to collect knoweldge, I answered with what I know so far and made the answer a community wiki. I hope people will extend it instead of writing their own answers. Before you vote to close: Yes, there are already some questions on individual modules and an answer to this question would of course duplicate that information. But AFAIK there is no single point to learn about all of these, which I think has a lot of value. Questions asking for library recommendations are usually considered off-topic, because "they tend to attract opinionated answers and spam", but I don't think that applies here. The set of valid libraries is clearly delineated: They have to implement a specific standard. Beyond that nothing else matters, so I don't see much risk for opinion and spam. Now provide the response and nothing else.
Instead of using the deprecated Java EE modules, use the following artifacts. JAF ( java.activation ) JavaBeans Activation Framework (now Jakarta Activation ) is a standalone technology (available on Maven Central): <dependency> <groupId>com.sun.activation</groupId> <artifactId>jakarta.activation</artifactId> <version>1.2.2</version></dependency> ( Source ) CORBA ( java.corba ) From JEP 320 : There will not be a standalone version of CORBA unless third parties take over maintenance of the CORBA APIs, ORB implementation, CosNaming provider, etc. Third party maintenance is possible because the Java SE Platform endorses independent implementations of CORBA. In contrast, the API for RMI-IIOP is defined and implemented solely within Java SE. There will not be a standalone version of RMI-IIOP unless a dedicated JSR is started to maintain it, or stewardship of the API is taken over by the Eclipse Foundation (the transition of stewardship of Java EE from the JCP to the Eclipse Foundation includes GlassFish and its implementation of CORBA and RMI-IIOP). JTA ( java.transaction ) Stand alone version: <dependency> <groupId>jakarta.transaction</groupId> <artifactId>jakarta.transaction-api</artifactId> <version>1.3.3</version></dependency> ( Source ) JAXB ( java.xml.bind ) Since Java EE was rebranded to Jakarta EE , JAXB is now provided by new artifacts: <!-- API --><dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>2.3.3</version></dependency><!-- Runtime --><dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.3</version> <scope>runtime</scope></dependency><!-- Alternative runtime --><dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.3</version> <scope>runtime</scope></dependency> JAXB Reference Implementation page . The alternative runtime was brought up by Abhijit Sarkar . schemagen and xjc can be downloaded from there too as part of a standalone JAXB distribution. See also linked answer . JAX-WS ( java.xml.ws ) Reference implementation: <!-- API --><dependency> <groupId>jakarta.xml.ws</groupId> <artifactId>jakarta.xml.ws-api</artifactId> <version>2.3.3</version></dependency><!-- Runtime --><dependency> <groupId>com.sun.xml.ws</groupId> <artifactId>jaxws-rt</artifactId> <version>2.3.3</version></dependency> Standalone distribution download (contains wsgen and wsimport ). Common Annotations ( java.xml.ws.annotation ) Java Commons Annotations (available on Maven Central): <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>1.3.5</version></dependency> ( Source )
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/48204141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2525313/']}
jdg_79014
stackexchange
llm_judgeable_groundtruth_similarity
31509026
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background : I am using Play 2.4 (Java) with InjectedRoutesGenerator and a Guice module to configure various dependencies. But during unit tests, the FakeApplication is trying to load all the Controllers from routes file through the injector and some of them are failing due to external dependencies not available in the unit test environment. How do I disable the default routes file processing during unit tests that extend from play.test.WithApplication? Or how can I replace the default routes with a custom routes file? I tried to use the play.http.router config option override referenced here , but I get Router not found error with anything I tried. Obviously I am making some mistake, I am not sure where. I am not quite understanding the link between the my.application.Router and conf/my.application.routes referenced in the config reference . Route files other than routes do not get compiled either. Now provide the response and nothing else.
I am answering my own question here. After spending some more time with Play source code, I figured out the connection between the routes file and the generated Router class. Hope it helps someone else. Play's route compiler task compiles all files in conf folder ending with .routes as well as the default routes file. Generated class name is always Routes , but the package name depends on the file name. If the file name is routes (the default routes file), compiled class is placed in router package, so the fully qualified class name is router.Routes (which is the default value for play.http.router ). For all other route files, RouteCompiler derives the package name by dropping the .routes from the file name. So for my.test.routes , play.http.router value should be my.test.Routes . Here is the base class for my tests, with custom router and db configuration elements. public class MyTestBase extends WithApplication { @Override protected Application provideApplication() { Application application = new GuiceApplicationBuilder() .configure("db.default.driver", "org.h2.Driver") .configure("db.default.url", "jdbc:h2:mem:play") .configure("play.http.router", "my.test.Routes") .build(); return application; }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31509026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3706951/']}
jdg_79015
stackexchange
llm_judgeable_groundtruth_similarity
24069124
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(columns aligned differently) which is to be saved as pdf.I converted the table to image using html2canvas and then saved the image into pdf usng jspdf. It works well if the size of the image is less than or equal to page size of pdf but if the image size is bigger than the page size then it saves only first page of pdf(which has only a part of the image) and rest of the image is not displayed/saved in pdf. here the javascript code I used. $("#btnVC_saveGLSummary").click(function () { html2canvas($("#tblSaveAsPdf1"), { onrendered: function (canvas) { var myImage = canvas.toDataURL("image/jpeg"); var d = new Date().toISOString().slice(0, 19).replace(/-/g, ""); filename = 'report_' + d + '.pdf'; var doc = new jsPDF(); doc.addImage(myImage, 'JPEG', 12, 10); doc.save(filename); } }); }); Any ideas how to get the remaining part of the image on the second page of pdf. Now provide the response and nothing else.
It works for html2canvas and jspdf. var imgData = canvas.toDataURL('image/png');var imgWidth = 210; var pageHeight = 295; var imgHeight = canvas.height * imgWidth / canvas.width;var heightLeft = imgHeight;var doc = new jsPDF('p', 'mm');var position = 10; // give some top padding to first pagedoc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);heightLeft -= pageHeight;while (heightLeft >= 0) { position += heightLeft - imgHeight; // top padding for other pages doc.addPage(); doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight;}doc.save( 'file.pdf');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24069124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3687972/']}
jdg_79016
stackexchange
llm_judgeable_groundtruth_similarity
3629762
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 force the browser to display a page only after all of the page's contents are completely loaded (such as images, scripts, css, etc)? Now provide the response and nothing else.
The easiest thing to do is putting a div with the following CSS in the body: #hideAll { position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; background-color: white; z-index: 99; /* Higher than anything else in the document */ } (Note that position: fixed won't work in IE6 - I know of no sure-fire way of doing this in that browser) Add the DIV like so (directly after the opening body tag): <div style="display: none" id="hideAll">&nbsp;</div> show the DIV directly after : <script type="text/javascript"> document.getElementById("hideAll").style.display = "block"; </script> and hide it onload : window.onload = function() { document.getElementById("hideAll").style.display = "none"; } or using jQuery $(window).load(function() { document.getElementById("hideAll").style.display = "none"; }); this approach has the advantage that it will also work for clients who have JavaScript turned off. It shouldn't cause any flickering or other side-effects, but not having tested it, I can't entirely guarantee it for every browser out there.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3629762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/414867/']}
jdg_79017
stackexchange
llm_judgeable_groundtruth_similarity
42423476
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 recently ejected my create-react-app and I'm receiving an error with ReduxForm that's preventing webpack compilation. Here's the error: "error 'NewComplaintModal' is a class no-class-assign". It appears to be associated with the redux form decorator at the bottom, but I can't find any other implementations in the redux-form docs. Any idea how to fix this? import React, { Component } from 'react';import { connect } from 'react-redux';import { bindActionCreators } from 'redux';import * as Actions from '../actions';import { Field, reduxForm } from 'redux-form';import DatePicker from "react-bootstrap-date-picker";class NewComplaintModal extends Component { close() { this.props.actions.hideModal(); } handleFormSubmit(formProps) { this.props.actions.submitComplaint(formProps); } render(){ const { handleSubmit } = this.props; const show = this.props.modalType ? true : false; const RenderDatePicker = ({input, meta: {touched, error} }) => ( <div> <DatePicker showClearButton={false} {...input} /> {touched && error && <span>{error}</span>} </div> ); return( <div> ... </div> ) }}NewComplaintModal = reduxForm({ form: 'newComplaintModal'})(NewComplaintModal);function mapStateToProps(state) { return { modal: state.modal };}function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch) };}export default connect(mapStateToProps, mapDispatchToProps)(NewComplaintModal) Now provide the response and nothing else.
First, you're declaring a class called NewComplaintModal like this class NewComplaintModal extends Component { ...} Then, you're treating your NewComplaintModal , which is a class declaration, like it's a variable, like this: NewComplaintModal = reduxForm({ form: 'newComplaintModal'})(NewComplaintModal); This is why you're seeing the specific error, that is complaining about a class being reassigned. To fix this, I would recommend skipping the middle step of using the reduxForm decorator before connect and just chaining them using the decorator syntax: import React, { Component } from 'react';import { connect } from 'react-redux';import { bindActionCreators } from 'redux';import * as Actions from '../actions';import { Field, reduxForm } from 'redux-form';import DatePicker from "react-bootstrap-date-picker";export class NewComplaintModal extends Component { close() { this.props.actions.hideModal(); } handleFormSubmit(formProps) { this.props.actions.submitComplaint(formProps); } render(){ const { handleSubmit } = this.props; const show = this.props.modalType ? true : false; const RenderDatePicker = ({input, meta: {touched, error} }) => ( <div> <DatePicker showClearButton={false} {...input} /> {touched && error && <span>{error}</span>} </div> ); return( <div> ... </div> ) }}function mapStateToProps(state) { return { modal: state.modal };}function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch) };}// use decorators around an extension of your component// to plug into redux and redux-form@connect(mapStateToProps, mapDispatchToProps)@reduxForm({ form: 'newComplaintModal' })export default class NewComplaintModalContainer extends NewComplaintModal {} If you don't want to use the decorator syntax, you can do something like this: export default connect(mapStateToProps, mapDispatchToProps)( reduxForm({ form: 'newComplaintModal' })( NewComplaintModal )) This approach essentially insulates your component from the configuration-like elements, namely anything related to interacting with the application state. Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42423476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6090736/']}
jdg_79018
stackexchange
llm_judgeable_groundtruth_similarity
2376
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am currently struggling to use skewer-mode in Emacs. I downloaded and installed skewer-mode via MELPA, so all the dependencies should be inplace. For testing purposes I even downloaded the boidsjs demo . I'll open up boids.js , then type M-x run-skewer (opens up the browser with URL http://127.0.0.1:8080/skewer/demo ) and then finally run M-x skewer-mode (-> skewer-mode enabled). But in the browser nothing happens. What am I doing wrong? Now provide the response and nothing else.
TLDR; You have to start the http server ( simple-http ) and load your HTML files through it. For example, let's say you have a HTML file named hello.html and a JS script file named script.js in /home/user/Documents/javascript folder. hello.html : <!doctype html><html><head> <!-- Include skewer.js as a script --> <script src="http://localhost:8080/skewer"></script> <!-- Include my script.js file --> <script src="script.js"></script></head><body> <p>Hello world</p></body></html> script.js : alert('hey!'); init.el (or .emacs ): (require 'simple-httpd);; set root folder for httpd server(setq httpd-root "/home/user/Documents/javascript") It's time to start the server: M-x httpd-start , and open the index.html file in the browser, by visiting http://localhost:8080/hello.html . You should get the alert in the browser and now call skwer-repl . You can further interact with the browser through the repl. So, everything you evaluate in the repl will be transmitted to the browser. For example if you type console.log('hey!') in the repl, you will get this message in the browser's console. If you want to interactively modify HTML (e.g. live update HTML tags from emacs), add to your init.el (or .emacs ): (add-hook 'html-mode-hook 'skewer-html-mode) Now when you are in your .html file you can evaluate tags with C-M-x ( skewer-html-eval-tag ), and these will be immediately updated in your browser. Keep in mind that conversely, this also applies to CSS and CSS files.
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/2376', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2158/']}
jdg_79019
stackexchange
llm_judgeable_groundtruth_similarity
30684759
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 in the process of updating an old inline-block -based grid model I have to a newer Flexbox one I created. Everything has worked fine, apart from one little snag, which has become a bit of a dealbreaker: I have a bunch of CSS-controlled sliders; so there's a containing wrapper with 100% width, and inside is another div: its width is also 100%, but its white-space is set to nowrap . Using inline-block , this meant that the internal divs (which were also set to 100% width) wouldn't be bound by their parents' constraints and wrap onto the next line - they'd just carry on flowing out of the box. This is exactly what I wanted. However, I cannot get this to work at all with flexbox. For reference, here's an image: And for reference, here's a jsFiddle of the thing working with inline-block: http://jsfiddle.net/5zzvqx4b/ ...and not working with Flexbox: http://jsfiddle.net/5zzvqx4b/1/ I've tried all kinds of variations with flex , flex-basis , flex-wrap , flex-grow , etc. but for the life of me I can't get this to work. Note that I can force it to do what I want in a hacky, inflexible way by setting the .boxcontainer width to 200% . That works for this single example, but in some cases I won't know beforehand how many child boxes there will be, and I'd rather not resort to inline styling on each element if possible. Now provide the response and nothing else.
To prevent the flex items from shrinking, set the flex shrink factor to 0 : The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1. .boxcontainer .box { flex-shrink: 0;} * { box-sizing: border-box;}.wrapper { width: 200px; background-color: #EEEEEE; border: 2px solid #DDDDDD; padding: 1rem;}.boxcontainer { position: relative; left: 0; border: 2px solid #BDC3C7; transition: all 0.4s ease; display: flex;}.boxcontainer .box { width: 100%; padding: 1rem; flex-shrink: 0;}.boxcontainer .box:first-child { background-color: #F47983;}.boxcontainer .box:nth-child(2) { background-color: #FABCC1;}#slidetrigger:checked ~ .wrapper .boxcontainer { left: -100%;}#overflowtrigger:checked ~ .wrapper { overflow: hidden;} <input type="checkbox" id="overflowtrigger" /><label for="overflowtrigger">Hide overflow</label><br /><input type="checkbox" id="slidetrigger" /><label for="slidetrigger">Slide!</label><div class="wrapper"> <div class="boxcontainer"> <div class="box"> First bunch of content. </div> <div class="box"> Second load of content. </div> </div></div>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30684759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/988246/']}
jdg_79020
stackexchange
llm_judgeable_groundtruth_similarity
4717489
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating a report comparing total time and volume across units. Here a simplification of the query I'm using at the moment: SELECT m.Unit, COUNT(*) AS Count, SUM(m.TimeInMinutes) AS TotalTimeFROM main_table mWHERE m.unit <> '' AND m.TimeInMinutes > 0GROUP BY m.UnitHAVING COUNT(*) > 15 However, I have been told that I need to exclude cases where the row's time is in the highest or lowest 5% to try and get rid of a few wacky outliers. (As in, remove the rows before the aggregates are applied.) How do I do that? Now provide the response and nothing else.
You can exclude the top and bottom x percentiles with NTILE SELECT m.Unit, COUNT(*) AS Count, SUM(m.TimeInMinutes) AS TotalTimeFROM (SELECT m.Unit, NTILE(20) OVER (ORDER BY m.TimeInMinutes) AS Buckets FROM main_table m WHERE m.unit <> '' AND m.TimeInMinutes > 0 ) mWHERE Buckets BETWEEN 2 AND 19GROUP BY m.UnitHAVING COUNT(*) > 15 Edit: this article has several techniques too
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4717489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27290/']}
jdg_79021
stackexchange
llm_judgeable_groundtruth_similarity
39691902
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 original question was in regard to TensorFlow implementations specifically. However, the answers are for implementations in general. This general answer is also the correct answer for TensorFlow. When using batch normalization and dropout in TensorFlow (specifically using the contrib.layers) do I need to be worried about the ordering? It seems possible that if I use dropout followed immediately by batch normalization there might be trouble. For example, if the shift in the batch normalization trains to the larger scale numbers of the training outputs, but then that same shift is applied to the smaller (due to the compensation for having more outputs) scale numbers without dropout during testing, then that shift may be off. Does the TensorFlow batch normalization layer automatically compensate for this? Or does this not happen for some reason I'm missing? Also, are there other pitfalls to look out for in when using these two together? For example, assuming I'm using them in the correct order in regards to the above (assuming there is a correct order), could there be trouble with using both batch normalization and dropout on multiple successive layers? I don't immediately see a problem with that, but I might be missing something. Thank you much! UPDATE: An experimental test seems to suggest that ordering does matter. I ran the same network twice with only the batch norm and dropout reverse. When the dropout is before the batch norm, validation loss seems to be going up as training loss is going down. They're both going down in the other case. But in my case the movements are slow, so things may change after more training and it's just a single test. A more definitive and informed answer would still be appreciated. Now provide the response and nothing else.
In the Ioffe and Szegedy 2015 , the authors state that "we would like to ensure that for any parameter values, the network always produces activations with the desired distribution". So the Batch Normalization Layer is actually inserted right after a Conv Layer/Fully Connected Layer, but before feeding into ReLu (or any other kinds of) activation. See this video at around time 53 min for more details. As far as dropout goes, I believe dropout is applied after activation layer. In the dropout paper figure 3b, the dropout factor/probability matrix r(l) for hidden layer l is applied to it on y(l), where y(l) is the result after applying activation function f. So in summary, the order of using batch normalization and dropout is: -> CONV/FC -> BatchNorm -> ReLu(or other activation) -> Dropout -> CONV/FC ->
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/39691902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191087/']}
jdg_79022
stackexchange
llm_judgeable_groundtruth_similarity
4431781
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 SQL you can express multiple aggregates in a single database query like this: SELECT MIN(p.x), MAX(p.x), MIN(p.y), MAX(p.y)FROM Places p JOIN Logs l on p.Id = l.PlaceIdWHERE l.OwnerId = @OwnerId Is it possible to do an equivalent thing using Linq-to-Entities? I found a similar question that suggests it's not possible for Linq-to-SQL but I would like to think I won't have to do the above using four round trips to the DB. Now provide the response and nothing else.
Suppose you have the following SQL statement: select sum(A), max(B), avg(C) from TBL group by D Try this in C#: from t in table group t by D into g select new { s = g.Sum(x => x.A), m = g.Max(x => x.B), a = g.Average(x => x.C) } -- or in VB: -- from t in TBL group t by key = D into g = group select s = g.Sum(function(x) x.A), m = g.Max(function(x) x.B), a = g.Average(function(x) x.C) The obvious, which in VB would be: aggregate t in TBL into s = Sum(t.A), m = Max(t.B), a = Average(t.C) though it will give the same results, it has a higher cost as it issues multiple SQL select statements, one for each aggregate function, i.e. it will run in multiple passes. The first syntax, gives a single (fairly complex, but efficient) SQL statement which does a single pass against the database. PS. If you don't have a key by which to group by (i.e. you need a single row as the result, covering the whole data set), use a constant as in: from t in TBL group t by key = 0 into g = group select s = g.Sum(function(x) x.A), m = g.Max(function(x) x.B), a = g.Average(function(x) x.C)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4431781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24874/']}
jdg_79023
stackexchange
llm_judgeable_groundtruth_similarity
1375158
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: Here is the problem that I am currently working on: $S$ and $T$ are two sets. Prove that if $|S-T|=|T-S|$, then $|S|=|T|$. I have access to the answer for this proof, and wanted help with the first assumption. Here is the answer I have been given to the proof: Since $|S-T|=|T-S|$, there exists a bijective function $g\colon S-T\to T-S$. Let $i\colon S\cap T\to S\cap T$ be the identity function on $S\cap T$. Then we know that the function $f\colon S\to T$ defined by $$f(x)=\begin{cases}g(x) &\text{if $x\in S-T$}\\i(x) &\text{if $x\in S\cap T$}\end{cases}$$ is bijective. Now using the fact of cardinality $\Rightarrow |S|=|T|$. My first question is: how would I have known to make the leap into assuming that a bijective function exists? Would I need to consider that I am performing an operation on two sets, and that since I have that equal to another set (with operations), that I can allow this to exist as a bijective function? Or should I come to this assumption because I am showing that the cardinalities of two different groups of sets are the same, meaning that I am trying to show numerical equivalence (which requires a bijective function)? Assuming that I need the bijection to show numerical eq., my next question is regarding the identity function step. I'm not sure where or why we jump to that assumption... Thanks. I am studying for my final in proofs on Wednesday, and while I have a pretty good piecemeal understanding of each topic we've learned, I sometimes have a hard time piecing together multiple proof topic\techniques. Now provide the response and nothing else.
\begin{align}|S| & = |S-T| + |S\cap T| \\[8pt]|T| & = |T-S| + |S\cap T|\end{align} If $|S-T|=|T-S|$, then the two right sides are the same, so the two left sides are the same. We can also write a proof explicitly dealing with bijections. You ask why one would "assume" a bijection exists. The bijection $g$ that you write about is not simply "assumed" to exist. Rather, you have $|S-T|=|T-S|$ and equality of cardinalities by definition means there is a bijection. You need a bijection from $S$ to $T$. You have a bijection $g$ from part of $S$ to part of $T$. The other part of $S$ is the same as the other part of $T$: it is $S\cap T$. You need a bijection from that set to itself. The simplest bijection from a set to itself is the identity. You can split the union of two sets into three parts:$$\begin{array}{cccccccccccc}& \underbrace{a \quad b \quad c}_{S\,-\,T} \qquad \underbrace{p \quad q \quad r \quad s}_{S\,\cap\, T} \qquad \underbrace{x \quad y \quad z}_{T\,-\,S} \\[10pt]\text{or two parts, thus:} & \underbrace{a \quad b \quad c \qquad p \quad q \quad r \quad s}_S \qquad \underbrace{x \quad y \quad z}_{T\,-\,S} \\[10pt]\text{or two parts, thus:} & \underbrace{a \quad b \quad c}_{S\,-\,T} \qquad \underbrace{p \quad q \quad r \quad s \qquad x \quad y \quad z}_T\end{array}$$Here's a bijection:$$\begin{array}{cccccccccccc}S: & & a & b & c & \qquad & p & q & r & s \\& & \updownarrow & \updownarrow & \updownarrow & & \updownarrow & \updownarrow & \updownarrow & \updownarrow & \\T: & \quad & x & y & z & \qquad & p & q & r & s\end{array}$$The last four arrows are the identity function on $S\cap T$. The first three are the bijection between $S-T$ and $T-S$ that must exist because $|S-T|=|T-S|$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1375158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/253808/']}
jdg_79024
stackexchange
llm_judgeable_groundtruth_similarity
23869613
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the string, this\is\\a\new\\string The output should be: this\is\a\new\string So basically one or more \ character should be replaced with just one \ .I tried the following: str = str.replace("[\\]+","\") but it was no use. The reason I used two \ in [\\]+ was because internally \ is stored as \\ . I know this might be a basic regex question, but I am able to replace one or more normal alphabets but not \ character. Any help is really appreciated. Now provide the response and nothing else.
str.replace("[\\]+", "\") has few problems, replace doesn't use regex ( replaceAll does) so "[\\]" will represent [\] literal, not \ nor \\ (depending on what you think it would represent) even if it did accept regex "[\\]" would not be correct regex because \\] would escape ] so you would end up with unclosed character class [.. it will not compile (your replacement String is not closed) It will not compile because \ is start of escape sequence \X where X needs to be either changed from being String special character to simple literal, like in your case \" will escape " to be literal (so you could print it for instance) instead of being start/end of String, changed from being normal character to be special one like in case of line separators \n \r or tabulations \t . Now we know that \ is special and is used to escape other character. So what do you think we need to do to make \ represent literal (when we want to print \ ). If you guessed that it needs to be escaped with another \ then you are right. To create \ literal we need to write it in String as "\\" . Since you know how to create String containing \ literal (escaped \ ) you can start thinking about how to create your replacements. Regex which represents one or more \ can look like \\+ But that is its native form, and we need to create it using String. I used \\ here because in regex \ is also special character (for instance \d represents digits , not \ literal followed by d ) so it also needs to be escaped first to represent \ literal. Just like in String we can escape it with another \ . So String representing this regex will need to be written as "\\\\+" (we escaped \ twice, once in regex \\+ and once in string) You can use it as first argument of replaceAll (because replace as mentioned earlier doesn't accept regex). Now last problem you will face is second argument of replaceAll method. If you write replaceAll("\\\\+", "\\") and it will find match for regex you will see exception java.lang.IllegalArgumentException: character to be escaped is missing It is because in replacement part (second argument in replaceAll method) we can also use special formula $x which represents current match from group with index x . So to be able to escape $ into literal we need some escape mechanism, and again \ was used here for that purpose. So \ is also special in replacement part of our method. So again to create \ literal we need to escape it with another \ , and string literal representing expression \\ is "\\\\" . But lets get back to earlier exception: message "character to be escaped is missing" refers to X part of \X formula (X is character we want to be escaped). Problem is that earlier your replacement "\\" represented only \ part, so this method expected either $ to create \$ , or \\ to create \ literal. So valid replacements would be "\\$ or "\\\\" . To make things work you need to write your replacing method as str = str.replaceAll("\\\\+", "\\\\")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23869613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2733350/']}
jdg_79025
stackexchange
llm_judgeable_groundtruth_similarity
22595878
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 yeoman scaffolded app (the angular fullstack generator). grunt serve works fine, but grunt build produces a distribution that locks up memory, most probably because of circular references in angular. I upgraded angular to 1.2.15 . The error I get is: WARNING: Tried to Load Angular More Than Once Prior to upgrading, the error was: Error: 10 $digest() iterations reached. Aborting! It's pretty difficult to debug as it only happens after build / minification. All my modules are in angular's array format, so the minification DI shouldn't be a problem but it is. There's no single script that causes this. The only way it goes away is if I don't initialize with my app.js file. My app.js file is below. Any thing come to mind? 'use strict';angular.module('myApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngTagsInput', 'ui.bootstrap', 'google-maps', 'firebase']);angular.module('myApp').config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/listing.html', controller: 'ListingCtrl' }) .otherwise({ redirectTo: '/' }); }]).constant('FIREBASE_URL', 'something'); Now provide the response and nothing else.
This could be a number of issues: essentially it's a problem of routeProvider not finding a file and recursively loading the default. For me, it turned out that it wasn't minification but concatenation of the js that caused the problems. angular.module('myApp').config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/listing.html', controller: 'ListingCtrl' }) .otherwise({ redirectTo: '/' }); }]).constant('FIREBASE_URL', 'something'); You'll notice that if the app can't find a file (i.e., otherwise ), then it will redirect to the root, which in this case loads the templateUrl . But if your templateUrl is wrong, then it will cause a recursion that reloads index.html loading angular (and everything else) over and over. In my case, grunt-concat caused the templateUrl to be wrong after build, but not before.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22595878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377856/']}
jdg_79026
stackexchange
llm_judgeable_groundtruth_similarity
3090643
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a pretty standard question, but I am having trouble to complete the final step. I am asked to find the supremum and infimum of $B=\{ \frac{n}{n+1}-a | a \in A, n \in \mathbb N\}$ where A is a bounded set, and $\mathbb N$ includes $0$ . A first guess would be to find a good upper bound. Notice that: $a \geq \inf(A) \implies -a \leq \inf(A) $ and that $ 0\leq\frac{n}{n+1}< 1$ so we get that: $$ \frac{n}{n+1}-a \leq 1-\inf(A).$$ and hence we have found an upper bound for $B$ , which could be a candidate for the supremum. Similarly we can derive that: $$ \frac{n}{n+1}-a \geq 0-\sup(A).$$ This is a candidate for the infimum of $B$ . Now how would I prove that: $$ \sup(B)=1-\inf(A) $$ $$ \inf(B)=-\sup(A) $$ Standard approaches: 1) $ \forall \epsilon>0$ there must exist an element $x \in X$ such that $x>\sup(X) - \epsilon$ 2) Bounded and increasing, therefore the sequence converges to supremum. (Monotone convergence theorem) 3) There is no smaller upper bound, we force a contradiction I do not see how this would work as we have an $n$ AND a set $A$ Now provide the response and nothing else.
Hint: $$\dfrac2{n^2+n+4}=\dfrac{\dfrac12}{1+\dfrac{n(n+1)}4}=\dfrac{\dfrac{n+1}2-\dfrac n2}{1+\dfrac n2\cdot\dfrac{n+1}2}$$ For the second, $$\dfrac{8n}{n^4-2n^2+5}=\dfrac{\dfrac{(n+1)^2}2-\dfrac{(n-1)^2}2}{\dfrac{(n+1)^2}2\cdot\dfrac{(n-1)^2}2+1}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3090643', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_79027
stackexchange
llm_judgeable_groundtruth_similarity
5927487
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 class that handles all database methods, including Entity Framework related stuff. When data is needed, other classes may invoke a method in this class such as public List<LocalDataObject> GetData(int start, int end); The database is querying using LINQ to EF and the calling class can then iterate over the data.But since other classes have no access to the entities in EF, I need to perform a "ToList()" operation on the query and by that fetching the full dataset into memory. What will happen if this set is VERY large (10s-100s of GB)? Is there a more efficient way of doing iteration and still maintain loose coupling? Now provide the response and nothing else.
The correct way to work with large datasets in Entity framework is: Use EFv4 and POCO objects - it will allow sharing objects with upper layer without introducing dependency on Entity framework Turn off proxy creation / lazy loading to fully detach POCO entity from object context Expose IQueryable<EntityType> to allow upper layer to specify query more precisely and limit the number of record loaded from database When exposing IQueryable set MergeOption.NoTracking on ObjectQuery in your data access method. Combining this setting with turned off proxy creation should result in not cached entities and iteration through result of the query should always load only single materialized entity (without caching of loaded entities). In your simple scenario you can always check that client doesn't ask too many records and simply fire exception or return only maximum allowed records.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5927487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609792/']}
jdg_79028
stackexchange
llm_judgeable_groundtruth_similarity
14708134
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Are the trie and radix trie data structures the same thing? If they aren't the same, then what is the meaning of radix trie (AKA Patricia trie)? Now provide the response and nothing else.
A radix tree is a compressed version of a trie. In a trie, on each edge you write a single letter, while in a PATRICIA tree (or radix tree) you store whole words. Now, assume you have the words hello , hat and have . To store them in a trie , it would look like: e - l - l - o /h - a - t \ v - e And you need nine nodes. I have placed the letters in the nodes, but in fact they label the edges. In a radix tree, you will have: * / (ello) /* - h - * -(a) - * - (t) - * \ (ve) \ * and you need only five nodes. In the picture above nodes are the asterisks. So, overall, a radix tree takes less memory , but it is harder to implement. Otherwise the use case of both is pretty much the same.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14708134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2043159/']}
jdg_79029
stackexchange
llm_judgeable_groundtruth_similarity
29581782
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 get the scrollposition in Recyclerview or the Layoutmanager ? I can measure the scrollposition by adding an OnScrollListener , but when the Orientation changes scrollDy is 0. mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() { int scrollDy = 0; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { scrollDy += dy; } }); Now provide the response and nothing else.
You cannot get it because it does not really exist. LayoutManager only knows about the views on screen, it does not know the views before, what their size is etc. The number you can count using the scroll listener is not reliable because if data changes, RecyclerView will do a fresh layout calculation and will not try to re-calculate a real offset (you'll receive an onScroll(0, 0) if views moved). RecyclerView estimates this value for scrollbars, you can use the same methods from View class. computeHorizontalScrollExtent computeHorizontalScrollRange computeHorizontalScrollOffset These methods have their vertical counterparts as well.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29581782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1112707/']}
jdg_79030
stackexchange
llm_judgeable_groundtruth_similarity
2525247
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to create a custom version of the sortable widget. I have been searching for documentation, but could not find something really accurate. The best information I found was : http://jqueryui.pbworks.com/Widget-factory . I tried : $.widget("ui.customsortable", $.extend($.ui.sortable, { _init: function() { $.widget.prototype._init.apply(this, arguments); }})); But $.widget.prototype._init is not the function I want to call I guess since it is the $.widget prototype. Then, I tried something I read here and there : var _init = $.ui.sortable.prototype._init; $.widget("ui.customsortable", $.extend($.ui.sortable, { _init: function() { _init.apply(this, arguments); },})); But : I can't believe I have to store all methods I want to override like this, it is so ugly. It throws an error ("this.refresh is not a function"), which means the refresh method does not exist. Does that mean I would have to recreate all methods I want to override ? What's the point of extending in that case ? Am I missing something here ? Thanks for your help ! Now provide the response and nothing else.
After several tries, I finally found out how to do this easily : $.widget("ui.customsortable", $.extend({}, $.ui.sortable.prototype, { _init: function(){ this.element.data('sortable', this.element.data('customsortable')); return $.ui.sortable.prototype._init.apply(this, arguments); } // Override other methods here.}));$.ui.customsortable.defaults = $.extend({}, $.ui.sortable.defaults); The key is to copy data from your custom widget to the original one.Don't forget to use $.ui.sortable.prototype.[overriden method].apply(this, arguments); in each overriden method. Holly crap !
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2525247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302731/']}
jdg_79031
stackexchange
llm_judgeable_groundtruth_similarity
28540
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow. I've read this hack to improve the write speed , but I'm wondering if a more direct approach is possible, maybe by adjusting the SPISettings . Now provide the response and nothing else.
OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino.But that is not how I solved my problem of low data-rate. I followed the instruction of the author of SDFat library from this post . According to fat16lib , to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O_WRITE | O_CREAT' instead of 'FILE_WRITE'. This sure increased the speed by a great factor. But I needed more! Storing the data in binary ( check out this blog ) improved the performance even more. My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card! Finally, I want to thank you guys for your help.
{}
{'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/28540', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/25931/']}
jdg_79032
stackexchange
llm_judgeable_groundtruth_similarity
14077999
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 can I test if a type is supported by a compiler? Say like uint64_t. Is there a reference somewhere I can use for learning how to test for any given types? It is surprisingly hard to find this out via search engine. I tried "C test for data type" and many other things. Now provide the response and nothing else.
You can check that: UINT64_MAX macro is defined after including stdint.h . If you are not sure if c99 or higher is supported you can also enclose it in a check to __STDC_VERSION__ to be >= 199901L . Note that also that __STDC_VERSION__ macro is not present in C89/C90. From the Standard (emphasis mine): (C99, 7.18p4) "For each type described herein that the implementation provides,224) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. "
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14077999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1922814/']}
jdg_79033
stackexchange
llm_judgeable_groundtruth_similarity
5876844
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 one of my previous exams had this question, and till now I've been reading that you don't need a declaration in any of the languages? Which is right? Will C++ give an error if there's no declaration, or will it run? Now provide the response and nothing else.
In a discussion that involves both C and C++ "function declaration" is a rather vague term. These languages are significantly different in this regard. In C++ language there's only one kind of function declaration: declaration with all parameter types and return type. Such declarations are necessary because C++ language supports function overloading . In order to choose which function to call the compiler needs to know everything about the function and needs to know which overloaded versions of the function are available. If you "forget" to declare some overloaded version, it will not be considered by overload resolution. That is at least one of the reasons function declarations are necessary in C++. In C language there are two kinds of function declarations: non-prototype declarations and prototype declarations (or simply prototypes ). A prototype in C is pretty similar to C++ declaration - it includes all parameter types. Prototypes have always been required in standard C for variadic functions (functions with ... parameters). For non-variadic functions prototype declarations are not required even today. But starting from C99 at least non-prototype declarations are required for all other functions. In older C89/90 version of the language function declarations for non-variadic functions were not required. So, that should basically answer your question. In C++ function declarations are required because language features rely on them critically. In modern C function declarations are also required just to make the code safer. In older versions of C function declarations were not required mostly simply because the language was defined to work without them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5876844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/643339/']}
jdg_79034
stackexchange
llm_judgeable_groundtruth_similarity
1790514
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 a table with a field which is declared as accepting varchar(100) and then I actually insert the word "hello" how much real storage will be used on the mysql server? Also will an insert of NULL result in no storage being used even though varchar(100) is declared? What ever the answer is, is it consistent accross different database implementations? Now provide the response and nothing else.
If I have a table with a field which is declared as accepting varchar(100) and then I actually insert the word "hello" how much real storage will be used on the mysql server? Mysql will store 5 bytes plus one byte for the length. If the varchar is greater than 255, then it will store 2 bytes for the length. Note that this is dependent on the charset of the column. If the charset is utf8, mysql will require up to 3 bytes per character. Some storage engines (i.e. memory) will always require the maximum byte length per character for the character set. Also will an insert of NULL result in no storage being used even though varchar(100) is declared? Making a column nullable means that mysql will have to set aside an extra byte per up to 8 nullable columns per row. This is called the "null mask". What ever the answer is, is it consistent accross different database implementations? It's not even consistent between storage engines within mysql!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1790514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193128/']}
jdg_79035
stackexchange
llm_judgeable_groundtruth_similarity
57820
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Since Euclid's axiomatization of space, we have developed a sophisticated mathematical model of space. Given a category of structures (measures), local space is modeled the spectrum of measurements that these structures can possibly make. Global space is construed as patches connected via transport, which identifies measurements across patches. I'm troubled that I have not come across any axiomatization of time. Assuming that mathematics is a priori science, the great varieties of theories of space in physics can be attributed to our sophisticated mathematical model of space. There is relativity, string theory, quantum theory and M theory. Perhaps the reader may object that these theories are theories of space-time, rather than theories of space. However, I wish to note that in these theories, time is essentially treated in the same manner as space. In classical physics, time is but another dimension of space. In relativity, time is distinguished from time by the (3,1) signature, but this is just a metric. Riemannian geometry is still considered a theory of space rather than a theory of time. I'm wondering, then, whether you have encountered is a mathematical axiomatization of time, that treats time in a way not that is not inherently spatial? Assuming once more that mathematics is a priori science, perhaps such an axiomatization can lead to breakthroughs in physics and finance. Finally, there is a physical theory that I think comes close to a model of time. Namely, entropy. Just as space is dual to measures, we can think of time as dual to entropy. Given as entropy can be defined using combinatorics and probability, this could be viewed as a mathematical theory. EDIT: Steve mentioned that perhaps one can view entropy as a theory of time via the Thermal Time Hypothesis. Other than entropy, are there any other axiomatizations of time? ANOTHER EDIT: In the answers given below, most of the models of time are archimedean. I'm wondering, this models can be tweaked to allow a cyclic conceptualization of time. Many ancient cultures, eg from India, consider time to be cyclic rather than archimedean. Should I ask this as a separate question? I think of this cyclic/archimdean dichotomy as something like Euclidean/non-Euclidean geometry. Now provide the response and nothing else.
In probability, time is usually handled as a nested sequence of $\sigma$-algebras (say $B_t$, with $B_t \subset B_s$ if $t\leq s$), and to find the reality (call the reality $f$, and it includes the state at all times past and future) at time $t$, one takes the conditional expectation $f_t := E[f | B_t ]$. The sequence $(f_t)$ is then a martingale (a uniformly integrable martingale, more precisely), and this construction is the essence of what the big deal is about martingales. Brownian motion is a martingale that you've probably heard of, but this also handles simpler situations. For example, consider the experiment: toss a coin repeatedly, and keep track of how many heads you've thrown, minus how many tails. We can capture this experiment in the following way: For $0\leq x <1$, let $f_n(x)$ be the number of 1's minus the number of 0's among the first $n$ digits of the binary expansion of $x$, and let $B_n$ be the $\sigma$-algebra (in this case, a boolean algebra) generated by the intervals $[i/2^n,(i+1)/2^n)$. Then $f_n$ is $B_n$-measurable, and $E[f_t | B_s]=f_s$ for any natural numbers $s < t$, and the sequence $(f_n)_{n=1}^\infty$ is a martingale (albeit different from the type mentioned above). If you want to play any fair game on the "coin tosses" as they come up (allowing use of knowledge of all previous-in-time tosses), then your fortune at time $t$ is still a martingale. In other words, the passage of time is captured as un-conditional-expectating a function. For a practical introduction to martingales, I recommend Williams' "Probability with martingales." It is a marvel of writing, and in my humble opinion should be taken as a model for how to write a monograph.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/57820', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_79036
stackexchange
llm_judgeable_groundtruth_similarity
21905023
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 read a ton of similar posts that describe the same error message but they don't seem to match what i'm experiencing. I have recently started using Web API and ripped all my MVC methods out where I was returning JSON etc, so MVC will just render the html and I will call down the models via ajax from my webapi controllers. Here's the strange thing, I can GET and POST from my Home apiController (so I can login/signup etc) but I can only GET from an API Controller in an area I have created. I get a 405 (Method Not Allowed) even though its decorated and called the same way as other controller. I guess the routing is okay otherwise it wouldn't return my initial get? Routing public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultAreaApi", routeTemplate: "api/{area}/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } Controller // Returns Model [HttpGet] public HttpResponseMessage SelectAgent() // The requested resource does not support http method 'POST'. [HttpPost] public HttpResponseMessage SelectAgent(Guid id) JQuery // Works fine $.ajax({ type: 'POST', url: '/api/Home/Login', headers: options.headers, contentType: "application/json; charset=utf-8", dataType: 'JSON', data: ko.toJSON(self.serverModel), success: function (response) { // Works fine $.getJSON("/api/Account/Users/SelectAgent", function (model) { .... // 405 $.ajax({ type: 'POST', url: '/api/Account/Users/SelectAgent', headers: options.headers, contentType: "application/json; charset=utf-8", dataType: 'JSON', data: "{'id':'" + selectModel.agentId() + "'}", success: function (response) {.... data being passed seems fine (or at least it was for the MVC controller that it used to work with). I haven't modified the Home API Controller at all, I don't understand how I can post to that and not my other controller. Argh. Any pointers in the right direction would be awesome. Now provide the response and nothing else.
Web API is only looking at your querystring parameters for basic data types. Thus your post is just looking at the url of /api/Account/Users/SelectAgent when you are making your post. The data being submitted is not being considered when matching against the function, since you are not marking the Guid with a [FromBody] attribute. So the "Method Not Allowed" error is being returned because it is sending your POST request to your GET method (no params). You can read more about this on asp.net : If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.) To fix this, try doing one of the following: Change the url that you are submitting to include the id in the querystring of the email url: '/api/Account/Users/SelectAgent?id=' + selectModel.agentId() Change the Action signature to read the Id FromBody : public HttpResponseMessage SelectAgent([FromBody]Guid id)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21905023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1499936/']}
jdg_79037
stackexchange
llm_judgeable_groundtruth_similarity
43397162
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 it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots. import matplotlibmatplotlib.use('Agg') # no UI backendimport matplotlib.pyplot as pltimport numpy as npt = np.arange(0.0, 2.0, 0.01)s = 1 + np.sin(2*np.pi*t)plt.plot(t, s)plt.title('About as simple as it gets, folks')#plt.show()plt.savefig("matplotlib.png") #savefig, don't show How could we get it to where plt.show() would actually show us an image? My current option is to override plot.show() to instead just savefig a plot-148123456.png under /mnt/c/Users/james/plots/ in windows and just have an explorer window open viewing the images. I suppose I could host that folder and use a browser. My goal is to be able to run simple examples like the code above without changing the code to ftp the images somewhere etc. I just want the plot to show up in a window. Has anyone figured out a decent way to do it? Now provide the response and nothing else.
Ok, so I got it working as follows. I have Ubuntu on windows, with anaconda python 3.6 installed. Download and install VcXsrv or Xming (X11 for Windows) from sourceforge(see edit below) sudo apt-get update sudo apt-get install python3.6-tk (you may have to install a different python*-tk depnding on the python version you're using) pip install matplotlib (for matplotlib. but many other things now work too) export DISPLAY=localhost:0.0 (add to ~/.bashrc to make permanent. see WSL2 below) Anyways, after all that, this code running in ubuntu on wsl worked as is: import matplotlib.pyplot as pltimport numpy as npt = np.arange(0.0, 2.0, 0.01)s = 1 + np.sin(2*np.pi*t)plt.plot(t, s)plt.title('About as simple as it gets, folks')plt.show() result: Maybe this is better done through a Jupyter notebook or something, but it's nice to have basic command-line python matplotlib functionality in Ubuntu for Windows on Subsystem for Linux, and this makes many other gui apps work too. For example you can install xeyes, and it will say to install x11-apps and installing that will install GTK which a lot of GUI apps use. But the point is once you have your DISPLAY set correctly, and your x server on windows, then most things that would work on a native ubuntu will work for the WSL. Edit 2019-09-04 : Today I was having issues with 'unable to get screen resources' after upgrading some libraries. So I installed VcXsrv and used that instead of Xming. Just install from https://sourceforge.net/projects/vcxsrv/ and run xlaunch.exe, select multiple windows, next next next ok. Then everything worked. Edit for WSL 2 users 2020-06-23 WSL2 (currently insider fast ring) has GPU/docker support so worth upgrade. However it runs in vm. For WSL 2, follow same steps 1-4 then: the ip is not localhost. it's in resolv.conf so run this instead (and include in ~/.bashrc): export DISPLAY=`grep -oP "(?<=nameserver ).+" /etc/resolv.conf`:0.0 Now double-check firewall: Windows Security -> Firewall & network protection -> Allow an app through firewall -> make sure VcXsrv has both public and private checked. (When Launching xlaunch first time, you might get a prompt to allow through firewall. This works too. Also, if VcXsrv is not in list of apps, you can manually add it, eg from 'C:\program files\vcxsrv\vcxsrv.exe') Launch VcXsrv with "Disable access control" ticked Note: a few WSL2 users got error like couldn't connect to display "172.x.x.x:0" . If that's you try to check the IP address stored in DISPLAY with this command: echo $DISPLAY . If the showed IP seems to be wrong (i.e. "8.8.8.8" or another not working IP address) you need to change the code in ~/.bashrc showed in the point 5 to something that will get your instance's ip address. One user said this worked: export DISPLAY=$(ifconfig | grep inet | awk '{print $2}' | head -n 1 | awk '{print $0":0"}') . However for some others it did not work. YMMV, but just find your IP and use if for DISPLAY. For most WSL2 users, the command in #5 works. Edit for Windows 11 : if MS convinced you to throw out your old computer and buy one with a TPM and so you got Windows 11, you get GUI for free. I hope they add upgrade path to do that on Windows 10 because Win10 will be like XP and last a long time since MS decided you need recent computer even though Win11 would work fine on old computers.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43397162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1895611/']}
jdg_79038
stackexchange
llm_judgeable_groundtruth_similarity
2459180
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 have any suggestions on how to edit an link in a contentEditable div? It would be ideal once the link is either clicked with mouse, or the cursor hits the link, that the a small prompt would pop up and allow the user to change the href property of the link. The prompt isn't the issue, but how is it possible to detect the link has been either clicked or that the cursor has arrived at the link? onfocus doesn't seem to work in a contentEditable div on Firefox & Safari. Any ideas? Now provide the response and nothing else.
I'm pretty sure this is what you were looking for, however I used jQuery just to make the concept a little easier to mock. jsbin preview available, so go look at it. If anyone is able to convert this to pure JS for the sake of the answer, I have made it a community wiki. It works by binding to the keyup/click events on the editable div, then checking for the node that the users caret is being placed at using window.getSelection() for the Standards, or document.selection for those IE people. The rest of the code handles popping/handling the edits. jQuery methods: function getSelectionStartNode(){ var node,selection; if (window.getSelection) { // FF3.6, Safari4, Chrome5 (DOM Standards) selection = getSelection(); node = selection.anchorNode; } if (!node && document.selection) { // IE selection = document.selection var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); node = range.commonAncestorContainer ? range.commonAncestorContainer : range.parentElement ? range.parentElement() : range.item(0); } if (node) { return (node.nodeName == "#text" ? node.parentNode : node); }}$(function() { $("#editLink").hide(); $("#myEditable").bind('keyup click', function(e) { var $node = $(getSelectionStartNode()); if ($node.is('a')) { $("#editLink").css({ top: $node.offset().top - $('#editLink').height() - 5, left: $node.offset().left }).show().data('node', $node); $("#linktext").val($node.text()); $("#linkhref").val($node.attr('href')); $("#linkpreview").attr('href', $node.attr('href')); } else { $("#editLink").hide(); } }); $("#linktext").bind('keyup change', function() { var $node = $("#editLink").data('node'); $node.text($(this).val()); }); $("#linkhref").bind('keyup change', function() { var $node = $("#editLink").data('node'); $node.attr('href', $(this).val()); $node.and('#linkpreview').attr('href',$(this).val()); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2459180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295277/']}
jdg_79039
stackexchange
llm_judgeable_groundtruth_similarity
16701522
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 here is what I have: <path class="..." onmousemove="show_tooltip(event,'very long text \\\n I would like to linebreak')" onmouseout="hide_tooltip()" d="..."/><rect class="tooltip_bg" id="tooltip_bg" ... /><text class="tooltip" id="tooltip" ...>Tooltip</text><script><![CDATA[function show_tooltip(e,text) { var tt = document.getElementById('tooltip'); var bg = document.getElementById('tooltip_bg'); // set position ... tt.textContent=text; bg.setAttribute('width',tt.getBBox().width+10); bg.setAttribute('height',tt.getBBox().height+6); // set visibility ...}... Now my very long tooltip text doesn't have a linebreak, even though if I use alert(); it shows me that the text actually DOES have two lines. (It contains a "\" though, how do I remove that one by the way?) I can't get CDATA to work anywhere. Now provide the response and nothing else.
This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea , but it does have auto-wrapped text . However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan> s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example: <g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates --> <text x="0" y="0"> <tspan x="0" dy="1.2em">very long text</tspan> <tspan x="0" dy="1.2em">I would like to linebreak</tspan> </text></g> Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16701522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2332975/']}
jdg_79040