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
79617
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to change the how the ends of the spline arrows in my figure are rendered to be "rounded", but Graphics@{CapForm["Round"], Thick, Arrow[BSplineCurve[{{0, 0}, {4, 7}, {2, 11}, {10, 10}}, SplineWeights -> {3, 5, 4, 5}], .05]} has no effect, yielding. How do I get my spline based arrows to have rounded ends? If it matters, these will be used as part of EdgeShapeFunction in a Graph . Now provide the response and nothing else.
Another take based on @rasher's comment: Graphics[{Thickness[.02], Arrowheads[{{-.1, 0, Graphics[{Thickness[.02], CapForm["Round"], Line[{{-1, 0}, {0, 0}}]}]}, {.2, 1}}], Arrow[BSplineCurve[{{0, 0}, {4, 7}, {2, 11}, {10, 10}}, SplineWeights -> {3, 5, 4, 5}], .05]}] Update: What if the arrow is dashed or dotted? Overlaying BSplineCurve (without Arrow ) with a transparent Arrow with some manual adjustments seems to work: ah = GraphElementData["FilledArrow", "ArrowSize" -> 0.1][{{0.`, 0.`}, {1.`, 0.`}}][[1, 1, 1, 3, 1]];g1 = Graphics[{Thickness[.03], Red, Dashing[.02], CapForm["Round"], BSplineCurve[{{0, 0}, {4, 7}, {2, 11}, {10, 10}}, SplineWeights -> {3, 5, 4, 5}]}, ImageSize -> 300];g2 = Graphics[{Thickness[.03], Arrowheads[{{.15, 1, {ah /. FilledCurve[x__] :> {Opacity[1], Red, FilledCurve[x]}, .5}}}], Red, Dashing[.02], CapForm["Round"], BSplineCurve[{{0, 0}, {4, 7}, {2, 11}, {9.2, 10.05}}, SplineWeights -> {3, 5, 4, 5}], Opacity[0], Arrow[BSplineCurve[{{0, 0}, {4, 7}, {2, 11}, {10, 10}}, SplineWeights -> {3, 5, 4, 5}]]}, ImageSize -> 300];Row[{g1, g2}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/79617', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/37/']}
jdg_79441
stackexchange
llm_judgeable_groundtruth_similarity
11538012
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 got README file and I want Sublime to highlight only some pieces of code idented by some "tag", for example: Here is an example of usage# This should be highlighted```ruby superhero = Superhero.new superhero.make_world_better``` or with [code lang=ruby] or whatever Now provide the response and nothing else.
Lazy answer ( for independent fast learners ) Install package control forsublime-text . Once you restarted sublime-text, see "Fast Answer". Fast answer ( for intermediate to advanced sublime-text users ) Ctrl + Shift + P and Package Control: Install Package ,then install Knockdown . That's it , now you have a Set Syntax: Markdown (Github flavored) option right at the reach of your fingertips. Elaborate answer ( powerless to powerfull ) - Installing Package Control Open sublime-text. [If you need this functionality available when you edit files on a directoryowned by root or www-data ( i.e. /var/www/ ) you may want to open sublime with adminprivileges using gksu sublime or similar and repeat every step] Activate sublime's console by pressing ctr + ` [That is CONTROL key plus GRAVE ACCENT key (usually above the TAB key)] Copy-paste one of the following options to sublime console's prompt . (and press enter ) : If sublime-text 2: import urllib2,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler()) ); by = urllib2.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); open( os.path.join( ipp, pf), 'wb' ).write(by) if dh == h else None; print('Error validating download (got %s instead of %s), please try manual install' % (dh, h) if dh != h else 'Please restart Sublime Text to finish installation') If sublime-text 3: import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) Close sublime when the console prints back a message saying " Please restart Sublime Text to finish installation" (usually almost instantaneous) . Open sublime-text again. Once you restarted sublime-text, the rest is easy, see "Fast Answer" (above) , or read on. About using Package Control What you just installed adds a new bunch of commands to your Palette and opens the door to a wonderful world of community contributed plugins; a way to extend sublime's functionality by other people or by yourself! (share your code!). Now lets use it to install knockdown . You can access Package Controll simply by pressing ctr + shift + P , and typing Package Control , pc , pack (or anything similar thanks to the fuzzy search feature of the command palette), in this case search the right command by writing Package Control: Install Package (or just pi ). (If something goes wrong you can always Remove Package ) . To see all the available packages just enter or click on it. Sublime will search for all the registered packages and will even check and show for you only the ones that are compatible with your version of sublime-text, you'll have to wait a few seconds. (or less than a second, depending on your internet+computer latency+speed) . Now search for and select knockdown . After you hit Enter or click on it it will take a brief moment to install. That's it , it just works . ## - How to use it you ask? To activate this highlighting in the current loaded buffer: (lets say "the open file") Inside sublime-text and with a .md file opened, press ctr + shift + P again. Search for Set Syntax: Markdown (Github Flavored) and enter or click on it. IF you want to activate for all .md files (that's a big IF) On current version (Latest Sublime Text 2 releases & any ver 3 release) : Navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice] . On previous versions of sublime: Go to a Packages/User , create (or edit) a .sublime-settings filenamed after the Syntax where you want to add the extensions, Markdown (Github Flavored).sublime-settings in your case, thenwrite there something like this: { "extensions": [ "md" ] } And then restart Sublime Text ... pics, else it shant have come to pass: (it totally works! here's the evidence) presto! You just took one further step to be a sublime-text master, I hope my answer helped you
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11538012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298624/']}
jdg_79442
stackexchange
llm_judgeable_groundtruth_similarity
13812580
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 all the emails sent from our staging server to have the phrase "[STAGING] " prefaced in the subject. Is there an elegant way to do this in Rails 3.2 using ActionMailer? Now provide the response and nothing else.
Here's an elegant solution I found using ActionMailer Interceptor based on an existing answer . # config/initializers/change_staging_email_subject.rbif Rails.env.staging? class ChangeStagingEmailSubject def self.delivering_email(mail) mail.subject = "[STAGING] " + mail.subject end end ActionMailer::Base.register_interceptor(ChangeStagingEmailSubject)end
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13812580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307438/']}
jdg_79443
stackexchange
llm_judgeable_groundtruth_similarity
1863287
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 curious whether this integral has a closed form expression : $$\int_{0}^{\infty}\left(\frac{x-1}{\ln^2 x}-\frac{1}{\ln x}\right)\frac{\mathrm{d}x}{x^2+1}$$ The integrand has a singularity at $x=1$, but it's removable. And as $x \to \infty$, the integrand behaves like $\frac{1}{x \ln^{2}x}$. So the integral clearly converges. Although I have not been able to derive its closed form, I think, by reverse symbolic calculators, up to 20 digits it could be $$I=\frac{4G}{\pi}$$ where $G$ is Catalan's constant. Is it true or is it completely fabulous? EDIT. NOTE : For better search to this integral I have renamed the title from Conjectured value of logarithmic definite integral , which is ambiguous and did not say anything, to the current one with integral explicitly written. Now provide the response and nothing else.
It is not necessary to exploit any symmetries of the integrand.Setting $x=e^y$ $$I=\int_{-\infty}^{\infty}\underbrace{e^y\left(\frac{e^y-1}{y^2}-\frac{1}{y}\right)\frac{1}{e^{2y}+1}}_{f(y)}\,dy$$ Integrating around a big semicircle in the UHP (exercise: show convergence in this domain of the complex plane) we obtain $$I=2 \pi i \sum_{n=0}^{\infty}\text{Res}(f(z),z=z_n)$$here $z_n=\frac{i\pi}2(2n+1)$. This is easily rewritten as $$I=2 \pi i\left(\left(\frac{1}{\pi}\color{blue}{\sum_{n=0}^{\infty}\frac{(-1)^n}{2n+1}}-\frac{2}{\pi^2}\color{red}{\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}}\right) -\frac{2i}{\pi^2}\color{green}{\sum_{n=0}^{\infty}\frac{(-1)^n}{(2n+1)^2}}\right)$$ since $\color{blue}{\sum_{n=0}^{\infty}\frac{(-1)^n}{2n+1}=\frac{\pi}{4}}$ and $\color{red}{\sum_{n=0}^{\infty}\frac{1}{(2n+1)^2}=\frac{\pi^2}{8}}$ the imaginary parts cancel and we are left with $$I= \frac{4}{\pi}\color{green}{\sum_{n=0}^{\infty}\frac{(-1)^n}{(2n+1)^2}}=\frac{4\color{green}{K}}{\pi}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1863287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/240067/']}
jdg_79444
stackexchange
llm_judgeable_groundtruth_similarity
3186562
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $G$ and $H$ be free groups and $g \in G$ . Is there a difference between $\langle H, G\rangle$ and the free product $H*G$ ?. In particular is $\langle H ,g \rangle = H * \langle g \rangle$ ? Now provide the response and nothing else.
Since none of these points are in the answers above, although they answer your question, I'd like to add some comments. I won't add a new counterexample, since the other answers already cover that, just add a more abstract viewpoint. First of all, there is an essential difference between $\langle G,H\rangle$ and $G*H$ , namely $\langle G,H\rangle$ presupposes that $G$ and $H$ are embedded in some larger group, which I'll call $K$ , whereas the free product does not. The group operation on $K$ may impose relations on $G$ and $H$ that are not present in the free product (which has no relations between the elements of $G$ and the elements of $H$ ). What this means concretely is that if we consider the homomorphism $\phi:G*H\to K$ given by the universal property of the free product, its image is $\langle G,H\rangle$ , and its kernel tells us whether or not $G*H$ and $\langle G,H\rangle$ are isomorphic (technically this only tells us if they're naturally isomorphic, but let's ignore that tangent). The elements of the kernel of $\phi$ will be the relations between elements of $G$ and $H$ imposed by the group operation on $K$ . If we look at giannispapav/Dietrich Burde's counterexamples, if we let $K=G=H=F_n$ be free groups, then $\langle G,H\rangle =K$ , and $G*H=F_{2n}$ , and the map sends the word $g_1h_1g_2h_2\cdots g_nh_n$ in $G*H$ to the result of evaluating this product in $K$ . The relations are $g_Gg^{-1}_H=1$ , where $g_G$ is an element $g$ of $K$ regarded as an element of $G$ , $g^{-1}_H$ is the inverse of the same element $g$ of $K$ regarded as an element of $H$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3186562', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/663835/']}
jdg_79445
stackexchange
llm_judgeable_groundtruth_similarity
102099
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why don't we consider them as linear? I don't understand. You just have to check for factorization up to sqrt of n. So it's even faster than linear.I assume it's not linear only if we compare the number of operations relative to the input in terms of binary representation. But why would we do so?It seems to me wrong. The growth in calculation should be calculated compared to the number itself. Why do we compare it to the binary representation? Now provide the response and nothing else.
It seems that the main sticking point of the question here is: Why express runtime in terms of the size of the input, rather than the numeric value that the input represents? And indeed in some cases it doesn't make much difference which way you choose to express it. For instance, we could say that the time to read all values in an $N\times N$ matrix is quadratic in the number of columns, or we could say it is linear in the number of cells, and the meaning of these is the same, just with different conventions. So let's look at some reasons why it is conventional to express operations on numbers in terms of the length of the number rather than its numeric value: It is more easily comparable to operations on other kinds of data, since every possible form of input has a length but not all forms of input have a numeric value. By consistently using the length of the input as our reference point across a variety of problem types, we also get some nice properties like "the runtime of an algorithm that reads the entire input can never be better than linear." It provides more useful time complexities in context. For instance, a common use for primality testing is for cryptography. When we're doing cryptography, we might use say a 512-bit number as a key. We would like to have algorithms that scale proportional to the length of the number (512), rather than its numeric value (about $2^{512}$ ), since $2^{512}$ is such an astronomically large number that even a "linear" time algorithm would never realistically finish. It relates better to the actual operations performed by the computer. Many people are accustomed to implicitly treating all numbers as capped at some fairly large constant like $2^{64}$ , and thus all arithmetic operations are constant-time and the actual internal representation of the number is irrelevant. But when we are analyzing the big-O performance of operations on the number itself we cannot assume that numbers are always small enough to ignore their internal representation. Ultimately, these operations are performed on bits so the number of bits is a good reference point to use for describing the performance. As a thought experiment, try analyzing the performance of the addition operation. You may have always considered it a constant-time operation, but what happens if the numbers in question get arbitrarily large? Ultimately, you'll need to sum each digit one-by-one, carrying as necessary. It makes sense to describe this as a linear-time operation based on the length of the input, rather than logarithmic time based on the numeric value of the input.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/102099', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/96035/']}
jdg_79446
stackexchange
llm_judgeable_groundtruth_similarity
43830545
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem getting the rolling function of Pandas to do what I wish. I want for each frow to calculate the maximum so far within the group. Here is an example: df = pd.DataFrame([[1,3], [1,6], [1,3], [2,2], [2,1]], columns=['id', 'value']) looks like id value0 1 31 1 62 1 33 2 24 2 1 Now I wish to obtain the following DataFrame: id value0 1 31 1 62 1 63 2 24 2 2 The problem is that when I do df.groupby('id')['value'].rolling(1).max() I get the same DataFrame back. And when I do df.groupby('id')['value'].rolling(3).max() I get a DataFrame with Nans. Can someone explain how to properly use rolling or some other Pandas function to obtain the DataFrame I want? Now provide the response and nothing else.
It looks like you need cummax() instead of .rolling(N).max() In [29]: df['new'] = df.groupby('id').value.cummax()In [30]: dfOut[30]: id value new0 1 3 31 1 6 62 1 3 63 2 2 24 2 1 2 Timing (using brand new Pandas version 0.20.1): In [3]: df = pd.concat([df] * 10**4, ignore_index=True)In [4]: df.shapeOut[4]: (50000, 2)In [5]: %timeit df.groupby('id').value.apply(lambda x: x.cummax())100 loops, best of 3: 15.8 ms per loopIn [6]: %timeit df.groupby('id').value.cummax()100 loops, best of 3: 4.09 ms per loop NOTE: from Pandas 0.20.0 what's new Improved performance of groupby().cummin() and groupby().cummax() ( GH15048 , GH15109 , GH15561 , GH15635 )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43830545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6204900/']}
jdg_79447
stackexchange
llm_judgeable_groundtruth_similarity
1802337
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to run PHP scripts automatically on a schedule. I learned about CRON recently. But I don't know how to install and use it. I'm using PHP, CSS, HTML, and running on XAMP apache server on localhost. How do I install and use Cron? Now provide the response and nothing else.
Do you have a Windows machine or a Linux machine? Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH. Under Linux you can create a crontab for your current user by typing: crontab -e [username] If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first: sudo apt-get updatesudo apt-get install cron If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes: */5 * * * * /home/user/test.pl The syntax is basically this: .---------------- minute (0 - 59) | .------------- hour (0 - 23)| | .---------- day of month (1 - 31)| | | .------- month (1 - 12) OR jan,feb,mar,apr ... | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat | | | | |* * * * * command to be executed Read more about it on the following pages: Wikipedia: crontab
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1802337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148814/']}
jdg_79448
stackexchange
llm_judgeable_groundtruth_similarity
23886
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: There are $n$ symmetric polynomials in the eigenvalues of a square matrix. Two of these are the determinant and the trace, each of which have countless applications and interpretations in algebra and geometry. What about the other symmetric polynomials? They are also similarity invariants, yet I've never seen them used or referenced. Are there any geometric interpretations, or applications, for these other invariants? Now provide the response and nothing else.
The trace and the determinant are the most useful invariants because the trace is additive and the determinant is multiplicative. The other coefficients of the characteristic polynomial are neither. The determinant also has a clear geometric interpretation. In addition, all of the coefficients of the characteristic polynomial of an operator $T$ can be computed from the traces of the operators $T^n$; this is one reason why it is not so surprising that traces of group elements in group representations carry a lot of information. This is not to say that people never use the other invariants, although they don't tend to have special names. For example, my understanding is that the Killing form in Lie theory, an important tool, was discovered by messing around with characteristic polynomials. And the construction underlying the coefficients of the characteristic polynomial, the exterior algebra , is enormously useful.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/23886', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7530/']}
jdg_79449
stackexchange
llm_judgeable_groundtruth_similarity
12426
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Ownership types and Separation Logic seem to have similar goals, control over ownership and aliasing. Perhaps, I should also add: the ability to write modular specifications. What is known about the relationship between ownership types and Separation Logic? Now provide the response and nothing else.
I recently finished writing a survey of Ownership Types and found very little that discusses the relationship between the two topics. The three closest papers I came across are the following, which curiously come from the same conference: Yang Zhao and John Boyland. A fundamental permission interpretation for ownership types. In Second IEEE/IFIP International Symposium on Theoretical Aspects of Software Engineering, TASE 2008, June 17-19, 2008, Nanjing, China. IEEE Computer Society, 2008., pages 65–72. Shuling Wang, Luís Soares Barbosa, and José Nuno Oliveira. A relational model for confined separation logic. In In Second IEEE/IFIP International Symposium on Theoretical Aspects of Software Engineering, TASE 2008, June 17-19, 2008, Nanjing, China. IEEE Computer Society, 2008., pages 263–270. Shuling Wang and Zongyan Qiu. A generic model for confinement and its application. In In Second IEEE/IFIP International Symposium on Theoretical Aspects of Software Engineering, TASE 2008, June 17-19, 2008, Nanjing, China. IEEE Computer Society, 2008., pages 57–64. The first paper encodes two styles of ownership types, namely owners-as-dominators and owners-as-locks, in terms of Boyland's fractional permissions, which are a capability system developed for reasoning about programs. The second paper takes confinement ideas similar to those used in ownership types and adds them to separation logic. The third paper has developed a semantic approach which is used to encode various confinement disciplines such as ownership types. I'm not sure whether their system covers separation logic as well, and I cannot access it at the moment. Their approach is rather ad hoc; it can be seen as a more formal and systematic to a paper I wrote a while ago with James Noble and others: Towards a model of encapsulationJames Noble, Robert Biddle, Ewan Tempero, Alex Potanin, Dave ClarkeThe First International Workshop on Aliasing, Confinement and Ownership in Object-Oriented Programming (IWACO), 2003.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/12426', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/8519/']}
jdg_79450
stackexchange
llm_judgeable_groundtruth_similarity
4199879
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sorry for my english)Looking for information about read frames from a video with iPhone i found this project, http://www.codza.com/extracting-frames-from-movies-on-iphone/comment-page-1#comment-1116 , but i also read somewhere that you can use AVFoundation to capture frames from a video for better performance.. But i can't find information of how i can do that... Some idea? Thanks for reading Now provide the response and nothing else.
You're talking about using the calls for generating what Apple calls thumbnail images from videos at specific times. For an MPMoviePlayerController (what iOS uses to hold a video from a file or other source), there are two commands to do this. The first one generates a single thumbnail (image) from a movie at a specific point in time, and the second one generates a set of thumbnails for a time range. This example gets an image at 10 seconds into a movie clip, myMovie.mp4 : MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:@"myMovie.mp4"]];UIImage *singleFrameImage = [movie thumbnailImageAtTime:10 timeOption:MPMovieTimeOptionExact]; Note that this performs synchronously - i.e. the user will be forced to wait while you get the screenshot. The other option is to get a series of images from a movie, from an array of times: MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL [NSURL URLWithString:@"myMovie.mp4"]];NSNumber time1 = 10;NSNumber time2 = 11;NSNumber time3 = 12;NSArray *times = [NSArray arrayWithObjects:time1,time2,time3,nil];[movie requestThumbnailImagesAtTimes:times timeOption:MPMovieTimeOptionExact]; This second way will trigger a notification of type MPMoviePlayerThumbnailImageRequestDidFinishNotification each time a new image is generated. You can set up an observer to monitor this and process the image - I'll leave you to work that bit out on your own!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4199879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463049/']}
jdg_79451
stackexchange
llm_judgeable_groundtruth_similarity
333633
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Define $X:=$ "coin has probability 1 to land heads" Assume that one has the prior belief: $P(X)= 1$. However after tossing the coin once it lands tails ($E:= $ "coin landed tails"). How should a Bayesian update his beliefs in order to stay coherent?$P(X|E)$ is undefined, as $P(E) = 0 $. However, it seems to me that as his prior beliefs are quite implausible (of course probability 0 does not mean impossible) he should somehow be able to update his belief according to some rule. Is this just a pathological case in which Bayesian updating does not work or am I unaware of a solution to this problem? Now provide the response and nothing else.
Any posterior probability is valid in this case This is an interesting question, which gets into the territory of the foundations of probability. There are a few possible approaches here, but for reasons that I will elaborate on soon, the approach I favour is to give a broader definition of conditional probability that is analogous to its definition when dealing with continuous random variables. (Details of this method are shown below.) In this particular case, this leads to the conclusion that the Bayesian can hold any posterior belief about $X$ , and this yields a coherent set of beliefs (notwithstanding that they have observed an event that they believe to have probability zero). The advantage of this approach is that it gives a well-defined posterior distribution, and allows the Bayesian to update their beliefs conditional on observing an event that was stipulated to occur with probability zero. The posterior is updated essentially arbitrarily (any posterior probability is equally coherent), but that flexibility is unsurprising given what has occurred. In this case, different Bayesians with the same prior beliefs could legitimately come to different posterior conclusions, owing to the fact that they have all observed an event with zero probability a priori . Conditional probability for continuous random variables: When we are dealing with continuous random variables, the conditional probability function is defined through the Radon-Nikodym derivative , and essentially just requires the function to satisfies the law of joint probability. If $X$ and $E$ were continuous random variables (rather than discrete events) in a probability space $(\Omega, \mathscr{G}, P)$ then we would define the conditional probability function $p(x|e)$ as any non-negative measureable function that satisfies the integral equation: $$p(x) = \int \limits_\mathscr{E} p(x|e) \ dP(e)\quad \quad \quad \text{for all } x \in \mathscr{X} \in \mathscr{G}.$$ Since $p(x)$ is also defined via the Radon-Nikodym derivative, this implicitly means that $p(x|e)$ can be any non-negative measureable function that satisfies the integral equation: $$\mathbb{P}(X \in \mathcal{A}) = \int \limits_\mathcal{A} \int \limits_\mathscr{E} p(x|e) \ dP(e) \ dx\quad \quad \quad \text{for all } \mathcal{A} \in \mathscr{G}.$$ This gives a non-unique solution for the conditional probability function, though in practice, every solution is "almost surely" equivalent (i.e., they differ only on a set of outcomes with probability zero) so there is no problem with the non-uniqueness. Defining conditional probability for discrete events: The standard definition for conditional probability for discrete events is the well-known ratio formula, where the denominator is the probability of the conditioning event. Obviously, in the case where the conditioning event has zero probability, this object is undefined. The obvious solution here is to broaden the definition in a manner that is analogous to the method used in the continuous case. That is, we define the conditional probability pair $\mathbb{P}(X|E)$ and $\mathbb{P}(X|\bar{E})$ as any pair of values between zero and one that satisfy the equation: $$\mathbb{P}(X) = \mathbb{P}(X|E) \times \mathbb{P}(E) + \mathbb{P}(X|\bar{E}) \times (1-\mathbb{P}(E)).$$ In the case stipulated in the question we have the prior belief $\mathbb{P}(X) = 1$ and the sampling distribution $\mathbb{P}(E|X) = 0$ , which leads to $\mathbb{P}(E) = 0$ . Substituting these values into the above equation gives: $$1 = \mathbb{P}(X|E) \times 0 + \mathbb{P}(X|\bar{E}) \times 1.$$ We can see that this equation is satisfied by taking $\mathbb{P}(X|\bar{E}) = 1$ and any $0 \leqslant \mathbb{P}(X|E) \leqslant 1$ . Thus, the (posterior) conditional probability $\mathbb{P}(X|E)$ may coherently be any value between zero and one. When we say that this is "coherent" we simply mean that the posterior probability is not inconsistent with the other stipulated probabilities in the problem (i.e., the prior and sampling probabilities). Why this approach makes the most sense: It is entirely possible that a Bayesian analysis could involve observation of a discrete event that has zero probability stipulated in the prior distribution. For example, in a standard model of coin-flipping, we stipulate a Bernoulli distribution for the heads/tails outcome, but it is possible that the coin could come to rest on its edge (thus being neither heads or tails). Brains should not explode in this case, and thus it is incumbent on Bayesian reasoning to have a well-defined way of proceeding in this case. The major advantage of the approach I have outlined is that it always leads to at least one allowable value for the posterior probability (i.e., the posterior probability is well-defined ). The posterior probability is not uniquely defined, but that is a natural offshoot of the fact that there are several values that are equally coherent with the zero-probability sampling observation. This approach means that the Bayesian is free to stipulate any posterior probability, and this is as coherent as any other. (Bear in mind that when we say "coherent" here, we are talking about coherence with a prior belief that stipulated zero probability for a discrete event that actually happened, so coherence with that is not a high bar!) There is another major benefit to this approach , which is that it allows the Bayesian to update his or her beliefs in response to observing an event that had zero sampling probablity under the prior, and in particular, the Bayesian can now revise his or her beliefs so that they no longer ascribe zero probability to this event . In the example you give, the Bayesian had a prior belief that $X$ is true almost surely, buy then observed an event with zero sampling probability conditional on this event. Now the Bayesian is free to update his or her belief to a posterior probabilty for $X$ that is not one (and so a corresponding posterior probability for $\bar{X}$ that is not zero). So, in essence, the Bayesian can now say "Oh shit! That was a silly prior! Let me update my belief in that event so that it no longer occurs almost surely!" Moreover, this is not some ad hoc change, but a legitimate "coherent" updating done under Bayes' theorem.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/333633', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/119920/']}
jdg_79452
stackexchange
llm_judgeable_groundtruth_similarity
14564644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to login with the postgres user from my windows machine to my server with Pgadmin. But it keeps giving me this error: psql: FATAL: password authentication failed for user "postgres" So then I tried to login from the command line with psql, which gave me the same error. I then resetted the password to 'test' using psql, after putting the local entry in pg_hba.conf to trust. And then I placed the entry back to md5, and tried to login with the password 'test'. In psql I have used these commands: ALTER ROLE postgres WITH PASSWORD 'test';ALTER ROLE postgres PASSWORD 'test';ALTER USER postgres WITH PASSWORD 'test';ALTER USER postgres PASSWORD 'test'; And this special psql command \password Every time, I returned the pg_hba.conf local entry to md5, and tried to login with psql: psql -U postgres And then I am asked for a password. After entering 'test', psql gives me the same error as I mentioned earlier. And of course, I restarted postgresql after each and every change to the pg_hba file. And I'm using psql with 'su postgres'. So, even though I am able to change the password the usual way, it isn't accepted as the password. I hope somebody is able to help me with this. Some info: Postgresql 9.1Ubuntu 12.04 Pg_hba file (as requested) local all postgres md5local all all md5# IPv4 local connections:host all all 127.0.0.1/32 md5# IPv6 local connections:host all all ::1/128 md5host all all <my-ip-address>/32 md5 When I wanted to modify the password, I changed the top md5 to trust.I want to mention that this configuration has worked without problems before. The results of sudo -u postgres psql -x -c "select * from pg_user where usename='postgres'" Are: usename | postgresusesysid | 10usecreatedb | tusesuper | tusecatupd | tuserepl | tpasswd | ********valuntil | 1970-01-01 00:00:00+01useconfig | Now provide the response and nothing else.
As shown in the latest edit, the password is valid until 1970, which means it's currently invalid.This explains the error message which is the same as if the password was incorrect. Reset the validity with: ALTER USER postgres VALID UNTIL 'infinity'; In a recent question, another user had the same problem with user accounts and PG-9.2: PostgreSQL - Password authentication fail after adding group roles So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime type). Possibly, there's a bug in PG itself or in some client tool that would create this situation. EDIT : it turns out to be a pgadmin bug. See https://dba.stackexchange.com/questions/36137/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14564644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939928/']}
jdg_79453
stackexchange
llm_judgeable_groundtruth_similarity
45015636
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created a hello.py, which will print hello world 10 times with delay of 1 sec each. import timefor i in range(0,10): print("hello") time.sleep(1) Now when I convert this to exe using cx_Freeze method, hello.exe is created and it is not running. I'am running this on Windows 7 64 bit PC. Now provide the response and nothing else.
The error comes from the bcrypt.hash method.In your case, you have the following piece of code : bcrypt.hash(newUser.password, salt , (err, hash) => { ... } I think that your problem comes from the newUser.password that must be empty ( null or undefined ). The error says data and salt arguments required . It looks like your salt is correctly generated and you didn't check if newUser.password === undefined , so here's my bet: somehow newUser.password is undefined. Also, you can check if the genSalt method works fine by adding if(err) throw (err); after calling it as you did for the bcrypt.hash method.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45015636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6571290/']}
jdg_79454
stackexchange
llm_judgeable_groundtruth_similarity
9209956
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 provide login with Facebook functionality in my app I am using spring security core, spring security ui and spring security facebook in my grails app. It is allowing me to login using with facebook and the pop up is disappearing. and then while accessing any part of app with out any request map settings also showing an error showing No such property: roles for class: SecUserNo such property: roles for class: FacebookUsergroovy.lang.MissingPropertyException: No such property: roles for class: com.redkan.FacebookUser org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:49) Now provide the response and nothing else.
import org.springframework.test.util.ReflectionTestUtils;@RunWith(MockitoJUnitRunner.class)public CustomServiceTest{@InjectMocksprivate CustomServiceImpl customService;@Mockprivate DataService dataService;@Beforepublic void setup() { ReflectionTestUtils.setField(customService, "url", "http://someurl");} ...}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9209956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199444/']}
jdg_79455
stackexchange
llm_judgeable_groundtruth_similarity
367885
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: Denote the set of all bounded sequences in $\mathbb{R}$ by $l^{\infty}$, endowed with the sup norm $\lVert \rVert _{\infty}$. Define a map $T:l^{\infty} \to l^{\infty}$ as follows: $$(x_n)_n \mapsto \Big(\frac{x_n}{n}\Big)_n.$$ Then the question is: Show that the image of $l^{\infty}$ under $T$ is not a closed set in $l^{\infty}$. My attempts: As it is enough to show the existence of a sequence $(t_n)$ of bounded sequences from $T(l^{\infty})$ which converges to a sequence outside of it, I first considered the constant sequence $$(1,1, \ldots, 1, \ldots) = t_0$$ $(\notin T(l^{\infty}))$ and tried to look for a sequence $(t_n)$ of sequences in $T(l^{\infty})$ which goes to it. The following are two (failed) attempts to construct such a sequence. First I thought the sequences $$t_n = (1,1,\ldots,1,\frac{1}{(n+1)^2},\frac{1}{(n+2)^2},\ldots)$$ would work. But they didn't, because $$\lVert t_n-t_0\rVert_{\infty} = \sup_{k\geq n}\Big|1-\frac{1}{k^2}\Big|=1 \nrightarrow 0$$ as $n\to \infty$ and thus $(t_n) \nrightarrow t_0$. Also I thought about the sequences $$t_n = (1,1,\ldots,1,1+\frac{1}{n+1},1+\frac{1}{n+2},\ldots,1+\frac{1}{n+m},\ldots).$$ In this case $(t_n) \to t_0$ as $n \to \infty$, but none of the $t_n$'s is an element of $T(l^{\infty})$. So this sequence also is of no use. Any help? Thanks a lot in advance. Now provide the response and nothing else.
Let $t_0=(1,\frac{1}{\sqrt{2}},\frac{1}{\sqrt{3}},\ldots)$ and $t_m=(1,\frac{1}{\sqrt{2}},\ldots,\frac{1}{\sqrt{m}},0,0,\ldots)$. Clearly $t_m\rightarrow t_0$, $t_m$ is in the image of $T$ and $t_0$ is not in the image of $T$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/367885', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12603/']}
jdg_79456
stackexchange
llm_judgeable_groundtruth_similarity
623969
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I replace the blank lines in tab delimited text file with the content of the row above on a Linux machine? For example: 101 abc group1765 efg group2345 hij group4456 gfd group9762 ert group7554 fgt group11 Expected Output: 101 abc group1765 efg group2345 hij group3345 hij group3456 gfd group9762 ert group7762 ert group7762 ert group7554 fgt group11 Now provide the response and nothing else.
In awk (note that this one will print any empty lines that come before the first non-empty one): $ awk '{ if(! NF){$0=last}else{last=$0;}}1' file101 abc group1765 efg group2 345 hij group4 345 hij group4 456 gfd group9 762 ert group7 762 ert group7 762 ert group7 554 fgt group11 Explanation : NF holds the number of fields. If the line is empty, there are no fields so the variable will be 0 . if(! NF){$0=last} : if the number of fields is 0 (empty line), set the current line ( $0 ) to the value of the variable last . else{last=$0;} : if there are fields, so this line is not empty, set last to hold the contents of this line. 1 : the lone one at the end is an awk trick: when something evaluates to true (1 or any other integer greater than 0 is always true, since 0 is false) awk will print the current line. So that 1 is equivalent to print $0 . $ awk '! NF ? $0=last : last=$0;' file101 abc group1765 efg group2 345 hij group4 345 hij group4 456 gfd group9 762 ert group7 762 ert group7 762 ert group7 554 fgt group11 Explanation This is the same idea as above, but written in a more concise way. We are using the ternary operator . Since one of the two conditions will always be true (either NF is true or it is not true, so the ternary operator will always return true), both outcomes result in the line being printed (except for cases where the line is empty and no non-empty lines have been seen or if a line consistes of nothing but 0 ). However, if NF is not set, we set $0 to last and if it is set, we set last to $0 . The result is the output we want. Since the above will not print lines that are just 0 , you can use this instead of that is a problem for you: awk '{! NF ? $0=last : last=$0};1' file
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/623969', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/312065/']}
jdg_79457
stackexchange
llm_judgeable_groundtruth_similarity
33097
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $L$ be a regular language with the alphabet $\Sigma$. I'm trying to find an algorithm to tell whether $L=\Sigma^{*}$, whether $L$ accepts all strings in its alphabet. I think this algorithm uses converting the language to a DFA, but I'm not sure what to do from there. I have only recently began learning about regular languages and complexity, so help would be appreciated Now provide the response and nothing else.
Elaborating Paul's suggestion for a $O(n \log n)$-time algorithm: Input: Let $u \in [m]^k$ and $v \in [m]^n$ with $k \leq n$, where $U=[m]=\{1,2,\cdots,m\}$. Define polynomials $$p(x,y) = \sum_{i \in [n]} x^i y^{v_i} \qquad \text{and} \qquad q(x,y) = \sum_{j \in [k]} x^{k-j} y^{m-u_j}.$$ Compute the polynomial $$r(x,y) = p(x,y) q(x,y).$$ Then $$r(x,y) = \sum_{t,s} x^t y^s \left|\left\{ (i,j) \in [n]\times[k] : i+k-j=t \wedge v_i + m - u_j =s \right\}\right|. $$In particular, for $k \leq t \leq n$, the coefficient of $x^{t} y^m$ in $r(x,y)$ is $$\left|\left\{ (i,j) \in [n]\times[k] : i=j+t-k \wedge v_i = u_j\right\}\right| = k-d_H(u,v[t-k+1,t]).$$Thus, the coefficients of $r(x,y)$ provide a lookup table for $d_H(u,v[t-k+1,t])$ for $k \leq t \leq n$.So, given the coefficients of $r(x,y)$, we can easily solve the problem by picking the $t$ such that $x^{t}y^m$ has the largest coefficient: Output: $f(u,v)+k=\mathrm{arg}\max_{k \leq t \leq n} \mathrm{coefficient}_{r(x,y)}(x^{t}y^m)$ So how fast is this algorithm? I claim it can be implemented in $O(nm \log (nm))$ time (assuming arithmetic operations with $O(\log (nm))$ bits of precision take constant time) using the Fast Fourier Transform . The core of the problem is computing $r(x,y)=p(x,y)q(x,y)$, where the degree of $p(x,y)$ is at most $n$ in $x$ and $m$ in $y$ and the degree of $q(x,y)$ is at most $k$ in $x$ and $m$ in $y$. We can first reduce it to univariate polynomial multiplication by defining $$p'(z) = p(z^{m+1},z) \qquad \text{and} \qquad q'(z)=q(z^{m+1},z),$$ computing $r'(z)=p'(z)q'(z)$, and then extracting $r(x,y)$ from the identity $r'(z)=r(z^{m+1},z)$. I won't go through the FFT algorithm (even though it's one of my favourite algorithms), but the general idea is: Pick $\ell = O(nm)$ special points $w_1, \cdots, w_\ell \in \mathbb{C}$, namely $w_j=\exp(2\pi\sqrt{-1}j/\ell)$ and $\ell$ is a power of $2$ with $\ell > \mathrm{degree}(r'(z))=O(nm)$. Evaluate $p'(w_j)$ and $q'(w_j)$ for all $j \in [\ell]$ in $O(\ell \log \ell)$-time using a divide and conquer algorithm. Compute the values $r'(w_j)=p'(w_j)q'(w_j)$ for all $j$ in $O(\ell)$-time. Interpolate the coefficients of $r'(z)$ from the values $r'(w_j)$ in $O(\ell \log \ell)$-time using essentially the same divide and conquer algorithm. The observation that makes the divide and conquer algorithm work is that we can write $p'(z) = p'_\text{even}(z^2) + z \cdot p'_\text{odd}(z^2)$, where $p'_\text{even}$ and $p'_\text{odd}$ have half the degree of $p'$. It then suffices to recursively evaluate $p'_\text{even}(w_{2j})$ and $p'_\text{odd}(w_{2j})$ for $j \in [\ell/2]$.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/33097', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/36374/']}
jdg_79458
stackexchange
llm_judgeable_groundtruth_similarity
32211232
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 using Doctrine's generator because I think the code is ugly, thus I am trying to make it work my editAction and render the form in my edit.html.twig page, but I can not make it work. I tried to follow other examples given by other answers but they did not work either. First, my editAction . public function editAction($id, Request $request){ $manager = $this->getDoctrine()->getManager(); $entity = $manager->getRepository('PanelBundle:Material')->find($id); if (!$entity) { throw $this->createNotFoundException('O material procurado não está cadastrado'); } $form = $this->createForm(new MaterialType()); $form->handleRequest($request); if ($request->getMethod() == 'POST') { $form->submit($request); if ($form->isValid()) { $manager->merge($entity); $manager->flush(); $this->addFlash('success', 'Material alterado'); return $this->redirect($this->generateUrl('panel_materials')); } } return $this->render('PanelBundle:Material:edit.html.twig', array( 'entity' => $entity ));} Now, my Twig {% extends '::layout.html.twig' %}{% block title %}Editar {{ entity.name }}{% endblock %}{% block body %} <div class="container"> <h1>Editar {{ entity.name }}</h1> <form action="{{ path('panel_edit_material', { 'id': entity.id }) }}" method="POST"> <div class="form-group"> {{ form_row(entity.name) }} </div> <div class="form-group"> {{ form_row(entity.description) }} </div> <div class="form-group"> {{ form_row(entity.quantity) }} </div> <div class="form-group"> {{ form_row(entity.price) }} </div> {{ form_rest(form) }} <button type="submit" class="btn btn-success">Alterar</button> </form> </div>{% endblock %} Two things: if I remove the { 'id': entity.id } , an error is shown saying a mandatory field is missing, if I let it like it is now, it says searchAndRenderBlock() must be an instance of Symfony\Component\Form\FormView , and if instead of returning $entity in controller, and return $form->createView() , the error says FormView could not be converted to string Now provide the response and nothing else.
You are using the style-loader, which, by default, embeds your CSS in Javascript and injects it at runtime. If you want real CSS files instead of CSS embedded in your Javascript, you should use the ExtractTextPlugin . A basic config would be: Add var ExtractTextPlugin = require('extract-text-webpack-plugin'); to the top of your Webpack config file. Add the following to your Webpack config: plugins: [ new ExtractTextPlugin('[name].css'),] Change your SASS loader config to the following: { test: /\.scss$/, loader: ExtractTextPlugin.extract( 'style-loader', // backup loader when not building .css file 'css-loader!sass-loader' // loaders to preprocess CSS )} What this does is extract all CSS it can find in your bundle to a separate file. The name will be based on your entrypoint name, which in your case will result in javascript.css (from the entry part of your config). The ExtractTextPlugin.extract -loader is used by the plugin to find the CSS in your code and put it in separate files. The first parameter you give it is the loader it should fall back to if it encounters files in an async module, for example. Generally this is pretty much always style-loader . The second parameter tells the plugin what loaders to use to process the CSS, in this case css-loader and sass-loader , but things like postcss-loader are often used too. More info on building your CSS with Webpack can be found here: https://webpack.github.io/docs/stylesheets.html#separate-css-bundle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32211232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4383363/']}
jdg_79459
stackexchange
llm_judgeable_groundtruth_similarity
46338932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could someone show me what is wrong? I try to use a Handler post a Runnable but it's not execute var mHandler: Handler? = nulloverride fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mHandler = Handler() var runnable = Runnable { Log.d("TEST", "++++ runable") Log.d("TEST", "++++ come end") } Log.d("TEST", "++++ runnable" + runnable) Log.d("TEST", "++++ handle" + mHandler) mHandler!!.post { runnable }} This is output 09-21 00:56:04.067 4419-4419/? D/TEST: ++++ runnablecom.vpioneer.activity.MainActivity$onCreate$runnable$1@529b8fb4 09-21 00:56:04.067 4419-4419/? D/TEST: ++++ handleHandler (android.os.Handler) {529b8cb4} Now provide the response and nothing else.
First at all, don't use !! operator, it is a very bad practice (from the doc ). With ? you will reach the same behaviour but checking if the instance became null before executing it. Saying this, using: mHandler?.post { runnable } You are actually creating a new lambda containing runnable line. see here below in a more readable way: mHandler?.post { runnable } This is the equivalent in Java: mHandler.post(new Runnable(){ public void run(){ runnable; }}); To solve this: Option 1: getting rid of the runnable declaration mHandler?.post { /*the content of your runnable*/ } Option 2: using your runnable instance mHandler?.post(runnable) // normal parentheses Option 3: crazy way mHandler?.post { runnable.run() }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46338932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3673299/']}
jdg_79460
stackexchange
llm_judgeable_groundtruth_similarity
5051970
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: An interview question: Given a function f(x) that 1/4 times returns 0, 3/4 times returns 1.Write a function g(x) using f(x) that 1/2 times returns 0, 1/2 times returns 1. My implementation is: function g(x) = { if (f(x) == 0){ // 1/4 var s = f(x) if( s == 1) {// 3/4 * 1/4 return s // 3/16 } else { g(x) } } else { // 3/4 var k = f(x) if( k == 0) {// 1/4 * 3/4 return k // 3/16 } else { g(x) } }} Am I right? What's your solution?(you can use any language) Now provide the response and nothing else.
If you call f(x) twice in a row, the following outcomes are possible (assuming thatsuccessive calls to f(x) are independent, identically distributed trials): 00 (probability 1/4 * 1/4)01 (probability 1/4 * 3/4) 10 (probability 3/4 * 1/4) 11 (probability 3/4 * 3/4) 01 and 10 occur with equal probability. So iterate until you get one of thosecases, then return 0 or 1 appropriately: do a=f(x); b=f(x);while (a == b);return a; It might be tempting to call f(x) only once per iteration and keep track of the twomost recent values, but that won't work. Suppose the very first roll is 1,with probability 3/4. You'd loop until the first 0, then return 1 (with probability 3/4).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5051970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241824/']}
jdg_79461
stackexchange
llm_judgeable_groundtruth_similarity
40787289
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 align the text under the circle, perfectly on the middle. Here a snippet (I simplified everything because circle and text are handled by angular so they are some difference between my screenshot and the snippet) .circle2 { border-radius: 50%; width: 18px; height: 18px; background: RoyalBlue; display: inline-block; z-index: 2;}.wrapper2 { display:flex; width:100%; justify-content: space-around; position:relative;}.wrapper2:after { position:absolute; content:''; display:block; width: 100%; top:7px; height: 3px; background: RoyalBlue;}.advanced2 { width: 18px; height: 18px;}.circleActive2 { border-radius: 50%; width: 25px; height: 25px; background: RoyalBlue; display: inline-block;} <div class="w3-container"> <div class="wrapper2"> <span> <span><div class="circle2 advanced2" ></div>test</span> <span><div class="circle2 advanced2 circleActive2" ></div>test2</span> <span><div class="circle2 advanced2" ></div>test3</span> <span><div class="circle2 advanced2" ></div>test4</span> <span><div class="circle2 advanced2" ></div>test5</span> </span> </div></div> Now provide the response and nothing else.
.Value on a nullable assumes it can't be null. Hence is applying the null-coalescing operator on it useless and forbidden. You could use the operator like this, but going on your code I am not sure if this is what you need: DateTime test = (model.SanctionExpires ?? DateTime.Now).ToUniversalTime(); For your update: you can shortcut that evaluation like this: DateTime? test = model.SanctionExpires?.ToUniversalTime();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40787289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3250142/']}
jdg_79462
stackexchange
llm_judgeable_groundtruth_similarity
60410
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This issue seems to rear its ugly head all the time, and I'm trying to decapitate it for my own understanding of statistics (and sanity!). The assumptions of general linear models (t-test, ANOVA, regression etc.) include the "assumption of normality", but I have found this is rarely described clearly. I often come across statistics textbooks / manuals / etc. simply stating that the "assumption of normality" applies to each group (i.e., categorical X variables), and we should we examining departures from normality for each group . Questions : does the assumption refer to the values of Y or the residuals of Y? for a particular group , is it possible to have a strongly non-normal distribution of Y values (e.g., skewed) BUT an approximately (or at least more normal) distribution of residuals of Y? Other sources describe that the assumption pertains to the residuals of the model (in cases where there are groups, e.g. t-tests / ANOVA), and we should be examining departures of normality of these residuals (i.e., only one Q-Q plot/test to run). does normality of residuals for the model imply normality of residuals for the groups ? In other words, should we just examine the model residuals (contrary to instructions in many texts)? To put this in a context, consider this hypothetical example: I want to compare tree height (Y) between two populations (X). In one population the distribution of Y is strongly right-skewed (i.e.,most trees short, very few tall), while the other is virtually normal Height is higher overall in the normally distributed population (suggesting there may be a 'real' difference). Transformation of the data does not substantially improve the distribution of the first population. Firstly, is it valid to compare the groups given the radically different height distributions? How do I approach the "assumption of normality" here? Recall height in one population is not normally distributed. Do I examine residuals for both populations separately OR residuals for the model (t-test)? Please refer to questions by number in replies, experience has shown me people get lost or sidetracked easily (especially me!). Keep in mind I am not a statistician; though I have a reasonably conceptual (i.e., not technical!) understanding of statistics. P.S., I have searched the archives and read the following threads which have not cemented my understanding: ANOVA assumption normality/normal distribution of residuals Normality of residuals vs sample data; what about t-tests? Is normality testing 'essentially useless'? Testing normality Assessing normality of distribution What tests do I use to confirm that residuals are normally distributed? What to do when Kolmogorov-Smirnov test is significant for residuals of parametric test but skewness and kurtosis look normal? Now provide the response and nothing else.
One point that may help your understanding: If $x$ is normally distributed and $a$ and $b$ are constants, then $y=\frac{x-a}{b}$ is also normally distributed (but with a possibly different mean and variance). Since the residuals are just the y values minus the estimated mean (standardized residuals are also divided by an estimate of the standard error) then if the y values are normally distributed then the residuals are as well and the other way around. So when we talk about theory or assumptions it does not matter which we talk about because one implies the other. So for the questions this leads to: yes, both, either No, (however the individual y-values will come from normals with different means which can make them look non-normal if grouped together) Normality of residuals means normality of groups, however it can be good to examine residuals or y-values by groups in some cases (pooling may obscure non-normality that is obvious in a group) or looking all together in other cases (not enough observations per group to determine, but all together you can tell). This depends on what you mean by compare, how big your sample size is, and your feelings on "Approximate". The normality assumption is only required for tests/intervals on the results, you can fit the model and describe the point estimates whether there is normality or not. The Central Limit Theorem says that if the sample size is large enough then the estimates will be approximately normal even if the residuals are not. It depends on what question your are trying to answer and how "approximate" your are happy with. Another point that is important to understand (but is often conflated in learning) is that there are 2 types of residuals here: The theoretical residuals which are the differences between the observed values and the true theoretical model, and the observed residuals which are the differences between the observed values and the estimates from the currently fitted model. We assume that the theoretical residuals are iid normal. The observed residuals are not i, i, or distributed normal (but do have a mean of 0). However, for practical purposes the observed residuals do estimate the theoretical residuals and are therefore still useful for diagnostics.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/60410', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/17714/']}
jdg_79463
stackexchange
llm_judgeable_groundtruth_similarity
20573235
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 know the attribute locations inside fixed pipeline (no shader attached) for nVidia OpenGL drivers: glVertex = 0glColor = 3glNormal = ?glTexCoord = ?glMultiTexCoord 0..7 = ?glSecondaryColor = ?glFog = ? Empirically I found the Vertex and primary Color locations but still will be nice to know them all. If you want to know why, then for compatibility reasons and even for GLSL debugging (just to see if I pass the correct data to correct locations when shader not works yet) and so on ... Now provide the response and nothing else.
Outside of NVIDIA drivers, this does not work (reliably). Compliant drivers will only alias glVertexPointer (...) to attribute slot 0 . NV in their infinite wisdom devised a standard non-standard scheme many years ago where they aliased all of the fixed-function pointers to certain attribute locations, but I do not know if new NV drivers support this (I honestly have never cared enough to try, it is such a bad practice). You might still be able to find NV's documentation for their alias mappings, but you are not benefiting anyone by taking advantage of their non-standard behavior. While other drivers may also alias the fixed-function pointers to generic vertex attribute locations, no documentation exists for their mappings. Unlike NV, I would not trust that the mapping would not change between driver versions, hardware or platform. In fact, even using NV drivers you should not take advantage of this - it was intended to promote legacy support and not as a feature used for new software. The bottom line is, use generic vertex attributes instead or use a compatibility profile and a version of GLSL that still supports the pre-declared variables that are specifically designed for getting fixed-function vertex data (e.g. gl_Color , gl_Normal , gl_MultiTexCoord0...7 , ...). But do not mix-and-match both the way you are describing. Also take some time to review glGetPointerv (...) . If you want to get information about the fixed-function pointers outside of GLSL, this is the proper way to do it. Do not rely on vertex attribute aliasing, because the concept of attribute locations is fundamentally a programmable pipeline feature. It did not even exist in unextended OpenGL prior to 2.0 (it was introduced with the ARB Vertex Program assembly language and promoted into core with GLSL). Update: While I still strongly advise against using this information, I was able to find exactly what you wanted: Release Notes for NVIDIA OpenGL Shading Language Support - November 9, 2006 - pp. 7-8 Vertex Attribute Aliasing GLSL attempts to eliminate aliasing of vertex attributes but this is integral to NVIDIA’s hardware approach and necessary for maintaining compatibility with existing OpenGL applications that NVIDIA customers rely on. NVIDIA’s GLSL implementation therefore does not allow built-in vertex attributes to collide with a generic vertex attributes that is assigned to a particular vertex attribute index with glBindAttribLocation . For example, you should not use gl_Normal (a built-in vertex attribute) and also use glBindAttribLocation to bind a generic vertex attribute named “whatever” to vertex attribute index 2 because gl_Normal aliases to index 2 . In case you were wondering, this is also outlined in Table X.1 of the ARB Vertex Program extension specification . The only reason I mentioned NV specifically is because they chose to re-use the aliasing in GLSL whereas compliant implementations from other vendors will only honor the first alias ( glVertexPointer (...) to 0 ) in GLSL.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20573235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2521214/']}
jdg_79464
stackexchange
llm_judgeable_groundtruth_similarity
51210445
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On my project there is REST API which implemented on AWS API Gateway and AWS Lambda. As AWS Lambda functions are serverless and stateless while we make a call to it, AWS starts a container with code of the Lambda function which process our call. According AWS documentation after finishing of lambda function execution AWS don't stop the container and we are able to process next call in that container. Such approach improves performance of the service - only in time of first call AWS spend time to start container (cold start of Lambda function) and all next calls are executed faster because their use the same container (warm starts). As a next step for improving the performance we created cron job which calls periodically our Lambda function (we use Cloudwatch rules for that). Such approach allow to keep Lambda function "warm" allowing to avoid stopping and restarting of containers. I.e. when the real user will call our REST API, Lambda will not spent time to start a new container. But we faced with the issue - such approach allow to keep warm only one container of Lambda function while the actual number of parallel calls from different users can be much larger (in our case that's hundreds and sometimes even thousands of users). Is there any way to implement warm up functionality for Lambda function which could warm not only single container, but some desired number of them? I understand that such approach can affect cost of Lambda function's using and possibly, at all it will be better to use good old application server, but comparison of these approaches and their costs will be the next steps, I think, and in current moment I would like just to find the way to warm desired count of Lambda function containers. Now provide the response and nothing else.
This can be long but bear with me as this would probably give you workaround and may be would make you understand better How Lambda Works ? Alternatively You can Skip to Bottom " The Workaround " if you are not interested in reading. For folks who are not aware about cold starts please read this blog post to better understand it. To describe this in short: Cold Starts When a function is executed for the first time or after having thefunctions code or resource configuration updated, a container will bespun up to execute this function. All the code and libraries will beloaded into the container for it to be able to execute. The code willthen run, starting with the initialisation code. The initialisationcode is the code written outside the handler. This code is only runwhen the container is created for the first time. Finally, the Lambdahandler is executed. This set-up process is what is considered a coldstart. For performance, Lambda has the ability to re-use containers createdby previous invocations. This will avoid the initialisation of a newcontainer and loading of code. Only the handler code will beexecuted. However, you cannot depend on a container from a previousinvocation to be reused. if you haven’t changed the code and not toomuch time has gone by, Lambda may reuse the previous container. If you change the code, resource configuration or some time haspassed since the previous invocation, a new container will beinitialized and you will experience a cold start. Now Consider these scenarios for better understanding: Consider the Lambda function, in the example, is invoked for the first time. Lambda will create a container, load the code into the container and run the initialisation code. The function handler will then be executed. This invocation will have experienced a cold start . As mentioned in the comments, the function takes 15 seconds to complete. After a minute, the function is invoked again. Lambda will most likely re-use the container from the previous invocation. This invocation will not experience a cold start. Now consider the second scenario , where the second invocation is executed 5 seconds after the first invocation. Since the previous function takes 15 seconds to complete and has not finished executing, the new invocation will have to create a new container for this function to execute. Therefore this invocation will experience a cold start. Now to Come up First Part of Problem that you have solved : Regarding preventing cold starts, this is a possibility, however, it is not guaranteed, the common workaround will only keep warm one container of the Lambda function. To do, you would run a CloudWatch event using a schedule event (cron expression) that will invoke your Lambda function every couple of minutes to keep it warm. The Workaround: For your use-case, your Lambda function will be invoked very frequently with a very high concurrency rate . To avoid as many cold starts as possible, you will need to keep warm as many containers as you expect your highest concurrency to reach. To do this you will need to invoke the functions with a delay to allow the concurrency of this function to build and reach the desired amount of concurrent executions . This will force Lambda to spin up the number of containers you desire. This, as a result, can bring up costs and will not guarantee to avoid cold starts. That being said, here is a break down on how you can keep multiple containers for your function warm at one time: You should have a CloudWatch Events Rule that is triggered on a schedule . This schedule can be a fixed rate or a cron expression. for example, You can set this rule to trigger every 5 minutes. You will then specify a Lambda function (Controller function) as the target of this rule. Your Controller Lambda function will then invoke the Lambda function (Function that you want to be kept warm) for as many concurrent running containers as you desire. There are a few things to consider here: You will have to build concurrency because if the first invocationis finished before another invocation starts then this invocationmay reuse the previous invocations container and not create a newone. To do this you will need to add some sort of delay on theLambda function if the function is invoked by the controllerfunction. This can be done by passing in a specific payload tothe function with these invocations. The lambda function that youwant to be kept warm will then check if this payload exists. Ifit does then the function will wait (to build concurrentinvocations), if it does not then the function can execute asexpected. You will also need to ensure you are not getting throttled on the Invoke Lambda API call if you are calling it repeatedly. YourLambda function should be written to handle this throttling if it occurs and consider adding a delay between API calls to avoid throttling. At the End this solution can reduce cold starts but it will increase costs and will not guarantee that cold starts will occur as they are inevitable when working with Lambda.If your application needs faster response times then what occurs with a Lambda cold start, I would recommend looking into having your server on a EC2 instance.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51210445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1145792/']}
jdg_79465
stackexchange
llm_judgeable_groundtruth_similarity
164035
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I do this? if [ -f town-*.swf ]thenmkdir townsfi This checks if town-*.swf exists, but I also need it to look for city-*.swf among others, so I need something like this: if [ -f town-*.swf, city-*.swf ]thenmkdir townsfi Now provide the response and nothing else.
POSIXly, you can use ls if ls town-*.swf >/dev/null 2>&1 && ls city-*.swf >/dev/null 2>&1 then mkdir townsfi or shorter if condition: if ls town-*.swf city-*.swf >/dev/null 2>&1 even if your shell supports brace expansion : if ls {town,city}-*.swf >/dev/null 2>&1
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/164035', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/79979/']}
jdg_79466
stackexchange
llm_judgeable_groundtruth_similarity
1639555
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 call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I'm trying to figure out why. function showGetResult (name) { var scriptURL = "somefile.php?name=" + name; return $.get(scriptURL, {}, function(data) { return data; });}alert (showGetResult("John")); The alert displays " [object XMLHttpRequest] ." However, if I run the jQuery statement by itself, outside of a function, it works fine -> $.get(scriptURL, {}, function(data) { alert(data); }) I'd like to be able to re-use this code by putting it inside of a function that returns the $.get data. What fundamental mistake am I making here? Now provide the response and nothing else.
You have a few different mistakes. First, $.get doesn't return the return value of the callback function. It returns the XHR object. Second, the get function isn't synchronous, it's asynchronous so showGetResult will likely return before get completes. Third, you can't return something from inside the callback to the outer scope. You can, however, bind a variable in the outer scope and set it in the callback. To get the functionality that you want, you'll need to use $.ajax and set the async option to false. Then you can define a variable in the outer scope and assign it in the ajax callback, returning this variable from the function. function showGetResult( name ){ var result = null; var scriptUrl = "somefile.php?name=" + name; $.ajax({ url: scriptUrl, type: 'get', dataType: 'html', async: false, success: function(data) { result = data; } }); return result;} You would probably be better served, though, figuring out how to do what you want in the callback function itself rather than changing from asynchronous to synchronous calls.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1639555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155387/']}
jdg_79467
stackexchange
llm_judgeable_groundtruth_similarity
13423593
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have installed: eclipse juno java-6-openjdk-i386 (selected as default JRE in Eclipse) java-7-openjdk-i386 When I try to add a new server Tomcat7, in Eclipse, I get this message 'Cannot create a server using the selected type' and I can not continue. No problem adding Tomcat6 server. I read this question but it didn't solve it for me Now provide the response and nothing else.
1 . To fix the error 'Cannot create a server using the selected type' run the following: cd ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/ rm org.eclipse.jst.server.tomcat.core.prefs rm org.eclipse.wst.server.core.prefs 2 . Once you do this, another error 'Could not load the Tomcat server configuration at /usr/share/tomcat7/conf. The configuration may be corrupt or incomplete /usr/share/tomcat7/conf/catalina.policy (No such file or directory)' So to fix this run the following commands: cd /usr/share/tomcat7sudo ln -s /var/lib/tomcat7/conf confsudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policysudo ln -s /var/log/tomcat7 logsudo chmod -R 777 /usr/share/tomcat7/conf 3 . Restart server and Eclipse 4 . Add new server Choose the Servers under the Server category; Create new server wizard ; Choose Apache / Tomcat v7.0 Server and press Next; Enter /usr/share/tomcat7 into the Tomcat installation directory and press Next; Select your project on the left pane under “Available” and press Add> to move it to the right pane under Configured ; press Finish ; Eclipse need to start the server, and to do that, first, it has to stop the one running in background. sudo service tomcat7 stop If you don't have to automatically start at boot, we can use the following command sudo update-rc.d tomcat7 disable If, during server start, you receive warnings like: WARNING: Problem with directory [/usr/share/tomcat7/common/classes], exists: [false], isDirectory: [false], canRead: [false]WARNING: Problem with directory [/usr/share/tomcat7/common], exists: [false], isDirectory: [false], canRead: [false]WARNING: Problem with directory [/usr/share/tomcat7/server/classes], exists: [false], isDirectory: [false], canRead: [false]WARNING: Problem with directory [/usr/share/tomcat7/server], exists: [false], isDirectory: [false], canRead: [false]WARNING: Problem with directory [/usr/share/tomcat7/shared/classes], exists: [false], isDirectory: [false], canRead: [false]WARNING: Problem with directory [/usr/share/tomcat7/shared], exists: [false], isDirectory: [false], canRead: [false] You may also need to run the following: cd /usr/share/tomcat7sudo ln -s /var/lib/tomcat7/common commonsudo ln -s /var/lib/tomcat7/server serversudo ln -s /var/lib/tomcat7/shared shared
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13423593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/953263/']}
jdg_79468
stackexchange
llm_judgeable_groundtruth_similarity
64706160
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 actually trying to run my app but i'm stucked with that error : Running "flutter pub get" in riverpod_stacked_app...Launching lib/main.dart on sdk gphone x86 arm in debug mode...Running Gradle task 'assembleDebug'...../../.pub-cache/hosted/pub.dartlang.org/get-3.15.0/lib/get_navigation/src/extension_navigation.dart:235:37: Error: No named parameter with the name 'shadowThemeOnly'. final theme = Theme.of(context, shadowThemeOnly: true); ^^^^^^^^^^^^^^^../../development/flutter/packages/flutter/lib/src/material/theme.dart:119:20: Context: Found this candidate, but the arguments don't match. static ThemeData of(BuildContext context) { ^^../../.pub-cache/hosted/pub.dartlang.org/get-3.15.0/lib/get_navigation/src/extension_navigation.dart:431:43: Error: No named parameter with the name 'shadowThemeOnly'. theme: Theme.of(key.currentContext, shadowThemeOnly: true), ^^^^^^^^^^^^^^^../../development/flutter/packages/flutter/lib/src/material/theme.dart:119:20: Context: Found this candidate, but the arguments don't match. static ThemeData of(BuildContext context) { ^^FAILURE: Build failed with an exception.* Where:Script '/Users/Alex/development/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 900* What went wrong:Execution failed for task ':app:compileFlutterBuildDebug'.> Process 'command '/Users/Alex/development/flutter/bin/flutter'' finished with non-zero exit value 1* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.* Get more help at https://help.gradle.orgBUILD FAILED in 19sException: Gradle task assembleDebug failed with exit code 1 I don't understand why it can't build. I don't see the link between those 2 errors : get_navigation something with the theme from material.dartAnd my actual motivation to use riverpod, stacked_services and firebase. Here is the result of flutter doctor -v : [✓] Flutter (Channel master, 1.24.0-8.0.pre.98, on Mac OS X 10.15.7 19H2 darwin-x64, locale fr-FR) • Flutter version 1.24.0-8.0.pre.98 at /Users/Alex/development/flutter • Framework revision ef4ec09a06 (6 hours ago), 2020-11-05 08:02:13 -0800 • Engine revision bf259226b2 • Dart version 2.12.0 (build 2.12.0-21.0.dev)[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2) • Android SDK at /Users/Alex/Library/Android/sdk • Platform android-30, build-tools 30.0.2 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593) • All Android licenses accepted.[✗] Xcode - develop for iOS and macOS ✗ Xcode installation is incomplete; a full installation is necessary for iOS development. Download at: https://developer.apple.com/xcode/download/ Or install Xcode via the App Store. Once installed, run: sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer sudo xcodebuild -runFirstLaunch ✗ CocoaPods not installed. CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side. Without CocoaPods, plugins will not work on iOS or macOS. For more info, see https://flutter.dev/platform-plugins To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.[✓] Android Studio (version 4.1) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)[✓] Connected device (1 available) • sdk gphone x86 arm (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)! Doctor found issues in 1 category. And here is my dependencies in pubspeck.yaml version: 1.0.0+1environment: sdk: ">=2.7.0 <3.0.0"dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.0 stacked_services: auto_route: 0.6.9 hooks_riverpod: 0.12.1 flutter_hooks: firebase_core: 0.5.1 firebase_auth: 0.18.2dev_dependencies: flutter_test: sdk: flutter build_runner: auto_route_generator: Any ideas ? I've trie to clean up my dependencies and reinstall. Also i start a blank project with flutter counter app and it runs properly. Now provide the response and nothing else.
I also had this problem today after upgrading Flutter. I was only able to solve it after I deleted that method parameter from the file that triggered the error. You'll have to delete it in two places. Search in .pub-cache/hosted/pub.dartlang.org/get-3.15.0/lib/get_navigation/src/extension_navigation.dart for Theme.of(key.currentContext, shadowThemeOnly: true) As replace it with Theme.of(key.currentContext) This is probably cause by the stacked_services dependency that uses the get: ^3.15.0 dependency Later edit: this is actually not the best solution, because somebody cloning your repo will not be able to compile the project unless they also to this change So it's better to upgrade the dependency that causes this error, or replace it with another one; but only after you ran flutter upgrade, or try changing the channel
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64706160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10785538/']}
jdg_79469
stackexchange
llm_judgeable_groundtruth_similarity
17645701
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this script that does a word search in text. The search goes pretty good and results work as expected. What I'm trying to achieve is extract n words close to the match. For example: The world is a small place, we should try to take care of it. Suppose I'm looking for place and I need to extract the 3 words on the right and the 3 words on the left. In this case they would be: left -> [is, a, small]right -> [we, should, try] What is the best approach to do this? Thanks! Now provide the response and nothing else.
def search(text,n): '''Searches for text, and retrieves n words either side of the text, which are retuned seperatly''' word = r"\W*([\w]+)" groups = re.search(r'{}\W*{}{}'.format(word*n,'place',word*n), text).groups() return groups[:n],groups[n:] This allows you to specify how many words either side you want to capture. It works by constructing the regular expression dynamically. With t = "The world is a small place, we should try to take care of it."search(t,3)(('is', 'a', 'small'), ('we', 'should', 'try'))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17645701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1398915/']}
jdg_79470
stackexchange
llm_judgeable_groundtruth_similarity
6954501
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 dictionary of the following form: { <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'}, <Category('View Results', 'True', 'False', 'True', 'INTERMEDIATE')>: {'link': '/story/step/3', 'name': u'View Results'}, <Category('Analyze', 'True', 'False', 'False', 'FINAL')>: {'link': '/story/step/2', 'name': u'Analyze'}} Category is a class representing an instance from a database. Now I have the following instance: <Category('Analyze', 'True', 'False', 'False', 'FINAL')> Now this is not the same instance. By this I mean, I get all the values from the database and create the dictionary. Then after a while I get an id and retrieve the instance from the database. Now they are not the same objects. I now have to check if it's in the dictionary, but: instance in disctionary Will return false. Now I could go the ugly way and iterate over the dictionary checking if all the values match, however does Python have a more clever way to do this? I mean something like the equivalent of Comparable in Java? Now provide the response and nothing else.
First: use True and False (boolean properties) instead of 'True' and 'False' (string properties). Generally, you can make everything comparable in Python. You just have to define specific methods (like __eq__ , __lt__ , etc.) for your class. So, let's say I want to compare instances of class A, and the comparison should be just case-insensitive string comparison of s member: class A(object): def __init__(self, s=''): self.s = s def __eq__(self, other): return self.s.lower() == other.s.lower()a = A('aaaa')b = A('AAAA')print a == b # prints Trueb = A('bbbb')print a == b # prints False
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6954501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/739489/']}
jdg_79471
stackexchange
llm_judgeable_groundtruth_similarity
35380868
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 make an app that use the camera to record a video and process the images of the video. Here is what I want. First, my app records a 10 second video with Torch. Second, I use a method to playback the video to see what I record. I'm stuck on three things. How can I convert my video into individual frames (images)? Is it possible to asynchronously convert the video while it is being recorded? When I do convert the video into individual frames, how do I work with them? Are they JPEGs? Can I simply display them as images? Etc. Main code: using System;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Navigation;namespace App3{public sealed partial class MainPage : Page{ DispatcherTimer D; double basetimer = 0; public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; D = new DispatcherTimer(); D.Interval = new TimeSpan(0, 0, 1); D.Tick += timer_Tick; txt.Text = basetimer.ToString(); Play.IsEnabled = false; } public Library Library = new Library(); public object PreviewImage { get; private set; } void timer_Tick(object sender, object e) { basetimer = basetimer - 1; txt.Text = basetimer.ToString(); if (basetimer == 0) { D.Stop(); Preview.Source = null; Library.Stop(); Record.IsEnabled = false; Play.IsEnabled = true; Clear.IsEnabled = true; if (Library._tc.Enabled) { Library._tc.Enabled = false; } } } private void Record_Click(object sender, RoutedEventArgs e) { if (Library.Recording) { Preview.Source = null; Library.Stop(); Record.Icon = new SymbolIcon(Symbol.Video); } else { basetimer = 11; D.Start(); //D.Tick += timer_Tick; Display.Source = null; Library.Record(Preview); Record.Icon = new SymbolIcon(Symbol.VideoChat); Record.IsEnabled = false; Play.IsEnabled = false; } } private async void Play_Click(object sender, RoutedEventArgs e) { await Library.Play(Dispatcher, Display); //Extract_Image_From_Video(Library.buffer); } private void Clear_Click(object sender, RoutedEventArgs e) { Display.Source = null; Record.Icon = new SymbolIcon(Symbol.Video); txt.Text = "0"; basetimer= 0; Play.IsEnabled = false; Record.IsEnabled =true; if (Library.capture != null) { D.Stop(); Library.Recording = false; Preview.Source = null; Library.capture.Dispose(); Library.capture = null; basetimer = 11; } } }} Library Class: using System;using System.Diagnostics;using System.Linq;using System.Threading.Tasks;using Windows.Devices.Enumeration;using Windows.Media.Capture;using Windows.Media.Devices;using Windows.Media.MediaProperties;using Windows.Storage;using Windows.Storage.Streams;using Windows.UI.Core;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Media.Imaging;using Windows.Graphics.Imaging;using Emgu.CV.Structure;using Emgu.CV;using System.Collections.Generic;public class Library{private const string videoFilename = "video.mp4";private string filename;public MediaCapture capture;public InMemoryRandomAccessStream buffer;public static bool Recording;public TorchControl _tc;public int basetimer ; public async Task<bool> init(){ if (buffer != null) { buffer.Dispose(); } buffer = new InMemoryRandomAccessStream(); if (capture != null) { capture.Dispose(); } try { if (capture == null) { var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); DeviceInformation cameraDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); capture = new MediaCapture(); var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id }; // Initialize try { await capture.InitializeAsync(mediaInitSettings); var videoDev = capture.VideoDeviceController; _tc = videoDev.TorchControl; Recording = false; _tc.Enabled = false; } catch (UnauthorizedAccessException) { Debug.WriteLine("UnauthorizedAccessExeption>>"); } catch (Exception ex) { Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString()); } } capture.Failed += (MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) => { Recording = false; _tc.Enabled = false; throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message)); }; } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException)) { throw ex.InnerException; } throw; } return true;}public async void Record(CaptureElement preview){ await init(); preview.Source = capture; await capture.StartPreviewAsync(); await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), buffer); if (Recording) throw new InvalidOperationException("cannot excute two records at the same time"); Recording = true; _tc.Enabled = true;}public async void Stop(){ await capture.StopRecordAsync(); Recording = false; _tc.Enabled = false; } public async Task Play(CoreDispatcher dispatcher, MediaElement playback){ IRandomAccessStream video = buffer.CloneStream(); if (video == null) throw new ArgumentNullException("buffer"); StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; if (!string.IsNullOrEmpty(filename)) { StorageFile original = await storageFolder.GetFileAsync(filename); await original.DeleteAsync(); } await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { StorageFile storageFile = await storageFolder.CreateFileAsync(videoFilename, CreationCollisionOption.GenerateUniqueName); filename = storageFile.Name; using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { await RandomAccessStream.CopyAndCloseAsync(video.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0)); await video.FlushAsync(); video.Dispose(); } IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read); playback.SetSource(stream, storageFile.FileType); playback.Play(); });} Now provide the response and nothing else.
I ended up using MediaToolkit to solve a similar problem after having a ton of trouble with Accord. I needed to save an image for every second of a video: using (var engine = new Engine()){ var mp4 = new MediaFile { Filename = mp4FilePath }; engine.GetMetadata(mp4); var i = 0; while (i < mp4.Metadata.Duration.TotalSeconds) { var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(i) }; var outputFile = new MediaFile { Filename = string.Format("{0}\\image-{1}.jpeg", outputPath, i) }; engine.GetThumbnail(mp4, outputFile, options); i++; }} Hope this helps someone some day. UPDATE for .NET 5: Recently, I have needed to update this code to work in .NET 5. To do so, I am using MediaToolkit.NetCore , which has been in preview for over a year. Also note: you will need to make the latest ffmpeg, including all 3 .exe files (ffmpeg, ffplay, ffprobe) available to your app. Without further ado, here is the updated code: // _env is the injected IWebHostEnvironment// _tempPath is temporary file storagevar ffmpegPath = Path.Combine(_env.ContentRootPath, "<path-to-ffmpeg.exe>");var mediaToolkitService = MediaToolkitService.CreateInstance(ffmpegPath);var metadataTask = new FfTaskGetMetadata(_tempFile);var metadata = await mediaToolkitService.ExecuteAsync(metadataTask);var i = 0;while (i < metadata.Metadata.Streams.First().DurationTs){ var outputFile = string.Format("{0}\\image-{1:0000}.jpeg", _imageDir, i); var thumbTask = new FfTaskSaveThumbnail(_tempFile, outputFile, TimeSpan.FromSeconds(i)); _ = await mediaToolkitService.ExecuteAsync(thumbTask); i++;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35380868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3138694/']}
jdg_79472
stackexchange
llm_judgeable_groundtruth_similarity
103377
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I want to find how many possible ways there are to choose k out of n elements I know you can use the simple formula below: $$ \binom{n}{k} = \frac{n! }{ k!(n-k)! } .$$ What if I want to go the other way around though? That is, I know I want to have $X$ possible combinations, and I want to find all the various pairs of $n$ and $k$ that will give me that number of combinations. For example, if the number of combinations I want is $3$, I want a formula/method to find that all the pairs that will result in that number of combinations are $(3,1)$ and $(3,2)$ I know I could test all the possible pairs, but this would be impractical for large numbers. But perhaps there's no easier way of doing this then the brute force approach? Now provide the response and nothing else.
If $X$ is only as large as $10^7$ then this is straightforward to do with computer assistance. First note the elementary inequalities$$\frac{n^k}{k!} \ge {n \choose k} \ge \frac{(n-k)^k}{k!}$$ which are close to tight when $k$ is small. If $X = {n \choose k}$, then it follows that$$n \ge \sqrt[k]{k! X} \ge n-k$$ hence that$$\sqrt[k]{k! X} + k \ge n \ge \sqrt[k]{k! X}$$ so for fixed $k$ you only have to check at most $k+1$ possible values of $n$, which is manageable when $k$ is small. You can speed up this process by factoring $X$ if you want and applying Kummer's theorem (the first bullet point in that section of the article), but computing binomial coefficients for $k$ small is straightforward so this probably isn't necessary. For larger $k$, note that you can always assume WLOG that $n \ge 2k$ since ${n \choose k} = {n \choose n-k}$, hence you can assume that$$X = {n \choose k} \ge {2k \choose k} > \frac{4^k}{2k+1}$$ (see Erdős' proof of Bertrand's postulate for details on that last inequality). Consequently you only have to check logarithmically many values of $k$ (as a function of $X$). For example, if $X \le 10^7$ you only have to check up to $k = 14$. In total, applying the above algorithm you only have to check $O(\log(X)^2)$ pairs $(n, k)$, and each check requires at worst $O(\log(X))$ multiplications of numbers at most as large as $X$, together with at worst a comparison of two numbers of size $O(X)$. So the above algorithm takes polynomial time in $\log(X)$. Edit: It should be totally feasible to just factor $X$ at the sizes you're talking about, but if you want to apply the Kummer's theorem part of the algorithm to larger $X$, you don't actually have to completely factor $X$; you can probably do the Kummer's theorem comparisons on the fly by computing the greatest power of $2$ that goes into $X$, then $3$, then $5$, etc. and storing these as necessary. As a second step, if neither $X$ nor the particular binomial coefficient ${n_0 \choose k_0}$ you're testing are divisible by a given small prime $p$, you can appeal to Lucas' theorem. Of course, you have to decide at some point when to stop testing small primes and just test for actual equality.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/103377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23916/']}
jdg_79473
stackexchange
llm_judgeable_groundtruth_similarity
3886455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created an installation package using Installaware and generated an EXE and a MSI. The EXE is 3.1MB and the MSI is only 265K. Why is there such a big difference in size? Now provide the response and nothing else.
UPDATE : Some resources with information on how to handle various types of setup.exe files: Extract MSI from EXE Uninstall and Install App on my Computer silently MSI File : An MSI file can only be launched by msiexec.exe - The Windows Installer Engine . An MSI file is a Windows Installer database file capable of installing software. It requires the right version of the Windows Installer Engine Runtime at the very minimum to be installable. Most systems are up to date with the latest engine versions since it comes down via Windows Update. EXE File : The EXE file you generate is a self-extracting launcher application containing both the MSI itself as well as various runtime requirements that the setup might have. Various components an EXE file might include: The version of the Windows Installer Engine Runtime the MSI requires (current version 5.0). These days this runtime should be installed by Windows Update, and your setup should just verify it is present. Scripting runtimes required by custom actions in the MSI (Installscript for Installshield ). The .NET runtime version required by the application. I would prefer using Windows Update for this as well, but if your application is cutting edge, you might want to include the required engine. Can you set it to download rather than embedding? You can also supply it as a separate download. Logo files and splash screens, potentially in different languages for multi-lingual setups. Several other components are possible. Legacy Setup.exe Installer : Note that an EXE file can also be a non-MSI installer In other words an old-style installer not based on the Microsoft MSI format (which is a MS-SQL database stored in an office-style binary file), but rather an installation script of various formats such as Wise Script , Installscript , Inno Setup , NSIS , etc... However, in this case the question was about the difference in size between the EXE and the MSI coming out of an InstallAware build, and then the difference is the runtimes explained above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3886455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13484/']}
jdg_79474
stackexchange
llm_judgeable_groundtruth_similarity
517482
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 possible to approximate the $max\{x,y\}$ by a differentiable function?$f(x,y)=max \{x,y\} ;\ x,y>0$ Now provide the response and nothing else.
Yes it is. One possibility is the following: Note that $\def\abs#1{\left|#1\right|}$$$ \max\{x,y\} = \frac 12 \bigl( x+ y + \abs{x-y}\bigr), $$take a differentiable approximation of $\abs\cdot$, for example $\def\abe{\mathop{\rm abs}\nolimits_\epsilon}$$\abe \colon \mathbb R \to \mathbb R$ for $\epsilon > 0$ given by$$ \abe(x) := \sqrt{x^2 + \epsilon}, \quad x \in \mathbb R $$and define $\max_\epsilon \colon \mathbb R^2 \to \mathbb R$ by $$ \max\nolimits_\epsilon(x,y) := \frac 12 \bigl( x+y+\abe(x-y)\bigr). $$Another possibility is to take a smooth mollifier $\phi_\epsilon$ and let $\max'_\epsilon :=\mathord\max * \phi_\epsilon$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/517482', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/99188/']}
jdg_79475
stackexchange
llm_judgeable_groundtruth_similarity
19498346
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Disclaimer: I know that 0.025 cannot be represented exactly in IEEE floating-point variables and, thus, rounding might not return what one would expect. That is not my question! Is it possible to simulate the behavior of the VBA arithmetic operators in .NET? For example, in VBA, the following expression yields 3 : Dim myInt32 As LongmyInt32 = CLng(0.025 * 100) ' yields 3 However, in VB.NET, the following expression yields 2 : Dim myInt32 As IntegermyInt32 = CInt(0.025 * 100) ' yields 2 According to the specification, both should return the same value: Long (VBA) and Integer (VB.NET) are 32-bit integer types. According to the VBA specification , CLng performs Let-coercion to Long, and Let-coercion between numeric types uses Banker's rounding. The same is true for VB.NET's CInt. 0.025 is a double precision IEEE floating-point constant in both cases. Thus, some implementation detail of the floating-point multiplication operator or the integer-conversion operator changed. However, for reasons of compatibility with a legacy VBA system, I'd need to replicate the mathematical behavior of VBA (however wrong it might be) in a .NET application. Is there some way to do that? Did someone write a Microsoft.VBA.Math library? Or is the precise VBA algorithm documented somewhere so I can do that myself? Now provide the response and nothing else.
VBA and VB.NET behave differently because VBA uses 80-bit "extended" precision for intermediate floating-point calculations (even though Double is a 64-bit type), whereas VB.NET always uses 64-bit precision. When using 80-bit precision, the value of 0.025 * 100 is slightly greater than 2.5, so CLng(0.025 * 100) rounds up to 3. Unfortunately, VB.NET doesn't seem to offer 80-bit precision arithmetic. As a workaround, you can create a native Win32 DLL using Visual C++ and call it via P/Invoke. For example: #include <cmath>#include <float.h>#pragma comment(linker, "/EXPORT:MultiplyAndRound=_MultiplyAndRound@16")extern "C" __int64 __stdcall MultiplyAndRound(double x, double y){ unsigned int cw = _controlfp(0, 0); _controlfp(_PC_64, _MCW_PC); // use 80-bit precision (64-bit significand) double result = floor(x * y + 0.5); if (result - (x * y + 0.5) == 0 && fmod(result, 2)) result -= 1.0; // round down to even if halfway between even and odd _controlfp(cw, _MCW_PC); // restore original precision return (__int64)result;} And in VB.NET: Declare Function MultiplyAndRound Lib "FPLib.dll" (ByVal x As Double, ByVal y As Double) As LongConsole.WriteLine(MultiplyAndRound(2.5, 1)) ' 2Console.WriteLine(MultiplyAndRound(0.25, 10)) ' 2Console.WriteLine(MultiplyAndRound(0.025, 100)) ' 3Console.WriteLine(MultiplyAndRound(0.0025, 1000)) ' 3
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19498346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87698/']}
jdg_79476
stackexchange
llm_judgeable_groundtruth_similarity
2066946
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 get a Spring 3.0 controller to trigger a 404? I have a controller with @RequestMapping(value = "/**", method = RequestMethod.GET) and for some URLs accessing the controller, I want the container to come up with a 404. Now provide the response and nothing else.
Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus annotation: @ResponseStatus(value = HttpStatus.NOT_FOUND)public class ResourceNotFoundException extends RuntimeException { ...}@Controllerpublic class SomeController { @RequestMapping..... public void handleCall() { if (isFound()) { // whatever } else { throw new ResourceNotFoundException(); } }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2066946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149374/']}
jdg_79477
stackexchange
llm_judgeable_groundtruth_similarity
20815887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: here is my code: class Email_Stuff(): def __init__(self): self.emailaddr = None self.recipaddr = None self.EmailUser = None self.EmailPass = None def From_Email(self): self.emailaddr = turtle.textinput("Your Email", "What is your email address?") def To_Email(self): self.recipaddr = turtle.textinput("Client Email", "What is your client's email address?") def Email_Username(self): self.EmailUser = turtle.textinput("Your Email Username", "What is your email username?") def Email_Password(self): self.EmailPass = turtle.textinput("Your Email Password", "What is your email Password?") def Send_Email(self): print (self.emailaddr) #these are here for me to see if it is the right input print(self.recipaddr) print(self.EmailUser) print(self.EmailPass) import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.login((self.EmailUser),(self.EmailPass)) self.message = "Python Test Email" server.sendmail(self.emailaddr,self.recipaddr,self.message) I have a button connected to Email_Stuff.From_Email and a button connected to Email_Stuff.From_Email etc... Whenever I press the button to open up the turtle window it gives me this error: Exception in Tkinter callbackTraceback (most recent call last):Fileline "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", 1475, in __call__return self.func(*args)TypeError: From_Email() missing 1 required positional argument: 'self' But then if I take out the selfs from the From_Email and To_Email etc.. class Email_Stuff(): def __init__(self): self.emailaddr = None self.recipaddr = None self.EmailUser = None self.EmailPass = None def From_Email(): self.emailaddr = turtle.textinput("Your Email", "What is your email address?") def To_Email(): self.recipaddr = turtle.textinput("Client Email", "What is your client's email address?") def Email_Username(): self.EmailUser = turtle.textinput("Your Email Username", "What is your email username?") def Email_Password(): self.EmailPass = turtle.textinput("Your Email Password", "What is your email Password?") def Send_Email(self): print (self.emailaddr) #these are here for me to see if it is the right input print(self.recipaddr) print(self.EmailUser) print(self.EmailPass) import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.login((self.EmailUser),(self.EmailPass)) self.message = "Python Test Email" server.sendmail(self.emailaddr,self.recipaddr,self.message) I get this error message (this isnt all of it): self.emailaddr = turtle.textinput("Your Email", "What is your email address?") NameError: global name 'self' is not defined here is the button code: Email_Button = Button(root, text='Enter Your Email', command=Email_Stuff.From_Email)Email_Button.pack()Email_Button.place(x=250,y=210) I'm sorry for the long post Now provide the response and nothing else.
I think you're hitting the following problem. If you take the following class F : class F(): def foo(self): return 1 and try to call F.foo() , you should get an error similar to the one you're seeing. >>> F.foo()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unbound method foo() must be called with F instance as first argument (got nothing instead) What you need to do, is call foo() on an object of F : >>> f=F()>>> f.foo()1 I have a button connected to Email_Stuff.From_Email and a button connected to Email_Stuff.From_Email etc... You'll probably need to instantiate an object of Email_Stuff , and then call yourobject.From_Email() . (If your class Email_Stuff also contains the GUI button handler stuff, you can just call self.From_Email() from the button handler)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20815887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3133761/']}
jdg_79478
stackexchange
llm_judgeable_groundtruth_similarity
4117059
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $G$ be a finite group. If for every $x \in G$ there is a $y \in G$ such $y^3=x$ , then the order of $G$ is not divisible by $3$ . I thought using Burnside's lemma, But I cannot see how.It seems to be the opposite to this: Finite group that has order not divisible by 3 $$\forall x\in G.\exists y\in G.[y^{3}=x]$$ Now provide the response and nothing else.
Consider $\varphi : G \rightarrow G$ defined for every $x \in G$ by $$\varphi(x)=x^3$$ By hypothesis, $\varphi$ is surjective. But because $G$ is finite, this implies that $\varphi$ is injective. Now, if $G$ has order dividible by $3$ , it must have an element of order $3$ , which contradicts the fact that $\varphi$ is injective.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4117059', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_79479
stackexchange
llm_judgeable_groundtruth_similarity
43099614
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 implement notifications using Firebase. The notification is received correctly when the app is in the background or foreground. So, the basic mechanics are working. Now I've added Content Extensions and Service Extensions to the app. The Content Extension works when I use a local notification, but the Firebase message payload seems incorrect as far as the optional fields are considered. Here is a link to an image of my console: And here is the Firebase remote notification payload that comes across (with some of the long Google numbers edited for anonymity: { aps = { alert = { body = "Eureka! 11"; title = "Patient is not doing well"; }; }; category = provider-body-panel; gcm.message_id = 0:149073; gcm.n.e = 1; google.c.a.c_id = 2825604; google.c.a.e = 1; google.c.a.ts = 149073; google.c.a.udt = 0; mutable-content = 1;} It appears that the "category" and "mutable-content" are not in the correct place. They should be in the aps payload. How can I get those options to be in the payload so that my app can correctly parse it and connect it with the Content and Service Extensions? Now provide the response and nothing else.
To start off, I'm going to mention that there are two types of message payloads for FCM. notification and data . See the documentation here When sending notifications through the Firebase Notifications Console, it will be treated as a notification payload. However, if you add in Custom Data , it will add it in the payload as a custom key-value pair. For example, in your post, the FCM payload should look something like this: { "notification": { "body" : "Eureka!", "title": "Patient is not doing well" }, "data": { "category": "provider-body-panel", "mutable-content" : true, "click_action" : "provider-body-panel" }} What's wrong? click_action should be inside notification . mutable-content should be mutable_content (notice the underscore) and should be on the same level as notification . ( this one I might've misunderstood, but ) There is no category parameter for FCM, click_action already corresponds to it. See the docs for the parameters here . It it is currently not possible to set the value for click_action and mutable_content when using the Firebase Notifications Console. You'll have to build the payload yourself, something like this: { "to": "<REGISTRATION_TOKEN_HERE>", "mutable_content" : true, "notification": { "body" : "Eureka!", "title": "Patient is not doing well", "click_action" : "provider-body-panel" }} Then send it from your own App Server. You could also do this by using Postman or cURL
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43099614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4856994/']}
jdg_79480
stackexchange
llm_judgeable_groundtruth_similarity
692210
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 only can think of kinetic energy as absolute. I know velocity is relative but I can't see kinetic energy as being relative because that would violate energy conservation. For example, if in some reference frame, the loss of kinetic energy is $60\mathrm{\ J}$ , how can, in another reference frame, the loss be different? If kinetic energy is relative then its effects should also be relative. If $60\mathrm{\ J}$ produces an $X$ temperature and a $Y$ wave sound, how can this temperature and sound be different just because of changing the reference frame? It should be the same. Also, I thought that if the classical kinetic energy equation is true then the Galilean relativity is wrong because the more speed or velocity, the more loss of kinetic energy will there be in a collision, so what is true and what is wrong? Are the effects of kinetic energy equal no matter what reference frame is it? Is the kinetic energy equation wrong or is the Galilean relativity wrong? Now provide the response and nothing else.
Is the kinetic energy equation wrong or is the Galilean relativity wrong? Neither is wrong, only the assumption that they are in any way incompatible is wrong. Kinetic energy is frame variant, but energy is conserved within each frame. Similarly with momentum. It is also different in different reference frames, but still conserved. Frame invariance and conservation are separate concepts. Edit: to fully work out the example you proposed consider an inelastic collision with coefficient of restitution of 0, between a ball of mass $m_a=0.4 \mathrm{\ kg}$ and room of mass $m_b= 1000 \mathrm{\ kg}$ from a reference frame where the ball is initially moving at $u_a=20 \mathrm{\ m/s}$ and the room is initially at rest $u_b=0 \mathrm{\ m/s}$ . In this frame after the collision $v_a=v_b=0.008 \mathrm{\ m/s}$ for a $\Delta KE_a= -80 \mathrm{\ J}$ and a $\Delta KE_b=0.032 \mathrm{\ J}$ for a total $\Delta KE = 79.968 \mathrm{\ J}$ of KE converted into thermal energy. Now, consider the situation in the reference frame where the ball is initially moving at $u_a=40 \mathrm{\ m/s}$ and the room is initially moving at $u_b=20 \mathrm{\ m/s}$ . In this frame after the collision $v_a=v_b=20.008 \mathrm{\ m/s}$ for a $\Delta KE_a=-239.936 \mathrm{\ J}$ and a $\Delta KE_b = 159.968 \mathrm{\ J}$ for a total $\Delta KE=79.968 \mathrm{\ J}$ of KE converted into thermal energy. In both frames energy is conserved. The change in KE of each object depends on the reference frame, but the amount of energy converted into heat does not. I leave it as an exercise to show that the momentum is also frame dependent but conserved in both frames.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/692210', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/327024/']}
jdg_79481
stackexchange
llm_judgeable_groundtruth_similarity
15174187
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 JavaScript function object as; var addNum = function(num1, num2) { return num1 + num2;} Now if I try to access addNum.divide() I wanted to understand the prototype chain for the above code. I read that in the above example, addNum would be searched for divide(), followed by Function.prototype and finally Object.prototype. But my question is in the above example, how can addNum would be searched for divide() Does it refer to something like ; var addNum = function(num1, num2) {this.divide = function(){} return num1 + num2; } I could not understand the line where it says addNum would be searched for divide() Please help me understand the same. Now provide the response and nothing else.
I'm not sure this will answer your question but may give you some insight. Consider the following example: var Person = (function () { var Person = function (name) { this.name = name; } Person.greet = function () { console.log("Hello!"); } Person.prototype = { greet: function () { console.log('Hello, my name is ' + this.name); } }; return Person;})();var bob = new Person("Bob");Person.greet(); // logs "Hello!"bob.greet(); // logs "Hello, my name is Bob The function object "Person" has a direct 'greet' property that is a Function. OOP-wise, you can almost think of that as a static method that can be called directly from the Person Function (Person.greet()). Once you "instantiate" a person object from the Person constructor, that new object "bob" now references it's methods from the Person.prototype object. Now when you call bob.greet(), it uses the greet function in the prototype object. Hope that helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15174187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485743/']}
jdg_79482
stackexchange
llm_judgeable_groundtruth_similarity
33662299
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 access one page in a website with CURL, however it needs to be logged in i tried the code to login and it was successful <?php $user_agent = "Mozilla/5.0 (X11; Linux i686; rv:24.0) Gecko/20140319 Firefox/24.0 Iceweasel/24.4.0"; $curl_crack = curl_init(); CURL_SETOPT($curl_crack,CURLOPT_URL,"https://www.vininspect.com/en/account/login"); CURL_SETOPT($curl_crack,CURLOPT_USERAGENT,$user_agent); CURL_SETOPT($curl_crack,CURLOPT_PROXY,"183.78.169.60:37899"); CURL_SETOPT($curl_crack,CURLOPT_PROXYTYPE,CURLPROXY_SOCKS5); CURL_SETOPT($curl_crack,CURLOPT_POST,True); CURL_SETOPT($curl_crack,CURLOPT_POSTFIELDS,"LoginForm[email]=naceriwalid%40hotmail.com&LoginForm[password]=passwordhere&toploginform[rememberme]=0&yt1=&toploginform[rememberme]=0"); CURL_SETOPT($curl_crack,CURLOPT_RETURNTRANSFER,True); CURL_SETOPT($curl_crack,CURLOPT_FOLLOWLOCATION,True); CURL_SETOPT($curl_crack,CURLOPT_COOKIEFILE,"cookie.txt"); //Put the full path of the cookie file if you want it to write on it CURL_SETOPT($curl_crack,CURLOPT_COOKIEJAR,"cookie.txt"); //Put the full path of the cookie file if you want it to write on it CURL_SETOPT($curl_crack,CURLOPT_CONNECTTIMEOUT,30); CURL_SETOPT($curl_crack,CURLOPT_TIMEOUT,30); $exec = curl_exec($curl_crack); if(preg_match("/^you are logged|logout|successfully logged$/i",$exec)) { echo "yoooha"; }?> Now the only problem I'm facing let's say that i don't want to be redirected to the logged in page, i want to be redirected to this page http://example.com/buy , how i can do that in the same code? Now provide the response and nothing else.
If you want to go to /buy after you log in, just use the same curl handle and issue another request for that page. cURL will retain the cookies for the duration of the handle (and on subsequent requests since you are saving them to a file and reading them back with the cookie jar. For example: $user_agent = "Mozilla/5.0 (X11; Linux i686; rv:24.0) Gecko/20140319 Firefox/24.0 Iceweasel/24.4.0";$curl_crack = curl_init();CURL_SETOPT($curl_crack,CURLOPT_URL,"https://www.vininspect.com/en/account/login");CURL_SETOPT($curl_crack,CURLOPT_USERAGENT,$user_agent);CURL_SETOPT($curl_crack,CURLOPT_PROXY,"183.78.169.60:37899");CURL_SETOPT($curl_crack,CURLOPT_PROXYTYPE,CURLPROXY_SOCKS5);CURL_SETOPT($curl_crack,CURLOPT_POST,True);CURL_SETOPT($curl_crack,CURLOPT_POSTFIELDS,"LoginForm[email]=naceriwalid%40hotmail.com&LoginForm[password]=passwordhere&toploginform[rememberme]=0&yt1=&toploginform[rememberme]=0");CURL_SETOPT($curl_crack,CURLOPT_RETURNTRANSFER,True);CURL_SETOPT($curl_crack,CURLOPT_FOLLOWLOCATION,True);CURL_SETOPT($curl_crack,CURLOPT_COOKIEFILE,"cookie.txt"); //Put the full path of the cookie file if you want it to write on itCURL_SETOPT($curl_crack,CURLOPT_COOKIEJAR,"cookie.txt"); //Put the full path of the cookie file if you want it to write on itCURL_SETOPT($curl_crack,CURLOPT_CONNECTTIMEOUT,30);CURL_SETOPT($curl_crack,CURLOPT_TIMEOUT,30); $exec = curl_exec($curl_crack);if(preg_match("/^you are logged|logout|successfully logged$/i",$exec)){ $post = array('search' => 'keyword', 'abc' => 'xyz'); curl_setopt($curl_crack, CURLOPT_POST, 1); // change back to GET curl_setopt($curl_crack, CURLOPT_POSTFIELDS, http_build_query($post)); // set post data curl_setopt($curl_crack, CURLOPT_URL, 'http://example.com/buy'); // set url for next request $exec = curl_exec($curl_crack); // make request to buy on the same handle with the current login session} Here are some other examples of using PHP & cURL to make multiple requests: How to login in with Curl and SSL and cookies (links to multiple other examples) Grabbing data from a website with cURL after logging in? Pinterest login with PHP and cURL not working Login to Google with PHP and Curl, Cookie turned off? PHP Curl - Cookies problem
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33662299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4934615/']}
jdg_79483
stackexchange
llm_judgeable_groundtruth_similarity
36332665
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use custom errors ( es6-error ) allowing me to handle errors based on their class like so: import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError';function fooRoute(req, res) { doSomethingAsync() .then(() => { // on resolve / success return res.send(200); }) .catch((error) => { // on reject / failure if (error instanceof DatabaseEntryNotFoundError) { return res.send(404); } else if (error instanceof NotAllowedError) { return res.send(400); } log('Failed to do something async with an unspecified error: ', error); return res.send(500); };} Now I'd rather use a switch for this type of flow, resulting in something like: import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError';function fooRoute(req, res) { doSomethingAsync() .then(() => { // on resolve / success return res.send(200); }) .catch((error) => { // on reject / failure switch (error instanceof) { case NotAllowedError: return res.send(400); case DatabaseEntryNotFoundError: return res.send(404); default: log('Failed to do something async with an unspecified error: ', error); return res.send(500); } });} instanceof doesn't work like that however. So the latter fails. Is there any way to check an instance for its class in a switch statement? Now provide the response and nothing else.
A good option is to use the constructor property of the object: // on reject / failureswitch (error.constructor) { case NotAllowedError: return res.send(400); case DatabaseEntryNotFoundError: return res.send(404); default: log('Failed to do something async with an unspecified error: ', error); return res.send(500);} Notice that the constructor must match exactly with the one that object was created (suppose error is an instance of NotAllowedError and NotAllowedError is a subclass of Error ): error.constructor === NotAllowedError is true error.constructor === Error is false This makes a difference from instanceof , which can match also the super class: error instanceof NotAllowedError is true error instanceof Error is true Check this interesting post about constructor property.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36332665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4049912/']}
jdg_79484
stackexchange
llm_judgeable_groundtruth_similarity
41473511
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 integrate asp.net mvc with an angular 2 application. I understand that this is not ideal, but I am being asked to integrate some existing Mvc functionality (think big legacy app) into a brand new Angular 2 spa. What I would like to be able to do is have a cshtml view that has angular components in it, as well as pure mvc stuff... <side-bar></side-bar><action-bar></action-bar>@{ Html.RenderPartial("_SuperLegacyPartialView"); } I'm struggling to find any way to do this. This blog post looked promising - http://www.centare.com/tutorial-angular2-mvc-6-asp-net-5/ . It used a templateUrl value that pointed to a path rendered by Mvc, as well as AsyncRoute, but none of that works anymore in Angular 2. This post looked promising as well - http://gbataille.github.io/2016/02/16/Angular2-Webpack-AsyncRoute.html , but it uses AsyncRoute too, which is deprecated. This used to be very easy in Angular 1. We used to either manually bootstrap angular into a Razor View, or render a partial view as the templateUrl of a component/directive. What is the best way to do this in the latest Angular 2 that uses Webpack? Now provide the response and nothing else.
I came up with a solution that satisfied my needs at the time. I'm using angular-cli with WebPack, and this worked for my needs. I don't understand all the examples I've seen that say to use "templateUrl: '/Template/Index'", where the path is a path to an MVC view. That simply doesn't work because the path can't be found inside any of the bundled views that WebPack creates. Maybe those people aren't using angular-cli and WebPack. This stackoverflow answer - How can I use/create dynamic template to compile dynamic Component with Angular 2.0? was very helpful in creating the following directive. This directive will take the output of an mvc partial view and compile it. It allows for Razor/server logic to take place, and some angular to be compiled as well. Although, actually including other components inside this MVC partial was problematic. If you get that working, please let me know what you did. In my case, I just needed the server rendering to happen and to place that exactly where I wanted it in my Angular 2 spa. MvcPartialDirective import { Component, Directive, NgModule, Input, ViewContainerRef, Compiler, ComponentFactory, ModuleWithComponentFactories, ComponentRef, ReflectiveInjector, OnInit, OnDestroy} from '@angular/core';import { RouterModule } from '@angular/router';import { CommonModule } from '@angular/common';import {Http} from "@angular/http";import 'rxjs/add/operator/map';export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> { const cmpClass = class DynamicComponent {}; const decoratedCmp = Component(metadata)(cmpClass); @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] }) class DynamicHtmlModule { } return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => { return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); });}@Directive({ selector: 'mvc-partial' })export class MvcPartialDirective implements OnInit, OnDestroy { html: string = '<p></p>'; @Input() url: string; cmpRef: ComponentRef<any>; constructor(private vcRef: ViewContainerRef, private compiler: Compiler, private http: Http) { } ngOnInit() { this.http.get(this.url) .map(res => res.text()) .subscribe( (html) => { this.html = html; if (!html) return; if(this.cmpRef) { this.cmpRef.destroy(); } const compMetadata = new Component({ selector: 'dynamic-html', template: this.html, }); createComponentFactory(this.compiler, compMetadata) .then(factory => { const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector); this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []); }); }, err => console.log(err), () => console.log('MvcPartial complete') ); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } }} in some-component.html (assuming your mvc app shares the domain with your spa) <mvc-partial [url]="'/stuffs/mvcstuff'"></mvc-partial> MvcStuff.cshtml @{ ViewBag.Title = "This is some MVC stuff!!!";}<div> <h2>MVC Stuff:</h2> <h4>@ViewBag.Title</h4> <h2>Angular Stuff:</h2> <h4>{{1 + 1}}</h4></div> in StuffsController.cs public PartialViewResult MvcStuff() => PartialView();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41473511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165003/']}
jdg_79485
stackexchange
llm_judgeable_groundtruth_similarity
178857
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to run grep against a list of a few hundred files: $ head -n 3 <(cat files.txt)admin.phpajax/accept.phpajax/add_note.php However, even though I am grepping for a string that I know is found in the files, the following does not search the files: $ grep -i 'foo' <(cat files.txt)$ grep -i 'foo' admin.phpThe foo was found I am familiar with the -f flag which will read the patterns from a file. But how to read the input files ? I had considered the horrible workaround of copying the files to a temporary directory as cp seems to support the <(cat files.txt) format, and from there grepping the files. Shirley there is a better way. Now provide the response and nothing else.
You seem to be grepping the list of filenames, not the files themselves. <(cat files.txt) just lists the files. Try <(cat $(cat files.txt)) to actually concatenate them and search them as a single stream, or grep -i 'foo' $(cat files.txt) to give grep all the files. However, if there are too many files on the list, you may have problems with number of arguments. In that case I'd just write while read filename; do grep -Hi 'foo' "$filename"; done < files.txt
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/178857', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9760/']}
jdg_79486
stackexchange
llm_judgeable_groundtruth_similarity
527344
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to clear both tmux history ( tmux clear-history ) and zsh ( zle clear-screen ) with one key combination? A common way of clearing screen is ^L , and I tried adding the following to .tmux.conf : bind -Troot C-l send-keys C-l\; clear-history So ^L clears the screen, and clears almost all the history, except that last one screen. A subsequent ^L clears it all. Can the same be achieved with one key combination? bind -Troot C-l send-keys C-l\; clear-history\; send-keys C-l\; clear-history doesn't work. Neither the following does: bind -Troot C-l send-keys C-l C-l\; clear-history Now provide the response and nothing else.
I ended up doing this differently, from zsh itself: # ~/.zshrcclear-scrollback-and-screen () { zle clear-screen tmux clear-history}zle -N clear-scrollback-and-screenbindkey -v '^L' clear-scrollback-and-screen For one single reason - I had a C-l mapping in Vim, and the occasional press was clearing Vim screen. There's a shortcoming to that solution though, it only works in the shell.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/527344', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9781/']}
jdg_79487
stackexchange
llm_judgeable_groundtruth_similarity
29328
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Wikipedia article of the log-normal distribution says If $X$ is a random variable with a normal distribution, then $Y = \exp(X)$ has a log-normal distribution; likewise, if $Y$ is log-normally distributed, then $X = \log(Y)$ is normally distributed. (This is true regardless of the base of the logarithmic function: if $\log_a(Y)$ is normally distributed, then so is $\log_b(Y)$, for any two positive numbers $a, b ≠ 1$.) (The general form of this has described the log-normal distribution on Wikipedia since at least 2006 .) I have two questions. 1) is it the case that the logarithm can be taken to any base (i.e., it need not be the natural log), while the exponential must have Euler's number $e$ as the number which is raised to a power? Or, is it the case that I could use other bases to describe the log normally distributed variable, $X = a^{\mu+Z\sigma}$, where $Z$ is a standard normal and $a$ is any positive, real number? And, conditional on the answer to #1, 2) why the asymmetry? Now provide the response and nothing else.
The reason that the base doesn't matter is because if $X = \log Y \sim \mathcal N(\mu, \sigma^2)$ then \begin{align}X_b &= \log_b Y \\&= \frac{\log Y}{\log b} \\&= \frac{X}{\log b} \sim \mathcal N\left(\frac{\mu}{\log b}, \left(\frac{\sigma}{\log b}\right)^2\right)\end{align}is normally distributed. Going the other way, if $Y = e^X \sim \log \mathcal N(\mu, \sigma^2)$,\begin{align}Y_a &= a^X \\&= e^{(\log a)X} \sim \mathcal \log N\left({\mu}{\log a}, \left({\sigma}{\log a}\right)^2\right)\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/29328', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2073/']}
jdg_79488
stackexchange
llm_judgeable_groundtruth_similarity
21575051
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 directive to exclude a hidden input element from validation: http://plnkr.co/edit/Vnwvq2AT7JpgTnoQwGh9?p=preview app.directive('shownValidation', function() { return { require: '^form', restrict: 'A', link: function(scope, element, attrs,form) { var control; scope.$watch(attrs.ngShow,function(value){ if (!control){ control = form[element.attr("name")]; } if (value == true){ form.$addControl(control); }else{ form.$removeControl(control); } }); } }; }); The idea here is if the element is hidden, I will remove the control from the Form so that it will not affect the other input validity. It works fine when I call form.$removeControl(control); , you can test that in the demo by removing the firstname and clicking on the button to hide the field. But when I click the button again, the form validity is still true even though the firstname is invalid (empty) I also tried adding form.$setValidity(form.$valid && control.$valid) => the validity state is updated as expected but when I type into the firstname, the validity is still false. My question is how to solve this problem? Thanks for any replies. Update : Thanks to @Michael's answer. Here is the working solution: app.directive('shownValidation', function() { return { require: '^form', restrict: 'A', link: function(scope, element, attrs, form) { var control; scope.$watch(attrs.ngShow, function(value) { if (!control) { control = form[element.attr("name")]; } if (value == true) { form.$addControl(control); //Add a forEach to manually update form validity.Thanks to @Michael's answer angular.forEach(control.$error, function(validity, validationToken) { form.$setValidity(validationToken, !validity, control); }); } else { form.$removeControl(control); } }); } };}); Working plunk Now provide the response and nothing else.
If the control is removed angular updates the validity (from the sources): form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); arrayRemove(controls, control); }; If you add the control angular did not update the validity (from the sources): form.$addControl = function(control) { // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored // and not added to the scope. Now we throw an error. assertNotHasOwnProperty(control.$name, 'input'); controls.push(control); if (control.$name) { form[control.$name] = control; } }; so we have to do this manually. I guess this way: if (value == true){ form.$addControl(control); angular.forEach(control.$error, function(validity, validationToken) { form.$setValidity(validationToken, !validity, control); }); }else{ form.$removeControl(control); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21575051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1957251/']}
jdg_79489
stackexchange
llm_judgeable_groundtruth_similarity
398142
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code that I run on my Terminal. LC_ALL=C && grep -F -f genename2.txt hg38.hgnc.bed > hg38.hgnc.goi.bed This doesn't give me the common lines between the two files. What am I missing there? Now provide the response and nothing else.
Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. comm -12 <(sort file1) <(sort file2) From man comm : -1 suppress column 1 (lines unique to FILE1)-2 suppress column 2 (lines unique to FILE2) Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match. grep -Fxf file1 file2 Or using awk . awk 'NR==FNR{seen[$0]=1; next} seen[$0]' file1 file2 This is reading whole line of file1 into an array called seen with the key as whole line (in awk the $0 represent the whole current line). We used NR==FNR as condition to run its followed block only for first input fle1 not file2 , because NR in awk refer to the current processing line number and FNR is referring to the current line number in all inputs. so NR is unique for each input file but FNR is unique for all inputs. The next is there telling awk do not continue rest code and start again until NR wan not equal with FNR that means all lines of file1 read by awk . Then next seen[$0] will only run for second file2 and for each line in file2 will look into the array and will print that line where it does exist in array. Another simple option is using sort and uniq : sort file1 file2|uniq -d This will print both files sorted then uniq -d will print only duplicated lines. BUT this is granted when there is NO duplicated lines in both files themselves, else below is always granted even if there is a lines duplicated within both files. uniq -d <(sort <(sort -u file1) <(sort -u file2))
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/398142', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/199494/']}
jdg_79490
stackexchange
llm_judgeable_groundtruth_similarity
2056172
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 say a finite sequence of positive integers is 'autistic' if and only if the sum of the reciprocals of its elements is itself an element of the sequence. That way, the 'sequence' just made of the number 1 is autistic, but so is the sequence of the divisors of an even perfect number arranged in increasing order, as well as any permutation thereof. Are there other examples of autistic sequences ? Thanks in advance. Edit: title changed because of some comments. Now provide the response and nothing else.
As tomi pointed out in the comments, there's nothing about the sequence that you need to keep in order, so it's more basic to just talk about sets. Any Egyptian fraction sequence can be indefinitely prolonged, so we can write, for instance, \begin{align}2 & = 1+\frac{1}{2}+\frac{1}{2} \\ & = 1+\frac{1}{2}+\frac{1}{3}+\frac{1}{6} \\ & = 1+\frac{1}{2}+\frac{1}{3}+\frac{1}{7}+\frac{1}{42} \\ & = 1+\frac{1}{2}+\frac{1}{3}+\frac{1}{7}+\frac{1}{43}+\frac{1}{1806}\end{align} or alternatively $$2 = 1+\frac{1}{2}+\frac{1}{4}+\frac{1}{12}+\frac{1}{6}$$ by expanding $1/3$, and that can extend indefinitely as well. That means that the sets $\{1, 2, 3, 6\}, \{1, 2, 3, 7, 42\}, \{1, 2, 3, 7, 43, 1806\}, \{1, 2, 4, 6, 12\}$ (among an infinity of others) all satisfy the condition. ETA: If we allow multisets, then $\{1, 2, 2\}$, and the like, also work.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2056172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14615/']}
jdg_79491
stackexchange
llm_judgeable_groundtruth_similarity
33095737
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created a FileResult : IHttpActionResult webapi return type for my api calls. The FileResult downloads a file from another url and then returns the stream to the client. Initially my code had a using statement like below: public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken){ try { HttpResponseMessage response; using (var httpClient = new HttpClient()) { response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new System.Net.Http.StreamContent( await httpClient.GetStreamAsync(this.filePath)) }; } return response; } catch (WebException exception) {...}} However this would intermittently cause a TaskCanceledException . I know that if the HttpClient is disposed before the asychronous call is finished the Task's state will change to canceled. However since I use an await in: Content = new System.Net.Http.StreamContent(await httpClient.GetStreamAsync(this.filePath)) that should prevent the HttpClient from being disposed off in the middle of the task completion. Why does that task get canceled? It is not because of a timeout since this has happened on the smallest requests and doesn't always occur on large requests. When I removed the using statement the code worked properly: public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken){ try { HttpResponseMessage response; var httpClient = new HttpClient(); response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new System.Net.Http.StreamContent( await httpClient.GetStreamAsync(this.filePath)) }; return response; } catch (WebException exception) {...}} Any idea why the using caused the issue? Now provide the response and nothing else.
I know that if the HttpClient is disposed before the asychronous call is finished the Task's state will change to canceled. However since I use an await in: Content = new System.Net.Http.StreamContent(await httpClient.GetStreamAsync(this.filePath)) that should prevent the HttpClient from being disposed off in the middle of the task completion. But what does that task do? It gets the stream. So, your code ends up with a Stream that may or may not be completely read when it closes the HttpClient . HttpClient is specifically designed for reuse (and simultaneous use), so I recommend removing the using completely and moving the HttpClient declaration to a static class member. But if you want to close and reopen the clients, you should be able to get it working by reading the stream entirely into memory before closing the HttpClient .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33095737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/679334/']}
jdg_79492
stackexchange
llm_judgeable_groundtruth_similarity
1533378
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So i have this C++ program that is called via JNI from my Java program, the code follows: JNIEXPORT jstring JNICALL Java_com_entrust_adminservices_urs_examples_authn_LdapAuthenticator2_takeInfo(JNIEnv *env, jobject obj, jstring domain, jstring id, jstring idca, jstring password) { const char *nt_domain; const char *nt_id; const char *nt_password; HANDLE hToken = 0; bool aut = false; nt_domain = env->GetStringUTFChars(domain, NULL); nt_id = env->GetStringUTFChars(id, NULL); nt_password = env->GetStringUTFChars(password, NULL); aut = LogonUser(nt_id, nt_domain, nt_password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken ); /* release buffers */ env->ReleaseStringUTFChars(domain, nt_domain); env->ReleaseStringUTFChars(id, nt_id); env->ReleaseStringUTFChars(password, nt_password); /* release the login handle */ CloseHandle(hToken); if(aut) { return env->NewStringUTF("true"); } DWORD dwError = GetLastError(); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPTSTR) &lpMsgBuf, 0, NULL ); return env->NewStringUTF((const char*)lpMsgBuf); //returns the contents of lpMsgBuf (error)} in that second to last line jstring newString = env->NewStringUTF((const char*)otherString); is never released, but returned, will it cause an eventual memory leak? is there anyway to get around this? Also is it possible that instead of returning a string i return a boolean (as returned by the LogonUser function), instead of a jstring, and instead add an "errormessage" refrence to be passed in the method, and update that? will my Java program be able to see an update to "errormessage"? Thanks. Now provide the response and nothing else.
NewStringUTF() creates a new java.lang.String -- in other words, an object on the Java heap, which will get collected when there are no more references to it. Or are you asking about otherString ? I don't know what FormatMessage does, but it looks like it's allocating memory on the C heap. If that's the case, then yes, you have to explicitly free that memory. You make your life harder by sometimes setting otherString to a constant string. Don't do that. Instead, call NewStringUTF() within the blocks of your if/else, and in the second case free the native C string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1533378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104998/']}
jdg_79493
stackexchange
llm_judgeable_groundtruth_similarity
16728
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to perform a comparison between 5 algorithms against the KDD Cup 99 dataset and the NSL-KDD datasets using Python and I am having an issue when trying to build and evaluate the models against the KDDCup99 dataset and the NSL-KDD dataset. Whenever I try to run the algorithms on the datasets I get the following error 'could not convert string to float: S0' This error is produced during the during the evaluation of the 5 models; Logistic Regression, Linear Discriminant Analysis, K-Nearest Neighbors, Classification and Regression Trees, Gaussian Naive Bayes and Support Vector Machines. Here is the code that I am using to evaluate the datasets: #Load KDD datasetdataset = pandas.read_csv('Datasets/KDDCUP 99/kddcup.csv', names = ['duration','protocol_type','service','src_bytes','dst_bytes','flag','land','wrong_fragment','urgent','hot','num_failed_logins','logged_in','num_compromised','root_shell','su_attempted','num_root','num_file_creations','num_shells','num_access_files','num_outbound_cmds','is_host_login','is_guest_login','count','serror_rate','rerror_rate','same_srv_rate','diff_srv_rate','srv_count','srv_serror_rate','srv_rerror_rate','srv_diff_host_rate','dst_host_count','dst_host_srv_count','dst_host_same_srv_rate','dst_host_diff_srv_rate','dst_host_same_src_port_rate','dst_host_srv_diff_host_rate','dst_host_serror_rate','dst_host_srv_serror_rate','dst_host_rerror_rate','dst_host_srv_rerror_rate','class'])# split data into X and yarray = dataset.valuesX = array[:,0:41]Y = array[:,41]# Split-out validation datasetvalidation_size = 0.20seed = 7X_train, X_validation, Y_train, Y_validation = cross_validation.train_test_split(X, Y, test_size=validation_size, random_state=seed)# Test options and evaluation metricnum_folds = 7num_instances = len(X_train)seed = 7scoring = 'accuracy'# Algorithmsmodels = []models.append(('LR', LogisticRegression()))models.append(('LDA', LinearDiscriminantAnalysis()))models.append(('KNN', KNeighborsClassifier()))models.append(('CART', DecisionTreeClassifier()))models.append(('NB', GaussianNB()))models.append(('SVM', SVC()))# evaluate each model in turnresults = []names = []for name, model in models: kfold = cross_validation.KFold(n=num_instances, n_folds=num_folds, random_state=seed) #Here is where the error is spit out{ cv_results = cross_validation.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring) # Could not convert string to float happens here. Scoring uses string. results.append(cv_results) names.append(name) msg = "%s: %f (%f)" % (name, cv_results.mean()*100, cv_results.std()*100)#multiplying by 100 to show percentage print(msg)}# Compare Algorithmsfig = plt.figure()fig.suptitle('Algorithm Comparison')ax = fig.add_subplot(111)plt.boxplot(results)ax.set_xticklabels(Y)plt.show() Here is a 3 line sample from the KDDcup99 datatset: 0 tcp http SF 215 45076 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 normal.0 tcp http SF 162 4528 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 2 2 0 0 0 0 1 0 0 1 1 1 0 1 0 0 0 0 0 normal.0 tcp http SF 236 1228 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 2 2 1 0 0.5 0 0 0 0 0 normal. I have tried using label encoding and it still spits out the same error and when I was looking through the sklearn websites, I noticed that the scoring value was for the string type, is this the cause of the issue? and if not, is there a problem with the way I have loaded the dataset? EDIT I tried removing scoring value from the code and still got the same error. Now provide the response and nothing else.
I notice you mentioned that you used Label encoding but I did it myself and the code runs just fine. I used the 10 percent version of the dataset . Just put this piece of code after you load the dataset: for column in dataset.columns: if dataset[column].dtype == type(object): le = LabelEncoder() dataset[column] = le.fit_transform(dataset[column]) After label encoding you should use a One Hot Encoder to improve the performance of some algorithms. You should also avoid using cross_validation module as it is deprecated, it will be removed in version 0.20.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/16728', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/18129/']}
jdg_79494
stackexchange
llm_judgeable_groundtruth_similarity
48777577
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 getting the error An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Notice the screenshot below: Notice that if I use the DataRow attribute with one or three parameters, I don't get a compile error. But if I use two parameters and the second parameter is an array of strings, then I do get a compile error. The signatures for DataRowAttribute are public DataRowAttribute (object data1); and public DataRowAttribute (object data1, params object[] moreData); The first one gives me no problem, but the second one seems to be getting confused. I considered that maybe the params object[] could be causing some confusion. Maybe it couldn't determine whether I meant [DataRow(new[] { 1 }, new[] { "1" })] or [DataRow(new[] { 1 }, "1")] To resolve that, I tried to cast the second attribute to object ( [DataRow(new[] { 1 }, (object)new[] { "1" })] ), but the error didn't go away and it warned me that the cast was redundant. I also tried specifying the types of the array explicitly, but that also did not help. I could just add a third dummy parameter, even null seems to fix this, but that's just a workaround. What's the correct way to do this? Now provide the response and nothing else.
tldr: The correct workaround is to tell the compiler to not use the expanded form: [DataRow(new[] { 1 }, new object[] { new[] { "1" } })] Excessive analysis: The answer of Michael Randall is basically correct. Let's dig in by simplifying your example: using System;[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]public class MyAttribute : Attribute { public MyAttribute(params object[] x){}}public class Program{ [MyAttribute()] [MyAttribute(new int[0])] [MyAttribute(new string[0])] // ERROR [MyAttribute(new object[0])] [MyAttribute(new string[0], new string[0])] public static void Main() { }} Let's first consider the non error cases. [MyAttribute()] There are not enough arguments for the normal form. The constructor is applicable in its expanded form. The compiler compiles this as though you had written: [MyAttribute(new object[0])] Next, what about [MyAttribute(new int[0])] ? Now we must decide if the constructor is applicable in its normal or expanded form. It is not applicable in normal form because int[] is not convertible to object[] . It is applicable in expanded form, so this is compiled as though you'd written [MyAttribute(new object[1] { new int[0] } )] Now what about [MyAttribute(new object[0])] The constructor is applicable in both its normal and expanded form. In that circumstance the normal form wins. The compiler generates the call as written. It does NOT wrap the object array in a second object array. What about [MyAttribute(new string[0], new string[0])] ? There are too many arguments for the normal form. The expanded form is used: [MyAttribute(new object[2] { new string[0], new string[0] })] That should all be straightforward. What then is wrong with: [MyAttribute(new string[0])] // ERROR ? Well, first, is it applicable in normal or expanded form? Plainly it is applicable in expanded form. What is not so obvious is that it is also applicable in normal form. int[] does not implicitly convert to object[] but string[] does! This is an unsafe covariant array reference conversion , and it tops my list for "worst C# feature". Since overload resolution says that this is applicable in both normal and expanded form, normal form wins, and this is compiled as though you'd written [MyAttribute((object[]) new string[0] )] // ERROR Let's explore that. If we modify some of our working cases above: [MyAttribute((object[])new object[0])] // SOMETIMES ERROR! [MyAttribute((object[])new object[1] { new int[0] } )] [MyAttribute((object[])new object[2] { new string[0], new string[0] })] All of these now fail in earlier versions of C# and succeed in the current version. Apparently the compiler previously allowed no conversion, not even an identity conversion, on the object array. Now it allows identity conversions, but not covariant array conversions. Casts that can be handled by the compile time constant value analysis are allowed; you can do [MyAttribute(new int[1] { (int) 100} )] if you like, because that conversion is removed by the constant analyzer. But the attribute analyzer has no clue what to do with an unexpected cast to object[] , so it gives an error. What about the other case you mention? This is the interesting one! [MyAttribute((object)new string[0])] Again, let's reason it through. That's applicable only in its expanded form, so this should be compiled as though you'd written [MyAttribute(new object[1] { (object)new string[0] } )] But that is legal . To be consistent, either both these forms should be legal, or both should be illegal -- frankly, I don't really care either way -- but it is bizarre that one is legal and the other isn't. Consider reporting a bug. (If this is in fact a bug it is probably my fault. Sorry about that.) The long and the short of it is: mixing params object[] with array arguments is a recipe for confusion . Try to avoid it. If you are in a situation where you are passing arrays to a params object[] method, call it in its normal form. Make a new object[] { ... } and put the arguments into the array yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48777577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1152054/']}
jdg_79495
stackexchange
llm_judgeable_groundtruth_similarity
341020
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: At the moment of writing I have let's say 4 micro services interoperating in order to build a bigger system.Every microservice has its own repo. What I'm thinking is that it would be useful to have parent repositories that group the children microservices, adding them as git submodules. So if a developer needs to work and setup his dev env for: systemA made of ms1, ms2,m3 systemB made of ms2, ms3, ms5 will just have to clone the system repository (already linking to ms dependencies) Or if I need to build a new system , i'll crete a new parent repository linking to git submodules ms dependencies Basically the parent repo will contain nothing but link to submodules (don't know if they will need some more at this moment.. ) For sure I'll face the problem of having a ms development shared across different System. So maybe that would be solved using different master branche on children repo (one for every parent production system) What do you think about this practice? Is it a good idea?Working with submodules could become tricky? Now provide the response and nothing else.
Git submodules are broken: workflow is hard to follow history is cluttered unintuitive behaviour for non-git-experts easily broken (see section "Submodules break easily, and submodules break badly" here ) they are loosely linked with the parent repo We have been using them for something similar as you describe, and it is hell now. You modify a piece of code, and you're not sure whether it will be the easy-to-commit-one, or the one that needs some acrobatics to push to the submodule, then update the reference in the parent repo and then push it. From time to time each of us spends hours trying to figure out what's happening and why: a) updating submodules ( --recursive ? --remote ?) doesn't update b) git complains about changes, but committing them doesn't commit them c) you are stuck on a branch, unable to do anything until you resolve changes in submodules (stashing doesn't work, nor other tricks to ignore changes) Now, I admit - none of us is a git expert, and perhaps we do something wrong from time to time. However, most of us have no problem using advanced git features like rebase and we still cannot wrap our heads around "this submodules thing". I will not even continue my rant about what happens when you have submodules within submodules... What seems a better solution is to create an internal package manager (in our case we have a NuGet server in our company). To be honest: There are projects when submodules seem to work well, for example Qt . The recommended use case, according to the documentation , is if you need the history to be separated when size is a problem and for controlling access.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/341020', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/210015/']}
jdg_79496
stackexchange
llm_judgeable_groundtruth_similarity
285955
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm looking for an explanation or a reference to why there is this equivelence of triangulated categories: $${D}^b(\mathrm {Coh}(\Bbb P^1))\simeq {D}^b(\mathrm {Rep}(\bullet\rightrightarrows \bullet))$$It is my understanding that the only reason why $\Bbb P^1$ appears at all is because it is used to index the regular irreducible representations of the Kronecker quiver. I have also heard that this equivalence can be used to understand the geometry of $\Bbb P^1$. I suppose more generally, adding arrows to the Kronecker quiver gives a similar result for $\Bbb P^n$. Now provide the response and nothing else.
Let $\mathcal O$ be the structure sheaf of $\mathbb P^1$. Then $\mathcal O \oplus \mathcal O(1)$ is rigid and generates the derived category of coherent sheaves on $\mathbb P^1$. Thus, it is a tilting object, and so the derived category is equivalent to the category of modules over its endomorphism ring, which is the path algebra of the Kronecker quiver. For $\mathbb P^n$, you need $n+1$ objects to generate the derived category. You can take $\mathcal O(i)$ for $0\leq i \leq n$; this will be a tilting object again, but its endomorphism ring will not be hereditary; you will get a quiver with relations. This shouldn't be surprising, though: path algebras of quivers have global dimension one, so you shouldn't expect their derived categories to agree with derived categories of sheaves on higher-dimensional varieties.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/285955', 'https://mathoverflow.net', 'https://mathoverflow.net/users/54401/']}
jdg_79497
stackexchange
llm_judgeable_groundtruth_similarity
9398541
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the Amazon S3 console I only see a permission option for "upload/delete". Is there a way to allow uploading but not deleting? Now provide the response and nothing else.
The permissions you are seeing in the AWS Management Console directly are based on the initial and comparatively simple Access Control Lists (ACL) available for S3, which essentially differentiated READ and WRITE permissions, see Specifying a Permission : READ - Allows grantee to list the objects in the bucket WRITE - Allows grantee to create, overwrite, and delete any object in the bucket These limitations have been addressed by adding Bucket Policies (permissions applied on the bucket level) and IAM Policies (permissions applied on the user level), and all three can be used together as well (which can become rather complex, as addressed below), see Access Control for the entire picture. Your use case probably asks for a respective bucket policy, which you an add directly from the S3 console as well. Clicking on Add bucket policy opens the Bucket Policy Editor , which features links to a couple of samples as well as the highly recommended AWS Policy Generator , which allows you to assemble a policy addressing your use case. For an otherwise locked down bucket, the simplest form might look like so (please ensure to adjust Principal and Resource to your needs): { "Statement": [ { "Action": [ "s3:PutObject" ], "Effect": "Allow", "Resource": "arn:aws:s3:::<bucket_name>/<key_name>", "Principal": { "AWS": [ "*" ] } } ]} Depending on your use case, you can easily compose pretty complex policies by combining various Allow and Deny actions etc. - this can obviously yield inadvertent permissions as well, thus proper testing is key as usual; accordingly, please take care of the implications when using Using ACLs and Bucket Policies Together or IAM and Bucket Policies Together . Finally, you might want to have a look at my answer to Problems specifying a single bucket in a simple AWS user policy as well, which addresses another commonly encountered pitfall with policies.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9398541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/686654/']}
jdg_79498
stackexchange
llm_judgeable_groundtruth_similarity
15464984
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Disclaimer: I'm completely new to parsing and accessing JSON, and I'm only starting to get the ropes of django. Details: I'm trying to access some data inside of a JSON object I obtain in a django template: example JSON: {"entry":[{"id":"1234567","hash":"1234567",..."name":{"givenName":"John","familyName":"Doel","formatted":"John H. Doe"},..."currentLocation":"Los Angeles, CA",..."emails":[{"primary":"true","value":"[email protected]"}],..."accounts":[ ...{"domain":"facebook.com","url":"http:\/\/www.facebook.com\/john.doe",..."shortname":"facebook"}, ...{"domain":"twitter.com","display":"@jdoe411","url":"http:\/\/twitter.com\/jdoe411",..."shortname":"twitter"}],..."urls":[{"value":"http:\/\/www.example.com","title":"example url"},]}]} Obtained with Django Template Tag: @register.inclusion_tag('includes/gravatar_links.html')def gravatar_links(email, first_name): url = "http://www.gravatar.com/" + hashlib.md5(email.lower()).hexdigest() url += '.json' response = urllib2.urlopen(url) interm = simplejson.load(response) data = simplejson.dumps(interm) name = first_namereturn {'gravatar_links': {'name': name, 'data': data}} which I just call {{ gravatar_links.name }} and {{ gravatar_links.data }} , and I can see the user's name and the JSON data as described. Goal: I want to access specific keys in the JSON object, namely "accounts" and "urls" , and customize the output, (e.g.) "Follow {{ gravatar_links.name }} on <a href="{{ gravatar_links.data.accounts.url }}">{{ gravatar_links.data.accounts.shortname }}</a> and see their work at <a href="{{ gravatar_links.data.urls.url }}">{{ gravatar_links.data.urls.title }}</a>" Which ideally would produce: "Follow John on Twitter and Facebook and see their work at example url" Questions: Should I just use django/python to do this, or is this something better handled by jQuery? If the "accounts" come as a list, how can I output it as a comma separated list? Are there any security issues I should be aware of with this method? Now provide the response and nothing else.
Yes, Less.js introduced extend in v1.4.0 . :extend() Rather than implementing the at-rule ( @extend ) syntax used by SASS and Stylus, LESS implemented the pseudo-class syntax, which gives LESS's implementation the flexibility to be applied either directly to a selector itself, or inside a statement. So both of these will work: .sidenav:extend(.nav) {...} or .sidenav { &:extend(.nav); ...} Additionally, you can use the all directive to extend "nested" classes as well: .sidenav:extend(.nav all){}; And you can add a comma-separated list of classes you wish to extend: .global-nav { &:extend(.navbar, .nav all, .navbar-fixed-top all, .navbar-inverse); height: 70px;} When extending nested selectors you should notice the differences: nested selectors .selector1 and selector2 : .selector1 { property1: a; .selector2 { property2: b; }} Now .selector3:extend(.selector1 .selector2){}; outputs: .selector1 { property1: a;}.selector1 .selector2,.selector3 { property2: b;} , .selector3:extend(.selector1 all){}; outputs: .selector1,.selector3 { property1: a;}.selector1 .selector2,.selector3 .selector2 { property2: b;} , .selector3:extend(.selector2){}; outputs .selector1 { property1: a;}.selector1 .selector2 { property2: b;} and finally .selector3:extend(.selector2 all){}; : .selector1 { property1: a;}.selector1 .selector2,.selector1 .selector3 { property2: b;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/15464984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/938865/']}
jdg_79499
stackexchange
llm_judgeable_groundtruth_similarity
20689575
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 look for a while now on this problem and have not found a straight answer.When adding a margin top to an element, in my case it happens mostly with headings. In many occasions the margin-top is shared with the parent. HTML <div> <h1>My title</h1> </div> CSS div{ padding:20px;}h1{ margin-top: 20px;} The result of the previous code will also add a margin-top to the div, as if we had the following: div{ padding:20px; margin-top:20px; /*this one is implemented by the browser, not written on the code*/} A way to solve this is by adding overflow:auto to the parent, in this case the div css has: div{ padding:20px; overflow:auto;} Although the previous example solves the problem, it is not clear to me WHY??? .This has something to do with "collapsing margins" , where apparently a margin is combined with the parent's margin. But why???? How do we know when a parent will collapse the margin of the child and when not, what is the purpose of this property of the blocks, or is it a bug? Here's a JSFiddle demo of the problem. And Here is a JSFiddle demo of the solution Thanks. Now provide the response and nothing else.
Thank you all for your answers, @gaurav5430 posted a link with a very precise definition that I would like to summarize into this answer. As of why they decided that this elements should behave like this it is still unclear for me; but at least we were able to find a rule that applies to collapsing margins: "In simple terms, this definition indicates that when the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero Basically in our example on the original question, the biggest margin-top is the one of the <h1> therefore taken and applied to the parent <div> . This rule is cancelled for: Floated elements Absolutely positioned elements Inline-block elements Elements with overflow set to anything other than visible (They do not collapse margins with their children.) Cleared elements (They do not collapse their top margins with their parent block’s bottom margin.) The root element That is the reason why overflow:hidden solved the issue. Thanks @gaurav5430; here is the reference: http://reference.sitepoint.com/css/collapsingmargins Also thanks to @Adrift that posted very good resources, although I found @gaurav5430's answer more straight forward and easier to understand.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20689575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243679/']}
jdg_79500
stackexchange
llm_judgeable_groundtruth_similarity
478898
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for: std::string result = system("./some_command"); I need to run an arbitrary command and get its output. I've looked at boost.org , but I have not found anything that will give me what I need. Now provide the response and nothing else.
#include <cstdio>#include <iostream>#include <memory>#include <stdexcept>#include <string>#include <array>std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose); if (!pipe) { throw std::runtime_error("popen() failed!"); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } return result;} Pre-C++11 version: #include <iostream>#include <stdexcept>#include <stdio.h>#include <string>std::string exec(const char* cmd) { char buffer[128]; std::string result = ""; FILE* pipe = popen(cmd, "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (fgets(buffer, sizeof buffer, pipe) != NULL) { result += buffer; } } catch (...) { pclose(pipe); throw; } pclose(pipe); return result;} Replace popen and pclose with _popen and _pclose for Windows.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/478898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3467/']}
jdg_79501
stackexchange
llm_judgeable_groundtruth_similarity
17567201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi Im trying to achieve a ascending sort order for particular columns in a sqlite database using sql alchemy, the issue im having is that the column I want to sort on has upper and lower case data and thus the sort order doesn't work correctly. I then found out about func.lower and tried to incorporate this into the query but it either errors or just doesn't work, can somebody give me a working example of how to do a case insensitive ascending sort order using sql alchemy. below is what I have so far (throws error):- session.query(ResultsDBHistory).order_by(func.lower(asc(history_sort_order_column))).all() python 2.6.6sql alchemy 0.7.10 Now provide the response and nothing else.
You need to reverse the ordering of your functions: session.query(ResultsDBHistory).order_by(asc(func.lower(history_sort_order_column))).all() so lower first , then declare the ascending order. Alternatively, change the collation to NOCASE : from sqlalchemy.sql import collatesession.query(ResultsDBHistory).order_by(asc(collate(history_sort_order_column, 'NOCASE'))).all() which arguably is a better idea anyway. I don't think the ASC is required, leaving that off simplifies your code somewhat: from sqlalchemy.sql import collatesession.query(ResultsDBHistory).order_by(collate(history_sort_order_column, 'NOCASE')).all()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17567201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1582112/']}
jdg_79502
stackexchange
llm_judgeable_groundtruth_similarity
53059609
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: setTimeout(() => { this.myFlatList.scrollToIndex({animated:true , index: 100}) }, 100); If i use scrolltoindex in flat list return to me this error; scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed I tried to use getItemLayout but my flatlist items have different height, how can i fix this? getItemLayout={(data, index) => ( {length: 40, offset: 40 * index, index} )} Now provide the response and nothing else.
I had a similar error with a horizontal list showing images where the selected image should be shown in a carousel when pressed. I solved it by setting the selected index on the FlatList by using initialScrollIndex . I also used onScrollToIndexFailed to scroll to the correct image for the times when initialScrollIndex failed to show the correct image. This is done by setting a timeout for 500ms and then scroll to the selected image. Complete example (with only the props regarding this error): const flatList = useRef<FlatList>(null);...<FlatList ref={flatList} initialScrollIndex={props.activeIndex} onScrollToIndexFailed={info => { const wait = new Promise(resolve => setTimeout(resolve, 500)); wait.then(() => { flatList.current?.scrollToIndex({ index: info.index, animated: true }); }); }}/>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53059609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5622499/']}
jdg_79503
stackexchange
llm_judgeable_groundtruth_similarity
42596068
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 crawl data from multiple domains using a single crawler. I have done crawling of single sites using beautiful soup but couldn't figure out how to create a generic one. Now provide the response and nothing else.
Your error comes from the fact that your X for some reason wasn't transformed to a numpy.array . In this your X is treated as a list of rows and this is a reason behind your error message (that it expected one input instead of list which has a number of rows elements). Transformation: X = numpy.array(X)Y = numpy.array(Y) I would check a data loading process because something might go wrong there. UPDATE: As it was mentioned in a comment - input_shape need to be changed to input_dim . UPDATE 2: In order to keep input_shape one should change to it to input_shape=(200,) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42596068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7657900/']}
jdg_79504
stackexchange
llm_judgeable_groundtruth_similarity
137844
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to have different fontconfig settings per screen ? I have two 1080p monitors, however one is 13" and the other 27". I would like antialiased fonts on the small monitor, and non-antialiased fonts on the big monitor. Now provide the response and nothing else.
xrdb uses the C preprocessor (because of course it does), so it supports conditions. Here's a snippet from my .Xresources : #if SCREEN_NUM == 0Xft.dpi: 157#endif#if SCREEN_NUM == 1Xft.dpi: 96Xft.antialias: 0#endif Now xrdb -merge will do the right thing on each monitor, and when you log in, assuming one of the myriad X initialization scripts bothers to look at your .Xresources , it will also be set correctly. (Note: the Arch Linux Font Configuration page has more examples, but in the interest of preserving this for posterity, I have included the relevant example above.)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/137844', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/69026/']}
jdg_79505
stackexchange
llm_judgeable_groundtruth_similarity
182875
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm talking here about matrices of Pearson correlations. I've often heard it said that all correlation matrices must be positive semidefinite. My understanding is that positive definite matrices must have eigenvalues $> 0$, while positive semidefinite matrices must have eigenvalues $\ge 0$. This makes me think that my question can be rephrased as "Is it possible for correlation matrices to have an eigenvalue $= 0$?" Is it possible for a correlation matrix (generated from empirical data, with no missing data) to have an eigenvalue $= 0$, or an eigenvalue $< 0$? What if it was a population correlation matrix instead? I read at the top answer to this question about covariance matrices that Consider three variables, $X$, $Y$ and $Z = X+Y$. Their covariance matrix, $M$, is not positive definite, since there's a vector $z$ ($=(1, 1, -1)'$) for which $z'Mz$ is not positive. However, if instead of a covariance matrix I do those calculations on a correlation matrix then $z'Mz$ comes out as positive. Thus I think that maybe the situation is different for correlation and covariance matrices. My reason for asking is that I got asked over on stackoverflow , in relation to a question I asked there. Now provide the response and nothing else.
Correlation matrices need not be positive definite. Consider a scalar random variable X having non-zero variance. Then the correlation matrix of X with itself is the matrix of all ones, which is positive semi-definite, but not positive definite. As for sample correlation, consider sample data for the above, having first observation 1 and 1, and second observation 2 and 2. This results in sample correlation being the matrix of all ones, so not positive definite. A sample correlation matrix, if computed in exact arithmetic (i.e., with no roundoff error) can not have negative eigenvalues.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/182875', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9162/']}
jdg_79506
stackexchange
llm_judgeable_groundtruth_similarity
17434
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 want to know more about how WEP (Wired Equivalent Privacy) protocol for wireless security. From this Wikipedia article I have got a basic Idea. But what is the initialize vector? Is some kind of token sent for each request? Or is the connecting device authenticated only once in the beginning or some kind of token sent for each request (equivalent to cookies for authentication in Gmail, Yahoo, etc.)? I have tried to set up WEP security for my Wi-Fi. As per instructions from my ISP, I did the following: Network Authentication - OpenWEP Encryption - EnabledCurrent Network Key -1Encryption Key -64 bitNetwork Key 1 -abcdefghij (10 characters)Network Key 2 -Network Key 3 -Network Key 4 - What are these network keys? Now provide the response and nothing else.
The initialization vector in WEP is a 24-bit random value that is used to seed the RC4 algorithm. RC4 is a stream cipher. This means that for each bit of plaintext, it produces one bit of keystream and xors the two, to generate the ciphertext. The keystream is simply a stream of random numbers, generated from the RC4 algorithm. In the most basic operation of a stream cipher, the algorithm is seeded with a key, such that the same key will always produce the same stream of random numbers. Since both the client and server know the key, they can produce the same keysteam. This allows the client to xor the plaintext with the keystream to produce the ciphertext, and the server to xor the ciphertext with the keystream to produce the plaintext again. The problem with this is that a key is only a few tens of bits long, but the plaintext may be gigabytes. After a large number of bits have been produced by RC4, the random numbers become predictable, and may even loop back round to the start. This is obviously undesirable, because a known plaintext attack would be able to compute the keystream (c1 xor c2 = k) and use it to decrypt new messages. In order to solve this problem, an IV was introduced to complement the seed. The IV is a random 24-bit value that changed periodically, in an attempt to prevent re-use of the keystream. Unfortunately, 24 bits is quite small, and the IV often wasn't generated in an unpredictable way, allowing attackers to guess future IVs and use them to deduce the key. Further attacks involved actively injecting packets into the network, tricking the access point into issuing lots of new IVs, which allowed attackers to crack WEP in minutes or seconds. Further reading: Fluhrer, Mantin and Shamir attack WEP Flaws How WEP cracking works (PDF)
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/17434', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/8201/']}
jdg_79507
stackexchange
llm_judgeable_groundtruth_similarity
224985
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: Evaluate the series $$\sum_{k=0}^{\infty}\frac{1}{(4k+1)(4k+2)(4k+3)(4k+4)}=?$$ Can you help me ? This is a past contest problem. Now provide the response and nothing else.
This is Problem 2 of Day 1 of the 2010 International Mathematics Competition. If you go to the competition website, you can find several solutions, but here is a solution I came up with using the Beta function: We have the identity ** $$\frac{3!}{(4l+1)(4l+2)(4l+3)(4l+4)}=\int_{0}^{1}x^{4l}(1-x)^{3}\text{d}x.$$ Thus we may write $$\sum_{l=0}^{\infty}\frac{1}{(4l+1)(4l+2)(4l+3)(4l+4)}=\sum_{l=0}^{\infty}\frac{1}{3!}\int_{0}^{1}x^{4l}(1-x)^{3}\text{d}x.$$ Rearranging the order of summation and integration yields $$\frac{1}{6}\int_{0}^{1}\left(\sum_{l=0}^{\infty}x^{4l}\right)(1-x)^{3}\text{d}x=\frac{1}{6}\int_{0}^{1}\frac{(1-x)^{3}}{1-x^{4}}\text{d}x=\frac{1}{6}\int_{0}^{1}\frac{(1-x)^{2}}{(1+x)(1+x^{2})}\text{d}x.$$ Using partial fractions to split up the integrand we then have $$\frac{1}{6}\int_{0}^{1}\frac{2}{1+x}-\frac{1+x}{1+x^{2}}\text{d}x=\frac{1}{3}\int_{0}^{1}\frac{1}{1+x}-\frac{1}{6}\int_{0}^{1}\frac{1}{1+x^{2}}\text{d}x-\frac{1}{6}\int_{0}^{1}\frac{x}{1+x^{2}}\text{d}x$$ and evaluating the integrals yields $$=\frac{1}{3}\log2-\frac{1}{6}\frac{\pi}{4}-\frac{1}{12}\log2=\frac{1}{4}\log2-\frac{\pi}{24}$$ ** This identity follows from the fact that $\text{B}(x,y)=\frac{\Gamma(x)\Gamma(y)}{\Gamma(x+y)}$ where $\text{B}(x,y)$ is the Beta Function , but it also follows directly from expanding and integrating since $l$ is an integer. Essentially, this integral encodes the partial fraction decomposition.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/224985', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44859/']}
jdg_79508
stackexchange
llm_judgeable_groundtruth_similarity
39653256
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While ng-model is used in select box and ng-selected is also used in options with some condition that time ng-selected is not working. If I will remove ng-model than ng-selected is working, but if i will remove ng-model than how I should get the value of select box in controller. Please help ! Here is my code... HTML: <select class="form-control" ng-change="accessModeSelected()"> <option ng-selected="mode.status == '1'" ng-repeat="mode in storageResult.accessMode" ng-value="mode.name" name="accessMode{{$index}}" id="accessMode"> {{mode.name}} </option></select> AngularJS: $scope.storageResult = { "storageAccount":"Enable", "user": "sdcard", "pass": "sdcard", "wifiIP": "0", "ipAddr": "0", "accessMode": [ {"name": "Local Storage","status": "0"}, {"name":"WiFi Storage", "status": "1"}, {"name":"Internet Storage", "status": "0"} ] } Now provide the response and nothing else.
Use ng-options and ng-init (for setting default value) instead of ng-repeat . ng-options is specifically for select <select class="form-control" ng-init="statusselect='WiFi Storage'" ng-model="statusselect" ng-options="mode.name as mode.name for mode in storageResult.accessMode"></select> Selected Value : {{statusselect}} FIDDLE Edit: Using ng-repeat I would prefer ng-options ,but if you want to use ng-selected with ng-repeat you'll need provide a default selected value to ng-model from your controller <select class="form-control" ng-model="statusselect"> <option ng-selected="{{mode.name == statusselect}}" ng-repeat="mode in storageResult.accessMode" value="{{mode.name}}" name="accessMode{{$index}}" id="accessMode"> {{mode.name}} </option></select> Selected Value : {{statusselect}} Inside Controller $scope.storageResult = { "storageAccount":"Enable", "user": "sdcard", "pass": "sdcard", "wifiIP": "0", "ipAddr": "0", "accessMode": [ {"name": "Local Storage","status": "0"}, {"name":"WiFi Storage", "status": "1"}, {"name":"Internet Storage", "status": "0"} ] } $scope.statusselect = $scope.storageResult["accessMode"][1]["name"]; FIDDLE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39653256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2251652/']}
jdg_79509
stackexchange
llm_judgeable_groundtruth_similarity
900591
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the process of learning Django and Python. I can't make sense of this. (Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.) from helloworld.views import * # <<-- this worksfrom helloworld import views # <<-- this doesn't workfrom helloworld.app import views # <<-- but this works. why? It seems like line #2 and #3 are practically the same. Why does like #2 not work? Edit -- Added the source of the two files. You might recognize this code from the Django Book project ( http://www.djangobook.com/en/2.0 ) helloworld/views.py from django.shortcuts import render_to_responsefrom django.http import HttpResponse, Http404import datetimedef hello(request): return HttpResponse("Hello world")def current_datetime(request): current_date = datetime.datetime.now() return render_to_response('current_datetime.html', locals())def offset_datetime(request, offset): try: offset = int(offset) except ValueError: raise Http404() next_time = datetime.datetime.now() + datetime.timedelta(hours=offset) return render_to_response('offset_datetime.html', locals())def display_meta(request): values = request.META.items() values.sort() path = request.path return render_to_response('metavalues.html', locals()) helloworld/app/views.py from django.shortcuts import render_to_responsedef search_form(request): return render_to_response('search_form.html')def search(request): if 'q' in request.GET: message = 'You searched for: %r' % request.GET['q'] else: message = 'You searched for nothing.' return render_to_response('search_results.html', locals()) Now provide the response and nothing else.
Python imports can import two different kinds of things: modules and objects. import x Imports an entire module named x . import x.y Imports a module named y and it's container x . You refer to x.y . When you created it, however, you created this directory structure x __init__.py y.py When you add to the import statement, you identify specific objects to pull from the module and move into the global namespace import x # the module as a wholex.a # Must pick items out of the modulex.bfrom x import a, b # two things lifted out of the modulea # items are globalb If helloworld is a package (a directory, with an __init__.py file), it typically doesn't contain any objects. from x import y # isn't sensibleimport x.y # importing a whole module. Sometimes, you will have objects defined in the __init__.py file. Generally, use "from module import x" to pick specific objects out of a module. Use import module to import an entire module.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/900591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111375/']}
jdg_79510
stackexchange
llm_judgeable_groundtruth_similarity
46006369
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using D3.js version 4, is there a way to get an array of the values for each tick on an axis? Edit: From D3 documentation # axis.tickValues([values]) <> If a values array is specified, the specified values are used for ticks rather than using the scale’s automatic tick generator. If values is null, clears any previously-set explicit tick values and reverts back to the scale’s tick generator. If values is not specified, returns the current tick values, which defaults to null. I am using the automatic tick generator so if I call var tickValues = axis.tickValues(); tickValues is null Now provide the response and nothing else.
If you have a reference to the axis , you can use: axis.scale().ticks() If you want them all formatted out, I'd get them from the DOM: d3.selectAll(".tick>text") .nodes() .map(function(t){ return t.innerHTML; }) Running code: <!DOCTYPE html><meta charset="utf-8"><svg width="960" height="500"></svg><script src="//d3js.org/d3.v4.min.js"></script><script>var svg = d3.select("svg"), margin = {top: 20, right: 0, bottom: 20, left: 0}, width = svg.attr("width") - margin.left - margin.right, height = svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");var x = d3.scalePoint() .domain([0, 1, 2]) .range([0, width]) .padding(1);var y = d3.scaleLinear() .domain([-1e6, 2e6]) .range([height, 0]);var axis = d3.axisLeft(y) .ticks(20, "s"); g.append("g") .attr("transform", "translate(" + x(0) + ",0)") .attr("class", "axis") .call(axis); console.log( axis.scale().ticks());console.log( d3.selectAll(".tick>text") .nodes() .map(function(t){ return t.innerHTML ; })); </script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46006369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/902630/']}
jdg_79511
stackexchange
llm_judgeable_groundtruth_similarity
50628374
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 ASP.NET Core Web-API project, I'm getting a HTTP POST call to one of my API controllers. While evaluating the JSON payload and deserializing its contents, Json.NET stumbles upon a DateTime value of 0001-01-01T00:00:00 and can't convert it to a DateTimeOffset property. I notice that the value propably should represent the value of DateTimeOffset.MinValue, but its lack of a timezone seems to trip the deserializer up. I can only imagine that the DateTimeOffset.Parse tries to translate it to the hosts current timezone, which results in an underflow of DateTimeOffset.MinValue. The property is pretty simplistic: [JsonProperty("revisedDate", NullValueHandling = NullValueHandling.Ignore)]public DateTimeOffset? RevisedDate { get; set; } And here is the response sent to the client: { "resource.revisedDate": [ "Could not convert string to DateTimeOffset: 0001-01-01T00:00:00. Path 'resource.revisedDate', line 20, position 44." ]} I'm using Newtonsoft.Json v11.0.2 and currently am in UTC + 2 (Germany). The exception traceback and error message are here: https://pastebin.com/gX9R9wq0 . I can't fix the calling code, so I have to fix it on my side of the line. But the question is: How? Now provide the response and nothing else.
The problem seems reproducible only when the machine's time zone TimeZoneInfo.Local has a positive offset from UTC, e.g. (UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna . I was unable to reproduce it in time zones with a non-positive offset such as UTC-05:00 or UTC itself. Specifically, in JsonReader.ReadDateTimeOffsetString() a call is made to DateTimeOffset.TryParse using DateTimeStyles.RoundtripKind : if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)){ SetToken(JsonToken.Date, dt, false); return dt;} This apparently causes an underflow error in time zones with a positive UTC offset. If in the debugger I parse using DateTimeStyles.AssumeUniversal instead, the problem is avoided. You might want to report an issue about this to Newtonsoft. The fact that deserialization of a specific DateTimeOffset string fails only when the computer's time zone has certain values seems wrong. The workaround is to use IsoDateTimeConverter to deserialize your DateTimeOffset properties with IsoDateTimeConverter.DateTimeStyles set to DateTimeStyles.AssumeUniversal . In addition it is necessary to disable the automatic DateTime recognition built into JsonReader by setting JsonReader.DateParseHandling = DateParseHandling.None , which must be done before the reader begins to parse the value for your DateTimeOffset properties. First, define the following JsonConverter : public class FixedIsoDateTimeOffsetConverter : IsoDateTimeConverter{ public override bool CanConvert(Type objectType) { return objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?); } public FixedIsoDateTimeOffsetConverter() : base() { this.DateTimeStyles = DateTimeStyles.AssumeUniversal; }} Now, if you can modify the JsonSerializerSettings for your controller, use the following settings: var settings = new JsonSerializerSettings{ DateParseHandling = DateParseHandling.None, Converters = { new FixedIsoDateTimeOffsetConverter() },}; If you cannot easily modify your controller's JsonSerializerSettings you will need to grab DateParseHandlingConverter from this answer to How to prevent a single object property from being converted to a DateTime when it is a string and apply it as well as FixedIsoDateTimeOffsetConverter to your model as follows: [JsonConverter(typeof(DateParseHandlingConverter), DateParseHandling.None)]public class RootObject{ [JsonProperty("revisedDate", NullValueHandling = NullValueHandling.Ignore)] [JsonConverter(typeof(FixedIsoDateTimeOffsetConverter))] public DateTimeOffset? RevisedDate { get; set; }} DateParseHandlingConverter must be applied to the model itself rather than the RevisedDate property because the JsonReader will already have recognized 0001-01-01T00:00:00 as a DateTime before the call to FixedIsoDateTimeOffsetConverter.ReadJson() is made. Update In comments , @RenéSchindhelm writes, I created an issue to let Newtonsoft know . It is Deserialization of DateTimeOffset value fails depending on system's timezone #1731 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50628374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1503584/']}
jdg_79512
stackexchange
llm_judgeable_groundtruth_similarity
43236152
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 Lambda function proxied by API Gateway. However, API Gateway only expose http s and not http. I searched everywhere but looks like API Gateway is not possible to accept http. So my question is how to translate http client calls to https and send to api gateway? I am asking because my client can only make http calls and they won't change. Now provide the response and nothing else.
I recently had a 4 hour long phone call with an AWS representative about a similar problem we had in production stage. My situation was similar, there was nothing we could change in APIGateway to fix it (the rep tried all kinds of tricks, but nothing seemed working). So our conclusion was to spin up an EC2 instance as a proxy server for APIGateway and forward all the traffic. There was some additional work such as transferring the domain name, but overall it worked just fine. In your case, as you only need to redirect HTTP traffic, a simple ElasticBeanstalk proxy app might be enough (EB uses HTTP by default and is behind a Nginx proxy server).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43236152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5351615/']}
jdg_79513
stackexchange
llm_judgeable_groundtruth_similarity
43164277
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First time button is clicked in form undefined is return, button has to be clicked twice to return correct result. How do I not process until result is return. When button clicked return correct result not previous one? Product.componet.html <div *ngIf="submitted"> <h2>Product found</h2> <div class="row"> <div class="col-xs-3">Price</div> <div class="col-xs-9 pull-left">Product details</div> <div class="col-xs-3">{{ product.price }}</div> <div class="col-xs-9 pull-left">{{product.description}}</div> </div></div><div *ngIf="result"> <h2>No Product found</h2></div> Product.compontent.ts onSubmit() { if (this.formModel.valid) { this.submitted = false; this.result = false; lens id = this.formModel.controls['id'].value; this.productService.getProductOne(id) .subscribe(product => this.product = product) //Check to see if object undefined if (this.product) { if (this.product.id != 0) { this.submitted = true; } else { this.result = true; } } }} product-service.ts getProductOne(id: number): Observable<Product> { // Parameters obj let params: URLSearchParams = new URLSearchParams(); params.set('id', id.toString()); //Http request return this.http .get("api/getProduct", { search: params }) .map(response => response.json()) .catch(handleError); } Web api – ProductController.cs [Route("api/getProduct")] public Product GetProduct(int id) { var product = products.FirstOrDefault((p) => p.id == id); if (product == null) { product = new Product(); } return product; } Now provide the response and nothing else.
You can use Directive . Try as follows. Put the following code in separate directive file. (social-sharing.directive.ts); import { Directive, HostListener } from '@angular/core';@Directive({ selector: '[socialSharing]'})export class SocialSharing { constructor() { } @HostListener('click') onClick() { // Your click functionality }} Import it into app.module.ts and than add to declarations . In HTML, just add attribute to any element which is the selector in your directive file. <button ion-button right socialSharing> <ion-icon name="md-share"></ion-icon></button> Additional Info: Passing values from component to directive. home.html <button ion-button right [socialSharing]="property"> <ion-icon name="md-share"></ion-icon> </button> home.component.ts export class HomePage { property: string = 'some url'; constructor() {} } social-sharing.directive.ts Import Input along with others from @angular/core . import { Directive, Input, HostListener } from '@angular/core';@Directive({ selector: '[socialSharing]'})export class SocialSharing { @Input('socialSharing') str: string; constructor() {} @HostListener('click') onClick() { console.log(this.str); }}; ngAfterInit() { console.log(this.str); };} Using Element in Directive: social-sharing.directive.ts Import ElementRef along with others from @angular/core import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[socialSharing]' }) export class SocialSharing { // Add ElementRef to constructor constructor(el: ElementRef) {}; ngOnInit() { let elRef = this.el.nativeElement; console.log(elRef.innerHTML); }; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43164277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/730381/']}
jdg_79514
stackexchange
llm_judgeable_groundtruth_similarity
132268
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is there an axiomatic system where the deduction theorem does not hold? Now provide the response and nothing else.
Failures of the deduction theorem are one of the more mysterious topics in logic, in my experience. The motto is that axioms are stronger than rules . Here is the simplest nontrivial example that I know. Start with propositional logic with two variables $A$ and $B$. Add the single new rule of inference $A \vdash B$ to the usual Hilbert-style deductive system, with no new axioms. Note that this does not in any way change the collection of formulas that can be derived. (Proof: the first time you use the new rule, you already had to derive $A$ in the original system, but you cannot, because the original system only derives tautologies. So you can never use the new rule.) Thus the new system has the rule $A \vdash B$ but does not derive $A \to B$, and hence the deduction theorem fails. But this new system is not completely trivial. If we add $A$ as a new axiom, then we can derive $B$ in the expanded logic, which we cannot do in ordinary propositional logic. So there is an interplay between the rules of inference and the axioms of a given theory. The deduction theorem for first order logic shows that this interplay is very well behaved in that context: an arbitrary first-order theory $\Delta$ with the usual deductive system has the derived rule $\phi \vdash \psi$ if and only if it has the derived rule $\vdash \phi \to \psi$. In retrospect, there is no reason to expect this to hold for arbitrary sets of deduction rules, because new axioms may give additional strength to the existing rules. As François G. Dorais has mentioned in the comments, more complicated examples are known in proof theory. They are similar to the above example in that they weaken an axiom by replacing it with a rule. The general idea is that an extensionality axiom of the form $x = y \to f(x) = f(y)$ might be replaced with a rule $x = y \vdash f(x) = f(y)$. This suggests immediately how the deduction theorem can fail: if $x$ and $y$ are terms that are not provably equal, but are equal in some interpretation, then the extensionality axiom might fail in that interpretation even if the rule of inference is satisfied in some sense. But this is just a heuristic sketch of the argument. For a short, rigorous explanation, see " A note on Spector’s quantifier-free rule of extensionality " by Ulrich Kohlenbach, Archive for Mathematical Logic 40:2 (2001), pp 89-92.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/132268', 'https://mathoverflow.net', 'https://mathoverflow.net/users/34515/']}
jdg_79515
stackexchange
llm_judgeable_groundtruth_similarity
42145287
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on an angular2 project. I am stuck with these errors. The error occured when I tried to send the JSON objects to the backend. It may be due the parsing of JSON objects. I am new to angualar, so please do help Signup.service.ts import {Injectable} from '@angular/core'; import {Http, Headers} from '@angular/http';import 'rxjs/add/operator/map' ;@Injectable() export class SignupService{ constructor (private http: Http){} insertform(newreg: any ){ console.log(); var headers = new Headers (); headers.append('Content-Type','application/json'); return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers}) .map(res=> res.json()); } } signup.component.ts import { Component, AfterViewInit } from '@angular/core';import {SignupService} from '../../services/signup.service';import {Signup} from '../../../signup';declare var $: any; @Component({ moduleId: module.id, selector: 'signup', templateUrl: 'signup.component.html', providers: [SignupService] }) export class SignupComponent { datas: Signup[]; data: any; first_name: string; last_name: string; address: string; email: string; pwd:string; pwdcnf:string; phone:number; constructor(private signupService: SignupService){ }; ngAfterViewInit() { $('#textarea1').trigger('autoresize'); }; regformSubmit(event: any){ event.preventDefault(); var newreg = { first_name: this.first_name, last_name: this.last_name, email: this.email, address: this.address, phone: this.phone, pwd:this.pwd, pwdcnf:this.pwdcnf }; this.signupService.insertform(newreg) .subscribe (data => { this.datas.push(data); this.first_name=''; this.last_name =''; this.email=''; this.address=''; this.phone=0; this.pwd=''; this.pwdcnf=''; }); } } signup.component.html <div class="container light-blue lighten-5"><form class="col s12" (ngSubmit)="regformSubmit($event)"> <div class="row"> <div class="input-field col s6"> <input id="first_name" type="text" class="validate" [(ngModel)]="first_name" name="first_name" required> <label for="first_name">First Name</label> </div> <div class="input-field col s6"> <input id="last_name" type="text" class="validate" [(ngModel)]="last_name" name="last_name" required> <label for="last_name">Last Name</label> </div> </div> <div class="row"> <div class="input-field col s12"> <textarea id="textarea1" class="materialize-textarea" [(ngModel)]="address" name="address" required></textarea> <label for="disabled">Address</label> </div> </div> <div class="row "> <div class="input-field col s5"> <input id="password" type="password" class="validate" [(ngModel)]="pwd" name="pwd" required> <label for="password">Password</label> </div> <div class="input-field col s5 offset-s2"> <input id="password1" type="password" class="validate" [(ngModel)]="pwdcnf" name="pwdcnf" required> <label for="password1">Confirm password</label> </div> </div> <div class="row"> <div class="input-field col s5"> <input id="email" type="email" class="validate" [(ngModel)]="email" name="email" required> <label for="email">Email</label> </div> <div class="input-field col s5 offset-s2"> <input id="password2" type="number" class="validate" [(ngModel)]="phone" name="number" required> <label for="password2">Phone</label> </div> </div> <div class="row"> <div class="input-field col s4 offset-s5"> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </div> </div></form> </div> <style> .ng-invalid { border-bottom-color: red; }</style> The full error message is EXCEPTION: Unexpected token U in JSON at position 0ORIGINAL STACKTRACE:yntaxError: Unexpected token U in JSON at position 0at JSON.parse (<anonymous>)at Response.Body.json (http.umd.js:777)at MapSubscriber.eval [as project] (signup.service.ts:13)at MapSubscriber._next (map.ts:75)at MapSubscriber.Subscriber.next (Subscriber.ts:95)at XMLHttpRequest.onLoad (http.umd.js:1180)at ZoneDelegate.invokeTask (zone.js:275)at Object.onInvokeTask (core.umd.js:3971)at ZoneDelegate.invokeTask (zone.js:274)at Zone.runTask (zone.js:151)at XMLHttpRequest.ZoneTask.invoke (zone.js:345)Uncaught SyntaxError: Unexpected token U in JSON at position 0at JSON.parse (<anonymous>)at Response.Body.json (http.umd.js:777)at MapSubscriber.eval [as project] (signup.service.ts:13)at MapSubscriber._next (map.ts:75)at MapSubscriber.Subscriber.next (Subscriber.ts:95)at XMLHttpRequest.onLoad (http.umd.js:1180)at ZoneDelegate.invokeTask (zone.js:275)at Object.onInvokeTask (core.umd.js:3971)at ZoneDelegate.invokeTask (zone.js:274)at Zone.runTask (zone.js:151)at XMLHttpRequest.ZoneTask.invoke (zone.js:345) Now provide the response and nothing else.
I normally see this when the server returns an error (e.g. a 500 server error). The problem is that the server is returning plain text or sometimes even HTML and then the client app is trying to parse JSON from it thus throwing the error. I would recommend opening the chrome dev tools, navigating to the network tab, refreshing the page, and then look for the request in question and see what is actually getting returned from the server. It should look something like this. My guess is that the text on the right will not be JSON.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42145287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6087555/']}
jdg_79516
stackexchange
llm_judgeable_groundtruth_similarity
676935
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: Can we write $x^2+y^2+z^2$ as a polynomial combination of $xyz$, $x+y+z$, and $\dfrac1x+\dfrac1y+\dfrac1z$? What about $x^3+y^3+z^3$? Now provide the response and nothing else.
Let our three expressions be $a$, $b$, and $c$. Note that $xy+yz+zx=ac$. For $x^2+y^2+z^2$, use the identity $$(x+y+z)^2=x^2+y^2+z^2+2xy+2yz+2xz.$$ For $x^3+y^3+z^3$, use the not difficult to verify identity$$x^3+y^3+z^3-3xyz=(x+y+z)(x^2+y^2+z^2-xy-yz-xz).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/676935', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79379/']}
jdg_79517
stackexchange
llm_judgeable_groundtruth_similarity
14517338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After a lot of research on forums, now I know that there is no way to find IMSI or SIM serial number for both the SIM cards in a dual SIM phone (except for contacting the manufacturer). Now my changed question is, can we at all detect that the phone has two SIMs? I believe it can be detected with some intelligence. Few ways I can think of are: Dialing an USSD code and tracing the logs for IMEI number (I tried this with *139# in India. It worked.) This will give me IMEI number for the SIM from which I dialed the USSD code. (It is presumed that the phone follows android guidelines and has two IMEI numbers.) Storing the SIM serial number and/or IMSI for the SIM. And after detection of any other IMSI/Serial number even if the phone was not rebooted (i.e. the SIM was switched) by tracing some logs or by some broadcast event handling. By dialing *06# you will get to see both IMEI numbers. By some way, get those two numbers. (Something like screen capturing and image parsing for text.) If anyone can think of some other ways, they are most welcome. I would really appreciate any kind of help regarding this. Also, if anyone has any information about any manufacturers APIs or links to contact them, please do share with the community people. Now provide the response and nothing else.
Update 23 March'15 : Official multiple SIM API is available now from Android 5.1 onwards Other possible option : You can use Java reflection to get both IMEI numbers. Using these IMEI numbers you can check whether the phone is a DUAL SIM or not. Try following activity : import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this); String imeiSIM1 = telephonyInfo.getImsiSIM1(); String imeiSIM2 = telephonyInfo.getImsiSIM2(); boolean isSIM1Ready = telephonyInfo.isSIM1Ready(); boolean isSIM2Ready = telephonyInfo.isSIM2Ready(); boolean isDualSIM = telephonyInfo.isDualSIM(); TextView tv = (TextView) findViewById(R.id.tv); tv.setText(" IME1 : " + imeiSIM1 + "\n" + " IME2 : " + imeiSIM2 + "\n" + " IS DUAL SIM : " + isDualSIM + "\n" + " IS SIM1 READY : " + isSIM1Ready + "\n" + " IS SIM2 READY : " + isSIM2Ready + "\n"); }} And here is TelephonyInfo.java : import java.lang.reflect.Method;import android.content.Context;import android.telephony.TelephonyManager;public final class TelephonyInfo { private static TelephonyInfo telephonyInfo; private String imeiSIM1; private String imeiSIM2; private boolean isSIM1Ready; private boolean isSIM2Ready; public String getImsiSIM1() { return imeiSIM1; } /*public static void setImsiSIM1(String imeiSIM1) { TelephonyInfo.imeiSIM1 = imeiSIM1; }*/ public String getImsiSIM2() { return imeiSIM2; } /*public static void setImsiSIM2(String imeiSIM2) { TelephonyInfo.imeiSIM2 = imeiSIM2; }*/ public boolean isSIM1Ready() { return isSIM1Ready; } /*public static void setSIM1Ready(boolean isSIM1Ready) { TelephonyInfo.isSIM1Ready = isSIM1Ready; }*/ public boolean isSIM2Ready() { return isSIM2Ready; } /*public static void setSIM2Ready(boolean isSIM2Ready) { TelephonyInfo.isSIM2Ready = isSIM2Ready; }*/ public boolean isDualSIM() { return imeiSIM2 != null; } private TelephonyInfo() { } public static TelephonyInfo getInstance(Context context){ if(telephonyInfo == null) { telephonyInfo = new TelephonyInfo(); TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)); telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();; telephonyInfo.imeiSIM2 = null; try { telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0); telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1); } catch (GeminiMethodNotFoundException e) { e.printStackTrace(); try { telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0); telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1); } catch (GeminiMethodNotFoundException e1) { //Call here for next manufacturer's predicted method name if you wish e1.printStackTrace(); } } telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY; telephonyInfo.isSIM2Ready = false; try { telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0); telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1); } catch (GeminiMethodNotFoundException e) { e.printStackTrace(); try { telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0); telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1); } catch (GeminiMethodNotFoundException e1) { //Call here for next manufacturer's predicted method name if you wish e1.printStackTrace(); } } } return telephonyInfo; } private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException { String imei = null; TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try{ Class<?> telephonyClass = Class.forName(telephony.getClass().getName()); Class<?>[] parameter = new Class[1]; parameter[0] = int.class; Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter); Object[] obParameter = new Object[1]; obParameter[0] = slotID; Object ob_phone = getSimID.invoke(telephony, obParameter); if(ob_phone != null){ imei = ob_phone.toString(); } } catch (Exception e) { e.printStackTrace(); throw new GeminiMethodNotFoundException(predictedMethodName); } return imei; } private static boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException { boolean isReady = false; TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try{ Class<?> telephonyClass = Class.forName(telephony.getClass().getName()); Class<?>[] parameter = new Class[1]; parameter[0] = int.class; Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter); Object[] obParameter = new Object[1]; obParameter[0] = slotID; Object ob_phone = getSimStateGemini.invoke(telephony, obParameter); if(ob_phone != null){ int simState = Integer.parseInt(ob_phone.toString()); if(simState == TelephonyManager.SIM_STATE_READY){ isReady = true; } } } catch (Exception e) { e.printStackTrace(); throw new GeminiMethodNotFoundException(predictedMethodName); } return isReady; } private static class GeminiMethodNotFoundException extends Exception { private static final long serialVersionUID = -996812356902545308L; public GeminiMethodNotFoundException(String info) { super(info); } }} Edit : Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist. If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices. Finding method names for other manufacturers can be done using Java reflection as follows : public static void printTelephonyManagerMethodNamesForThisDevice(Context context) { TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); Class<?> telephonyClass; try { telephonyClass = Class.forName(telephony.getClass().getName()); Method[] methods = telephonyClass.getMethods(); for (int idx = 0; idx < methods.length; idx++) { System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass()); } } catch (ClassNotFoundException e) { e.printStackTrace(); }} EDIT : As Seetha pointed out in her comment : telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1); It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device. Add <uses-permission android:name="android.permission.READ_PHONE_STATE" /> EDIT 2 : The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa ): telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0); telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1);
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14517338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/840669/']}
jdg_79518
stackexchange
llm_judgeable_groundtruth_similarity
19474
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to close a GUI application in friendly " please quit yourself now " way, without graphical access to the applications window? For example, if Gnome/X display crashes to black, I'd like to switch to tty2 and close applications like firefox in a way which lets them save their config etc. At best without further user queries. Now provide the response and nothing else.
Usually, you can use SIGHUP to "friendly" close an application (with or without graphical interface). kill -HUP <application_pid> EDITED : added some other info The way SIGHUP is handled is application dependent so, as Dave noted, it can happen that this signal is masked or handled. However quite all interactive applications exit gracefully with a SIGHUP. On the other side, I have to admit that usually I follow this schema: kill -HUP <application_pid># check if application is still runningkill -INT <application_pid># check if application is still runningkill -KILL <application_pid> Obviously the last command is not so "friendly".
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/19474', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9868/']}
jdg_79519
stackexchange
llm_judgeable_groundtruth_similarity
5502002
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 really has me scratching my head. Namely because it only happens in IE, not Firefox, and I was under the impression that jQuery was effectively browser neutral. I've been cracking at this thing for the past few hours and have nailed down, at least, what is happening. This jqGrid: $("#DocumentListByPartRecordsGrid").jqGrid( { datatype: 'local', colNames: ['<b>Id</b>', '<b>Document Name</b>', '<b>Document Type</b>', '<b>Effective Date</b>', '<b>Expiration Date</b>', '<b>Delete</b>'], colModel: [ { name: 'ASSOCIATION_ID', Index: 'ASSOCIATION_ID', resizable: true, align: 'left', hidden: true, sortable: false }, { name: 'FILE_NAME', Index: 'FILE_NAME', resizable: true, align: 'left', sortable: false, width:'20%' }, { name: 'DOCUMENT_TYPE', Index: 'DOCUMENT_TYPE', resizable: true, align: 'left', sortable: false, width:'20%' }, { name: 'EFFECTIVE_DATE', Index: 'EFFECTIVE_DATE', resizable: true, align: 'left', sortable: false, width:'20%' }, { name: 'EXPIRATION_DATE', Index: 'EXPIRATION_DATE', resizable: true, align: 'left', sortable: false, width:'20%' }, { name: 'Delete', Index: 'Delete',resizable: true, align: 'center', sortable: false, width:'20%' }, ], rowNum: 15, rowList: [15, 50, 100], imgpath: '/Drm/Content/jqGrid/steel/images', viewrecords: true, height: 162, loadui: 'block', forceFit: true }); Filled by this function: var mydata = ''; <% if(!string.IsNullOrEmpty(Model.PCAssociatedDocuments)) { %> var mydata = <%= Model.PCAssociatedDocuments %>;<% } %>for (var i = 0; i <= mydata.length; i++){ jQuery("#DocumentListByPartRecordsGrid").addRowData(i, mydata[i], "last"); } Which is cleanly populated from the model. This is not the issue. The issue arises when using the delete functionality, which is formatted back in the controller like so: <a class='deleteAttachment' style='cursor: pointer;' href='#' onclick='javascript:PCDocumentDelete(" + s.AssociationId.ToString() + ", " + pcId + ");'>Delete</a> and calls this function function PCDocumentDelete(id, pcid) {if (confirm("Are you sure you want to delete this document?")) { $.blockUI({ message: "Working...", css: { background: '#e7f2f7', padding: 10 } }); $.ajax( { url: '/DRM/Pc/DeleteAssociation?associationId=' + id + '&pcid=' + pcid, async: true, dataType: "json", success: function(result) { if (result.Success == true) { //Reload grid $.ajax({ async: false }); $("#DocumentListByPartRecordsGrid").setGridParam({ url: "/Drm/Pc/DeAssociatePartRecordsWithDocument?pcid=" + pcid, datatype: 'json', myType: 'GET', page: 1 }); $("#DocumentListByPartRecordsGrid").trigger("reloadGrid"); $.unblockUI(); $.showGlobalMessage('Specified document has been successfully disassociated from this part record.'); } else { $.unblockUI(); $.showGlobalMessage('An error occurred deleting the attachment.'); } }, error: function(res, stat) { alert(res.toString()); alert(stat.toString()); } }); return false;}else { return false;} } (showGlobalMessage is an internal function that creates a particularly formatted blockUI) The ajax calls a method back in the controller, but the issue arises before we make it that far, so unless someone thinks it important, I'm not going to post that code. What happens is, often for inexplicable reasons, the first burst of ajax that calls PC/DeleteAssociation is coming back with a 304 (not modified) response. I know that happens on a get when nothing has changed that needs to be refreshed. But this isn't a get, it should be treated as a post, and I was under the impression that jquery.ajax was designed to, unless otherwise instructed, not generate 304 responses. I'm obviously missing something here and have been staring at it far too long to catch it myself. Anyone see what I missed? Thank you. Now provide the response and nothing else.
I cannot see, you specifying the ajax request as a POST. So basically add: $.ajax({ type: 'POST' }); and if that still fails (due to some browser AJAX weirdness), you could try setting cache: false : $.ajax({ type: 'POST', cache: false }); Btw, all cache: false does, is adding some random stuff to the request URL. EDIT1: Regarding the ... and I was under the impression that jquery.ajax was designed to, unless otherwise instructed, not generate 304 responses jQuery istn't generating any responses here. And the 304-header is just an HTTP header. HTTP AJAX requests are ordinary HTTP requests and may return any valid header. If the server responds with 304, the XHR object will simply serve up the locally cached response from the server. It's completely transparent for the user, though. EDIT2: Removed the advice about preventing caching. Seems like Voodoo to me. EDIT3: Added that bit in again because it apparently was necessary. Looking around the web, IE seems to be illegally caching AJAX POSTs to some extent.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5502002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535198/']}
jdg_79520
stackexchange
llm_judgeable_groundtruth_similarity
3011179
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 website, which was working before, suddenly started breaking with the error ImproperlyConfigured at / The included urlconf resume.urls doesn't have any patterns in it The project base is called resume. In settings.py I have set ROOT_URLCONF = 'resume.urls' Here's my resume.urls, which sits in the project root directory. from django.conf.urls.defaults import *# Uncomment the next two lines to enable the admin:from django.contrib import adminadmin.autodiscover()urlpatterns = patterns('', # Example: # (r'^resume/', include('resume.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^accounts/login/$', 'django.contrib.auth.views.login'), #(r'^employer/', include(students.urls)), (r'^ajax/', include('urls.ajax')), (r'^student/', include('students.urls')), (r'^club/(?P<object_id>\d+)/$', 'resume.students.views.club_detail'), (r'^company/(?P<object_id>\d+)/$', 'resume.students.views.company_detail'), (r'^program/(?P<object_id>\d+)/$', 'resume.students.views.program_detail'), (r'^course/(?P<object_id>\d+)/$', 'resume.students.views.course_detail'), (r'^career/(?P<object_id>\d+)/$', 'resume.students.views.career_detail'), (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'C:/code/django/resume/media'}),) I have a folder called urls and a file ajax.py inside. (I also created a blank init .py in the same folder so that urls would be recognized.) This is ajax.py. from django.conf.urls.defaults import *urlpatterns = patterns('', (r'^star/(?P<object_id>\d+)$', 'resume.students.ajax-calls.star'),) Anyone know what's wrong? This is driving me crazy. Thanks, Now provide the response and nothing else.
TL;DR: You probably need to use reverse_lazy() instead of reverse() If your urls.py imports a class-based view that uses reverse() , you will get this error; using reverse_lazy() will fix it. For me, the error The included urlconf project.urls doesn't have any patterns in it got thrown because: project.urls imported app.urls app.urls imported app.views app.views had a class-based view that used reverse reverse imports project.urls , resulting in a circular dependency. Using reverse_lazy instead of reverse solved the problem: this postponed the reversing of the url until it was first needed at runtime. Moral: Always use reverse_lazy if you need to reverse before the app starts.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3011179', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146478/']}
jdg_79521
stackexchange
llm_judgeable_groundtruth_similarity
7227427
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created a simple C# asp.net web service function which returns a string message and I am calling it from page using jquery ajax. C#: [WebMethod][ScriptMethod(ResponseFormat = ResponseFormat.Json)]public string HelloWorld() { return DateTime.Now.ToString();} JS: $(document).ready(function() { //alert("ready"); $.ajax({ type: "POST", contentType: "application/json; chatset=utf-8", url: "WebService2.asmx/HelloWorld", data: "{}", dataType: "json", success: function(msg) { //alert(msg); //doesnt works alert(msg.d); } }); }); My question is that why does alert(msg); doesnt works Now provide the response and nothing else.
It's a security hardening mechanism. Essentially, it helps protecting against CSRF type of attacks where the attacker reads a JavaScript array (downloaded as Json) from a victim website. They can do that by overriding JavaScript's Array type. d causes the returned Json to not be an array and thus turns Array overriding useless for the attacker. See this great blog post: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7227427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223752/']}
jdg_79522
stackexchange
llm_judgeable_groundtruth_similarity
2746901
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: Question: Let $S=\{1,2, \cdots, 10 \}$. Then the number of pairs $(A, B)$, where $A$ and$B$ are non-empty disjoint subsets of $S$ is? [I could solve the question as demonstrated below, but it involves calculating a tedious sum of products, which would take up a lot of time. It is typically expected to solve this in a couple of minutes, so I was wondering if there was a faster way to do this.] My approach: Let the set $A$ consist of $x$ elements. There are ${10 \choose x}$ ways of making that selection. We are now left with $10-x$ elements. Let the set $B$ consist of $y$ elements. This selection can be done by ${10-x \choose y}$ ways. The total number of ways can be found out by summing over the product of the two above as $\sum_{x=1}^{9} \sum_{y=1}^{10-x} {10 \choose x}{10-x \choose y} $ which comes out to be $57002$ Now provide the response and nothing else.
Suppose we have set $A$, $B$ and $S=\{1,2,...10\}$. So for each $x\in S$ you can put it in exactly one of this sets: $A$ or in $B$ or $(A\cup B)'$. So for each $x$ you have 3 choices and thus you can choose $A,B$ on $3^{10}$ ways. Now we have to substract all pairs where one of the sets is empty. If $A$ is empty, $B$ could be any subset apart from $A$. So we have $2^{10}$ choices. The same is true if $B$ is empty. So we have $2^{11}$ such pair of sets. But we have pair $(\emptyset,\emptyset )$ counted twice, we have to substract $2^{11}-1$ bad pairs of sets. So the finaly result is $3^{10}-2^{11}+1$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2746901', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/331943/']}
jdg_79523
stackexchange
llm_judgeable_groundtruth_similarity
7591343
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 3 square images of the same size that are floating next to each other. I want the three images, in total, to take up the full 100% of the browser window width, with no gaps. Giving each image a width of 33.33333333% works in Firefox, but does not work in most other browsers at certain widths, which can sometimes leave a small gap to the right of the 3rd image. This may be a problem with many solutions, but nothing I've tried so far works reliably. Now provide the response and nothing else.
Try this: HTML <div class="container"> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div></div> CSS html, body { margin:0; padding:0; width:100%; height:100%;}.container { width:100%;}.column { width:33.33333333%; float:left;}.column img { width:100%; height:auto;} Demo http://jsfiddle.net/andresilich/2p8uk/ Single page demo http://fiddle.jshell.net/andresilich/2p8uk/show/ CSS3 demo html, body { margin:0; padding:0; width:100%; height:100%;}.container { display:-moz-box; display:-webkit-box; display:box; -moz-box-orient:horizontal; -webkit-box-orient:horizontal; box-orient:horizontal; width:100%;}.column { -moz-box-flex:1; -webkit-box-flex:1; box-flex:1; background-color:#ddd;}.column img { width:100%; height:auto;} Demo http://jsfiddle.net/andresilich/2p8uk/2/ Single page demo http://fiddle.jshell.net/andresilich/2p8uk/2/show/ Update: (safari, sorta, fix)Safari does not equate 33.33% to 100% like other browsers, you can either use my CSS3 demo, which does the sizing automatically through CSS, or you can encase everything inside a container with a 101% width and just hide that extra 1% with overflow:hidden; off of the third image. Try this: <div class="container"> <div class="inner"> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div> <div class="column"> <img src="http://nssdc.gsfc.nasa.gov/planetary/image/neptune_voy2.jpg" /> </div> </div></div>html, body { margin:0; padding:0; width:100%; height:100%;}.container { width:100%;}.inner { width:101%; overflow:hidden;}.column { width:33.33333333%; float:left;}.column img { width:100%; height:auto;} Demo: http://fiddle.jshell.net/andresilich/2p8uk/4/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7591343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179827/']}
jdg_79524
stackexchange
llm_judgeable_groundtruth_similarity
10168
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Are there any problems with leaving my Raspberry Pi powered even though it is shutdown? Sometimes I forget to unplug it after running sudo halt , so I was wondering if I was affecting the lifespan of my Raspberry Pi or something like that. Now provide the response and nothing else.
Yes, every electronics degrades while it ages, if connected on some power source. The "problem" lies in electronic characteristics itself. One of the phenomena is called electromigration , where IC (actually whole PCB) degrades under various "nonideal" (i.e. working) conditions: current, time, temperature (which is also consequently caused by resistance properties, when device/IC is attached to power source), etc. But... those degradations will probably not be felt for the time of your life. What can be critical is flash memory in SD card. Every read/write cycle will slightly kill cells and you can't do nothing about it. Regarding the endurance ( Sandisk SD specs , 1.8): SanDisk SD cards have an endurance specification for each sector of 100,000 writes typical (reading a logical sector is unlimited). This far exceeds what is typically required in almost all SD Card applications. Therefore, extremely heavy use of the card in cellular phones, personal communicators, pagers and voice recorders will use only a fraction of the total endurance over the device’s lifetime. For instance—it would take over 10 years to wear out an area on an SD Card based on a file of any size (from 512 bytes to maximum capacity) being rewritten 3 times per hour, 8 hours a day, 365 days per year. With typical applications, the endurance limit is not of any practical concern to the vast majority of users. But... If you sudo shutdown the system, the SD will unmount and no I/O activity will be on the SDI line (at least in theory). So... You WILL NOT feel any degradations regarding Raspberry Pi hardware characteristics over time if it stay plugged into power source (of course, we assume that everything else, e.g. power source stability, room temerature, etc. stays in normal conditions).
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/10168', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/8631/']}
jdg_79525
stackexchange
llm_judgeable_groundtruth_similarity
3489543
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: let's say I have a method doWork() . How do I call it from a separate thread (not the main thread). Now provide the response and nothing else.
Create a class that implements the Runnable interface. Put the code you want to run in the run() method - that's the method that you must write to comply to the Runnable interface. In your "main" thread, create a new Thread class, passing the constructor an instance of your Runnable , then call start() on it. start tells the JVM to do the magic to create a new thread, and then call your run method in that new thread. public class MyRunnable implements Runnable { private int var; public MyRunnable(int var) { this.var = var; } public void run() { // code in the other thread, can reference "var" variable }}public class MainThreadClass { public static void main(String args[]) { MyRunnable myRunnable = new MyRunnable(10); Thread t = new Thread(myRunnable) t.start(); } } Take a look at Java's concurrency tutorial to get started. If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future , Callable , Executor classes in the java.util.concurrent package.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3489543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385387/']}
jdg_79526
stackexchange
llm_judgeable_groundtruth_similarity
3100148
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: Since $$\dfrac{d}{dx} \left( \dfrac{1}{2} \arctan(x) \right) = \dfrac{d}{dx} \left( \arctan(x-\sqrt{x^2+1}) \right) $$ then the format of their graphs are the same, but separated by a constant, which is $\dfrac{\pi}{4}$ . That is, $$\dfrac{1}{2} \arctan(x) = \arctan(x-\sqrt{x^2+1}) + \dfrac{\pi}{4} $$ My question is: why is this constant and what procedure is done to discover it. Now provide the response and nothing else.
It's even nicer if you use simple trigonometry. Consider the following Figure, for positive $x$ (for negative $x$ see edit , thanks to Steven for pointing this out in comment). $\hskip1.in$ The triangle $OAB$ is right-angled, and such that $\overline{OA} = 1$ , and $\overline{AB} = x$ . We have \begin{equation}\angle BOA = 2\alpha = \arctan x\tag{1}\label{eq:0}\end{equation} and $$\overline{OB} = \sqrt{x^2+1}.$$ Extend $BA$ to a segment $BC$ such that $$ BC \cong OB.$$ Then $$\overline{AC} = \sqrt{1+x^2}-x,$$ and so \begin{equation}\beta = \angle AOC = \arctan\left(\sqrt{1+x^2}-x\right).\tag{2}\label{eq:0p}\end{equation} By considering the right-angled triangle $OAB$ , youobtain \begin{equation}\angle OBA = \frac{\pi}{2}-2\alpha,\tag{3}\label{eq:1}\end{equation} and, by considering the isosceles triangle $OBC$ , you get \begin{equation}\angle OBA = \pi - 2(2\alpha+\beta).\tag{4}\label{eq:2}\end{equation} Equating \eqref{eq:1} and \eqref{eq:2} yields $$\alpha = -\beta + \frac{\pi}{4}.$$ Plugging in \eqref{eq:0} and \eqref{eq:0p} and using the odd symmetry of the $\arctan(\cdot )$ function leads to $$ \frac{1}{2}\cdot \arctan x = \arctan\left(x-\sqrt{1+x^2}\right) + \frac{\pi}{4},$$ the desired result. $\blacksquare$ EDIT The same result applies if $x<0$ . Use then the Figure below. $\hskip1.in$ Now $\overline{AB} = -x$ , $\overline{OB} = \overline{BC} = \sqrt{1+x^2}$ , and $\overline{CA} = \sqrt{1+x^2}-x$ . Then, again using right-angled triangle $OAC$ and isosceles triangle $OBC$ , we get $$\angle OCA = \frac{\pi}{2}-\beta = \beta - 2\alpha,$$ where $2\alpha = \angle BOA$ , and $\beta = \angle COA$ . The equality of OP follows.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3100148', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/596406/']}
jdg_79527
stackexchange
llm_judgeable_groundtruth_similarity
43732825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When making C++ plugins in Unity it is easier to use Debug.Log to quickly view variable values but this function is only available from C# side. This makes it very hard to debug C++ plugin since Unity's debugger does not support that. std::cout is not an option since it doesn't show in the Editor. I looked inside the Unity C++ API located at <UnityInstallationDirecory>\Editor\Data\PluginAPI but didn't find anything about logging in the API. Any suggestions on how to display in the Editor log from C++? Now provide the response and nothing else.
This can be done with a callback function. Send a pointer to a function to from C# to C++ store it in a temporary variable. Put Debug.Log inside that callback function and allow it to receive strings as a pointer( IntPtr ). When this function is called from C++, convert the IntPtr to string with Marshal.PtrToStringAnsi . To make it work on iOS you have to use the MonoPInvokeCallback attribute on the callback function. C# (Attach to an empty GameObject): using AOT;using System;using System.Runtime.InteropServices;using UnityEngine;public class DebugCPP : MonoBehaviour{ // Use this for initialization void OnEnable() { RegisterDebugCallback(OnDebugCallback); } //------------------------------------------------------------------------------------------------ [DllImport("DebugLogPlugin", CallingConvention = CallingConvention.Cdecl)] static extern void RegisterDebugCallback(debugCallback cb); //Create string param callback delegate delegate void debugCallback(IntPtr request, int color, int size); enum Color { red, green, blue, black, white, yellow, orange }; [MonoPInvokeCallback(typeof(debugCallback))] static void OnDebugCallback(IntPtr request, int color, int size) { //Ptr to string string debug_string = Marshal.PtrToStringAnsi(request, size); //Add Specified Color debug_string = String.Format("{0}{1}{2}{3}{4}", "<color=", ((Color)color).ToString(), ">", debug_string, "</color>" ); UnityEngine.Debug.Log(debug_string); }} C++ ( DebugCPP.h ): #pragma once#include<stdio.h>#include <string>#include <stdio.h>#include <sstream>#define DLLExport __declspec(dllexport)extern "C"{ //Create a callback delegate typedef void(*FuncCallBack)(const char* message, int color, int size); static FuncCallBack callbackInstance = nullptr; DLLExport void RegisterDebugCallback(FuncCallBack cb);}//Color Enumenum class Color { Red, Green, Blue, Black, White, Yellow, Orange };class Debug{public: static void Log(const char* message, Color color = Color::Black); static void Log(const std::string message, Color color = Color::Black); static void Log(const int message, Color color = Color::Black); static void Log(const char message, Color color = Color::Black); static void Log(const float message, Color color = Color::Black); static void Log(const double message, Color color = Color::Black); static void Log(const bool message, Color color = Color::Black);private: static void send_log(const std::stringstream &ss, const Color &color);}; C++ ( DebugCPP.cpp ): #include "DebugCPP.h"#include<stdio.h>#include <string>#include <stdio.h>#include <sstream>//-------------------------------------------------------------------void Debug::Log(const char* message, Color color) { if (callbackInstance != nullptr) callbackInstance(message, (int)color, (int)strlen(message));}void Debug::Log(const std::string message, Color color) { const char* tmsg = message.c_str(); if (callbackInstance != nullptr) callbackInstance(tmsg, (int)color, (int)strlen(tmsg));}void Debug::Log(const int message, Color color) { std::stringstream ss; ss << message; send_log(ss, color);}void Debug::Log(const char message, Color color) { std::stringstream ss; ss << message; send_log(ss, color);}void Debug::Log(const float message, Color color) { std::stringstream ss; ss << message; send_log(ss, color);}void Debug::Log(const double message, Color color) { std::stringstream ss; ss << message; send_log(ss, color);}void Debug::Log(const bool message, Color color) { std::stringstream ss; if (message) ss << "true"; else ss << "false"; send_log(ss, color);}void Debug::send_log(const std::stringstream &ss, const Color &color) { const std::string tmp = ss.str(); const char* tmsg = tmp.c_str(); if (callbackInstance != nullptr) callbackInstance(tmsg, (int)color, (int)strlen(tmsg));}//-------------------------------------------------------------------//Create a callback delegatevoid RegisterDebugCallback(FuncCallBack cb) { callbackInstance = cb;} Usage from C++ : Debug::Log("Hellow Red", Color::Red);Debug::Log("Hellow Green", Color::Green);Debug::Log("Hellow Blue", Color::Blue);Debug::Log("Hellow Black", Color::Black);Debug::Log("Hellow White", Color::White);Debug::Log("Hellow Yellow", Color::Yellow);Debug::Log("Hellow Orange", Color::Orange);Debug::Log(true, Color::Black);Debug::Log(false, Color::Red); Output from the Editor : Now, you can easily implement Debug.LogWarning and Debug.LogError .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43732825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3785314/']}
jdg_79528
stackexchange
llm_judgeable_groundtruth_similarity
1902109
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: restart application without restarting server? How do I reset a Coldfusion Application / application.cfc without resetting the Coldfusion Server instance? If I remember right, there are a few tricks out there such as creating a reinit function within application.cfc or renaming the file. Now provide the response and nothing else.
A couple of steps: First, make sure all your application initialization logic is contained inside the OnApplicationStart method of your CFC. If it has nested calls, that is fine - just so long as you can re-initialize your application easily through a single call makes your life much easier. Second, this is the code I use in the OnRequestStart method of application.cfc <cfif structKeyExists(url,'resetappvars')> <cfset OnApplicationStart() /></cfif> Feel free to use whatever coded value you would like in place of resetAppVars .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1902109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177260/']}
jdg_79529
stackexchange
llm_judgeable_groundtruth_similarity
20726881
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 ActionBarActivity from support library V7.However, when I specify android:showAsAction="always" in the menu xml, it does not take effect. I have to do it in the Java code in the method onCreateOptionsMenu(), to find the item and set the property manually. Is there anything wrong with my code? Why does this happen? Here is my activity code, most from the document sample : public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); Tab tab = actionBar .newTab() .setText("ArtistFragment") .setIcon(android.R.drawable.ic_input_add) .setTabListener( new TabListener<ArtistFragment>(this, "ArtistFragment", ArtistFragment.class)); actionBar.addTab(tab); tab = actionBar .newTab() .setText("AlbumFragment") .setIcon(android.R.drawable.btn_radio) .setTabListener( new TabListener<AlbumFragment>(this, "AlbumFragment", AlbumFragment.class)); actionBar.addTab(tab); } public static class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final Activity mActivity; private final String mTag; private final Class<T> mClass; /** Constructor used each time a new tab is created. * @param activity The host Activity, used to instantiate the fragment * @param tag The identifier tag for the fragment * @param clz The fragment's Class, used to instantiate the fragment */ public TabListener(Activity activity, String tag, Class<T> clz) { mActivity = activity; mTag = tag; mClass = clz; } /* The following are each of the ActionBar.TabListener callbacks */ public void onTabSelected(Tab tab, FragmentTransaction ft) { // Check if the fragment is already initialized if (mFragment == null) { // If not, instantiate and add it to the activity mFragment = Fragment.instantiate(mActivity, mClass.getName()); mFragment.setHasOptionsMenu(true); //MUST manually set here ft.add(android.R.id.content, mFragment, mTag); } else { // If it exists, simply attach it in order to show it ft.attach(mFragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (mFragment != null) { // Detach the fragment, because another one is being attached ft.detach(mFragment); } } public void onTabReselected(Tab tab, FragmentTransaction ft) { // User selected the already selected tab. Usually do nothing. } } public static class ArtistFragment extends Fragment { @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu1, menu); // Manually set will take effect menu.findItem(R.id.menu_item1) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } } public static class AlbumFragment extends Fragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu2, menu); // XML set android:showAsAction="always" does not work } }} And here are the two menu xml files: menu1.xml <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_item1" android:icon="@android:drawable/ic_menu_view" android:title="menu1" android:showAsAction="always"/></menu> And menu2.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_item2" android:icon="@android:drawable/ic_menu_view" android:title="menu2" android:showAsAction="always"/></menu> Now provide the response and nothing else.
Problem solved, thanks to the answer posted at THIS PAGE The trick is that I have to modify my menu xml file as this: <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:mytest="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_item1" android:icon="@android:drawable/ic_media_ff" android:title="menu1" mytest:showAsAction="always"/></menu> From the official document, there is a explanation of why this is necessary: Using XML attributes from the support library Notice that the showAsAction attribute above uses a custom namespace defined in the tag. This is necessary when using any XML attributes defined by the support library, because these attributes do not exist in the Android framework on older devices . So you must use your own namespace as a prefix for all attributes defined by the support library.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20726881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1153396/']}
jdg_79530
stackexchange
llm_judgeable_groundtruth_similarity
79943
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Consider the two types of Grassmannians Gr(2,7) and Gr(3,6) having their plucker embeddings in $\mathbb P^{20}$ and $\mathbb P^{19}$ respectivley. The first one is 10-dimensional and latter is 9-dimensional, so each having codimension 10. We can easily compute their defining equations and both of them are defined by 35 equations. By using computer algebra system(such as Macaulay 2 or Magma) we can also compute their Hilbert series and so the Hilbert numerator. If we do the computation then both varieties have basically same numerator, which suggests that both idels have the same(kind of) free resolution. This raises the question whether Gr(3,6) is a linear section of Gr(2,7) or not.? Now provide the response and nothing else.
I don't know whether the ideals have the same kind of free resolutions, but $Gr(3,6)$ is definitely not a hyperplane section of $Gr(2,7)$. Otherwise, their $H^{\leq 8}$ would be the same by the Lefschetz hyperplane theorem. However, $H^6(Gr(3,6))$ is 3-dimensional and is spanned by $c_1^3, c_1c_2$ and $c_3$, and $H^6(Gr(2,7))$ is 2-dimensional: it is spanned by $c_1^3$ and $c_1c_2$. Here $c_i$'s are the Chern classes of the respective tautological bundles.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/79943', 'https://mathoverflow.net', 'https://mathoverflow.net/users/19001/']}
jdg_79531
stackexchange
llm_judgeable_groundtruth_similarity
12664062
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 got a strange problem with date translations in my Ruby On Rails 3 application, and I really don't understand why... Here are my en.yml and fr.yml : fr: date: formats: default: "%d/%m/%Y" short: "%e %b" long: "%e %B %Y" time: formats: default: "%d %B %Y %H:%M:%S" short: "%d %b %H:%M" long: "%A %d %B %Y %H:%M" am: 'am' pm: 'pm'en: date: formats: default: "%Y-%m-%d" long: "%B %d, %Y" short: "%b %d" time: am: am formats: default: ! '%a, %d %b %Y %H:%M:%S %z' long: ! '%B %d, %Y %H:%M' short: ! '%d %b %H:%M' pm: pm This is not specific to a particuliar view, but for instance in one of my view : <td><%=l job_application.created_at, :format => :default %></td> I get those strange outputs : With locale = :en=> t, 30 o 2012 18:09:33 +0000With locale = :fr=> 30 o 2012 18:09:33 Where do these wrong "formats" come from ? I'm using Rails 3.2.8 (with Postgresql / gem pg), and everything related to I18n works fine except for dates . Thanks for any help ! Now provide the response and nothing else.
I think I've finally figured this out, sorry for taking so long. The Rails l helper just calls I18n.localize . If you trace through the I18n.localize code, you'll end up here : format = format.to_s.gsub(/%[aAbBp]/) do |match| case match when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon] when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour endend So the localize helper doesn't use strftime for the "stringy" parts of the date/time, it tries to do it by itself. Add the translations (as arrays in your YAML) for the month and day names as above and your localized dates and times should start working. If you don't have those translation arrays in your YAML, then I18n.t(:"date.abbr_month_names") will give you strings like this: "translation missing: en.date.abbr_month_names" and then I18n.localize will end up doing silly things like this: "translation missing: en.date.abbr_month_names"[10] That will use String#[] instead of the expected Array#[] and you end up with random looking single character month and day names.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12664062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/447074/']}
jdg_79532
stackexchange
llm_judgeable_groundtruth_similarity
142912
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: Taking the following simple method, how would you suggest I write a unit test for it (I am using MSTest however concepts are similar in other tools). public void MyMethod(MyObject myObj, bool validInput){ if(!validInput) { // Do nothing } else { // Update the object myObj.CurrentDateTime = DateTime.Now; myObj.Name = "Hello World"; }} If I try and follow the rule of one assert per test, my logic would be that I should have a Class Initialise method which executes the method and then individual tests which check each property on myobj. public class void MyTest{ MyObj myObj; [TestInitialize] public void MyTestInitialize() { this.myObj = new MyObj(); MyMethod(myObj, true); } [TestMethod] public void IsValidName() { Assert.AreEqual("Hello World", this.myObj.Name); } [TestMethod] public void IsDateNotNull() { Assert.IsNotNull(this.myObj.CurrentDateTime); }} Where I am confused is around the TestInitialize . If I execute the method under TestInitialize , I would need separate classes per variation of parameter inputs. Is this correct? This would leave me with a huge number of files in my project (unless I have multiple classes per file). Now provide the response and nothing else.
You need to look at the "Arrange Act Assert" pattern. For each test you: Arrange the Code Under Test and any dependent variables. Act by calling the method on the Code Under Test. Assert what you need to ensure the test passes (this should be one thing per test). In this case you will use: [TestMethod]public void MyMethod_CalledWithValidName_HasHelloWorldName(){ //Arrange bool isValid = true; MyObj objectParameter = new MyObj(); ClassUnderTest objectUnderTest = new ClassUnderTest(); //Act objectUnderTest.MyMethod(objectParameter, isValid); //Assert string expectedName = "Hello World"; string actualName = this.myObj.Name; Assert.AreEqual(expectedName, actualName);} This allows you to see exactly what you are testing and by copying this test and changing the variables, quickly write additional tests for other conditions. Notice the MethodUnderTest_Condition_ExpectedResult naming pattern for the test. To actually answer your question: If I execute the method under TestInitialize, I would need seperate classes per variation of parameter inputs. Why? TestInitialize is to set up the environment needed for every test in that class and run before each test. In my experience these tend to be relatively small since different methods you are testing have different dependencies and should be isolated enough that you won't need to set up too much the same for each test. If you need to vary the parameter inputs for each test, then it doesn't belong in TestInitialize, it belongs in the Arrange part of your test. In this class you have a test against a method on an unspecified class (MyMethod), and a test against myObj. These tests should be in different classes. You are confusing TestInitalize (setup before each test) as ClassInitialize (setup before all tests in that class). ClassInitialize can be abused and can make the order of the tests important. A test should not depend on another test. You can end up with passes/fails based on the order of test execution, which in some cases can't be specified, and cause breaks when tests are updated or removed or run in isolation. The way to make sure that myObj.CurrentDateTime isn't null when testing your unspecified class is to set it, you won't be asserting anything on that myObj in those tests. You can assert against them in the test class for myObj. One test class per object with one assert per test. It also appears that MyMethod is static. This breaks test isolation by meaning that when the code under test runs with works with other production code. This turns this test into an integration test (because the code under test and the static class are both being run during the test); this is bad because a failure in the static class can cause failures in the code under test in methods which are perfectly functional. I've covered a lot of different aspects of testing in this answer based on a lot of different principles. Grab the fantastic The Art Of Unit Testing and read it cover to cover. It's a great, easy read and is one of the books I'd grab (along with Code Complete) if the office caught fire.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/142912', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/50825/']}
jdg_79533
stackexchange
llm_judgeable_groundtruth_similarity
7993686
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here i want to know about strcpy() and strcat() disadvantages i want to know about these functions danger area in embedded domain/environment. somebody told me we never use strcpy,strcat and strlen functions in embedded domain because its end with null and sometimes we works on encrypted data and null character comes so we cant got actual result because these functions stop on null character. So i want to know all things and other alternative of these functions. how we can use other alternatives functions Now provide the response and nothing else.
The str* functions works with strings. If you are dealing with strings, they're fine to use as long as you use them correctly - it's easy to create a buffer overflow if you use them incorrectly. If you are dealing with binary data, which it sounds like you are, string handling functions are unsuitable (They're meant for strings after all, not binary data). Use mem* functions for dealing with binary data. In C , a string is a sequence of chars that end with a nul byte. If you're dealing with binary data, there might very well be a char with the value 0 in that data, which string handling functions assume to be the end of the string, or the data does not contain any nul bytes and is not nul terminated, which will cause the string functions to run past the end of your buffer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7993686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004437/']}
jdg_79534
stackexchange
llm_judgeable_groundtruth_similarity
28921
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: My textbook explains Newton's Third Law like this: If an object A exterts a force on object B, then object B exerts an equal but opposite force on object A It then says: Newton's 3rd law applies in all situations and to all types of force. But the pair of forces are always the same type, eg both gravitational or both electrical. And:If you have a book on a table the book is exerted a force on the table (weight due to gravity), and the table reacts with an equal and opposite force. But the force acting on the table is due to gravity (is this the same as a gravitational force?), and the forcing acting from the table to the book is a reaction force. So one is a gravitational, and the other is not. Therefore this is not Newton's Third Law as the forces must be of the same type. Now provide the response and nothing else.
And: If you have a book on a table the book is exerted a force on the table (weight due to gravity), That's where you went wrong. The force that the book exerts on the table is not a gravitational force, it's a normal force. and the table reacts with an equal and opposite force. That's also a normal force. So the book exerts a (normal) force on the table, and the table exerts a (normal) force on the book. But the force acting on the table is due to gravity (is this the same as a gravitational force?), No, it's not, and in fact this force (the normal force) is only indirectly due to gravity. The only relevant gravitational force is the force exerted by the Earth on the book. And the book also exerts a gravitational force back on the Earth, but because the Earth is so heavy, that force has no noticeable effect. (The Earth also exerts a gravitational force on the table, and the table on the Earth, but those don't matter so much in this particular scenario.)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/28921', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4/']}
jdg_79535
stackexchange
llm_judgeable_groundtruth_similarity
8429058
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 hope this question doesn't end up being closed for being too broad a subject but I was wondering about Responsive/Adaptive Web Design, i.e. one website for all browsers, all devices. What is the best way to implement such a site when it comes to structure and layout? I've being trying to read up on it since mobile websites are the big thing right now and will be for a while but I can't find a list of tips and guidelines and I figured that if such a resource was available here on SO then we could all benefit. Another thing that gets me is how is dynamic image scaling done? Out of everything this is the thing that puzzles me most because layouts I'm guessing are probably done using percentages rather than pixel values because pixels will vary from one device to another but images are probably the key factor in achieving one website for everything. I'm looking forward to reading people's opinions and answers, even if it is just links to tutorials on the web that I haven't found. Now provide the response and nothing else.
1. One website all browsers. As @Tak mentioned the answers here is 'Progressive Enhancement' and 'Graceful degradation'. However the definitions he gave are not quite right. Here are the proper ones: ' Progressive enhacement ' ( see link ) means that you code for the old browser first (IE6/7 with/without JavaScript is a good starting point) using tried-and-tested technologies such as HTML4 and CSS1, then add enhacement as you progress through testing on more modern browsers down to Chome and Safari on mobile devices which support CSS3 and most of HTML5. This way, you aim to provide any browser with the best possible combination of features supported in it (its never going to be perfect by the way so bear in mind the 80/20 rule to avoid running project into the ground). ' Graceful degradation ' ( see link ) is kinda the same thing but backwards, its a more lazy way of doing it. You start building your site against a modern browser and then apply 'patches' and 'fixes' until its acceptable on older browsers. This ends up creating a lot more work than planning it properly from the start and what generally tends to happen with this approach is that the developer/stakeholder will give up at some point (ie. what the hell? its too much work to get this working in IE6/7 - I'll just de-scope them) 2. Best way to standardise the layout Personally, my suggestion is that if you want a standard layout across mobile and desktop devices I suggest you use a combination of BIG fonts (so they are visible in a tiny mobile screen) and small ones (so people that have a Desktop browser can read all the detail) on a Desktop-size 900-1000px width. This site is an example: http://www.valuetrader.net When I open it in my Desktop browser I see a lot of detail, but when I'm on the go and use my Smartphone all the critical information (ie should I BUY or SELL a share?) is displayed on a very big font that appears legible in my tiny screen. UPDATE 2014 This part of the question has now effectively changed to 'Whats the best way to implement the layout?' . At the moment (and for the last few years of widely available CSS3 support) the standard approach for cross-device layout design is to use a so called 'Responsive' layout based on media queries . There are many CSS frameworks available to get users started with mobile-friendly layouts. The basic principle for 'Responsive' design is that scrolling on mobiles devices makes vertical space virtually endless so you are only limited by horizontal space. Thus you have to ensure that as the screen gets smaller you let the page flow to fill up all the available horizontal space, and any navigation bars or horizontal elements are folded over vertically so that items are stacked on top of each other rather than using space horizontally. The standard way to test a site's 'responsiveness' is by dragging the side of your browser window to reduce available width. The better way is using Developer Tools, for example Chrome has a button to toggle device mode, here is an example using Stackoverflow: An example of a media query to specify a layout for the #site-banner element on desktop and mobile screens would be as follows: /* DESKTOP SUPPORT */#site-banner { width: 1000px; background: #fff; margin: 0px auto; height: 120px; }/* TABLET SUPPORT - rules apply below 1000px width */@media all and (max-width: 1000px) { #site-banner { width: 700px; }}/* PHABLET & MOBILE SUPPORT - rules apply below 700px width */@media all and (max-width: 700px) { #site-banner { width: 480px; height: auto; }}/* MOBILE SUPPORT - rules apply below 480px width */@media all and (max-width: 480px) { #site-banner { width: auto; height: auto;}} 3. How is dynamic image scaling done? The mobile device does a lot of this for you so generally you just need an understanding of how it works. Basically, when the first mobile browsers came out they had to make sure that the sites that were already out there working for desktop browsers worked on a mobile too (otherwise nobody would use their smartphone to browse the web) so they had to come up with clever ways to detect the width of the site and resize it to the screen resolution that they had available. For example my site ' www.desalasworks.com ' is coded to 900px width, but it works fine by getting down-scaled on a small 320px screen (images on the page are automatically resampled using a variety of methods - such as nearest-neighbour sampling and bicubic interpolation , and the fonts replaced with native fonts wherever possible). As far as the image sampling goes, if you have ever pinched a photo on your smartphone to 'zoom in' and 'zoom out' you know what I'm talking about. You generally dont need to worry about CSS to get your images to resample properly, I noticed that sometimes they are a bit funny when using percentage widths so stick to pixels if thats the case to make it easier for the browser to tell where items are in relation to one another. Note that you CAN specifically detect the mobile browser and set the width of your site to 320px and everything in it to fall in-line accordingly but in reality this is not necessary to have a working site on a mobile device and doing this will force you to maintain 2 sites, a mobile site and a desktop site (which some companies are happy to do). 4. Percentages / fixed width. Personally I tend to use fixed width centered on a screen (using CSS margin: 0px auto), I haven't used percentage widths for a LONG time, mostly because its a bit of a nightmare to standardise the layout. If you do use percentage widths you'll basically have to do a lot more testing so I would tend to veer away from them. Bear in mind this is just my opinion, some 'reponsive web' gurus will swear by percentage widths on just about everything, I'm just not sold on the idea of sacrificing predictability of the layout for what I see as marginal benefit. But then I come from a background of building desktop webapps, I'd probably think differently if I was just focused on mobile web (where horizontal space is at a premium and layouts tend to be simpler).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8429058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634120/']}
jdg_79536
stackexchange
llm_judgeable_groundtruth_similarity
2310697
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: A well-known Euler's series representing Euler-Mascheroni's constant $$\sum_{n = 1}^{\infty}\left[{1 \over n} -\ln\left(n + 1 \over n\right)\right] = \gamma\label{1}\tag{1}$$ The generalisation of \eqref{1} is: $$\sum_{n = 1}^{\infty}\left[{x \over n} -\ln\left(n + x\over n\right)\right] = x\gamma +\ln\left(x!\right)\label{2}\tag{2}$$ I have no idea how shows it; it was base on a guess and some numerical trial we conjecture \eqref{2}. How can we prove \eqref{2} ? . Now provide the response and nothing else.
We use the relationship between the Harmonic numbers and the digamma function: $$\psi(x+1)+\gamma=H_x=\sum_{n=1}^\infty\frac1n-\frac1{n+x}$$ Take the integral of both sides from $0$ to $x$ and you will find that $$\ln(x!)+\gamma x=\ln(\Gamma(x+1))+\gamma x=\sum_{n=1}^\infty\frac xn-\ln(n+x)+\ln(n)$$ $$\ln(x!)+\gamma x=\sum_{n=1}^\infty\frac xn-\ln\left(\frac{n+x}n\right)$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2310697', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_79537
stackexchange
llm_judgeable_groundtruth_similarity
897469
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: It seems from playing around with small values of $n$ that $$\det \left( \begin{array}{ccccc}-1 & t & t & \dots & t\\t & -1 & t & \dots & t\\t & t & -1 & \dots & t\\\vdots & \vdots & \vdots & \ddots & \vdots\\t & t & t & \dots& -1\end{array}\right) = (-1)^{n-1}(t+1)^{n-1}((n-1)t-1)$$ where $n$ is the size of the matrix. How would one approach deriving (or at least proving) this formally? Motivation This came up when someone asked what is the general solution to: $$\frac{a}{b+c}=\frac{b}{c+a}=\frac{c}{a+b},$$ and for non-trivial solutions, the matrix above (with $n=3$) must be singular. In this case either $t=-1\implies a+b+c=1$ or $t=\frac{1}{2}\implies a=b=c$. So I wanted to ensure that these are also the only solutions for the case with more variables. Now provide the response and nothing else.
Using elementary operations instead of induction is key.$$\begin{align}&\begin{vmatrix}-1 & t & t & \dots & t\\t & -1 & t & \dots & t\\t & t & -1 & \dots & t\\\vdots & \vdots & \vdots & \ddots & \vdots\\t & t & t & \dots& -1\end{vmatrix}\\&=\begin{vmatrix}-t-1 & 0 & 0 & \dots & t+1\\0 & -t-1 & 0 & \dots & t+1\\0 & 0 & -t-1 & \dots & t+1\\\vdots & \vdots & \vdots & \ddots & \vdots\\t & t & t & \dots& -1\end{vmatrix}\\&=\begin{vmatrix}-t-1 & 0 & 0 & \dots & 0\\0 & -t-1 & 0 & \dots & 0\\0 & 0 & -t-1 & \dots & 0\\\vdots & \vdots & \vdots & \ddots & \vdots\\t & t & t & \dots& (n - 1)t -1\end{vmatrix}\\&=(-1)^{n - 1}(t + 1)^{n - 1}((n - 1)t - 1)\end{align}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/897469', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/60273/']}
jdg_79538
stackexchange
llm_judgeable_groundtruth_similarity
11375096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple class Apple extends from another simple class Fruit. At run-time, I could use Fruit fruit = new Apple();fruit.getClass(); to get the actual type of fruit object, which is Apple.class. I could also use fruit instanceof Apple , and fruit instanceof Fruit to verify if this fruit object is an instance of Apple or Fruit. Both of these 2 expressions return true, which is normal. But is there a way to determine precisely the declared type of fruit identifier? Which in this case is Fruit . Now provide the response and nothing else.
You're actually asking a question about the variable declaration of fruit rather than the actual runtime type of the object (which is an Apple in this case). I think this is in general a bad idea: you just declared the variable and told the compiler that it is a Fruit , so why do you need to now need to find this out? Just to confuse matters even more, it's worth noting that you can also have multiple variables with different declared types referencing the same object (which is still an Apple): Fruit fruit = new Apple(); // fruit declared as Fruit, but refers to an AppleObject thing = fruit; // thing declared as Object, refers to the same Apple If you really want to find out the declared type, then you have a few options: Make fruit an instance variable, and query the declared type using reflection. Do some processing of the source code to find the variable declaration Do some processing of the compiled bytecode to find the declaration type (although there is a possibility that an aggressive compiler might even optimise the compile time declaration away altogether, e.g. after realising that fruit can only ever be an Apple in this code) I think all of these are pretty ugly, so my general advice would be "don't do it".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11375096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113230/']}
jdg_79539
stackexchange
llm_judgeable_groundtruth_similarity
7084112
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is driving me nuts: HTML: <div><h1>Hello World!</h1></div> CSS: *:not(div) h1 { color: #900; } Doesn't this read, "Select all h1 elements that have an ancestor that is not a div element...?" Thus, "Hello World!" should not be coloured red, yet it still is. For the above markup, adding the child combinator works: *:not(div) > h1 { color: #900; } But doesn't affect the h1 element if it is not a child of a div element. For example: <div><article><h1>Hello World!</h1></article></div> Which is why I'd like to indicate the h1 element as a descendant, not a child, of the div element. Anyone? Now provide the response and nothing else.
Doesn't this read, "Select all h1 elements that have an ancestor that is not a div element...?" It does. But in a typical HTML document, every h1 has at least two ancestors that are not div elements — and those ancestors are none other than body and html . This is the problem with trying to filter ancestors using :not() : it just doesn't work reliably, especially when the :not() is not being qualified by some other selector such as a type selector or a class selector, e.g. .foo:not(div) . You'll have a much easier time simply applying styles to all h1 elements and overriding them with div h1 . In Selectors 4 , :not() has been enhanced to accept full complex selectors containing combinators, including the descendant combinator. Whether this will be implemented in the fast profile (and thus CSS) remains to be tested and confirmed, but once it is implemented, then you will be able to use it to exclude elements with certain ancestors. Due to how selectors work, the negation has to be done on the element itself and not the ancestor in order to work reliably, and therefore the syntax will look a little different: h1:not(div h1) { color: #900; } Anyone who's familiar with jQuery will quickly point out that this selector works in jQuery today . This is one of a number of disparities between Selector 3's :not() and jQuery's :not() , which Selectors 4 seeks to rectify.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7084112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/897416/']}
jdg_79540