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
40434367
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 cause a bottle of zsh 5.1.1 to be created for Sierra because zsh 5.2 has a pretty bad bug that breaks certain functionality. Sierra comes with zsh 5.2 which is broken for multibyte bindkey keystrokes (see: http://www.zsh.org/mla/users/2015/msg01400.html ). I've managed to get 5.1.1 to build from source on one machine but for broader distribution a Sierra bottle of zsh 5.1.1 would be much better until a new release of zsh comes out. The bug not only prevents binding of utf-8 multibyte ascii characters (I use a lot of Option key combos) but blocks other characters from even being typed if they have the same initial byte. I think this is the last version of the zsh recipe before the bug comes into play: https://github.com/Homebrew/homebrew-core/blob/1a4461ad2a0f1bc7074d9817db059147a31eeee6/Formula/zsh.rb Now provide the response and nothing else.
How do I create homebrew bottle for old version on a new macOS version? I've successfully build a zsh 5.1.1 bottle on macOS Sierra. Here is how: First you need to download all commits from the homebrew-core repository because by defaut it's a shallow repository (not all commits are present). cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-coregit fetch --unshallow You then have to select the last commit of zsh 5.1.1 with brew log zsh Here, it's the commit 1a4461ad2a0f1bc7074d9817d , checkout the zsh formula for this commit git checkout 1a4461ad2a0f1bc7074d9817d -- Formula/zsh.rb Install zsh with --build-bottle brew install --build-bottle zsh and build the bottle brew bottle zsh You then obtain the bottle file zsh-5.1.1.sierra.bottle.1.tar.gz Don't forget to restore the original state of zsh.rb with git checkout -- Formula/zsh.rb For installing the bottle, just copy it in /usr/local/Cellar , extract it with tar xzvf zsh-5.1.1.sierra.bottle.1.tar.gz and link it with brew link zsh == Edit to answer the OP comment == Official homebrew bottles are stored in bintray.com. Bintray is a distribution platform with REST api. When you launch brew install , it first check if there is a bottle there. The zsh 5.1.1 bottles are stored in : https://bintray.com/homebrew/bottles/zsh/5.1.1#files . As you can see there is a version for yosemite, mavericks and el capitan, but no version for sierra. You could ask on github to put the zsh-5.1.1 sierra bottle there.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40434367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370746/']}
jdg_372441
stackexchange
llm_judgeable_groundtruth_similarity
6192493
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having trouble with my array of references which point to another array. Here's a snippet of my code: # @bah is a local variable array that's been populated, @foo is also initialized as a global variable$foo[9] = \@bah; # this works perfectly, printing the first element of the array @bahprint $foo[9][0]."\n"; # this does not work, nothing gets printedforeach (@$foo[9]) { print $_."\n";} Now provide the response and nothing else.
Always use strict; and use warnings; . The @ dereference takes precedence, so @$foo[9] expects $foo to be an array reference and gets element 9 from that array. You want @{$foo[9]} . use strict would have alerted you that $foo was being used, not @foo . For some easily memorizable rules for dereferencing, see http://perlmonks.org/?node=References+quick+reference .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6192493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112678/']}
jdg_372442
stackexchange
llm_judgeable_groundtruth_similarity
471339
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 going through the derivation of soft threholding at http://dl.dropboxusercontent.com/u/22893361/papers/Soft%20Threshold%20Proof.pdf . It says the three unique solutions for $\operatorname{arg min} \|x-b\|_2^2 + \lambda\|x\|_1$ is given by $\operatorname{arg min} \|x-b\|^2 + \lambda x$ assuming $x > 0$ $\operatorname{arg min} \|x-b\|^2 - \lambda x$ assuming $x < 0$ $\operatorname{arg min} \|x-b\|^2 = 0 $ assuming $x = 0$ I am confused in the third case. For $x = 0$, how come the solution is zero. I mean when x = 0, I will have $\operatorname{arg min} \|x-b\|^2$. If I solve this, I will get x = b, the solution then how come it is $x = 0$ Now provide the response and nothing else.
I wrote a more detailed derivation of the soft-thresholding operator, following the source you mention and other ones . I hope it helps. The soft-thresholding is just the proximal mapping of the $l_1$ -norm. Let $f(x) = \lambda\|x\|_1$ , then the proximal mapping of $f$ is defined as \begin{equation}\operatorname{prox}_f(x) = \operatorname{argmin}_z\{\frac{1}{2}\|x-z\|^2_2 + \lambda\|z\|_1 \}\end{equation} The optimality condition for the previous problem is \begin{equation}0 \in \nabla(\frac{1}{2}\|x-z\|^2_2) + \partial(\lambda\|z\|_1) \Leftrightarrow 0 \in z-x + \lambda\partial\|z\|_1\end{equation} The $l_1$ -norm is separable and thus we can consider each of its components separately. Let's examine first the case where $z_i \neq 0$ . Then, $\partial \|z_i\|=\operatorname{sign}(z_i)$ and the optimum $z_i^*$ is obtained as \begin{equation}0 = z_i-x_i + \lambda \operatorname{sign}(z_i) \Leftrightarrow z_i^* = x_i - \lambda \operatorname{sign}(z_i^*)\end{equation} Note also that if $z_i^* < 0$ , then $x_i < -\lambda$ and equivalently if $z_i^* > 0 \Rightarrow x_i > \lambda$ . Thus, $|x_i| > \lambda$ and $\operatorname{sign}(z_i^*) = \operatorname{sign}(x_i)$ . Substituting in the previous equation we get \begin{equation}z_i^* = x_i - \lambda \operatorname{sign}(x_i)\end{equation} In the case where $z_i = 0$ , the subdifferential of the $l_1$ -norm is the interval $[-1,1]$ and the optimality condition is \begin{equation}0 \in -x_i + \lambda[-1,1] \Leftrightarrow x_i \in [-\lambda,\lambda] \Leftrightarrow |x_i| \leq \lambda\end{equation} Putting all together we get \begin{equation}[\operatorname{prox}_f(x)]_i = z_i^* = \left\{ \begin{array}{lr} 0 & \text{if } |x_i| \leq \lambda \\ x_i - \lambda \operatorname{sign}(x_i) & \text{if } |x_i| > \lambda \end{array}\right.\end{equation} The previous equation can also be written as \begin{align*}[\operatorname{prox}_f(x)]_i &= \operatorname{sign}(x_i)\max(|x_i|-\lambda, 0) \\ &= \operatorname{sign}(x_i)(|x_i|-\lambda)_+\end{align*} where $(\cdot)_+$ denotes the positive part .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/471339', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34790/']}
jdg_372443
stackexchange
llm_judgeable_groundtruth_similarity
17337789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Am having the AJAX calls to my controller in my MVC Application Controller/FunctionName$.ajax({ type: "GET", contentType: "application/json; charset=utf-8", url: '/Controller/FunctionName', . . . )}; Am using MVC 4 and making use of JQUERY Ajax function as shown in the above code. It works totally fine when i run from Visual studio. I depolyed this to the server machine and as expected it works fine . No issues found in AJAX calls. Now am trying to deploy this in my local machine IIS which is same as my server version (IIS 7.5) but am getting 404 for all the ajax calls in firebug. I verified the build and even i pointed to my web folder and am still looking for what went wrong !! It works in other IIS so It wont be a URL resolving issue is my gues. Am i missing any settings or Any timely idea to fix this would be great. Thanks Now provide the response and nothing else.
That's normal. You have hardcoded the url to your controller action: url: '/Controller/FunctionName', If you deploy your application in a virtual directory in IIS the correct url should be: url: '/YourAppName/Controller/FunctionName', That's the reason why you should absolutely never hardcode urls in an ASP.NET MVC application but ALWAYS use url helpers to generate it: url: '@Url.Action("FunctionName", "Controller")', and if this AJAX call is in a separate javascript file where you cannot use server side helpers, then you could read this url from some DOM element that you are AJAXifying. For example let's suppose that you had an anchor: @Html.ActionLink("click me", "FunctionName", "Controller", null, new { id = "myLink" }) that you AJAXify: $('#myLink').click(function() { $.ajax({ url: this.href, contentType: 'application/json; charset=utf-8', type: 'GET', . . . )}; return false;}); Notice how we are reading the url from the DOM element which was generated by a helper. Conclusion and 2 rules of thumb: NEVER EVER hardcode an url in an ASP.NET MVC application ABSOLUTELY ALWAYS use url helpers when dealing with urls in an ASP.NET MVC application
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17337789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2067567/']}
jdg_372444
stackexchange
llm_judgeable_groundtruth_similarity
42238183
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 Neo4j CE 3.1.1 and I have a relationship WRITES between authors and books. I want to find the N (say N=10 for example) books with the largest number of authors. Following some examples I found, I came up with the query: MATCH (a)-[r:WRITES]->(b)RETURN r,COUNT(r) ORDER BY COUNT(r) DESC LIMIT 10 When I execute this query in the Neo4j browser I get 10 books, but these do not look like the ones written by most authors, as they show only a few WRITES relationships to authors. If I change the query to MATCH (a)-[r:WRITES]->(b)RETURN b,COUNT(r) ORDER BY COUNT(r) DESC LIMIT 10 Then I get the 10 books with the most authors, but I don't see their relationship to authors. To do so, I have to write additional queries explicitly stating the name of a book I found in the previous query: MATCH ()-[r:WRITES]->(b)WHERE b.title="Title of a book with many authors"RETURN r What am I doing wrong? Why isn't the first query working as expected? Now provide the response and nothing else.
Aggregations only have context based on the non-aggregation columns, and with your match, a unique relationship will only occur once in your results. So your first query is asking for each relationship on a row, and the count of that particular relationship, which is 1. You might rewrite this in a couple different ways. One is to collect the authors and order on the size of the author list: MATCH (a)-[:WRITES]->(b)RETURN b, COLLECT(a) as authorsORDER BY SIZE(authors) DESC LIMIT 10 You can always collect the author and its relationship, if the relationship itself is interesting to you. EDIT If you happen to have labels on your nodes (you absolutely SHOULD have labels on your nodes), you can try a different approach by matching to all books, getting the size of the incoming :WRITES relationships to each book, ordering and limiting on that, and then performing the match to the authors: MATCH (b:Book)WITH b, SIZE(()-[:WRITES]->(b)) as authorCntORDER BY authorCnt DESC LIMIT 10MATCH (a)-[:WRITES]->(b)RETURN b, a You can collect on the authors and/or return the relationship as well, depending on what you need from the output.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42238183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5913102/']}
jdg_372445
stackexchange
llm_judgeable_groundtruth_similarity
50332040
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following Flutter layout (two rows inside a column, each row containing a text widget and a field widget) compiles and runs - but the text and text field widgets are not displaying. What you are supposed to see is the word "username" followed by a text field in one row, and the word "password" followed by a text field in the next row. What am I doing wrong, please? import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Welcome to Flutter', home: new Scaffold( appBar: new AppBar( title: new Text('Welcome to Flutter'), ), body: new Container( padding: new EdgeInsets.all(20.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Text('User Name'), new TextField( autofocus: true, decoration: new InputDecoration( border: InputBorder.none, hintText: 'Please enter your user name'), ), ], ), new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Text('User Name'), new TextField( decoration: new InputDecoration( border: InputBorder.none, hintText: 'Please enter your pasword'), ), ], ), ], ), )), ); }} Now provide the response and nothing else.
Per https://stackoverflow.com/a/45990477/1649135 if you put widgets that don't have an intrinsic width inside a row, you must nest them inside a flexible widget. import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Welcome to Flutter', home: new Scaffold( appBar: new AppBar( title: new Text('Welcome to Flutter'), ), body: new Container( padding: new EdgeInsets.all(20.0), child: new Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Flexible( child: new Text('User Name:'), ), new Flexible( child: new Container( margin: const EdgeInsets.all(15.0), padding: const EdgeInsets.all(3.0), decoration: new BoxDecoration( border: new Border.all(color: Colors.blueAccent)), child: new TextField( style: Theme.of(context).textTheme.body1, ), ), ), ], ), new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Flexible( child: new Text('Password:'), ), new Flexible( child: new Container( margin: const EdgeInsets.all(15.0), padding: const EdgeInsets.all(3.0), decoration: new BoxDecoration( border: new Border.all(color: Colors.blueAccent)), child: new TextField( style: Theme.of(context).textTheme.body1, ), ), ), ], ), ], ), )), ); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50332040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9788574/']}
jdg_372446
stackexchange
llm_judgeable_groundtruth_similarity
209039
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: Recently I asked a question about the morphing between two functions and got two excellent answers. The accepted answer is using the continuous optimal transport theory . This seems to be very suitable for this problem. This figure is made with Adobe Illustrator, MA solution is desirable. However, I have difficulties to convert the code from symbolic to pure numeric one. In particular, I do not know how to numerically construct inverse functions and derivatives efficiently. My intention is to apply the code of Federico to the pair of two functions such as shown below f[x_]:=UnitBox[x+3]g[x_]:=UnitTriangle[x-3] I take the liberty to copy the symbolic code here: F[x_] = Integrate[f[x], {x, -∞, x}];G[x_] = Integrate[g[x], {x, -∞, x}];Ginv[q_] = InverseFunction[G][q];T[t_, x_] = (1 - t) x + t Ginv[F[x]] // Simplify;dT[t_, x_] = D[T[t, x], x] // Simplify;ParametricPlot[Evaluate@Table[ {T[t, x], f[x]/dT[t, x]}, {t, 0, 1, .1}], {x, -10, 5}, PlotRange -> All, AspectRatio -> 1/2] I am seeking a pure numeric solution that can be further applied to any pair of interpolation functions. f[x] and g[x] presented above is just a simple example that cannot be integrated symbolically and because piecewise functions are hard to invert symbolically too. I've selected them because it is known that MA is not able to integrate UnitBox and UnitTriangle symbolically. Edit MichaelE2 suggested to provide interpolation functions. Below are two strongly truncated realistic data to work with dataA= "1:eJx9m0mOpclShUuIPVAMWQAh75s9MKoVIAZPYsTgsUiWxXd+99/dLlyLLKmyKiPSrlt37FgT//If//XX3/7njz/++Ps/8q9/+8+///ff/sH+31//zH/8a/mZc+Y0z68Wev339vPXn3w1/OSYcu2xhf0rpcYXHUGtxDETv41UYop5ZiMo5dRC60jPvY1R0/AFpRnKqFtU7uP53ldQLrXEOCtPiTm01P0XjZln6GPMUnrKLcfSjKDSIn/+vDW0wBerL6iO3nrcb+qzjmQE1Zk7fxxCDanytJR9QTwjbQPxoWXMaQT11EsNocxUWtJruysIrTBRf5WLOT9e+6claLQRI/LXizC9L6fKoK9XSmvVOK2EODuPLDkRAiPM4GuGdVIo+TVSDsNoVuIMtc4Wz4t877eBV3PjtxIJFxxdjKCMUj2lHkYticBMvtPkqHTCUWoYp5VaeykNBcOspXde+P8F/bkFxUSYrHDDXCGaKCq9zMxTntfk2sYvzsddpEjdXsu9R6sZ1ilhtJ5Gk715si+IzwvbAnxmJnivoIpKgTf1vIyICX1BoWPQuP0/SRIrCPukVFJLg5f1GH/JfUIwxZ1mcUQ+2dio6osBcStnI7J8QRmfj74DCVsH4zT5noxpxPckffucvo0Uu3mEEhIyQsFxBkQaBq6hjdcXpJIrCF36fI0Z9SyjGnrmB9pyjg1UGL+k7PMt7f3O2WM3qdZDlqXzC8O83BVETNf4wmMJGL0bQUVeAF5HKZg9huLbSN7o9UQ2ZjLQL0uH3PMbZeSvL0hPL0dSBeSuoJHniGkmfge2Z0eUKyjOSOyONytjn8ZrwDlRVBeCEPY1+gFJms2a4862QVqWi4+zBn0V0H9iP/dfHpQCj98lgvJX8nFa/CG26hxA1EraHKvvNNKVCvLiFgV3dCNoElg1lJOIv7wIBEWxF0ixdahXECBM7SAia+zULKq5D0foTnnMO/0HpdSolppSjNK/Fa/dQ+z8Q7CmIs9OQqaGWG5Riz9yZlRheTKWMhW8DEFQqTGcch1zmeUKAiBTm4ovvbkg1LMRggIocaIojxHTFdRa1J8RQQ+wUfY8G+UfkGhQlA8g8c1XUG+ZAjPyY+k8W3MBMisJGuCwc2CElQRbkHQZGX13DSnzlxcRJUXFWMgWKM/hQHYijgYm7C+dGz6uZV4/S9hlH6Ro/cnvJ0PST8IB0JE2Z5moD3Pz5Qi4HtcKIfPotdwHFT4EExGRD/DV7IJI/uHDIAaz8WwRIEpOuoJkPAoINfJJthmaV0MQhF/G/kSglkwZV9CktIKZ/APk1kho+PHYhKJvnPQAah+n5R+Rx1wFbo+ROpzLFSSGGOKhtMLJKwi7ATCg70pE0tB/Ua3ASDwcotc+r6AWlWM4czGIPH4JowogwoleyKZaGtVGVJzWQdGu8OuS3DqbfwrY2udJkZnz8RoQAxqRslFslkdXv31AEKgGHr1Pqr2NK0icBgM1Uk5pTbL47qdIE/oPexTYtnarGkUYxKxiXs+TMKXL13AM9bzuTxSQ1BSNoNlxhYj3QwxKdJEWQSplLwAqOmu/gvBXEfOGEhDc9DO/BCTtGA9Kb12bqRvVSiQNIQYLHCLf4L8owXjz49xHO3Deqhbh3BSXXR9JXq+sIYj0nqefSaSbUS1RPPlyX+1DxKt+9idYYX3rbBSJNapBYpI40wps8rH6uAb8hXi830XdX1xTYZDLgZfFjRZNdeTkNvoCZMF2RrWbIcDj0wbu16rz8QUFmN7DQp+STZybVCOmQlfMPw0W6Fd97/PcOhdVE7gB/hZF1MfxzP0xYZFCR5Ca3fDSH+GbUQ2FwaLQN641H/sBUzV6+xtBAIL8qMYXwaIkWvuEKxzBpf18L25pix5KnJqSKwi50BOc/1Qq6ET1jC14JwrH20E/Db4pIrgJqt7UyVInh8/XEmQTJnL6a2zyUdaAOrUQu5zHETyARJA6zX67NdNjUWf5u2Rr3jyF2u+rNpQbzZDjVdZWwY6wmqQcWuHapu80cAucOFwEgxvNgqAsUsxWnGEv/0G9BqDhYv+4VS1qiEMlp5at8CCMvHhEEPk+ys21ng3LAoSzMGSHPZTbtzWexZhHN4ieIZA9R0g3edFX/0hX6gsqZYZdRwVdVDFDIImIquKwIT26+KiQI4VWcouwQWuNakQGFF6cTTUP1tZ9GxFEyCm71XiixnBjAOapB6ua59WlOIIyeH0GPkWTOkP7yRxCIL+zt/ZLqtGv5HL6kAbrN/FIAFKFNRAUNkDr/XgsSvxTHLF1LheNoH2P2jsNVbN9QTynHp8FGK0parB4yiXosWGtZK+EpB9xuvhQ+oeLYu1+XwSbDDFiw/WiGdxBDYJa7n3NRAQ5NBsWRODv6JV2uMK/fXzM4tAb96FTNEY2HlvQaO79lBp/8X7C0BpfzhVKddHf0z3i+cdn61f4JfmpxxCIeLqoNs0wazT15zGfIjK+eO3PLShp2rXqMYyEv2XnNE3JGnewZmLSfZBSop/5YyG0zVSkdBg2qr3BOtx2FkEVI+U7Fct2AEkDAzuGCm7CM93CjyD6zHnJmiZRV1DSmBMIP23KL7mv76oHQ7BTN6opSWN4podPR1O6j0ahKBUPyQYijWrow3MhbPvF7VtDs51G0NPRvKSmEL9XTqQhCJpvrgSCkXq2pkqQHWm+NaRRvY1mxHkQ1XuhKlQvQRBENo1hcrYZzaLqT1a7tlJtuB1WFEMUPr42olQap4kTany5swds8mxN3SIUQ39HlVlV1QgixJ4VyTsy/UW1oWnqOw+nds9pRlkUfToaAO9FPV+zIaK6CZYweXSrGbSZEBvnc34RRGRAVd7eAXFtmAeRrDyypo0N7oD+KcgQ8fpOvGsJ1meQAc3wjktdCIkqNrRf43RYdl8UnyUR1t+dRXMntA+QQmjXeFYejrV/CIJOpKO2T2gQpG5lU1BSCWL/oVnVvGe8Y4WUvdUDDIFwHPEdMBHF88NleYAie8NB8+/HEKakuQqn4+uror0xFLS/Si/bjR6kIYdOJ4R3uijYt4oBBFWTtwVoOXzb8mzF+E5i8WzCogUiPEaZJqzLomrFJcXIqeDhmRiCt719pCv9snZY68XDnTwjCJC4y0CAzU7n4zMgg+CcCY6vmYpePvQKwmEWc5FOHw4SzkTBfw88HH/fMcawQ34FVdFWaoN+SV5jjSA+qbbbNvZgFWvaR5JpOwnzt0ZmKwaDooAemo69jZwegF+w6fWZS0GQA7vs5bCi/H8EqSJi7HcD5HJrBAWKerlVKFrqELX6om94mUX7hrBbM3APAnoSv8yPaqbpFjbcq6TYfFNDvAjrY2u4aDO+n9rukBWbgww/W8HUHu/0WsYwDyIqAJBUFkbl+C1dt2K0AmeELz5j1zIiEjR4VMUdqdVj1lp0QL4O01d/bQlIKDTsavdWvQ8usw4/ujUYpwSRSC1bQZBcEviF/DG/+P7PLaiqKTsWGiuol6XxN0SmzbCDzO3zEEPEh9MIz/Cx21XfAdEhRXZsuFkG44VRtneWDsXqwyqm7jzMZxyhA4DwrTvfiqmwpncGzuvax4MGdUzFfq/kXBaLHAHeW2Iy0Zs+BWm3B6jsOWjzTSRQLPWeGpT4odnoz5pw5+v4tnDYmpHzOdxVSk7TyhExo4d5maB7soCcKAucVRpx+aFZ1d6a0v1UOkGEK6h1Fd+7uligdYJIJwPxpEfwFdPdy0h3UDwszQ+inJoArRo+3XMVrbfJ9GTmcsMC49SVie4MFs3vLrHSwh0qGM8cpNX2AYyzqCnFgguC3SKEIGh0C7fv/PAZAYaUQe6/5ddXjTyi2zhEv6dgkVFjr6KGcXVvwyNW9HFa3s3DrEYYxmURaIEQgQfLgO68UXckIoy3mH1QT9iQGkWyYr23uqN9+kGAaN5RGo83zpcM9cl8yAp5d1SAIB1edeM0W6YDJH8C36JXqzHxEz+D0Lcd0HnAtIKyhlDPMdYa7nvlldAVgB523vS0D0E9FJ0svAMp3/laUudbPGLr40PQCAr2N/XLL4KoWfNqRkB9qsbf1Vv7quMu2VMOaIn+zktk3PFpbJGrFuPyxLfToFdQ0dJy3rncpyBIJGjAexZc/ZJp1Aa1wvHl6N1W2ACxrbijaSX77FH9DBGVz/FedJltgwStMaG2RA9NaX5k410K7LmgqcFS/QBKzaHeBI71pLUfR881UrgXC82CSNC5WwNH4AIUNyXJd5yVOWkGLzpSc9LHg6qWx0qR5wTJY0V8K0/Plw+TENZngLU8AWRP6Z2+TZz2t6oFvHsdMsreqmibjQx+E+z3Ml05UZOAO/zWVl9yZD36jh+KVMTQpav2y7VfUG3jH9rUu/mKxY4/H8zUmUl+cjB9258fYqj54ilEI5qFRSXTgSnyZi1Aonc39wymWi63pUrR7PM1qA2o1KkvInEjuPbRRrTfXSX5eDA/YmeKQNAMdY1Hv0H1ntyFNqPdna6R/hLD/1fRKoW0x4W3GApwvbvcUaJdMUztQ0LVNYX64/KtJd9yuhpTs1zOw2gF+dXSmMBZ/N99Dsal6TDrzktgEx7QKDfp0O0Rlr+dAm45BYpyt++khbnhocSTt9TL+fRH7WsMbjlQ+nhXQlBU4yzq6Zg6DysrZbwBo44Ye2/3NTXaeTdU4ZnBou4D0PHbiduWI9i89xK6VLlyBAJa5Nay+uw0nH4DOdq33AOOUqZZ45CxQC3olNbpa/s2yt0DbS0T7kUJvYDRS+DfNUgfzyGVdvCuHFhFuicuuhu+cqCH5EHR1OuhU+HbRcGWo0C+Nzdx2FHepCBpx6NS+DjBFaPiFw6RLjRAhgUBOk13UjPsRYefFCp85d4k4bmPpYIGK5E437XNG8IgBx447pHUTNmohbVoNRSAmyC50fOMEOzRliV3/YknIGUuFhm/dYfn5ZCe2/r0YO8siVF1Kik8rAUkc6OQ/MzBnrUloxaR3DV2FD4Blt3P9amx8z2zE4bd5yj8NFPOO/W61/goPrSXOxPlsS7yXjnasjf1mU+BjOvS/YucKIJAZ3g3LnEatR5QrrqZf/SuwQmeKMIy+qUZwgfzHP52UhDu4IrfDtG2HApKvO1la81M8Krwi9qXX57m5ER8xrz1zhPp1Q09UEPY1KbtxqB+63m2HPSZ55JVcw17o63JIFX2bayGRzO03Ksl3+uBEiwxrOJfQFt+OysPeqJIeO0XmXOsVq+olX/XHHgNub4t67ecqgH7EVNqSNfM69izz7qxySvrUV0KxPr82EksNrfW3RXAtQdK/dvwbhcDwHve6+xQ7RJBLBrpulBb3eJ0zUNC0e295+JttmrcVbSkDWG85Tp9a7+2HCzQ7/36WCfBr3kUnzCPsFsPP7dgIFSBF3iQaBsUXQhqb5ZfN3gDt6jGGyu/2yptLYxauWlqFwmeVUdGduWQOz2E25/kZtyl4+BetKJeWVM8nhE1mcANp4MHUu0P0hCUAFiPL2f0QUPrgXH5Qck2u6jVVFkqzp7DN99dkNmY7M+I2D1EDlR6+sS6Of7X1nTLUVDYH1qx2aXlrH46Ymw2/HU/v+U8GX62eS3Zn6OgpsW1AFyn39HPdrQCG85aHasaf2lFwxcx726kv53TbTnlmV7cnzOymywdEabn4Hj1h92j3yLqWimauyzbBCaqiAjvYY7fthBLDp0H2W4OF6fVC320fukbDLLXLCGnPj/P8jJDGs+PqSY1nayp78zi2955y6GYF/ujanZUrz091GfMd1717VJkU3W1A5enqi02coZ+AE93ZHtO7cfhFHRfVNWZmpEDjuoeqf22E9lyMF4P91fNVi/Cs1OKx/vThY99/hcRQ4hM";dataB= "1:eJx9m0uuNLeRhYWG12DJPfPY6AsG39xDj7SChgcGPOqBe5FeVn+HjyTLTpYA6er/q24kGY8TJx7557/+7+9/++cvv/zyjz/wn//++z/+72//cf7p9z/xP/8Vf1procS2/snVhf/JP7//xqfuJzpfXA5lfcoX+fBfBP02BeXoQ/T8qD6a9+YPOVajpVZ9tuByCrE/5HIg31wLqQ1JoaaUJejXISikFFJwrcbmY/Y5X+XUFlrytbYYiw851BKPA6UQYi1myZUUCp/Gu6BUq3mr80jNmh2Cik85mQtlfCG2+824TS421OOyS9mXQ1DjrCnVcZ5ai0tXQYVvBlfKvBzCDpsliy1ZspxDsJxKdHa1Gc8Kza1HxhLqISdU45ddtOJqih4t3A9kXKotHaBNy4egHIOVllMrrbaWqn9xoiko12CuZn70xzYLh9FSs4g/1JCtuubwtbs35sgTy3JGl9Kh6uzNoveeSxXDoVr+ciDz1Zflt8FhmENQkhj8HmsGZxHVXwWlgooz5+hWw9/i4UUon5tGpCQrqZbwxa9lipjqPDxHG4JGfOCNiaB1y8m6h13kOKybVgDU5sphs5Iz4RODt+yqiy5/Mb48MMcRZVYxUTtsVgkNCyHIvVCWtfISH9NmEQfygNHwI3R9eHXNhF3TbfvNzJW7qvH4VoOTHgz/LQMlpqBmUlDKuXCoDCKlu/H1BUAtDH8EB91hs1aSywqLLDUlwPEesEQivzsCsnp0bW0Jsh8cmVhLmfv1EMntLojgStlNbMR8MaUtyCz4kHzpYgjr/AXU8Gjc1i/HRmw8BNWaQZUoXETtePY90BChJy5JHG7L8RgRxbgBIMVKuLsjz7FAGAD+KRbcyNUtCPUUQiMtp89frM+3Wqsgew81gi37LSi2YgBtySOBpG+BRvzw2IHVim6uuQVlWdTlIjQj8Lnj3Y0kxvJSQpB5VsTaTyH8sANolD23ti8Q4pLj6o4fPhnfdyFsOWhNkCiP1+cufpFDCCiJztgnjz6q9j+on1Alj3Gr4skzV1WHn1YdGW/iOqotNW9BoCbYKi8ireDT8XozBAGdxEBbIJJ3QvM/Mbds2B9EikQtKekloS1BXN/CdKKCqkPbgki+EuOXQXPxV0GwhYpm6kCjTBY8rtYIPEzBfYOCFte8eRGCApBn85v4pW/P1QIuZimT9afVqk+3AEGQQ9PW0VhWBpnbFsQJsBu0yYYfJbvhdQDbUbcbGR9IBijzFoTxHXm3dVTwaCh8ERQiTGwCKUQCSNqCSoWeBRJePxEB/ZZkfx2CcmtGBppBCbRtMfxVdvCQafziv9gs5ygdTuKDqsMDjkQzRxUH6X4Bu8rlfjE0SJ4fAQl4QRf8FkT2xcUgO17IbzCbG1yjTXHrvJij98TJFhSQRKDFEYjig/cAgRhmlyemKTP742pcN3QOOqla+RJpCY4O1i+8jiWeV8vilQDLogRvBGsKirUGH8uKEPRQD0GhEh9w0O5ixonvAQIIUx24eSRz47vLaq4qxS4egi3uAUKR4WJYSkCohdOPiC9ONeDcv1cyU1AA053vuU84Imq7BXWXAOtEZmxc8i4IX4O3dM8lRuQJC7DlZJyXf3tGI5Fc6QNyjCSLO8+kRkVkWw7Mi991boaPveH1b0OOL9jLwRBGXifA9708ZkyCqCFGlPd6Hi9S1FYdA7qlA0FwU24TV3pBl3dv9I503J4My6GeE3kgGGpLvTATHme7lVYAaYHj11WqAMjuwP0e7FQV0xA43F3VRFKzMkxSxYDPlEY2gaNgR0EjdDB+wX1YEwlipWNL/kxpQSUuwTEeYl8DzWUelSceQzuwz5FkkUuIlO6LVLv2xYswFJVh17Qs44fHTUGoN2cjwmaiSldlk/6o8AiLnvKJfxR6MKymTA+uLIblvwmiuoLytMUggj84H9ARVDjM+OB0N4dEEFrgHL0lEHSVndJgWCSzRlZZlLDUm7LxORnGr8IaZe8qDc7XitC1LYSp+QZGCOJZzS/Kp+x8kkfqoADxW4U3UXsXRHAk21jky9MOMWpBbI9/rWZJux9IsGEuP0Sk2EmL0T9+bbMPoPLoLgjukFtbyC/acQiCVSltjqoC/nRFEQQRFJx8xRqofJQgGJ4whZz0hA3nc/cTZVGWJ5ZIIvG8GswkVQrrQdShB7e8jyDl4zIKOsJK5eoBR3AQ9aOGZ0DFyv1qVEEVaMuTrekWBzOijIU0lFHq4/f5RmlAHOgDiSNNsgEE2hbUxAF15mGLeEfaDl094iftc0d5JYiBQXjhZgdJQvaLIKcezFODqAFxFA+h9kPNeoAy7a5s1OkhP3EV4paPUAvqpMkPRyMIynY/ETLgPstoJOddp1GlOyozU+OtPyVCfa6CSGnYAnY1sAtnSluQUqYpAchoYmDX4hpBfJmKbvWpONDZMSSciZm2oKHmLyfC7NUG8IvT5nw06IL4BCSyc1RVx9c2llclDm0dISBfGmqYgpAORRVdHpf7djXImAqwp1qt+WjzwlGci62uVpC9NXuWIM/R22RRSX3eo7GmNlKlWFq1hV3bT17NCo6xWo+xWTmuZgp4oe+C2nCPNeAIgF9VMdV9Oq4mxq/EsLzDXQss5VKQqCy2Bm77w2rmsQPuMVt99V7NEk4cnrS8aj686byalE/+DKtb6u9WI6+nlNok2V7M7RCEOdXkecrvLxmbr5IlVpcBZdtxNaVOYf7ockGVwu1q0IQCCD7QVXCD42pwNZQDGZzOUa5QiyDqixDKsgtQa6cgyBG8Z1cXt6shyGWVvUtJNrBr9lWpzzgsAPHA/1VOd0UfFt2EuR/tUFe8OuC2SFhIt+BHkKYFtlrhfPXsPhLypNq6Wyb+lh8RxLOKe7o0qPs0Wm7du1bnrVzrGVNXGF4/ywenhHJeLZMMgP/VWHD1RkYQREVT28xqQv5wXk0By+er83Z3bFGyDFI81J6g/bgaKaZRXK7y8YprCIL8ooM8aYImLKcgcnYTfxp5Dze/C1JHuAweSvxTxNinssGj6dVZmHIVpJ6izzPbQD3xgtP8xAc14yrBXLvBEYJS7x6kWfdlVz4dEpRGd9P+KOAuyJPL0soSYTKgRxDsIsMNlzHy/WpRbYb4zGZK9R9XayqMw9N9uTaNEZTUVV8xgLLdeTXyAmBW1xygXRs14q1qDzza5ADHUMWNeM6L8l47R/AWEWmfnuZa/gi1quEDtdXK5/UOa4E7RVuxj0OeWQ2gVbFDnAx3zV9UpA6dW3wcbu7tNBqOBcmFqU2mci0g7EdwnV18+Lo7J2EUsKrUol/tyWv7GUG4vUY5kx7h3IfRzBH4TeE6rp6/uJHXbLK5JxvVz6wGv8oImlwlfLEajBW/DTv6z1CjaMr4NIqbOvziRmSiKmUubaf2cbUi9G/5KTDuJyKeiabVxsbtyuGPaooV9L/w6FoamZg9OphOnaTU8iGH8guYmSH7BWdlFSjEJP1Ubf7jYlV6s3nYXN+8qLeg4OO4bohPKiq1fsiBmvTJ1Ej8V00jhyTaonseWT7oI7ChDkeYqJb8TdMIosbUFHx1IXL4uBnlDl8oq6d87WO6n1pVaKw5J79pH97o7eTq+drwQVAnPGvDgcrsM9A0PzRKtTlLvGKIZq8Avk0Y5aH2ka7hOjE0QmxwiJFe3gUVtUBdWgsHweIHxyKjwAMfMpduFBtBUV2auka8RO8H8KsO0VRl+mO6X62Y9zC9NVPz+SOnZVWELVEVdHPYW108/TFD9CkLnyFGOmGW+kYJIcUJVVeqjhyegtmepnH0R6CBv07ZnLQwx9d3OWrRlBWv6oCeF8OEHElcpDc7vHtR9byYRo4kht0VqR9yULNmKStT3QMtBZJ6yitnFXcGmlOvTaPEMqHK321PqqZIb8tLqPg/buYVO1G0cO7r/LugX4cgdZh89A/FKp9isrKuX/hygzStEoE3IT0JzXn/KYjjQgOWs941pIEuie+BkBDDhyCUo32NaYc3sJ4mCyKp3h6bfR7INLdrBNvMd3cACerf2V7ecO3TZBrOwC7nCOjaoaOeJ+g5/mLpyPkwWSdYAVuszZ67oJR46MoeGoKeYdYHc9xIc77uGnejEfWiD+tmqllPQbB2wr4sdLzSInUY0GCdtIeCr3xwWSgyVhXTW2nhajQTryyrrxJDOHXtEvLxZq3V9efcjW8af6w+vnDkdCIhkdMCUZrE4i7Hae8pP/2O+OGMGoH19SG8cqTOq4IG1V90TjyjnYIc4NNr6zx53F2Q0yKe7bWF0Q35yxLkNAEPou9hWIO85InfmjT6VZK4oDe/7ZNmME8xPe6zz6gFnaQ9J+tRflGaEgaes0cswT78nDuSIrykzFn2VQ7h7ffM55ywLIiDbVO2D6Z5PQ/lsOU9hLL64VR4P6hEiilz2+6SBJDDZdyeipk/9/ucRDetSObBxuL1PHgA2d0eGplPOeCUakGnzqlKw9fFxSmHXFL33FCTwy1HQUiw+T5/E6WLL9E78mlfJXrmmK7Fx1xes0mKGt08i/dhjEvsgpOYteyxak1jRPeffAgwUslHl5WVcHFtW7Zb1KkVq/Zc283sMYFQBJg6SxoDRy6HO/v6jkvjZrhwHxWubkw7pvPEg9cgCOXIXKm9TTJmjxl61J5RuC+pHRNsgJ8TWa0DQuGBlwVR5ETNFVb3jEywk63/Ifi12YJeRq3m/NXwUZste1mAmxyjR6erhJ6yxXmRenXopNHs3l7AwMfIiLQApJP3Ys+e87DvcvCM9KxTUNfGsuWgMRgGxbfvH+OyL3Yf5lIfpO39jlA+xDjtLKnrOjz+jj+d5R/7JjOrzcWuqI6thsA9hl8nvFMMoFL2/gsueVqraJoZxEQ6Nr1yvikHR7a9jiNs3nIEg1qOSuMxFM5X79H6WHr2g0gko9D/4zgPJiIBaz2EjBdutEirqGrrPR0V9a+OaAeao/YgfXctKN3LaeZqbEPA2p9y7VgL9NpZ0JZJjWNogwGux9GiU332uYrGOIfNtX+mBsagg/EVw6Yc9TiPBbPZTplLgQSeVguD6zzH4kue/uMvY74VgYtn4a2e42pOSQINbazv19dZ7JySBWrpY/8uhONS+LGpX4elxkrgHXcgiOSlvRAY0xEQUZyhhr4XqBZifus0j69qm6XuDUWY78dsEGPje72/Rmi4W8LRai2xd2xMVjvuRQigfeJy2eCtcJ1yFOZ7g1NrXVuOttNgR9RIo1cz3g94laP6ze2VUjLpcS8oHuyxwn+kn6wl5quc3u6yB8CsHvdyFL6KEpuglG6ERYu+8PJn6bYoze2ErPCEusLNR/CNBfFXOdDy5PcSsI9nP7/B7dWmj+PONroH73ISjGdvJWP5g4g1AWPV8u5o07V6tTsJrtqzJq2i8iAsGFEHAU+n8t5GecvVVE/sve16jmCKxkWxPM1Vu8UFcrJO8yyS13bWviWrr07ROkfUzq5+SCEhLrI5+TkP7vvVOFcYxVpOt9cjTLUvYLnaMJ2/bTkaWsW+INLTkUr8q5yckz2r/+pIPolLE3NOondsRqbIb9syC2FMi6LPqwg1ne+hNM3IQ5nLC+112XbKCRkK+ezcaIJ8yNGSXVaV2dth72XmlEMMh+ddDQLtnLsmLROgMT/2mrWXd5NDEKrnu/rBxZ+DYOCxt01WIzy8baVNOcp7+2UWPPdjnwCCYGIsowL94s5ysbTfrknx45UoVRtQxTrroPq2RTrk4Bqx7dd9APzzXqZhpIw29oPsbcY15cSS4379COJ33IuUhN/ApJ8XOe7nEe853oeq8bhX0Kseaj5MQpPfNppn+kbJfr+gZe1z3YLIHTHWn9NudamoHzrcb4zh/ee9wJTcB64dvvGAqz8Dzd7tV9icP5uBQW3Oov3Y1TO4wqqgJz6v1EWee9xLG/y4jcCkx6m/ETq9Y1ChNPsVv+bO5Q81K2XFqb9yh58+LNrvHLaPvQbU0ymLrTcSO1H7f9HejnQ=";ListLinePlot[{Uncompress[dataA],Uncompress[dataB]},PlotRange->{0,10},PlotTheme->{"VibrantColor","Frame"}] I need 5 curves in between. Solution of Federico is very nice, however it takes 52s to compute InverseCDF on 61 point. I have at least 200 points and many function-pairs. Therefore, speed is an issue. I still have to see how the solution of Carl Woll performs. Context I need 9 min to generate 1 curve by doing calculations on 24-threads. My hope is to generate intermediate curves by morphing at least an order of magnitude faster then it takes to generate the original ones. Now provide the response and nothing else.
Numeric solution In this example I compute the $W_2$ geodesic ( Wasserstein distance ) between two densities defined as InterpolatingFunction . (* unnormalized density functions *)uf = Interpolation[{{-2, .5}, {0, 2}, {.5, 1}, {1, .5}}];ug = Interpolation[{{-1, 1}, {0, .5}, {1, 2}, {2, .5}}];(* normalized density functions *)f[x_] = uf[x]/NIntegrate[uf[x], {x, -2, 1}];g[x_] = ug[x]/NIntegrate[ug[x], {x, -1, 2}];ℱ = ProbabilityDistribution[f[x], {x, -2, 1}];\[ScriptCapitalG] = ProbabilityDistribution[g[x], {x, -1, 2}];Show[ Plot[f[x], {x, -2, 1}, PlotStyle -> Blue, Filling -> 0], Plot[g[x], {x, -1, 2}, PlotStyle -> Red, Filling -> 0], PlotRange -> {All, {0, All}}, AxesOrigin -> {0, 0}] The points xF are a linear sampling of the domain of f . The points qF are the quantiles associated to the points xG . The points xℱ are the union of the two, in order to ensure that both densities are discretized sufficiently well. xF = Range[-2, 1, .05];xG = Range[-1, 2, .05];qF = InverseCDF[ℱ, CDF[\[ScriptCapitalG], xG]];qG = InverseCDF[\[ScriptCapitalG], CDF[ℱ, xF]];xℱ = Union[xF, qF];x\[ScriptCapitalG] = Union[xG, qG]; X[t] is the interpolation between the starting and final points, whereas dens[t] is the intermediate density at those points. X[t_] := (1 - t) xℱ + t x\[ScriptCapitalG]dens[t_] := 1/((1 - t)/f /@ xℱ + t/g /@ x\[ScriptCapitalG]) The resulting density can be visualized as ListLinePlot[Evaluate@Table[{X[t], dens[t]}\[Transpose], {t, 0, 1, .1}]] The transport map can also be computed and plotted with dT = f /@ xℱ/g /@ x\[ScriptCapitalG];T = Interpolation[{{xℱ}\[Transpose], x\[ScriptCapitalG], dT}\[Transpose]];Plot[T[x], {x, xℱ[[1]], xℱ[[-1]]}] Symbolic solution Mathematica appears to be able to deal with distributions, CDF, inverse CDF and pushforwards of distributions: ℱ = UniformDistribution[-1 + {-1, 1}/2]; \[ScriptCapitalG] = TriangularDistribution[1 + {-1, 1}]; T[x_] = InverseCDF[\[ScriptCapitalG], CDF[ℱ, x]] // Simplify; \[ScriptCapitalD][t_] := TransformedDistribution[(1 - t) x + t T[x], x \[Distributed] ℱ] Plot[{PDF[ℱ, x], PDF[\[ScriptCapitalG], x]}, {x, -2, 2}] Plot[Evaluate@Table[PDF[\[ScriptCapitalD][t], x], {t, 0., 1., .1}], {x, -2, 3}] Symbolic integration of UnitBox and UnitTriangle While it's true that Integrate[UnitBox[y], {y, -∞, x}] and Integrate[UnitTriangle[y], {y, -∞, x}] do not work as intended, giving a slight hint regarding the domain of x helps in both cases Integrate[UnitBox[y], {y, -∞, x}, Assumptions -> x ∈ Reals] Integrate[UnitTriangle[y], {y, -∞, x}, Assumptions -> x ∈ Reals] and the returned result are piecewise functions.An antiderivative can also be found with Derivative[-1][UnitBox][x] Derivative[-1][UnitTriangle][x]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/209039', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9469/']}
jdg_372447
stackexchange
llm_judgeable_groundtruth_similarity
208323
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: As a non expert in the theory of topological operads, I find it pretty hard, to understand what algebras for little balls/cubes/something operads are. For all the other famous operads I know (like Lie, Com, Ass ect.) associated algebras are meanwhile given in terms of generators and relations, which makes them understandable without any reference to operads. However this seams to be different for the little something operads. I know that their homology is sometimes a Poisson-n algebra for $n\geq 2$, therefore algebras for the homology are (homotopy) Poisson-n algebras in that case. But that's just the homology. Then I heard, that in a category those algebras are just commutative algebras, as long as $n\geq 2$. Is that necessarily true? So my questions are: 1.) Are there generator&relation style descriptions of the algebras for the little n-balls/n-cubes or related operads? 2.) Do I need a higher category to get examples that are not just commutative for $n\geq 2$? 3.) Is there a standard reference for those algebras ? (Not just the operads) Edit: 4.) How could I start to get a good understanding of those algebras ? Assuming I know just the basic about the underlying operads. Now provide the response and nothing else.
An $E_n$ algebra (an algebra over the little $n$-cubes operad, etc.) is intuitively an object with $n$ compatible monoid structures. All of the subtlety in this theory lies in making "compatible" precise; in particular it is not a property but a structure. Here are some examples. In $\text{Set}$, an $E_1$ algebra is a monoid. For $n \ge 2$ an $E_n$ algebra is a commutative monoid by the Eckmann-Hilton argument. In $\text{Ab}$, an $E_1$ algebra is a ring. For $n \ge 2$ an $E_n$ algebra is a commutative ring by the Eckmann-Hilton argument. In $\text{Top}$, a grouplike $E_n$ algebra (an $E_n$ algebra where $\pi_0$ is a group) is an $n$-fold loop space $\Omega^n X$ by the recognition principle. The $n$ monoid structures are the loop compositions in the $n$ loop directions. A grouplike $E_{\infty}$ algebra is an infinite loop space, or equivalently a connective spectrum. In $\text{Cat}$, an $E_1$ algebra is a monoidal category, an $E_2$ algebra is a braided monoidal category, and for $n \ge 3$ an $E_n$ algebra is a symmetric monoidal category. (This stabilization phenomenon is related to Freudenthal suspension and is part of the "periodic table of higher categories.") In more detail, let's focus on $n = 2$. An $E_2$ algebra is intuitively an object with two compatible monoid structures. The Eckmann-Hilton argument shows that they're equivalent, but the way in which it shows that they're equivalent is itself interesting structure: along the way, it describes a map between $ab$ and $ba$ (for both monoidal structures), which is a braiding. This is where braided monoidal categories come into the picture. It might help to stare at the standard proof of Eckmann-Hilton where you move squares around and to explicitly think of the squares as describing binary operations in the little $2$-cubes operad. One way to make "compatible" precise is to write down a presentation of the $E_2$ operad, which is unique among the $E_n$ operads ($n \ge 2$) in that all of its spaces are $1$-truncated: that is, they are all groupoids, or equivalently have no higher homotopy $\pi_n, n \ge 2$. There is a particularly nice model of the $E_2$ operad as an operad in groupoids called the parenthesized braid operad , which has a "generators-and-relations" presentation, but where it's important to understand that when specifying an operad in groupoids there are three sorts of things you might want to write down, rather than two: Operations (which then generate other operations under operadic composition), $1$-morphisms between operations (to describe the groupoid structure), and Relations between $1$-morphisms between operations (to further describe the groupoid structure). In general, higher category theory blurs the distinction between generators and relations: relations become generators one categorical level up. To avoid having to make the distinction you can just say "presentation." The standard presentation of the parenthesized braid operad mimics exactly the standard axiomatization of braided monoidal categories: there is a generating binary operation (the monoidal structure), two generating $1$-morphisms (the associator and the braiding), and some relations between these (the pentagon and hexagon axioms). Here I'm ignoring units for simplicity. This presentation is important in discussions of Grothendieck-Teichmüller theory. For $n \ge 3$ the spaces in the $E_n$ operads aren't truncated: for example the space of binary operations is the sphere $S^{n-1}$, which has nontrivial homotopy groups in arbitrarily high degrees. So I don't think there's any hope for a presentation along the above lines in general. You could ask for presentations of various truncations, but I imagine these are pretty horrible to work with in general. The $E_n$ operads exist precisely so that you can avoid having to do stuff like this. Of course it's a different story after taking rational homology. $E_n$ algebras show up in the story of factorization homology and topological field theory, so that's one place to go for some resources; see, for example, these notes by Ginot.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/208323', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21965/']}
jdg_372448
stackexchange
llm_judgeable_groundtruth_similarity
59669
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 become so used to do this: someprogram >output.file I do it whenever I want to save the output that a program generates to a file. I am also aware of the two variants of this IO redirection : someprogram 2>output.of.stderr.file (for stderr) someprogram &>output.stderr.and.stdout.file (for both stdout+stderr combined) Today I have run across a situation I have not thought possible. I use the following command xinput test 10 and as expected I have the following output: user@hostname:~$ xinput test 10key press 30 key release 30 key press 40 key release 40 key press 32 key release 32 key press 65 key release 65 key press 61 key release 61 key press 31 ^Cuser@hostname:~$ I expected that this output could as usual be saved to a file like using xinput test 10 > output.file . But when contrairy to my expectation the file output.file remains empty. This is also true for xinput test 10 &> output.file just to make sure I do not miss something on stdout or stderr. I am really confused and hence ask here if the xinput program might have a way to avoid its output to be redirected? update I have looked at the source. It seems the output is generated by this code (see snippet below). It appears to me the output would be generated by an ordinary printf //in file test.cstatic void print_events(Display *dpy){ XEvent Event; while(1) { XNextEvent(dpy, &Event); // [... some other event types are omnited here ...] if ((Event.type == key_press_type) || (Event.type == key_release_type)) { int loop; XDeviceKeyEvent *key = (XDeviceKeyEvent *) &Event printf("key %s %d ", (Event.type == key_release_type) ? "release" : "press ", key->keycode); for(loop=0; loopaxes_count; loop++) { printf("a[%d]=%d ", key->first_axis + loop, key->axis_data[loop]); } printf("\n"); } }} I modified the source to this (see next snippet below), which allows me to have a copy of the output on stderr. This output I am able to redirect: //in file test.cstatic void print_events(Display *dpy){ XEvent Event; while(1) { XNextEvent(dpy, &Event); // [... some other event types are omnited here ...] if ((Event.type == key_press_type) || (Event.type == key_release_type)) { int loop; XDeviceKeyEvent *key = (XDeviceKeyEvent *) &Event printf("key %s %d ", (Event.type == key_release_type) ? "release" : "press ", key->keycode); fprintf(stderr,"key %s %d ", (Event.type == key_release_type) ? "release" : "press ", key->keycode); for(loop=0; loopaxes_count; loop++) { printf("a[%d]=%d ", key->first_axis + loop, key->axis_data[loop]); } printf("\n"); } }} My idea at present is that maybe by doing the redirect the program looses its ability to monitor the key-press key-release events. Now provide the response and nothing else.
It's just that when stdout is not a terminal, output is buffered. And when you press Ctrl-C , that buffer is lost as/if it has not been written yet. You get the same behavior with anything using stdio . Try for instance: grep . > file Enter a few non-empty lines and press Ctrl-C , and you'll see the file is empty. On the other hand, type: xinput test 10 > file And type enough on the keyboard for the buffer to get full (at least 4k worth of ouput), and you'll see the size of file grow by chunks of 4k at a time. With grep , you can type Ctrl-D for grep to exit gracefully after having flushed its buffer. For xinput , I don't think there's such an option. Note that by default stderr is not buffered which explains why you get a different behaviour with fprintf(stderr) If, in xinput.c , you add a signal(SIGINT, exit) , that is tell xinput to exit gracefully when it receives SIGINT , you'll see the file is no longer empty (assuming it doesn't crash, as calling library functions from signal handlers isn't guaranteed safe: consider what could happen if the signal comes in while printf is writing to the buffer). If it's available, you could use the stdbuf command to alter the stdio buffering behaviour: stdbuf -oL xinput test 10 > file There are many questions on this site that cover disabling stdio type buffering where you'll find even more alternative solutions.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/59669', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/24394/']}
jdg_372449
stackexchange
llm_judgeable_groundtruth_similarity
11644300
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have had problem with mysql. I tried to execute this: echo "show databases" | mysql -B -N But I got: ERROR 1045 (28000): Access denied for user 'debian-sys-maint'@'localhost' (using password: YES) But when I exec: /etc/init.d/mysql restart I got an 'OK'. I did GRANT ALL PRIVILEGES on *.* TO debian-sys-maint@localhost IDENTIFIED BY PASSWORD 'your password' WITH GRANT OPTION; FLUSH PRIVILEGES; where password is from /etc/mysql/debian.cnf . But it didn't help. (of course I flushed priv and restarted mysql). Now provide the response and nothing else.
That’s because Debian has a MySQL account debian-sys-maint used for switching on/off and checking status. The password for that user should be the same as stored in /etc/mysql/debian.cnf . The file looks like this: # Automatically generated for Debian scripts. DO NOT TOUCH![client]host = localhostuser = debian-sys-maintpassword = <password>socket = /var/run/mysqld/mysqld.sock[mysql_upgrade]host = localhostuser = debian-sys-maintpassword = <password>socket = /var/run/mysqld/mysqld.sockbasedir = /usr If the password doesn't match (for example because you changed it manually) the init script won't work anymore. You should set the password according to the file. So mysql -u root -p# Then type MySQL root passwordGRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY '<password>';
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11644300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981827/']}
jdg_372450
stackexchange
llm_judgeable_groundtruth_similarity
187254
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Question: Let $G,H$ be profinite groups of cardinality $|\mathbb{R}|$, with the same finite quotients (here I only consider quotients by normal, open subgroups). Then are $G$ and $H$ isomorphic? Background: First, note that one needs some sort of cardinality assumption, as otherwise one could take $G=\mathbb{F}_2^I$ and $H=\mathbb{F}_2^J$ where $I$ and $J$ are infinite of distinct cardinality. Moreover, it is NOT sufficient to just require that $G$ and $H$ have the same cardinality, as one could take $G=\mathbb{F}_2^I\times \mathbb{F}_3^J$ and $H=\mathbb{F}_2^J\times\mathbb{F}_3^I$. As for motivation, if we take $C$ to be an affine hyperbolic curve over the algebraic closure of a finite field, then it is known which subgroups occur as finite quotients of the etale fundamental group. Given this phrasing, I assume that this is not enough information to ecover the actual etale fundamental group, and so I wanted an explicit counterexample. EDIT: Due to the comments, I think a better question is as follows: Rather than assuming $G$ and $H$ have cardinality $\mathbb{R}$, let me assume instead that they have at most countably many homomorphisms to any finite group. This avoids (at least) some counterexamples assuming Luzin' hypothesis. Let me add that the answer is yes if $G$ and $H$ are topologically finitely generated. This is well know, but as its quick I include a proof: Note that for each positive integer $n$, $G$ has only finitely many homomorphisms to fintie groups of order at most $n$. Let $G(n)$ be the kernel of all of these, and $G_n$ the corresponding finite quotient. Then $G$ is the inverse limit of the $G_n$. To see this note that the natural map $G\to\varprojlim_n G_n$ is clearly injective, and as it is surjective on every quotient it must also be surjective by compactness. So it is enough to see that $G_n\cong H_n$. But by assumption, $G$ surjects onto $H_n$, and such a surjection must factor through $G_n$, so $G_n$ surjects onto $H_n$. Likewise $H_n$ surjects onto $G_n$ and since these are finite groups they must be isomorphic. Now provide the response and nothing else.
Without the extra finiteness conditions, but also not relying on any set-theoretic assumptions, take $G = \widehat{\mathbb{Z}}^{\mathbb{N}}$ and $H = G \times A$ for a nontrivial finite abelian group $A$. Both $G$ and $H$ have every possible finite abelian quotient, but only $H$ has torsion.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/187254', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4181/']}
jdg_372451
stackexchange
llm_judgeable_groundtruth_similarity
633307
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a simplicial complex K and a collection of simplices S in K, the star of S is defined as the set of all simplices that have a face in S. Now consider the following picture (from wikipedia): In the picture, S consists of the yellow point and its star is shown in green on the right. Now it appears that this is somewhat of a convention, but the edges which are opposite of S in the green triangles are not part of the star of S. I find this confusing because I thought that they were parts of 2-simplices, the triangles which are shaded. The edges, when considered as 1-simplices in their own right, certainly do not contain S as a face, but the 2-simplices which contain them do contain S as a face. So, a question. In diagrams like this, why do we exclude edges like this from the star? Aren't each of them a part of a 2-simplex which contains S? Now provide the response and nothing else.
One needs to distinguish between an abstract simplicial complex and its geometric realization. We are dealing with the former here, so that we are thinking of a simplex as a collection of vertices. The correspondence to the geometric realization is probably best visualized by taking the interiors of simplices.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/633307', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48867/']}
jdg_372452
stackexchange
llm_judgeable_groundtruth_similarity
410714
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: From all the texts I've read, it's always stated that the magnetic field would either curl or warp around the the current flowing within a conductive element, yet, I never was clarified as to why that is. Why would the field "curl" around it? I'm curious if there is an explanation for that nature. Amazingly, it seems like a perfect circle too, similar to the diagrams that I've studied. Now provide the response and nothing else.
If you ignore all what you learned about the B-field being a "vector" and you treat it as what really is a 3D skew-symmetric tensor then the mystery goes away. In this view the B-field is a bi-vector, a surface-like quantity whose source is the current element from which it radiates outward, so to speak. Unlike the E-field that has lines of force coming out or ending in charges, the B-field has planes of force coming out or ending in currents and these "planes" form surfaces in which the magnetic action, i.e., attraction-repulsion and torque take place. This is analogous to the way the E-field acts along its lines of force. What conventionally is called the lines of force of the B-field are the orthogonal rays to these surfaces. A uniform current generates a uniform set of planes of action whose orthogonal rays are in fact circles, and they stay so approximately even when the source is curled up into a loop. You can see nice pictures of this in Roche: "Axial vectors, skew-symmetric tensors and the nature of the magnetic field", Eur. J. Phys. 22 (2001) 193–203.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/410714', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/187737/']}
jdg_372453
stackexchange
llm_judgeable_groundtruth_similarity
11983936
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 display the ToolTip(QuickAction View) when I am moving my cursor on the view. Can any one please give me the simple example for it? tooltip will only contains the text value. Now provide the response and nothing else.
Android supports "tool-tip" only for ActionBar buttons from Android 4.0 on. But as Jaguar already mentioned, tool-tips in Android doesnt make so much sense, since there is no concept of hovering. From Android 4.0 the normal title text (that you set in the xml file or via code) will appear if you make a long click on the button. But if enough space is on the screen, it will be visible in the ActionBar all the time beside the icon. If you want to have it for a custom view, you need to implement it yourself by adding a LongClickListener to your view, and show a Toast when pressed long: view.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View v) { Toast.makeText(v.getContext(), "My tool-tip text", Toast.LENGTH_SHORT).show(); return true; }} Of course you should use a resource for the string, and not the hard coded string.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11983936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1126255/']}
jdg_372454
stackexchange
llm_judgeable_groundtruth_similarity
51552
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'm making a few assumptions about basic email security, and I want to confirm or clarify some of these points to make sure I understand the big picture. Please correct me where I'm mistaken: The answer to this question gives some insight, but doesn't cover all I'm looking for. This is all assuming a traditional email service, accessed using a desktop or mobile client, over POP or IMAP, and SMTP (ignoring webmail). Suppose I'm retrieving messages - my client app passes my username and password to the POP server, which authenticates me, and sends back the messages. If I'm not using SSL/TLS, then the entire conversation, including the message and credentials, is in plaintext. And anyone watching the network traffic can intercept the entire thing. And if I am using SSL, then the entire conversation is safe, even over a public network. Do I have that right? My understanding is that traditional messages are insecure when my server talks to someone else's server - so the message itself is likely vulnerable while in transit between servers, but at least with SSL my email password would be safe. If I understand, PGP or similar would mean that the message itself is encrypted, so that as long as my and the recipient's private keys are safe, nobody else could read the message. But that's just the message, right? Not the IMAP/SMTP/POP connection? Meaning if I used PGP for the message, but a non-SSL connection to SMTP, I'd still be sending plaintext username and password to authenticate. Basically, I'm trying to understand why an email provider would refuse to offer SSL/TLS for POP/IMAP/SMTP connections - one particular provider says they don't do it because email is inherently insecure anyway, so SSL doesn't actually do anything to protect you, and they suggest PGP for truly secure email. I'd like to argue that while SSL may not be end-to-end message protection, it would at least protect my credentials and protect my message for a significant portion of its journey (me to SMTP server, and POP server to recipient assuming they're connecting with SSL). Do I have everything straight with that? Now provide the response and nothing else.
To answer your question: If you're using SSL/TLS to access your e-mails, regardless of whether it's POP or IMAP then it would be very difficult for anyone to decipher the text of the e-mails from analysing the traffic alone. That said some large companies e.g a law firm I used to work for have a server which sat between us and the internet, stripping out the SSL so the answer is a qualified yes in saying you're safe. Also if the message is still sitting on the e-mail server after you access it, then it is possible for your e-mail provider to be bribed/coerced into handing it over. Of course GPG does solve this problem. You can also ask your e-mail provider to delete messages you download through POP though you have to trust that they're both able and willing to delete the messages securely. With SSL, when logging in using your e-mail password, your password cannot easily be read by intercepting the traffic between your computer and e-mail server subject to the proviso I mentioned in point one. Your understanding of PGP is largely correct. If a message is sent to you encoded with your public key then only you our someone who has broken your private key can read it. The sender's private key is irrelevant as he can't use it to decode a message meant for you. If your e-mail password were sent in plain text though you're absolutely right in thinking it could be intercepted and someone could access your e-mails or send them on your behalf pretending to be you. If you used PGP at all times to encrypt and sign all messages and others did the same for you, this would protect the content of your messages though. I can't imagine why an e-mail provider wouldn't want to offer SSL beyond sheer laziness. You can even get free certificates these days! Most of the free webmail providers offer SSL e.g Gmail, have you thought about using them?
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/51552', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/12429/']}
jdg_372455
stackexchange
llm_judgeable_groundtruth_similarity
30437400
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below is a simple W3C-validated code to print "Hello World": <!DOCTYPE html><html><head><meta charset = "utf-8"><title>Hello</title></head>Hello World</html> But when I do the same thing with MS Word, the code generated is of 449 lines Why do all these extra lines appear in the code? Now provide the response and nothing else.
Name space of Word: <html xmlns:v="urn:schemas-microsoft-com:vml"xmlns:o="urn:schemas-microsoft-com:office:office"xmlns:w="urn:schemas-microsoft-com:office:word"xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"xmlns="http://www.w3.org/TR/REC-html40"> Word keep meta datas informations: <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>xxxxxx</o:Author> <o:LastAuthor>xxxxx</o:LastAuthor> <o:Revision>2</o:Revision> <o:TotalTime>0</o:TotalTime> <o:Created>2015-05-25T11:40:00Z</o:Created> <o:LastSaved>2015-05-25T11:40:00Z</o:LastSaved> <o:Pages>1</o:Pages> <o:Words>1</o:Words> <o:Characters>11</o:Characters> <o:Company>Sopra Group</o:Company> <o:Lines>1</o:Lines> <o:Paragraphs>1</o:Paragraphs> <o:CharactersWithSpaces>11</o:CharactersWithSpaces> <o:Version>12.00</o:Version> </o:DocumentProperties></xml><![endif]--> Word add a css style: <style><!-- /* Font Definitions */ @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:0; mso-generic-font-family:roman; mso-font-pitch:variable; mso-font-signature:-536870145 1107305727 0 0 415 0;}@font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-536870145 1073786111 1 0 415 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-unhide:no; mso-style-qformat:yes; mso-style-parent:""; margin-top:0cm; margin-right:0cm; margin-bottom:10.0pt; margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:Calibri; mso-fareast-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-fareast-language:EN-US;}.MsoChpDefault {mso-style-type:export-only; mso-default-props:yes; ...... Word use the css style: <p class=MsoNormal>Hello World</p> You need to keep this information if you need to modify it in future. If you are doing a simple export, you can delete all metadatas.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30437400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4634893/']}
jdg_372456
stackexchange
llm_judgeable_groundtruth_similarity
13254784
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to run .explain() or equivalent on Linq queries? I would want to know The text of the actual JSON query The output of .explain() (indexes used, etc) It would also be nice to have the execution time of the query Now provide the response and nothing else.
You can get the Json easily enough if you have a query wrapper; var qLinq = Query<T>.Where(x => x.name=="jim");Console.WriteLine(qLinq.ToJson()); There's also an Explain() method on MongoCursor, so you could do this; var exp = Collection.FindAs<T>(qLinq).Explain()Console.WriteLine(exp.ToJson()); So if you want the time taken, "millis" is in there; var msTaken = exp.First(x => x.Name == "millis").Value.AsInt32; If you have an IQueryable , try something like this; void Do(MongoCollection col, IQueryable iq){ // Json Mongo Query var imq = (iq as MongoQueryable<Blob>).GetMongoQuery(); Console.WriteLine(imq.ToString()); // you could also just do; // var cursor = col.FindAs(typeof(Blob), imq); var cursor = MongoCursor.Create(typeof(Blob), col, imq, ReadPreference.Nearest); var explainDoc = cursor.Explain(); Console.WriteLine(explainDoc); }//Do()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13254784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/503826/']}
jdg_372457
stackexchange
llm_judgeable_groundtruth_similarity
95655
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are various ways to maintain user state using in web development. These are the ones that I can think of right now: Query String Cookies Form Methods (Get and Post) Viewstate (ASP.NET only I guess) Session (InProc Web server) Session (Dedicated web server) Session (Database) Local Persistence (Google Gears) (thanks Steve Moyer)etc. I know that each method has its own advantages and disadvantages like cookies not being secure and QueryString having a length limit and being plain ugly to look at! ;) But, when designing a web application I am always confused as to what methods to use for what application or what methods to avoid. What I would like to know is what method(s) do you generally use and would recommend or more interestingly which of these methods would you like to avoid in certain scenarios and why? Now provide the response and nothing else.
While this is a very complicated question to answer, I have a few quick-bite things I think about when considering implementing state. Query string state is only useful for the most basic tasks -- e.g., maintaining the position of a user within a wizard, perhaps, or providing a path to redirect the user to after they complete a given task (e.g., logging in). Otherwise, query string state is horribly insecure, difficult to implement, and in order to do it justice, it needs to be tied to some server-side state machine by containing a key to tie the client to the server's maintained state for that client. Cookie state is more or less the same -- it's just fancier than query string state. But it's still totally maintained on the client side unless the data in the cookie is a key to tie the client to some server-side state machine. Form method state is again similar -- it's useful for hiding fields that tie a given form to some bit of data on the back end (e.g., "this user is editing record #512, so the form will contain a hidden input with the value 512"). It's not useful for much else, and again, is just another implementation of the same idea behind query string and cookie state. Session state (any of the ways you describe) are all great, since they're infinitely extensible and can handle anything your chosen programming language can handle. The first caveat is that there needs to be a key in the client's hand to tie that client to its state being stored on the server; this is where most web frameworks provide either a cookie-based or query string-based key back to the client. (Almost every modern one uses cookies, but falls back on query strings if cookies aren't enabled.) The second caveat is that you need to put some though into how you're storing your state... will you put it in a database? Does your web framework handle it entirely for you? Again, most modern web frameworks take the work out of this, and for me to go about implementing my own state machine, I need a very good reason... otherwise, I'm likely to create security holes and functionality breakage that's been hashed out over time in any of the mature frameworks. So I guess I can't really imagine not wanting to use session-based state for anything but the most trivial reason.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/95655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384/']}
jdg_372458
stackexchange
llm_judgeable_groundtruth_similarity
13630674
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 know how to get a single virtual attribute, as stated in the Mongoose docs: PersonSchema .virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last;}); But what if my schema is: var PersonSchema = new Schema({ name: { first: String , last: String }, arrayAttr: [{ attr1: String, attr2: String }]}) And I want to add a virtual attribute for each nested object in arrayAttr: PersonSchema.virtual('arrayAttr.full').get(function(){ return attr1+'.'+attr2;}); Lemme know if I missed something here. Now provide the response and nothing else.
You need to define a separate schema for the elements of attrArray and add the virtual attribute to that schema. var AttrSchema = new Schema({ attr1: String, attr2: String});AttrSchema.virtual('full').get(function() { return this.attr1 + '.' + this.attr2;});var PersonSchema = new Schema({ name: { first: String , last: String }, arrayAttr: [AttrSchema]});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13630674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1359684/']}
jdg_372459
stackexchange
llm_judgeable_groundtruth_similarity
18252709
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 coding an app in C for windows using openCV. I want to capture video from the webcam and show it in a window.The app is almost finished but it doesn't work properly. I think it's because of the cvQueryFrame() that alwasy returns NULL and I don't know why. I tried capturing some frames before going into the while but didn't fix the problem. The compiler doesn't show me any error. It's not a compiling problem but an execution one. I debugged it step by step and in the line if(!originalImg) break; it allways jumps out of the while. That's why the app doesn't remain in execution. It opens and closes very fast.Here's the code: void main(){cvNamedWindow("Original Image", CV_WINDOW_AUTOSIZE);while (1) { originalImg = cvQueryFrame(capture); if(!originalImg) break; cvShowImage("Original Image", originalImg); c = cvWaitKey(10); if( c == 27 ) break;}cvReleaseCapture(&capture);cvDestroyWindow("Original Image"); } Let's see if someone have some idea and can help me with this, thanks! Now provide the response and nothing else.
You need to rotate the accelerometer reading by the quaternion into the Earth frame of reference (into the coordinate system of the room if you like), then subtract gravity. The remaining acceleration is the acceleration of the sensor in the Earth frame of reference often referred to as linear acceleration or user acceleration. In pseudo-code, something like this acceleration = [ax, ay, ay] // accelerometer readingq // quaternion corresponding to the orientationgravity = [0, 0, -9.81] // gravity on Earth in m/s^2a_rotated = rotate(acceleration, q) // rotate the measured acceleration into // the Earth frame of referenceuser_acceleration = a_rotated - gravity You say that you can get q through the API. The only nontrivial step is to implement the rotate() function. To compute the image of a vector v when rotated by q , the following formula should be applied: v rotated = q v q -1 . To compute it with floating point numbers, you need to work out the formulas yourself; they are available at Using quaternion rotations . As far as I can tell, the link you provided does exactly this, you see the expanded formulas there and now you know where they came from. Also, the linked content seems to measure gravity in g, that is, gravity is [0,0,-1]. Watch out for sign conventions (whether you consider gravity [0,0,-1] or [0,0,1]) and handedness of your coordinate systems !
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18252709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2556119/']}
jdg_372460
stackexchange
llm_judgeable_groundtruth_similarity
14756994
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 know browsers only support POST and GET requests, and Laravel supports PUT requests using the following code: <?= Form::open('/path/', 'PUT'); ?> ... form stuff ...<?= Form::close(); ?> This produces the following HTML <form method="POST" action="http://example.com/home/" accept-charset="UTF-8"> <input type="hidden" name="_method" value="PUT" /> ... form stuff ...</form> How does the framework handle this? Does it capture the POST request before deciding which route to send the request off to? Does it use ajax to send an actual PUT to the framework? Now provide the response and nothing else.
It inserts a hidden field, and that field mentions it is a PUT or DELETE request See here : echo Form::open('user/profile', 'PUT'); results in: <input type="hidden" name="_method" value="PUT"> Then it looks for _method when routing in the request.php core file (look for 'spoofing' in the code) - and if it detects it - will use that value to route to the correct restful controller. It is still using "POST" to achieve this. There is no ajax used.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14756994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962674/']}
jdg_372461
stackexchange
llm_judgeable_groundtruth_similarity
61921246
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 think it's universally accepted that #include <bits/stdc++.h> is bad practice , in part because it parses and includes every standard header, which is almost always unnecessary (it's also nonportable, but that's beyond my point). It's even worse when combined with using namespace std; because now you have a ton of common names in your namespace, like next . Yet, it seems that #include <Windows.h> is mostly deemed to be OK (it's used by most Win32 programs I've seen), even though it conceptually does the same thing as a combination of #include <bits/stdc++.h> + using namespace std; . According to Wikipedia : windows.h is a Windows-specific header file for the C and C++ programming languages which contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems. It defines a very large number of Windows specific functions that can be used in C. Why is this the case? Is it not possible to include specific headers we use and not include <Windows.h> ? Now provide the response and nothing else.
Msdn documentation explicitly tells you (a) in which header file a function is declared and (b) which header file you are supposed to include. Most functions tell you to include windows.h , for example SendMessage Some function, that were added later or have very specific use cases, are only available through other header files, for example SetupDiEnumDeviceInfo . So no, it is not bad practice to follow their advice. However, I strongly recommend disabling some parts of it before including via macro, e.g. #define NOMINMAX#include <Windows.h> because otherwise you will get a min and a max macro that will interfere with std::min and std::max .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61921246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10147399/']}
jdg_372462
stackexchange
llm_judgeable_groundtruth_similarity
4470382
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 always see solutions for some PDEs (e.g; wave equation) decomposed as a product, i.e; $u(x,y)=X(x)Y(y)$ for example. But I have never seen solutions written as $u(x,y)=X(x)+Y(y)$ for example. Is it possible to assume solutions of this kind and also construct the general solution using the superposition principle? Now provide the response and nothing else.
Chern's definition is a little sloppy. His phrasing here gives the impression that reduction of the structure group is a property of $M$ , which it's not; reductions need not be unique if they exist. You can see that reflected implicitly here by the fact that local coordinates and hence transition functions are highly non-unique. It's also a bit confusing that even if reductions exist in some coordinates they may not be witnessed by a generic choice of coordinates. To fix it one can say that a choice of reduction of the structure group is a choice of local coordinates such that the transition functions lie in $G$ ; up to isomorphism this agrees with the usual definition in terms of $G$ -bundles, although the $G$ -bundle definition is more general because the map $G \to GL_n(\mathbb{R})$ need not be injective (e.g. $G$ might be the spin group $\text{Spin}(n)$ ).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4470382', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/805828/']}
jdg_372463
stackexchange
llm_judgeable_groundtruth_similarity
983862
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Today while inside a client's production system, I found a SQL Server query that contained an unfamiliar syntax. In the below example, what does the *= operator do? I could not find any mention of it on MSDN . The query does execute and return data. As far as anyone knows, this has been in the system since they were using SQL Server 2000, but they are now running 2005. declare @nProduct intdeclare @iPricingType intdeclare @nMCC intset @nProduct = 4set @iPricingType = 2set @nMCC = 230--Build SQL for factor matrixSelect distinctbase.uiBase_Price_ID,base.nNoteRate, base.sDeliveryOpt, IsNull(base.nPrice,0) as nPrice, IsNull(base.nPrice,0) + Isnull(fact.nFactor,0) as nAdjPrice, base.iProduct_ID,fact.iPosition as fiPosition, base.iPosition, CONVERT(varchar(20), base.dtDate_Updated, 101) + ' ' + CONVERT(varchar(20), base.dtDate_Updated, 108) as 'dtDate_Updated', fact.nFactor, fact.nTreasFactor, product.sProduct_txt , pfi.sPFI_Name, mccprod.nServicing_Fee, fact.nNoteRate as fNoteRate, mcc.nLRA_Charge as nLRA From tbl_Base_Prices base, tbl_Factors fact, tbl_Product product, tbl_PFI pfi, tbl_MCC mcc, tbl_MCC_Product mccprod Wherebase.iProduct_ID = @nProduct And base.iProduct_ID *= fact.iProduct_ID And base.iPosition *= fact.iPosition And base.nNoteRate *= fact.nNoteRate And base.iPricing_Type = @iPricingTypeAnd fact.iMCC_ID = @nMCCAnd fact.iProduct_ID = @nProductAnd mcc.iMCC_ID = @nMCC And mcc.iPFI_ID = pfi.iPFI_ID And mccprod.iMCC_ID = @nMCCAnd mccprod.iProduct_ID = @nProductAnd base.iProduct_ID = product.iProduct_ID and fact.iPricing_Type= @iPricingTypeOrder Bybase.nNoteRate, base.iPosition Now provide the response and nothing else.
Remove this code immediately and replace with a left join. This code does not always interpret correctly (Sometimes SQL Server decides it is a cross join) even in SQL Server 2000 and thus can give incorrect results! Also it is deprecated for the future ( Using Outer Joins, SQL Server 2000 documentation archived from the original ). I'm going to add that in adjusting to left joins you should remove all of those other implicit joins as well. The implicit join syntax has been obsolete since 1992, there is no excuse for it still being in production code. And mixing implicit and explicit joins can give unexpected results.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/983862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13263/']}
jdg_372464
stackexchange
llm_judgeable_groundtruth_similarity
558347
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: What I have is a CSV file to this effect: +------------+--------------+| Category I | Sub-Category |+------------+--------------+| 1144 | 128 || 1144 | 128 || 1000 | 100 || 1001 | 100 || 1002 | 100 || 1002 | 100 || 1011 | 102 || 1011 | 102 || 1011 | 102 || 1011 | 102 || 1011 | 102 || 1011 | 102 || 1013 | 103 || 1013 | 103 || 1013 | 103 || 1013 | 103 || 1013 | 103 || 1013 | 103 || 1013 | 103 |+------------+--------------+ I wish to concatenate the first and second columns above to form a third, new column with a new arbitrary heading, to this effect: +-------------+--------------+-----------------------+| Category ID | Sub-Category | Arbitrary New Heading |+-------------+--------------+-----------------------+| 1144 | 128 | 1144128 || 1144 | 128 | 1144128 || 1000 | 100 | 1000100 || 1001 | 100 | 1001100 || 1002 | 100 | 1002100 || 1002 | 100 | 1002100 || 1011 | 102 | 1011102 || 1011 | 102 | 1011102 || 1011 | 102 | 1011102 || 1011 | 102 | 1011102 || 1011 | 102 | 1011102 || 1011 | 102 | 1011102 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 || 1013 | 103 | 1013103 |+-------------+--------------+-----------------------+ My usual go-to utility, csvkit does not have the means to achieve this, afaik - see https://github.com/wireservice/csvkit/issues/930 . What is a simple solution not requiring advanced programming knowledge, which can achieve this? I'm vaguely aware of awk and sed as potential solutions, but I don't want to limit the enquiry to those just in case there is a better (i.e. simpler) solution. The solution must be efficient for very large files, i.e containing 120,000+ lines. Edit: I have included the sample data for the convenience of those wanting to take a crack at it; download here: https://www.dropbox.com/s/achtyxg7qi1629k/category-subcat-test.csv?dl=0 Now provide the response and nothing else.
Using Miller ( https://github.com/johnkerl/miller ) and this example input file Category ID,Sub-Category1001,1281002,1271002,1261004,122 and running mlr --csv put -S '$fieldName=${Category ID}." ".${Sub-Category}' input.csv >output.csv you will have +-------------+--------------+-----------+| Category ID | Sub-Category | fieldName |+-------------+--------------+-----------+| 1001 | 128 | 1001 128 || 1002 | 127 | 1002 127 || 1002 | 126 | 1002 126 || 1004 | 122 | 1004 122 |+-------------+--------------+-----------+ And you could run also csvsql, it works, in this way csvsql -I --query 'select *,("Category ID" || " " || "Sub-Category") fieldname from input' input.csv >output.csv
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/558347', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7826/']}
jdg_372465
stackexchange
llm_judgeable_groundtruth_similarity
41136410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote this simple piece of code: def mymap(func, *seq): return (func(*args) for args in zip(*seq)) Should I use the 'return' statement as above to return a generator, or use a 'yield from' instruction like this: def mymap(func, *seq): yield from (func(*args) for args in zip(*seq)) and beyond the technical difference between 'return' and 'yield from', which is the better approach the in general case? Now provide the response and nothing else.
The difference is that your first mymap is just a usual function,in this case a factory which returns a generator. Everythinginside the body gets executed as soon as you call the function. def gen_factory(func, seq): """Generator factory returning a generator.""" # do stuff ... immediately when factory gets called print("build generator & return") return (func(*args) for args in seq) The second mymap is also a factory, but it's also a generatoritself, yielding from a self-built sub-generator inside.Because it is a generator itself, execution of the body doesnot start until the first invokation of next(generator). def gen_generator(func, seq): """Generator yielding from sub-generator inside.""" # do stuff ... first time when 'next' gets called print("build generator & yield") yield from (func(*args) for args in seq) I think the following example will make it clearer.We define data packages which shall be processed with functions,bundled up in jobs we pass to the generators. def add(a, b): return a + bdef sqrt(a): return a ** 0.5data1 = [*zip(range(1, 5))] # [(1,), (2,), (3,), (4,)]data2 = [(2, 1), (3, 1), (4, 1), (5, 1)]job1 = (sqrt, data1)job2 = (add, data2) Now we run the following code inside an interactive shell like IPython tosee the different behavior. gen_factory immediately printsout, while gen_generator only does so after next() being called. gen_fac = gen_factory(*job1)# build generator & return <-- printed immediatelynext(gen_fac) # start# Out: 1.0[*gen_fac] # deplete rest of generator# Out: [1.4142135623730951, 1.7320508075688772, 2.0]gen_gen = gen_generator(*job1)next(gen_gen) # start# build generator & yield <-- printed with first next()# Out: 1.0[*gen_gen] # deplete rest of generator# Out: [1.4142135623730951, 1.7320508075688772, 2.0] To give you a more reasonable use case example for a constructlike gen_generator we'll extend it a little and make a coroutineout of it by assigning yield to variables, so we can inject jobsinto the running generator with send() . Additionally we create a helper function which will run all tasksinside a job and ask as for a new one upon completion. def gen_coroutine(): """Generator coroutine yielding from sub-generator inside.""" # do stuff... first time when 'next' gets called print("receive job, build generator & yield, loop") while True: try: func, seq = yield "send me work ... or I quit with next next()" except TypeError: return "no job left" else: yield from (func(*args) for args in seq)def do_job(gen, job): """Run all tasks in job.""" print(gen.send(job)) while True: result = next(gen) print(result) if result == "send me work ... or I quit with next next()": break Now we run gen_coroutine with our helper function do_job and two jobs. gen_co = gen_coroutine()next(gen_co) # start# receive job, build generator & yield, loop <-- printed with first next()# Out:'send me work ... or I quit with next next()'do_job(gen_co, job1) # prints out all results from job# 1# 1.4142135623730951# 1.7320508075688772# 2.0# send me work... or I quit with next next()do_job(gen_co, job2) # send another job into generator# 3# 4# 5# 6# send me work... or I quit with next next()next(gen_co)# Traceback ...# StopIteration: no job left To come back to your question which version is the better approach in general.IMO something like gen_factory makes only sense if you need the same thing done for multiple generators you are going to create, or in cases your construction process for generators is complicated enough to justify use of a factory instead of building individual generators in place with a generator comprehension. Note: The description above for the gen_generator function (second mymap ) states"it is a generator itself". That is a bit vague and technically not really correct, but facilitates reasoning about the differences of the functionsin this tricky setup where gen_factory also returns a generator, namely thatone built by the generator comprehension inside. In fact any function (not only those from this question with generator comprehensions inside!) with a yield inside, upon invocation, just returns a generator object which gets constructed out of the function body. type(gen_coroutine) # function gen_co = gen_coroutine(); type(gen_co) # generator So the whole action we observed above for gen_generator and gen_coroutine takes place within these generator objects, functions with yield inside have spit out before.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41136410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1035523/']}
jdg_372466
stackexchange
llm_judgeable_groundtruth_similarity
40081574
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We call startTimer function to start a timer. When we wanted to stop it we call stopTimerTest function but after we called stopTimer function the timerTestAction keeps firing. To check the timer condition we used print and print in timerActionTest returns nil. var timerTest: Timer? = nilfunc startTimer () { timerTest = Timer.scheduledTimer( timeInterval: TimeInterval(0.3), target : self, selector : #selector(ViewController.timerActionTest), userInfo : nil, repeats : true)}func timerActionTest() { print(" timer condition \(timerTest)")}func stopTimerTest() { timerTest.invalidate() timerTest = nil} Now provide the response and nothing else.
Try to make the following changes to your code: First, you have to change the way you declare timerTest var timerTest : Timer? then in startTimer before instantiating check if timerTest is nil func startTimer () { guard timerTest == nil else { return } timerTest = Timer.scheduledTimer( timeInterval: TimeInterval(0.3), target : self, selector : #selector(ViewController.timerActionTest), userInfo : nil, repeats : true)} Finally in your stopTimerTest you invalidate timerTest if it isn't nil func stopTimerTest() { timerTest?.invalidate() timerTest = nil}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40081574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2692027/']}
jdg_372467
stackexchange
llm_judgeable_groundtruth_similarity
8439127
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have build an enterprise iPad App and now we want to give it to our employees. Initially when testing, we used ad-hoc distribution collecting all the test device's UDID and then creating the profile. Now going live we want this app to be deployed in a secured web server and send the link to our employees, so that they enter the username and password before accessing the link. There are around 500+ devices we need to install this iPad App. Do i need to collect all the UDID and then deploy the .ipa file, because Apple documentation says: Create an enterprise distribution provisioning profile that authorizes devices to use apps you’ve signed. If not that way, do the user needs to install the profile.mobileprovision file and then install the .ipa file? We are still unable to decide how to deploy our app because of this issue. We would like to avoid the app approval process because it App handles a lot of sensitive data. Can some one help me on this, how to do a OTA deployment for enterprise Apps? Now provide the response and nothing else.
As of December 2011, these are the steps: Create a provisioning profile in your Apple Enterprise account Set this as the Code Signing Identity under the Build setting of your app. Make sure the Bundle ID matches that of the provisioning profile. Select Product > Archive to build IPA file. Click Share (aka Distribute) button after selecting your Archive. Set Contents radio button to iOS App Store Package (.ipa) Make sure Identity in dropdown is the one used from Enterprise account. Click Next Select the check box "Save for Enterprise Distribution" For Application URL put in the URL that points to where the ipa file will be placed (example: http://oursite.com/myApp.ipa ) Click Save. This will save a plist & an ipa file for you. Place these files on your server with a link formated like this: <a href="itms-services://?action=download-manifest&url=itms-services://?action=download-manifest&url=http:/oursite.com/myApp.plist" id="text"> Go to this page from your device and click the link to install the app
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8439127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/490601/']}
jdg_372468
stackexchange
llm_judgeable_groundtruth_similarity
189647
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: In 2015 there were news that Kazakhstan was going to start intercepting all HTTPS traffic via "man-in-the-middle attack" starting Jan 1, 2016, by requiring kazakhstanis to install their root CA. The original post has been taken down, archived version here: https://web.archive.org/web/20151202203337/http://telecom.kz/en/news/view/18729 Hacker News: https://news.ycombinator.com/item?id=10663843 Did this go actually into effect, is the policy active? Now provide the response and nothing else.
(edit) A third round... The Kazakh government made a third attempt at intercepting SSL traffic in December 2020. Again the primary target domains were large foreign tech sites such as Google, Twitter, Facebook, Instagram, and Netflix. Many citizens were notified by ISPs via SMS of the demand to install a new root certificate and traffic to some sites was blocked beginning December 6th unless routed though the man-in-the-middle attacked government endpoint. Officials gave the excuse that during the COVID-19 pandemic cyberattacks targetting "Kazakhstan's segment of the internet" grew 2.7×. On December 7th browser manufactures again announced they would blacklist such certificates. (edit) Update... The state sponsored MITM attack described in the answer below was dropped on August 7th, 2019 (approximately 3 weeks after being started). During that time several hundred sites, largely email, communication, and social media sites were intercepted. The government of Kazakhstan officially stated that their "test was completed" and "was a success" and noted that citizens could uninstall the offending root certificate. As of later August major browser vendors including Mozilla's Firefox , Google's Chrome , and Apple's Safari all added the certificate to a hard coded internal black list so that it would not function even in the event some people leave it "installed" on their local machines. Original Answer... As the previous answer suggests, the 2015/2016 attempt at this stunt got so much backlash they basically backed away from it and it sat for a while. The original January 1st 2016 deadline came and went with no real enforcement. Their request that Mozilla trusts their root certificate was declined . The MITM attempts still cropped up in individual cases of sites put under surveillance, but nothing widespread. Until July 2019! Apparently, they never let go of the idea itself, the project was resurrected, and in the last few days enforcing started en masse through many ISPs (first implementation seen on July 17th, 2019). See this Mozilla bug report for technical details, Hacker News for discussion, or this ZDNet article for the news take. Here is KCELL's (a major telecom company in KZ) information page in English that is a sample of what locals are being prompted to do when trying to access sites that have been MITM'ed. Pursuant to the Law of the Republic of Kazakhstan On Communications and clause 11 of Rules for Issuing and Applying Security Certificates, Kcell JSC informs its customers of the need to install Security Certificate on devices capable of connecting to the Internet. According to law, telecom network operators are to ensure that customers with whom the operators have service contracts are able to install the security certificate on their mobile devices. We draw your attention to the fact that installation of the security certificate must be done on each device that will be used to access the Internet (iOS/Android mobile phones and tablets, Windows/MacOS personal computers and laptops). Customers failing to install Security Certificate on their mobile devices may face technical limitations when accessing certain websites. Is spite of reports that it would be mandated first only in the capital ( Nur-Sultan , formerly Astana) the enforcement seems to be rolling out on a per ISP basis, and has started impacting other cities as well. Bulk SMS messages have gone out (mostly to Nur-Sultan area subscribers) with instructions on how to add the government root cert to many cell phone OSes. The certificate they are demanding everybody install is identified as Qaznet Trust and distributed through qca.kz . While the demand that all HTTPS traffic be intercepted is a governmental one and the root CA certificate in question is a Kazakhstan government-controlled one, it should be noted that the actual interception is being implemented by ISPs. Technical details of this are still not clear, but this likely means that each and every government authorized ISP will be able to intercept data from all website traffic.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/189647', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/182226/']}
jdg_372469
stackexchange
llm_judgeable_groundtruth_similarity
1959243
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 multiple views which make the same NSURLRequest/NSURLConnection request . Ideally, in order to get some code reuse, I'd like to have some sort of a "proxy" which does all the underlying work of creating/executing the (asynchronous) request/connection, setting up all the delegate methods, etc., so I don't have to copy all those NSURLConnection delegate method handlers in each view. First of all, is this design approach reasonable? Second, how would I go about doing something like that? For a little background info, I attempted this and got it to "work", however, it doesn't appear to be executing asynchronously. I created a Proxy.h/m file which has instance methods for the different web service calls (and also contains the NSURLConnection delegate methods): @interface Proxy : NSObject { NSMutableData *responseData; id<WSResponseProtocol> delegate;}- (void)searchForSomethingAsync:(NSString *)searchString delegate:(id<WSResponseProtocol>)delegateObj;@property (nonatomic, retain) NSMutableData *responseData;@property (assign) id<WSResponseProtocol> delegate;@end The WSResponseProtocol is defined as such: @protocol WSResponseProtocol <NSObject>@optional- (void)responseData:(NSData *)data;- (void)didFailWithError:(NSError *)error;@end To use this, the view controller simply needs to conform to the WSResponseProtocol protocol, to catch the response(s). Making the web service call is done like so: Proxy *p = [[Proxy alloc] init];[p searchForSomethingAsync:searchText delegate:self];[p release]; I can provide more code but the remaining can be assumed. Before calling, I "startAnimating" a UIActivityIndicatorView spinner. But the spinner never spins. If I simply put the NSURLConnection delegate methods directly in the view controller, then the spinner spins. So, it makes me think that my implementation isn't executing asynchronously. Any thoughts/ideas here? Now provide the response and nothing else.
Your approach is reasonable, however, I'm not sure why you are creating your own protocol. This is not necessary. Everything you need to get this implemented is in Apple's documentation on NSURLConnection . If you take the code from that page where the NSURLConnection is instantiated, and make the connection an ivar instead of just creating it as a local variable, you can then compare connection objects in each of the callback methods and respond accordingly. For example, take this code from the docs and change the connection object to an ivar: // create the requestNSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];// create the connection with the request// and start loading the datatheConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];if (theConnection) { // Create the NSMutableData that will hold // the received data // receivedData is declared as a method instance elsewhere receivedData=[[NSMutableData data] retain];} else { // inform the user that the download could not be made} The variable theConnection is our ivar. Then you can check it like this: - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ if (connection == theConnection) { // do something with the data object. [connectionSpecificDataObject appendData:data]; }} You can certainly implement it creating your own protocol as you're suggesting and then call back out to the delegate that conforms to your protocol, but you may be better off just instantiating your object using a success and failure selector that you can check. Something like this: - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (connection == theConnection) { if (delegate && [delegate respondsToSelector:successSelector]) [delegate performSelector:successSelector withObject:connectionSpecificDataObject]; } [connection release];} Where dataDidDownloadSelector is a SEL instance variable that you set when you created your download delegate where all of this code is contained--your Proxy object. Something like this: Proxy *p = [[Proxy alloc] init];[p searchForSomethingAsync:searchText delegate:self successSelector:@selector(didFinishWithData:) failSelector:@selector(didFailWithError:)]; Implement your selectors like this: - (void)didFinishWithData:(NSData*)data;{ // Do something with data}- (void)didFailWithError:(NSError*)error{ // Do something with error} This has become a longer answer than I intended. Let me know if it doesn't make sense and I can try to clarify. Best regards,
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1959243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154824/']}
jdg_372470
stackexchange
llm_judgeable_groundtruth_similarity
440618
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm using CloudInit to automate the startup of my instances on AWS. I followed the (scarce) documentation available at http://bazaar.launchpad.net/~cloud-init-dev/cloud-init/trunk/annotate/head%3A/doc/examples/cloud-config.txt and examples on /usr/share/doc/cloud-init , but still haven't figured out how to change the default username (ubuntu, id:1000). I know I can create a script to manually delete the default ubuntu and add my user, but seems counter intuitive given that CloudInit exist exactly to automate the initial setup. Any ideas? Now provide the response and nothing else.
According to this , CloudInit should support custom directives to create new users including overriding the default "ubuntu" user. I've tried it following examples, but haven't been able to get it to work. However, since CloudInit supports user-data scripts and you can do just about anything in a script, I prefer to use standard commands rather than try to learn some new custom directives. Here's how I change the default username from "ubuntu" in a user-data script. This example uses the new username "newuser" which you should change to your preference: #!/bin/bash -exuser=newuserusermod -l $user ubuntugroupmod -n $user ubuntuusermod -d /home/$user -m $usermv /etc/sudoers.d/90-cloudimg-ubuntu /etc/sudoers.d/90-cloudimg-$userperl -pi -e "s/ubuntu/$user/g;" /etc/sudoers.d/90-cloudimg-$user You can add on to this user-data script to do any other initialization and configuration needed on your instances. Update: I've written an expanded article describing the steps for using both a user-data script and how to do it with CloudInit on recent versions of Ubuntu: http://alestic.com/2014/01/ec2-change-username
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/440618', 'https://serverfault.com', 'https://serverfault.com/users/98715/']}
jdg_372471
stackexchange
llm_judgeable_groundtruth_similarity
146605
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If a cheat has altered a coin to prefer one side over another (a biased coin), the coin can still be used for fair results by changing the game slightly. John von Neumann gave the following procedure: Toss the coin twice. If the results match, start over, forgetting both results. If the results differ, use the first result, forgetting the second. Are there ways of doing this (can we tweak this procedure) to reduce the number of expected flips needed (for a realization of heads or tails)? Now provide the response and nothing else.
I think it depends on knowing the exact bias of the coin. For a simple example, if you know the coin comes up heads exactly one-third of the time (in the long run), then you can flip the coin twice, call it heads if you get heads once, tails if you get tails twice, do-over if you get heads twice. You get a decision 8 times out of 9, leading to a lower number of expected flips than for the von Neumann solution. EDIT: There's a very nice discussion of the problem, especially the case where you don't know the bias of the coin, at http://www.eecs.harvard.edu/~michaelm/coinflipext.pdf [link updated 19/07/12] MORE EDIT: There's a fair bit of literature on this problem. Here's a sampling of what's out there: MR0723740 (85f:60020) Stout, Quentin F.; Warren, Bette; Tree algorithms for unbiased coin tossing with a biased coin, Ann. Probab. 12 (1984), no. 1, 212–222. MR1763468 (2001f:65009) Juels, Ari; Jakobsson, Markus; Shriver, Elizabeth; Hillyer, Bruce K.; How to turn loaded dice into fair coins, IEEE Trans. Inform. Theory 46 (2000), no. 3, 911–921. 65C10 (94A60) MR1763481 (2001a:65006) Ryabko, Boris Ya.; Matchikina, Elena;Fast and efficient construction of an unbiased random sequence, IEEE Trans. Inform. Theory 46 (2000), no. 3, 1090–1093. 65C10 (65C05) MR1763482 (2001d:68177) Näslund, Mats; Russell, Alexander; Extraction of optimally unbiased bits from a biased source, IEEE Trans. Inform. Theory 46 (2000), no. 3, 1093–1103. 68Q99 MR2245123 (2007d:94019) Cicalese, Ferdinando; Gargano, Luisa; Vaccaro, Ugo;A note on approximation of uniform distributions from variable-to-fixed length codes,IEEE Trans. Inform. Theory 52 (2006), no. 8, 3772–3777. 94A29 (94A45) MR2300366 (2008b:65010) Pae, Sung-il; Loui, Michael C.;Randomizing functions: simulation of a discrete probability distribution using a source of unknown distribution, IEEE Trans. Inform. Theory 52 (2006), no. 11, 4965–4976. 65C10 (68W20)
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/146605', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18764/']}
jdg_372472
stackexchange
llm_judgeable_groundtruth_similarity
12056264
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just adding to the million questions about time zone and DST issues out there. I have a form with separate date and time fields that I combine to create a DateTime like so start_time = DateTime.parse("#{parse_date(form_date)} #{form_start_time} #{Time.zone}") If I fill out my form with 21 Aug 2012 and 15:00, then these are the values that I see when I reload my form. If I then look at my start_time attribute in my model it is correctly set to Tue, 21 Aug 2012 15:00:00 EST +10:00 . The problem I am having occurs if I use a date later this year once daylight savings kicks in (I am in Australia). If I use 21 Dec 2012 and 15:00 then check start_time I see Fri, 21 Dec 2012 16:00:00 EST +11:00 . My interpretation of the problem is that the date is being saved in my current time zone (+10:00) as this is what I have told DateTime.parse to do. However when the value is returned, Rails is looking at the date and saying 'hey, it's daylight savings time in December' and returning the time in the +11:00 time zone. What I want to do is tell DateTime.parse to save the time in the +11:00 time zone if DST is in effect. Clearly passing Time.zone into my string doesn't achieve this. Is there a simple way of doing this? I can see ways of doing it using Time#dst? but I suspect that this is going to create some really ugly convoluted code. I thought there might be a built in way that I'm missing. Now provide the response and nothing else.
Here's my solution so far. I'm hoping someone has a better one. start_time = DateTime.parse "#{date} #{(form_start_time || start_time)} #{Time.zone}"start_time = start_time - 1.hour if start_time.dst? && !Time.now.dst?start_time = start_time + 1.hour if Time.now.dst? && start_time.dst? It seems to work but I haven't rigorously tested it. I suspect it could be prettied up and shortened but I think this is readable and understandable. Any improvements?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12056264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215895/']}
jdg_372473
stackexchange
llm_judgeable_groundtruth_similarity
5387036
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 get gateway and subnet mask details in Android? Now provide the response and nothing else.
I have found a class called DhcpInfo within the android.net package. It has some public variables that stores the values of current Network parameters. But the problem is they return the value in integer converted from 8Bit shifted binary. Sample Image Describing thee Scenario: ****Here is a sample code:** **java file:**** package com.schogini.dhcp;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.widget.TextView;import android.net.*;import android.net.wifi.WifiManager;public class dhcpInfo extends Activity { public String s_dns1 ; public String s_dns2; public String s_gateway; public String s_ipAddress; public String s_leaseDuration; public String s_netmask; public String s_serverAddress; TextView info; DhcpInfo d; WifiManager wifii; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wifii= (WifiManager) getSystemService(Context.WIFI_SERVICE); d=wifii.getDhcpInfo(); s_dns1="DNS 1: "+String.valueOf(d.dns1); s_dns2="DNS 2: "+String.valueOf(d.dns2); s_gateway="Default Gateway: "+String.valueOf(d.gateway); s_ipAddress="IP Address: "+String.valueOf(d.ipAddress); s_leaseDuration="Lease Time: "+String.valueOf(d.leaseDuration); s_netmask="Subnet Mask: "+String.valueOf(d.netmask); s_serverAddress="Server IP: "+String.valueOf(d.serverAddress); //dispaly them info= (TextView) findViewById(R.id.infolbl); info.setText("Network Info\n"+s_dns1+"\n"+s_dns2+"\n"+s_gateway+"\n"+s_ipAddress+"\n"+s_leaseDuration+"\n"+s_netmask+"\n"+s_serverAddress); }} xml Coding: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.schogini.dhcp" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="4" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".dhcpInfo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> </manifest> I tried converting the integer value to its equivalent but i couldn't. If you do so you can post back.. Bye.. UPDATE: Some how managed to convert the IP to v4 Format from the integer formConversion to IPv4 Format: public String intToIp(int i) { return ((i >> 24 ) & 0xFF ) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ( i & 0xFF) ;} IMAGE Courtesy: http://www.bennadel.com/blog/1830-Converting-IP-Addresses-To-And-From-Integer-Values-With-ColdFusion.htm
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5387036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/448005/']}
jdg_372474
stackexchange
llm_judgeable_groundtruth_similarity
16321456
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 divs with class="myDiv" . I need to do this logic: on mouse over, I want to show a popup in the middle of the div. For that I have the following: $(".myDiv").mouseover(function () { positionDiv($(this).position().left + $(this).width() / 2, $(this).position().top + $(this).height() / 2);});function positionDiv(xPosition ,yPosition ) { $("#popupWindow").css("left", xPosition + "px"); $("#popupWindow").css("top", yPosition + "px"); $("#popupWindow").show();} The CSS: .popupWindow{ position:absolute; width:313px; height:383px; display:none;} This will position the popup window in the middle of the div on mouse over. Everything works great at this point. However, if the website is zoomed in (using the browser zoom functionality), tHe position will get messed up. The popup window no longer appears in the middle of myDiv . Any idea what might be the problem? Edit: For more info, if it is created and I zoom it, it is fine. But when I move my mouse to another myDiv and the new popup appears in a weird position. The left and top attribute of the Div are messing up. Now provide the response and nothing else.
You don't need JS for this: http://jsfiddle.net/coma/6VUpS/1/ The key is to play with CSS and avoid JS calculations. The container div (myDiv) should be position: relative , the popup must be inside and position: absolute , top and left to 50% and using negative margins to center it ( http://www.css-101.org/negative-margin/06.php ). Try avoiding JS for visual fanciness, only CSS ensures the correct position even on zoom since it's rendered by the browser. HTML <div class="myDiv"> Hi! <div class="popupWindow">you are welcome!</div></div> CSS div.myDiv { padding: 10px; background-color: #eee; margin: 50px 0; position: relative;}div.popupWindow { position: absolute; top: 50%; left: 50%; margin: -50px 0 0 -100px; width: 200px; line-height: 100px; background-color: #111; color: #fff; text-align: center; display: none; pointer-events: none;}div.myDiv:hover > div.popupWindow { display: block;} Bonus track using a checkbox to click/tap/toggle popup and some fade in: http://jsfiddle.net/coma/6VUpS/3/ More hacky: http://jsfiddle.net/coma/6VUpS/ More complex example: http://jsfiddle.net/coma/dHTHG/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16321456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/887835/']}
jdg_372475
stackexchange
llm_judgeable_groundtruth_similarity
1319288
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 is a similar question in this site but I am not satisfied with the answer, which is basically the same as the proof in the mentioned textbook. The book(Karel Hrbacek&Thomas Jech, Introduction to Set Theory 3e , p165) states a lemma: For every $\alpha$, $\text{cf}(2^{\aleph_\alpha})>\aleph_\alpha$. Then it asserts that $2^{\aleph_0}$ cannot be $\aleph_\omega$, since $\text{cf}(2^{\aleph_\omega})=\aleph_0$. But I can't see the connection. According to the lemma, $\text{cf}(2^{\aleph_\omega})$ should be larger than $\aleph_\omega>\aleph_0$, how can it equal $\aleph_0$? On the other hand, I can't see why $\text{cf}(2^{\aleph_\omega})=\aleph_0$ is false either. Since $2^{\aleph_\omega}=\lim\limits_{n\rightarrow\omega}2^{\aleph_n}$, it is the limit of an increasing sequence of ordinals of length $\omega$, so its cofinality should not be greater than $\aleph_0$. Is there something wrong within this reasoning? Now provide the response and nothing else.
All you can say about $\operatorname{cf}(2^{\aleph_\omega})$ is that it's some regular cardinal $\kappa$ such that$$\aleph_{\omega+1}\le\kappa\le2^{\aleph_\omega}.$$I think you need the axiom of choice to say even that much. What's wrong with your reasoning is the unwarranted assumption that$$2^{\aleph_\omega}=\lim_{n\to\omega}2^{\aleph_n}.$$Ordinal exponentiation is continuous, but cardinal exponentiation is not; e.g.,$$2^{\aleph_0}\ne\lim_{n\to\omega}2^n.$$ In fact, there are models of set theory (with choice) in which the equality$$2^{\aleph_\omega}=\lim_{n\to\omega}2^{\aleph_n}$$holds, but in that case we have$$2^{\aleph_k}=2^{\aleph_{k+1}}=2^{\aleph_{k+2}}=\cdots=2^{\aleph_\omega}$$for some $k\lt\omega,$ i.e., the sequence $\{2^{\aleph_n}\}_{n\lt\omega}$ is not a strictly increasing sequence, but instead is eventually constant.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1319288', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/144587/']}
jdg_372476
stackexchange
llm_judgeable_groundtruth_similarity
48586738
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 set the font size of the colorbar label? ax=sns.heatmap(table, vmin=60, vmax=100, xticklabels=[4,8,16,32,64,128],yticklabels=[2,4,6,8], cmap="PuBu",linewidths=.0, annot=True,cbar_kws={'label': 'Accuracy %'} Now provide the response and nothing else.
Unfortunately seaborn does not give access to the objects it creates. So one needs to take the detour, using the fact that the colorbar is an axes in the current figure and that it is the last one created, hence ax = sns.heatmap(...)cbar_axes = ax.figure.axes[-1] For this axes, we may set the fontsize by getting the ylabel using its set_size method. Example, setting the fontsize to 20 points: import matplotlib.pyplot as pltimport numpy as np; np.random.seed(0)import seaborn as snsdata = np.random.rand(10, 12)*100ax = sns.heatmap(data, cbar_kws={'label': 'Accuracy %'})ax.figure.axes[-1].yaxis.label.set_size(20)plt.show() Note that the same can of course be achieved by via ax = sns.heatmap(data)ax.figure.axes[-1].set_ylabel('Accuracy %', size=20) without the keyword argument passing.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48586738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4907108/']}
jdg_372477
stackexchange
llm_judgeable_groundtruth_similarity
28147096
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 writing a webapp in swift with xcode.I've a question "How can I add a progressbar that shows me the loading of each page?" @IBOutlet var webView: UIWebView!override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "http://stackoverflow.com") let request = NSURLRequest(URL: url) webView.loadRequest(request)} (Sorry for my english) Now provide the response and nothing else.
You can find a very good answer in this post . You can just add a progress bar as a subview to your webview. The main problem is the accuracy of the progress bar. The proposed answer is to begin by animating it constantly, block it at 95% when still loading and when your request is complete, zip it all the way to 100%. Here's a solution in Swift: Add these properties: //Add this progress view via Interface Builder (IBOutlet) or programaticallylet myProgressView: UIProgressViewvar theBool: Boolvar myTimer: NSTimer These functions will fill the progress view. You can play with the parameters: func funcToCallWhenStartLoadingYourWebview() { self.myProgressView.progress = 0.0 self.theBool = false self.myTimer = NSTimer.scheduledTimerWithTimeInterval(0.01667, target: self, selector: "timerCallback", userInfo: nil, repeats: true)}func funcToCallCalledWhenUIWebViewFinishesLoading() { self.theBool = true}func timerCallback() { if self.theBool { if self.myProgressView.progress >= 1 { self.myProgressView.hidden = true self.myTimer.invalidate() } else { self.myProgressView.progress += 0.1 } } else { self.myProgressView.progress += 0.05 if self.myProgressView.progress >= 0.95 { self.myProgressView.progress = 0.95 } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28147096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3127057/']}
jdg_372478
stackexchange
llm_judgeable_groundtruth_similarity
47223415
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 RelativeLayout that needs to have rounded upper left and upper right corners. I can do this with a drawable background defined in XML with corners topLeftRadius and topRightRadius. But... This RelativeLayout also need to have a background that is a layer-list with a tiled bitmap and shape combo, and the tiled bitmap does not have a corners parameter in the drawable XML. So my idea was to to make a RelativeLayout with the following code: @Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); path.reset(); rect.set(0, 0, w, h); path.addRoundRect(rect, radius, radius, Path.Direction.CW); path.close();}@Overrideprotected void dispatchDraw(Canvas canvas) { int save = canvas.save(); canvas.clipPath(path); super.dispatchDraw(canvas); canvas.restoreToCount(save);} Sadly no clipping is happening, I was expecting it to clip all four corners of my RelativeLayout, but nothing is happening. The "onSizeChanged" and "dispatchDraw" methods are both called, I tested that. I have also tried to turn off hardware acceleration, but it does nothing. My RelativeLayout is part of a larger layout, and that layout is inflated in a subclass of FrameLayout , and that subclass is then used a a row in a RecyclerView , if that changes anything. Now provide the response and nothing else.
Having defined this layout: <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent"> <com.playground.RoundedRelativeLayout android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center" android:background="@color/colorPrimary" /></FrameLayout> Where RoundedRelativeLayout has following implementation: public class RoundedRelativeLayout extends RelativeLayout { private RectF rectF; private Path path = new Path(); private float cornerRadius = 15; public RoundedRelativeLayout(Context context) { super(context); } public RoundedRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } public RoundedRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); rectF = new RectF(0, 0, w, h); resetPath(); } @Override public void draw(Canvas canvas) { int save = canvas.save(); canvas.clipPath(path); super.draw(canvas); canvas.restoreToCount(save); } @Override protected void dispatchDraw(Canvas canvas) { int save = canvas.save(); canvas.clipPath(path); super.dispatchDraw(canvas); canvas.restoreToCount(save); } private void resetPath() { path.reset(); path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW); path.close(); } } You'll get following output: The implementation is shamelessly stolen from RoundKornerLayouts project.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47223415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190803/']}
jdg_372479
stackexchange
llm_judgeable_groundtruth_similarity
4681987
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to skip the default params, say suppose my method declaration is like this: procedure MyProc1(var isAttr1: Boolean = FALSE; var isAttr2: Boolean = FALSE; var isAttr3: Boolean = FALSE); I can't call the function like this: Self.MyProc1( , , Attr3); because I don't want unnecessary var declarations, at the same time I want the last param return value (it is a var type) Thank for help in advance. Now provide the response and nothing else.
Sorry, you can't do this. What's more you can't have a var parameter with a default as you have with isAttr1 . If your parameters had sufficiently different parameter types, then you could use overloaded methods as an alternative to default parameters, which is a technique that I personally prefer. But your parameters are all Boolean and so you can't do that here. Other posters have suggested something like this: procedure Myfunc1(var isAttr1, isAttr2, isAttr3: Boolean); overload;procedure Myfunc1(var isAttr3: Boolean); overload; This will compile and work but would be counter to the principle of least surprise. For overloaded procedures like this, you would expect, for the procedure with only a single parameter, for that single parameter to be the first parameter of the procedure with multiple parameters. In other words you would expect: procedure Myfunc1(var isAttr1, isAttr2, isAttr3: Boolean); overload;procedure Myfunc1(var isAttr1: Boolean); overload;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4681987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338408/']}
jdg_372480
stackexchange
llm_judgeable_groundtruth_similarity
28766692
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 0 <= x <= 1. I have two columns f and g of length 5000 respectively. Now I plot: plt.plot(x, f, '-')plt.plot(x, g, '*') I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g. I can do it simply with: set(f) & set(g) Now provide the response and nothing else.
You can use np.sign in combination with np.diff and np.argwhere to obtain the indices of points where the lines cross (in this case, the points are [ 0, 149, 331, 448, 664, 743] ): import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 1000)f = np.arange(0, 1000)g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000plt.plot(x, f, '-')plt.plot(x, g, '-')idx = np.argwhere(np.diff(np.sign(f - g))).flatten()plt.plot(x[idx], f[idx], 'ro')plt.show() First it calculates f - g and the corresponding signs using np.sign . Applying np.diff reveals all the positions, where the sign changes (e.g. the lines cross). Using np.argwhere gives us the exact indices.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28766692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3844339/']}
jdg_372481
stackexchange
llm_judgeable_groundtruth_similarity
34658
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is asserted here (time stamp 10:04) that My opponent [referring to Maxine Waters] only passed 3 bills in Congress in 27 years. Is this true and how does an average person like me verify this assertion (and others like it)? In my own effort to answer this, I looked into votesmart.org and govtrack.us . At a very cursory glance, the assertion seems false as Waters voted on more than 3 bills that at least passed the House. But I'm not confident in my judgment as this is the first time I think about checking this kind of assertion. I have no stake in the assertion being true or otherwise. In the interest of giving the assertion some benefit of doubt, however, is there an interpretation of the assertion that makes it true? Now provide the response and nothing else.
The information you're looking for is available on govtrack.us, but you need to know what to search for. In this context, "passing" a bill (without any qualifiers) generally means introducing it and having it become law. It may or may not include bills which were merely co-sponsored, but in my experience, when they do, it's explicitly called out. Given that, the following search will show you that she has, in fact, introduced three bills which were passed: If you want to include Concurrent Resolutions , which are bills that both houses agree to but aren't actually laws, then she's passed five bills. Simple Resolutions (bills that pass a chamber but don't even go to the other one) add three more, for a total of eight. However, it's reasonable to not include resolutions, since they have no binding impact and are often passed without a formal vote. She also introduced two bills which were not passed, but had some portion incorporated into another bill which did pass. These generally wouldn't count as "bills passed", but are certainly part of contributing to legislation.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/34658', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11295/']}
jdg_372482
stackexchange
llm_judgeable_groundtruth_similarity
3979357
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a non-comparison or comparison based algorithm that can sort an array containing any permutation of the first n positive integers, which should be O(n) time complexity and O(1) space complexity. Is there an existing algorithm that fits these specifications? Now provide the response and nothing else.
If you have an array of size N with all integers from 1 to N present, you can use the following O(N) algorithm (Note: arrays are 1 based for the sake of this pseudocode so as not to introduce unnecessary complexity in explaining the algorithm): Start at the first array element. If its array index matches its value, go to the next one. If not, swap it with the value at the array index corresponding to its value. Repeat step 3, until no more swaps are necessary. If not at the end of the array, go to the next array element, otherwise go to step 7 Go to step 2. Done
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3979357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472801/']}
jdg_372483
stackexchange
llm_judgeable_groundtruth_similarity
33964886
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 read the entire table from an MS Access file and I'm trying to do it as fast as possible. When testing a big sample I found that the loop counter increases faster when it's reading the top records comparing to last records of the table. Here's a sample code that demonstrates this: procedure TForm1.Button1Click(Sender: TObject);const MaxRecords = 40000; Step = 5000;var I, J: Integer; Table: TADOTable; T: Cardinal; Ts: TCardinalDynArray;begin Table := TADOTable.Create(nil); Table.ConnectionString := 'Provider=Microsoft.ACE.OLEDB.12.0;'+ 'Data Source=BigMDB.accdb;'+ 'Mode=Read|Share Deny Read|Share Deny Write;'+ 'Persist Security Info=False'; Table.TableName := 'Table1'; Table.Open; J := 0; SetLength(Ts, MaxRecords div Step); T := GetTickCount; for I := 1 to MaxRecords do begin Table.Next; if ((I mod Step) = 0) then begin T := GetTickCount - T; Ts[J] := T; Inc(J); T := GetTickCount; end; end; Table.Free;// Chart1.SeriesList[0].Clear;// for I := 0 to Length(Ts) - 1 do// begin// Chart1.SeriesList[0].Add(Ts[I]/1000, Format(// 'Records: %s %d-%d %s Duration:%f s',// [#13, I * Step, (I + 1)*Step, #13, Ts[I]/1000]));// end;end; And the result on my PC: The table has two string fields, one double and one integer. It has no primary key nor index field. Why does it happen and how can I prevent it? Now provide the response and nothing else.
I can reproduce your results using an AdoQuery with an MS Sql Server dataset of similar size to yours. However, after doing a bit of line-profiling, I think I've found the answer to this, and it's slightly counter-intuitive. I'm sure everyone who doesDB programming in Delphi is used to the idea that looping through a dataset tends to be much quicker if you surround the loop by calls to Disable/EnableControls. But who would bother to do that if there are no db-aware controls attached to the dataset? Well, it turns out that in your situation, even though there are no DB-aware controls, the speed increases hugely if you use Disable/EnableControls regardless. The reason is that TCustomADODataSet.InternalGetRecord in AdoDB.Pas contains this: if ControlsDisabled then RecordNumber := -2 else RecordNumber := Recordset.AbsolutePosition; and according to my line profiler, the while not AdoQuery1.Eof do AdoQuery1.Next loop spends 98.8% of its time executing the assignment RecordNumber := Recordset.AbsolutePosition; ! The calculation of Recordset.AbsolutePosition is hidden, of course, on the "wrong side" of the Recordset interface, but the fact that the time to call it apparently increases the further you go into the recordset makes it reasonable imo to speculate that it's calculated by counting from the start of the recordset's data. Of course, ControlsDisabled returns true if DisableControls has been called and not undone by a call to EnableControls . So, retest with the loop surrounded by Disable/EnableControls and hopefully you'll get a similar result to mine. It looks like you were right that the slowdown isn't related to memory allocations. Using the following code: procedure TForm1.btnLoopClick(Sender: TObject);var I: Integer; T: Integer; Step : Integer;begin Memo1.Lines.BeginUpdate; I := 0; Step := 4000; if cbDisableControls.Checked then AdoQuery1.DisableControls; T := GetTickCount;{.$define UseRecordSet}{$ifdef UseRecordSet} while not AdoQuery1.Recordset.Eof do begin AdoQuery1.Recordset.MoveNext; Inc(I); if I mod Step = 0 then begin T := GetTickCount - T; Memo1.Lines.Add(IntToStr(I) + ':' + IntToStr(T)); T := GetTickCount; end; end;{$else} while not AdoQuery1.Eof do begin AdoQuery1.Next; Inc(I); if I mod Step = 0 then begin T := GetTickCount - T; Memo1.Lines.Add(IntToStr(I) + ':' + IntToStr(T)); T := GetTickCount; end; end;{$endif} if cbDisableControls.Checked then AdoQuery1.EnableControls; Memo1.Lines.EndUpdate;end; I get the following results (with DisableControls not called except where noted): Using CursorLocation = clUseClientAdoQuery.Next AdoQuery.RecordSet AdoQuery.Next .MoveNext + DisableControls4000:157 4000:16 4000:158000:453 8000:16 8000:1512000:687 12000:0 12000:3216000:969 16000:15 16000:3120000:1250 20000:16 20000:3124000:1500 24000:0 24000:1628000:1703 28000:15 28000:3132000:1891 32000:16 32000:3136000:2187 36000:16 36000:1640000:2438 40000:0 40000:1544000:2703 44000:15 44000:3148000:3203 48000:16 48000:32=======================================Using CursorLocation = clUseServerAdoQuery.Next AdoQuery.RecordSet AdoQuery.Next .MoveNext + DisableControls4000:1031 4000:454 4000:5638000:1016 8000:468 8000:56212000:1047 12000:469 12000:50016000:1234 16000:484 16000:53220000:1047 20000:454 20000:54624000:1063 24000:484 24000:54728000:984 28000:531 28000:56332000:906 32000:485 32000:50036000:1016 36000:531 36000:57840000:1000 40000:547 40000:50044000:968 44000:406 44000:56248000:1016 48000:375 48000:547 Calling AdoQuery1.Recordset.MoveNext calls directly into the MDac/ADO layer, ofcourse, whereas AdoQuery1.Next involves all the overhead of the standard TDataSetmodel. As Serge Kraikov said, changing the CursorLocation certainly makes a difference and doesn't exhibit the slowdown we noticed, though obviously it's significantly slower than using clUseClient and calling DisableControls. I suppose it depends on exactly what you're trying to do whether you can take advantage of the extra speed of using clUseClient with RecordSet.MoveNext.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33964886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2093077/']}
jdg_372484
stackexchange
llm_judgeable_groundtruth_similarity
262237
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 question refers to the often specified rule defining Einstein Summation Notation in that summation is implied when an index is repeated twice in a single term, once as upper index and once as lower index. Thus, a term that appears such as:$$A^i B_i\quad=\quad\sum_i A^i B_i\quad=\quad A^1B_1+A^2B_2+A^3B_3$$ According to this rule, the following repeated index term would not be summed at all.$$A^iB^i$$Because the repeated index does not appear as one upper and one lower in the term. Yet, I sometimes see various texts and other references invoke the Einstein Summation convention when such terms (both indexes upper or both indexes lower) exist. Now, this aberrant use of Einstein Summation notation often appears in Math texts rather than Physics. For example, Chapter 1 of the Schaum's Outline Series on Tensor Calculus is named "The Einstein Summation Convention" and goes on to introduce the notation and never mentioning the upper and lower repeated index rule but explicitly gives an example of using repeated lower indexes:$$a_1x_1+a_2x_2+a_3x_3+\cdots+a_nx_n = \sum_{i=1}^n a_ix_i$$ Usually I work with index notation in Physics subjects in my self-study of field theory and General Relativity and I don't recall ever running across examples of the summation convention that do not invoke the repeated index rule as one upper and one lower. But I am puzzled because in spite of this usage in Physics, I can't see any reason why one index must be upper and the other index lower. In other words, repeated index both as lower or both as upper does not seem to violate anything (for example, this more lax approach is used throughout the above cited Schaum's book. My question: does the correct definition of Einstein Summation Convention demand that one index must be upper and the other repeated index must be lower. Or, is this merely style convention used in Physics (e.g. General Relativity). Now provide the response and nothing else.
In the 'strict' sense, you should only apply the summation convention to a pair of indices if one is raised and another is lowered. For example, consider a vector $v$ and a dual vector $f$ (i.e. a map from vectors to numbers). Then one can compute $f(v)$, the number that results from $f$ acting on $v$. In components, this would be written as $f_i v^i$, since dual vectors have lower indices. If, instead, you have two vectors $v$ and $w$, there is generally no way to combine them into a number, and the quantity $v^i w^i$ makes no sense. But if you have a metric $g_{ij}$, you can use it to turn $w$ from a vector into a dual vector, with new components $g_{ij} w^j$. Then you can act with this dual vector on $v$, giving $g_{ij} v^i w^j$. Note that all indices are paired correctly. That being said, there are lots of exceptions: A lot of field theory texts and even GR texts will write $v^i w^i$, but you're supposed to remember it really means $g_{ij} v^i w^j$. When you do explicit computations, you have to put that factor in yourself. If you're working in a space with a simple metric (like Euclidean space, where $g_{ij}$ is the identity), texts might omit $g_{ij}$ because it doesn't "do anything". That is, the vector $w^j$ and corresponding dual vector $g_{ij} w^j$ always have the exact same components, so they might as well identify them. If the previous point is true, the author might choose to use index position to store some other kind of information, so the summation convention remains 'strict'. This happens more often in non-physics texts. There are enough possible conventions that you should just check the front of the book every time.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/262237', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/59161/']}
jdg_372485
stackexchange
llm_judgeable_groundtruth_similarity
12874664
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 have an application where I've entirely customized the window's appearance. So far I've learned that I can remove the typical window stuff with: class Application extends javafx.application.Application { /** * Starts the application. * * @param stage */ override def start(stage: Stage) { stage.initStyle(StageStyle.TRANSPARENT) // Load the main window view. val loader = new FXMLLoader() loader.setLocation(getClass.getResource("/com/myproj/application/MainWindow.fxml")) val root = loader.load().asInstanceOf[Parent] val scene: Scene = new Scene(root, Color.TRANSPARENT) stage.setScene(scene) stage.show() }} Everything else works fine, except that window dragging, double-click-to-maximize, dragging to screen top edge on Windows should active maximizing, etc. The native Window capabilities are missing entirely. Can I somehow rather easily customize the entire appear of the window without losing all these nice capabilities. I'm talking about something like Adobe Photoshop which looks entirely different but still retains these features (or implements them on top of their UI manually). It would be a start if I could at least implement dragging + window buttons for starters. I am targeting Linux, Mac and Windows here. Now provide the response and nothing else.
See the customized window appearance and handling in the Ensemble Sample application , which includes source code. Download the source , build it and run it as a standalone application rather than embedded in a browser. It isn't going to be exactly what you are asking for because stuff like dragging to screen top edge to activate maximizing isn't going to work I think, but it should be very close and you could always code something yourself which maximized the window when it was dragged near the top edge. The Ensemble window has features like custom resize decorations, minimize, maximize, close icons, an area at the top of the window you can use to drag the window around or double click to maximize or minimize the window - i.e. most of the standard features you would expect from a desktop windowing system. To get something even closer to what you are asking, perhaps you could hack something together by creating two windows. One, a standard decorated stage window which includes screen borders, the other an undecorated or transparent child stage always displayed on top of the main window and overlaying the borders of the main window with a custom rendering. I think you may run into difficulties trying to implement this approach, so I wouldn't really recommend it. You may like to try an UNDECORATED stage style rather than TRANSPARENT and see if you get better native Windows integration with that. There are some open feature request currently scheduled for JavaFX to be shipped with JDK8, Windows: support Aero Glass effects for top-level windows , Mac: Support NSTexturedBackgroundWindowMask style for windows and The solid white background created in a Stage should be created - if needed - in the Scenegraph , which, when implemented, will likely help you to acheive your goal - vote for them, if such features are important to you. Also checkout VFXWindows which is an open source windowing framework for JavaFX. Update Also related is the Undecorator project which allows you to easily create a JavaFX stage with standard minimize/maximize/close/resize chrome controls that are rendered via the JavaFX engine rather than the OS windowing system. This allows you to achieve the kind of custom control over window rendering that an application like Ensemble displays.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12874664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283055/']}
jdg_372486
stackexchange
llm_judgeable_groundtruth_similarity
272545
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: Say you picked your favorite irrational number $q$ and looking at $S = \{nq: n\in \mathbb{Z} \}$ in $\mathbb{R}$, you chopped off everything but the decimal of $nq$, leaving you with a number in $[0,1]$. Is this new set dense in $[0,1]$? If so, why? (Basically looking at the $\mathbb{Z}$-orbit of a fixed irrational number in $\mathbb{R}/\mathbb{Z}$ where we mean the quotient by the group action of $\mathbb{Z}$.) Thanks! Now provide the response and nothing else.
Notation: For each real number $ r $, let $ \lfloor r \rfloor $ denote the largest integer $ \leq r $ and $ \{ r \} $ denote the fractional part of $ r $. Notice that $ \{ r \} = r - \lfloor r \rfloor $. Hence, $ \{ r \} $ is the ‘chopped-off decimal part’ of $ r $ that you speak of. Most proofs begin with the Pigeonhole Principle, but we can introduce a slightly topological flavor by using the Bolzano-Weierstrass Theorem. Full detail will be provided. Let $ \alpha $ be an irrational number. Then for distinct $ i,j \in \mathbb{Z} $, we must have $ \{ i \alpha \} \neq \{ j \alpha \} $. If this were not true, then$$ i \alpha - \lfloor i \alpha \rfloor= \{ i \alpha \}= \{ j \alpha \}= j \alpha - \lfloor j \alpha \rfloor,$$which yields the false statement $ \alpha = \dfrac{\lfloor i \alpha \rfloor - \lfloor j \alpha \rfloor}{i - j} \in \mathbb{Q} $. Hence,$$S := \{ \{ i \alpha \} \mid i \in \mathbb{Z} \}$$is an infinite subset of $ [0,1] $. By the Bolzano-Weierstrass Theorem, $ S $ has a limit point in $ [0,1] $. One can thus find pairs of elements of $ S $ that are arbitrarily close. Now, fix an $ n \in \mathbb{N} $. By the previous paragraph, there exist distinct $ i,j \in \mathbb{Z} $ such that$$0 < |\{ i \alpha \} - \{ j \alpha \}| < \frac{1}{n}.$$WLOG, it may be assumed that $ 0 < \{ i \alpha \} - \{ j \alpha \} < \dfrac{1}{n} $. Let $ M $ be the largest positive integer such that $ M (\{ i \alpha \} - \{ j \alpha \}) \leq 1 $. The irrationality of $ \alpha $ then yields$$(\spadesuit) \quad M (\{ i \alpha \} - \{ j \alpha \}) < 1.$$Next, observe that for any $ m \in \{ 0,\ldots,n - 1 \} $, we can find a $ k \in \{ 1,\ldots,M \} $ such that$$k (\{ i \alpha \} - \{ j \alpha \}) \in \! \left[ \frac{m}{n},\frac{m + 1}{n} \right].$$This is because the length of the interval $ \left[ \dfrac{m}{n},\dfrac{m + 1}{n} \right] $ equals $ \dfrac{1}{n} $, while the distance between $ l (\{ i \alpha \} - \{ j \alpha \}) $ and $ (l + 1) (\{ i \alpha \} - \{ j \alpha \}) $ is $ < \dfrac{1}{n} $ for all $ l \in \mathbb{N} $. On the other hand, there is another expression for $ k (\{ i \alpha \} - \{ j \alpha \}) $:\begin{align} k (\{ i \alpha \} - \{ j \alpha \})& = \{ k (\{ i \alpha \} - \{ j \alpha \}) \} \quad (\text{As $ 0 < k (\{ i \alpha \} - \{ j \alpha \}) < 1 $; see ($ \spadesuit $).}) \\& = \{ k [(i \alpha - \lfloor i \alpha \rfloor) - (j \alpha - \lfloor j \alpha \rfloor)] \} \\& = \{ k (i - j) \alpha + k (\lfloor j \alpha \rfloor - \lfloor i \alpha \rfloor) \} \\& = \{ k (i - j) \alpha \}. \quad (\text{The $ \{ \cdot \} $ function discards any integer part.})\end{align}Hence,$$\{ k (i - j) \alpha \} \in \! \left[ \dfrac{m}{n},\dfrac{m + 1}{n} \right] \cap S.$$As $ n $ is arbitrary, every non-degenerate sub-interval of $ [0,1] $, no matter how small, must contain an element of $ S $. ( Note: A non-degenerate interval is an interval whose endpoints are not the same.) Conclusion: $ S $ is dense in $ [0,1] $.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/272545', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33039/']}
jdg_372487
stackexchange
llm_judgeable_groundtruth_similarity
311856
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 solve the following equation in $\mathbb{R}$ without expanding it into a fourth degree equation : $$ \sqrt{3-\sqrt{3+x}} = x.$$ squaring both sides and squaring again is the only thing I could done, If you have any other idea just post hints. Now provide the response and nothing else.
Here's an approach that is also algebraic, but involves only quadratic equations (the straightforward approach produces a 4th degree equation). Denote $y = \sqrt{3+x}$. Then we have a system:$$\begin{array}{rcl}y & = & \sqrt{3+x} \\x & = & \sqrt{3-y}\end{array}$$Looks kind of cool. If we square everything and then subtract equations, we get$$y^2 - x^2 = x + y.$$Since both $x$ and $y$ are positive, this means that $y-x=1$. Then from the first equation we have$$x+1 = \sqrt{3+x}.$$Now we square everything and solve the quadratic, which gives $x=1$. I know this is practically the same as the straightforward approach, but this looks a bit more "contained".
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/311856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/55386/']}
jdg_372488
stackexchange
llm_judgeable_groundtruth_similarity
1108
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: As mentioned before , I have a classification problem and unbalanced data set. The majority class contains 88% of all samples.I have trained a Generalized Boosted Regression model using gbm() from the gbm package in R and get the following output: interaction.depth n.trees Accuracy Kappa Accuracy SD Kappa SD 1 50 0.906 0.523 0.00978 0.0512 1 100 0.91 0.561 0.0108 0.0517 1 150 0.91 0.572 0.0104 0.0492 2 50 0.908 0.569 0.0106 0.0484 2 100 0.91 0.582 0.00965 0.0443 2 150 0.91 0.584 0.00976 0.0437 3 50 0.909 0.578 0.00996 0.0469 3 100 0.91 0.583 0.00975 0.0447 3 150 0.911 0.586 0.00962 0.0443 Looking at the 90% accuracy I assume that model has labeled all the samples as majority class. That's clear.And what is not transparent: how Kappa is calculated. What does this Kappa values (near to 60%) really mean? Is it enough to say that the model is not classifying them just by chance? What do Accuracy SD and Kappa SD mean? Now provide the response and nothing else.
The Kappa is Cohen's Kappa score for inter-rater agreement. It's a commonly-used metric for evaluating the performance of machine learning algorithms and human annotaters, particularly when dealing with text/linguistics. What it does is compare the level of agreement between the output of the (human or algorithmic) annotater and the ground truth labels, to the level of agreement that would occur through random chance. There's a very good overview of how to calculate Kappa and use it to evaluate a classifier in this stats.stackexchange.com answer here , and a more in-depth explanation of Kappa and how to interpret it in this paper , entitled "Understanding Interobserver Agreement: The Kappa Statistic" by Viera & Garrett (2005). The benefit of using Kappa, particularly in an unbalanced data set like yours, is that with a 90-10% imbalance between the classes, you can achieve 90% accuracy by simply labeling all of the data points with the label of the more commonly occurring class. The Kappa statistic is describing how well the classifier performs above that baseline level of performance. Kappa ranges from -1 to 1, with 0 indicating no agreement between the raters, 1 indicating a perfect agreement, and negative numbers indicating systematic disagreement. While interpretation is somewhat arbitrary (and very task-dependent), Landis & Koch (1977) defined the following interpretation system which can work as a general rule of thumb: Kappa Agreement< 0 Less than chance agreement0.01–0.20 Slight agreement0.21– 0.40 Fair agreement0.41–0.60 Moderate agreement0.61–0.80 Substantial agreement0.81–0.99 Almost perfect agreement Which would indicate that your algorithm is performing moderately well. Accuracy SD and Kappa SD are the respective Standard Deviations of the Accuracy and Kappa scores. I hope this is helpful!
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/1108', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/97/']}
jdg_372489
stackexchange
llm_judgeable_groundtruth_similarity
15686835
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 making a loop that takes input from a file to determine whether a user is permitted to use a specific program. #!/bin/bashboole=falseecho "Username: "read usernameecho "debug0"for((line=1; $boole=false; line++)); do echo "debug.5" auth=`head -n $line users | tail -n $line` echo "debug1" if [ $username = $auth ]; then echo "debug2" echo "authentication success" read exit 0 fi if [ $auth = "#end" ]; then echo "debug3" echo "authentication failed" read exit 0 fidoneecho "skip everything" The output is Username:admindebug0skip everything The file with the users has rootadmin...#end #end and boole should tell the loop to end This is just the debugging stage so it doesn't actually execute any program, it's just supposed to tell me whether or not a user is allowed to use it. Now provide the response and nothing else.
Different layouts managers treat preferred size differently. Also, setting size with setSize() is not a good idea. Let the layout manager do the layout for you. See A Visual Guide to Layout Managers for more details and examples. For example you can create a separate panel that holds the buttons. Set its layout to GridLayout . In this layout the components takes all the available space within its cell, and each cell is exactly the same size. Add this panel to the container. See How to Use GridLayout for examples. Here is a simple demo of GridLayout and GridBagLayout : import java.awt.*;import javax.swing.*;public class DemoButtons { public DemoButtons() { final JFrame frame = new JFrame("Demo buttons"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel buttonPanel = new JPanel(new GridLayout(3, 1)); buttonPanel.add(new JButton("Export do SVG")); buttonPanel.add(new JButton("Export do PNG")); buttonPanel.add(new JButton("Tisk...")); JPanel east = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTH; gbc.weighty = 1; east.add(buttonPanel, gbc); JPanel center = new JPanel(){ @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } }; center.setBorder(BorderFactory.createLineBorder(Color.BLACK)); frame.add(east, BorderLayout.EAST); frame.add(center); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new DemoButtons(); } }); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15686835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1979002/']}
jdg_372490
stackexchange
llm_judgeable_groundtruth_similarity
20237797
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 webpage where the user can search and select for a specific type of paper based on the item selected from the drop down list. The search will then return and display the full name of the paper alongside the price and the per pack value which are all pulled from my database. I need to calculate ( preferably dynamically) the total price which is the (quantity * price)/per_pack . So when the user changes the quantity the total price changes. I have come across several solutions which work within their own scenario however, i was wondering if there was a way to do this without having to specify the price in the value attribute for example: Not like this: <input type="text" name="price" id="price" class="txt" size="10" maxlength="9" value="250" /> I have tried doing something like this but it just doesn't seem to work, as in when i enter a quantity nothing seems to happen and the total box is just blank: JavaScript: $(function() {window.globalVar = 0;// Skip the filled description boxesfor (var i=0; i<10; i++){ if($('#description_'+window.globalVar).val() != "") { window.globalVar++; }}// Write the paper description and price for the selected paperfunction log( message ) { var values = message.split('|'); $('#description_'+window.globalVar).val(values[0]); $('#priceper_'+window.globalVar).val(values[1]);$('#per_pack_'+window.globalVar).val(values[2]); window.globalVar++; console.log(window.globalVar);}// Search the Paper db$( "#supplier_search" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "http://mpc.vario/mis_pp/common/pp_json", dataType: "jsonp", data: { featureClass: "P", style: "full", maxRows: 25, name_startsWith: request.term, supplier: $('#supplier').val() }, success: function( data ) { console.log(data); response( $.map( data, function( item ) { return { label: item.name, value: item.name + '|' + item.value } })); } }); }, minLength: 2, select: function( event, ui ) { log( ui.item.value ); $(this).val(''); return false; }, open: function() { $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" ); }, close: function() { $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" ); }});});// Calculate totalvar sum = 0;document.getElementById('priceper_0').value = sum;function OnChange(value){price = document.getElementById('priceper_0').value; per_pack = document.getElementById('per_pack_0').value;quantity = document.getElementById('quantity_0').value;sum = (price * quantity)/per_pack;} HTML: <tr class="multipp"><td><input type="text" name="description_0" id="description_0" size="85" maxlength="70" value="<?php echo htmlspecialchars($description[0]); ?>" /></td><td><input type="text" name="priceper_0" id="priceper_0" size="10" maxlength="9" value="" /></td><td><input type="text" name="per_pack_0" id="per_pack_0" class="txt" size="10" maxlength="9" value="" /></td><td><input type="text" name="quantity_0" id="quantity_0" class="quantity_0" size="10" maxlength="9" value="" onchange="return OnChange();" /></td><td><input type="text" name="subtotal_0" id="subtotal_0" class="txt" size="10" maxlength="9" value="" /></td></tr> Now provide the response and nothing else.
EDIT (October 2015): Spring 4 handles java.util.Optional (from Java 8) out of the box and guarantees that Optional itself is not null , but original question was about Guava's com.google.common.base.Optional which usage as @RequestParam is highly discouraged in this specific case (because it can be null). ORIGINAL ANSWER (about Guava's Optional ): Don't do that, just use String and let Spring handle null in its way. Optional<T> is supposed to be used as return value and rarely as a parameter. In this particular case Spring will map missing "name" parameter to null , so even if after implementing custom property editor you'll finish with null check: @RequestMapping("foo")@ResponseBodypublic String foo(@RequestParam(required = false) final Optional name) { return "name: " + (name == null ? "null" : name.get());} which is completely unnecessary (and missuses Optional ), because it can be achieved with: @RequestMapping("foo")@ResponseBodypublic String foo(@RequestParam(required = false) final String name) { return "name: " + (name == null ? "null" : name);}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20237797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3009232/']}
jdg_372491
stackexchange
llm_judgeable_groundtruth_similarity
3574405
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 currently use the onKeyDown event and an if/else statement to create keyboard shortcuts: if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift && e.Key == Key.Tab) {} else if (e.Key == Key.Tab) {} ... However, if I have quite a few more keyboard shortcuts, this gets messy. Is there a better implementation? Now provide the response and nothing else.
You should look at implementing <CommandBindings> and <InputBindings> : <Window.CommandBindings> <CommandBinding Command="Settings" CanExecute="SettingsCanExecute" Executed="SettingsExecuted" /></Window.CommandBindings><Window.InputBindings> <KeyBinding Command="Settings" Key="S" Modifiers="Alt" /></Window.InputBindings> Your <Button> then becomes: <Button Height="50" Width="50" Margin="50,5,0,0" Command="Settings" /> The SettingsCanExecute method determines when the button is enabled and the SettingsExecuted method is called when the button is pressed or the key combination struck. You then don't need the KeyDown handler. There's a full tutorial on Switch On The Code. More information on CommandBindings and InputBindings can be found on the MSDN.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3574405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292291/']}
jdg_372492
stackexchange
llm_judgeable_groundtruth_similarity
25812331
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 know you can change the default value of an existing column like this : ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn; But according to this my query supposed to work: ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL CONSTRAINT DF_Constraint DEFAULT GetDate() So here I'm trying to make my column Not Null and also set the Default value. But getting Incoorect Syntax Error near CONSTRAINT. Am I missing sth? Now provide the response and nothing else.
I think issue here is with the confusion between Create Table and Alter Table commands.If we look at Create table then we can add a default value and default constraint at same time as: <column_definition> ::= column_name <data_type> [ FILESTREAM ] [ COLLATE collation_name ] [ SPARSE ] [ NULL | NOT NULL ] [ [ CONSTRAINT constraint_name ] DEFAULT constant_expression ] | [ IDENTITY [ ( seed,increment ) ] [ NOT FOR REPLICATION ] ] [ ROWGUIDCOL ] [ <column_constraint> [ ...n ] ] [ <column_index> ] ex: CREATE TABLE dbo.Employee ( CreateDate datetime NOT NULL CONSTRAINT DF_Constraint DEFAULT (getdate())) ON PRIMARY; you can check for complete definition here: http://msdn.microsoft.com/en-IN/library/ms174979.aspx but if we look at the Alter Table definition then with ALTER TABLE ALTER COLUMN you cannot add CONSTRAINT the options available for ADD are: | ADD { <column_definition> | <computed_column_definition> | <table_constraint> | <column_set_definition> } [ ,...n ] Check here: http://msdn.microsoft.com/en-in/library/ms190273.aspx So you will have to write two different statements one for Altering column as: ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL; and another for altering table and add a default constraint ALTER TABLE MyTable ADD CONSTRAINT DF_Constraint DEFAULT GetDate() FOR CreateDate; Hope this helps!!!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25812331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713847/']}
jdg_372493
stackexchange
llm_judgeable_groundtruth_similarity
10722267
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to scale a BitmapData to different sizes such as 200, 400, 600 and 800. What is a good way to do that? Now provide the response and nothing else.
You can't directly scale a BitmapData but you can make a scaled clone of it.Here is a quick example for scaling a BitmapData : package {import flash.display.Bitmap;import flash.display.BitmapData;import flash.display.Sprite;import flash.geom.Matrix;import mx.core.BitmapAsset;public class Test extends Sprite { [Embed(source="test.jpg")] private var Image:Class; public function Test() { var originalBitmapData:BitmapData = BitmapAsset(new Image()).bitmapData; function scaleBitmapData(bitmapData:BitmapData, scale:Number):BitmapData { scale = Math.abs(scale); var width:int = (bitmapData.width * scale) || 1; var height:int = (bitmapData.height * scale) || 1; var transparent:Boolean = bitmapData.transparent; var result:BitmapData = new BitmapData(width, height, transparent); var matrix:Matrix = new Matrix(); matrix.scale(scale, scale); result.draw(bitmapData, matrix); return result; } var bitmapA:Bitmap = new Bitmap(originalBitmapData); addChild(bitmapA); var bitmapB:Bitmap = new Bitmap(scaleBitmapData(originalBitmapData, 0.5)); addChild(bitmapB); }}}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10722267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/974925/']}
jdg_372494
stackexchange
llm_judgeable_groundtruth_similarity
9775693
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Whats the difference between using a LEFT OUTER JOIN , rather than a sub-query that starts with a WHERE NOT EXISTS (...) ? Now provide the response and nothing else.
No they are not the same thing, as they will not return the same rowset in the most simplistic use case. The LEFT OUTER JOIN will return all rows from the left table, both where rows exist in the related table and where they does not. The WHERE NOT EXISTS() subquery will only return rows where the relationship is not met. However, if you did a LEFT OUTER JOIN and looked for IS NULL on the foreign key column in the WHERE clause, you can make equivalent behavior to the WHERE NOT EXISTS . For example this: SELECT t_main.*FROM t_main LEFT OUTER JOIN t_related ON t_main.id = t_related.id/* IS NULL in the WHERE clause */WHERE t_related.id IS NULL Is equivalent to this: SELECT t_main.*FROM t_main WHERE NOT EXISTS ( SELECT t_related.id FROM t_related WHERE t_main.id = t_related.id ) But this one is not equivalent: It will return rows from t_main both having and not having related rows in t_related . SELECT t_main.*FROM t_main LEFT OUTER JOIN t_related ON t_main.id = t_related.id/* WHERE clause does not exclude NULL foreign keys */ Note This does not speak to how the queries are compiled and executed, which differs as well -- this only addresses a comparison of the rowsets they return.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9775693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434089/']}
jdg_372495
stackexchange
llm_judgeable_groundtruth_similarity
53562
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it true that "Companies with diverse workforces outperform those with homogenous teams"? That's what TrendsWatching says anyway. And is it "diverse workforce" or "workforce comprising people from a variety of backgrounds"? I don't immediately see what racial diversity per ce may have to do with performance. TrendsWatching references this report Now provide the response and nothing else.
Does diversity lead to more productivity? Some diversity enhances productivity some doesn't. For example, age diversity Ilmakunnas & Ilmakunnas 2011) , cultural diversity or knowledge/experience (Navon 2010) diversity among employees is related to increase in productivity. On the other hand educational ( Ilmakunnas & Ilmakunnas 2011) or linguistic diversity (Dale-Olsenab Finseraas 2021) is shown to negatively impact productivity. These are some examples. A workforce diversity can be measured along plethora of multiple dimensions so no answer can look at every single possible dimension diversity. I don't immediately see what racial diversity per ce may have to do with performance. Neither the poster, nor the report to which you link, talks about racial diversity. It talks about homogeneous vs heterogenous teams. A team composed of same racial group can be heterogenous (i.e. diverse) along some other dimension such as education or age. Underrepresented group is any group that is not proportionally represented in some area relative to their proportion in total population, so for example in some industries that can be women, or Hindu etc. Team heterogeneity can be measured among myriads of different dimensions (some examples: age, sex, gender, sexual orientation, experience, skill set, education, culture, language, geographic, nationality, religion, ideology etc...).
{}
{'log_upvote_score': 5, 'links': ['https://economics.stackexchange.com/questions/53562', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/25838/']}
jdg_372496
stackexchange
llm_judgeable_groundtruth_similarity
631501
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: Does anybody know why this is happening and how to fix it? me@box:~$ echo "eyJmb28iOiJiYXIiLCJiYXoiOiJiYXQifQ" | base64 -di{"foo":"bar","baz":"bat"}base64: invalid input Now provide the response and nothing else.
If you do the reverse, you'll note that the string isn't complete: $ echo '{"foo":"bar","baz":"bat"}' | base64eyJmb28iOiJiYXIiLCJiYXoiOiJiYXQifQo=$ echo "eyJmb28iOiJiYXIiLCJiYXoiOiJiYXQifQo=" | base64 -di{"foo":"bar","baz":"bat"} Extracts of Why does base64 encoding require padding if the input length is not divisible by 3? What are Padding Characters? Padding characters help satisfy length requirements and carry no meaning. However, padding is useful in situations where base64 encoded stringsare concatenated in such a way that the lengths of the individualsequences are lost, as might happen, for example, in a very simplenetwork protocol. If unpadded strings are concatenated, it's impossible to recover theoriginal data because information about the number of odd bytes at theend of each individual sequence is lost. However, if padded sequencesare used, there's no ambiguity, and the sequence as a whole can bedecoded correctly.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/631501', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/38649/']}
jdg_372497
stackexchange
llm_judgeable_groundtruth_similarity
23850176
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get text/labels from application controls with Automation in C#. So far I am able to obtain AutomationElement tree of application (for example Notepad) with this function: private void WalkControlElements(AutomationElement rootElement, TreeNode treeNode) { AutomationElement elementNode = TreeWalker.ContentViewWalker.GetFirstChild(rootElement);; while (elementNode != null) { TreeNode childTreeNode = treeNode.Nodes.Add(elementNode.Current.ControlType.LocalizedControlType); // here I want to get text from 'elementNode' WalkControlElements(elementNode, childTreeNode); elementNode = TreeWalker.ControlViewWalker.GetNextSibling(elementNode); } } I tried to follow this article http://msdn.microsoft.com/en-us/library/ms788751(v=vs.110).aspx but it only can get text attributes as font name, font weight and so on. Could anybody point me to the right procedure how to get element text with Automation? Now provide the response and nothing else.
That sample is showing you how to get text attributes , i.e. information about the display of the text in the UI, not the actual displayed text. Getting all the actual displayed text for a general application is more difficult that it might first appear. It is made difficult by the fact that there are several ways get text and there is inconsistent support by applications and controls. There are two patterns that are of some use, ValuePattern and TextPattern . By convention the Name property contains text displayed to the user however adherence to this is inconsistent. Below is a helper method that I've used in UI automation for testing. It basically goes through those patterns checking the control for support and falls back to the Name. public static class AutomationExtensions{ public static string GetText(this AutomationElement element) { object patternObj; if (element.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj)) { var valuePattern = (ValuePattern)patternObj; return valuePattern.Current.Value; } else if (element.TryGetCurrentPattern(TextPattern.Pattern, out patternObj)) { var textPattern = (TextPattern)patternObj; return textPattern.DocumentRange.GetText(-1).TrimEnd('\r'); // often there is an extra '\r' hanging off the end. } else { return element.Current.Name; } }} This takes care of getting the text out of simple controls like labels, textboxes (both vanilla textbox and richtextbox), and buttons. Controls like listboxes and comboboxes (esp. in WPF) can be tricker because their items can be virtualized so they may not exist in the automation tree until the user interacts with them. You may want to filter and call this method only on certain UI Automation control types like Edit, Text, and Document which you know contain text.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23850176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/855289/']}
jdg_372498
stackexchange
llm_judgeable_groundtruth_similarity
432137
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: The 2018 Nobel Prize in Physics was awarded recently, with half going to Arthur Ashkin for his work on optical tweezers and half going to Gérard Mourou and Donna Strickland for developing a technique called "Chirped Pulse Amplification". In general, optical tweezers are relatively well known, but Chirped Pulse Amplification is less well understood on a broader physics or optics context. While normally the Wikipedia page is a reasonable place to turn to, in this case it's pretty technical and flat, and not particularly informative. So: What is Chirped Pulse Amplification? What is the core of the method that really makes it tick? What pre-existing problems did its introduction solve? What technologies does it enable, and what research fields have become possible because of it? Now provide the response and nothing else.
The problem Lasers do all sorts of cool things in research and in applications, and there are many good reasons for it, including their coherence, frequency stability, and controllability, but for some applications, the thing that really matters is raw power. As a simple example, it had long been understood that if the intensity of light gets high enough, then the assumption of linearity that underpins much of classical optics would break down, and nonlinear optical phenomena like second-harmonic generation would become available, getting light to do all sorts of interesting things. Using incoherent light sources, the required intensities are prohibitively high, but once the laser was invented, it took only one year until the first demonstration of second-harmonic generation , and a few short years after that until third-harmonic generation , a third-order nonlinear process that requires even higher intensities. Put another way, power matters, and the more intensity you have available, the wider a range of nonlinear optical phenomena will be open for exploration. Because of this, a large fraction of laser science has been focused on increasing the available intensities, generally using pulsed lasers to achieve this and with notable milestones being Q-switching and mode-locking . However, if you try to push onward with a bigger laser amplifier and more and more power, you are basically destined sooner or later to hit a brick wall, rather brusquely, in the form of catastrophic self-focusing . This is a consequence of yet another nonlinear effect, the Kerr effect , happening inside the laser medium itself. At face value, the Kerr effect looks harmless enough: basically, it says that if the intensity is high enough, the refractive index of the material will rise slightly, in proportion to the intensity: $$n(I) = n_0 + n_2\: I.$$ So, what's the big deal? In short, if you have a laser beam propagating through such a medium, then the intensity of the light will be higher in the center, which means that the refractive index will be higher in the center. In other words, the material's optical properties will look like those of a convex lens, and it will tend to focus the beam. This will tend to make the beam sharper, which will increase the intensity at the center, which will raise the refractive index at the center even higher... ... which will then focus the beam even more tightly, leading to higher and higher intensities. This makes up a positive feedback loop, and if the initial intensity is high enough, the medium is long enough, and there isn't enough initial diffraction to counteract it, then it will spiral out of control and cause catastrophic laser-induced damage in the very medium that you're trying to use to amplify that laser beam. (Moreover, it is quite common, particularly in air, that the laser will diffract on the damaged spot and then re-self-focus a bit further down the line, a phenomenon known as laser filamentation . If you get things just right wrong, this can propagate a failure in the gain medium up to the destruction of an entire beamline.) Image source This sounds like a funky mechanism, but it was a huge roadblock for a very long time. If you plot the highest laser intensity available at different times since the invention of the laser, it climbs quickly up during the sixties, and then it hits a wall and stays put for some ten to fifteen years: Image source This represents the barrier of Kerr-lens self-focusing, and at the time the only way to overcome it was to build a laser which was physically bigger, to dilute the intensity over more gain medium to try to prevent the problem. Until, that is, Chirped Pulse Amplification came around to solve the problem. The solution At its core, Chirped Pulse Amplification (CPA) works by diluting the light, so that it can be amplified to a larger total power without reaching a dangerous intensity, but it does this stretching in time , i.e. longitudinally along the laser pulse. The basic sequence consists of four steps: First of all, you start with a short laser pulse that you want to amplify You then stretch it in time, by introducing chirp into the signal: that is, you use some sort of dispersive element, like a prism or a diffraction grating, which decomposes the pulse into all of its constituent colors and sends the longer wavelengths first and the shorter wavelengths last. This will naturally reduce the intensity of the pulse. (Why "chirp"? because the upward (or downward) sweep of frequencies over the pulse is precisely what gives bird chirps their characteristic sound.) You then pass this lower-intensity pulse through your laser amplifier, which is safe because the instantaneous intensity is below the self-focusing damage threshold of your gain medium. Finally, you pass your pulse through a reversed set of gratings which will undo the relative delay between the longer- and shorter-wavelengths of your pulse, putting them all together into a single pulse of the same shape and length as your original pulse... ... but at the much higher amplified power, and at intensities which would be impossible to achieve safely using direct amplification of the pulse. The core feature that makes the method tick is the fact that, when done correctly, the stretching of the pulse will completely conserve the coherence between the different frequency components, which means that it is fully reversible and when you add a cancelling chirp the pulse will go back to its initial shape. Furthermore, the method relies on the fact that stimulated emission will completely duplicate, in a coherent way, the photons that it is amplifying, which means that the photons that are introduced by the amplification will have the same frequency and phase characteristics as the initial pulse, which means that when you remove the chirp from the amplified pulse the added-in photons will also compress into a tight envelope. Applications Like I said at the beginning, CPA is particularly useful in places where raw laser power, and particularly concentrated laser power, is of paramount importance. Here are some examples: In the same way that lasers gave us nonlinear optics, CPA has been integral in the development of high-order harmonic generation which has pushed past the second- or third-order harmonics to happily produce tens or hundreds of harmonics. (The current record goes all the way to harmonic 5,000 .) This isn't only 'more', it's qualitatively different: it pushes nonlinear optics to regimes where the usual perturbative expansion completely breaks down, and where it needs to be replaced with a completely new set of tools, which revolve around the so-called three-step model , and which involve a nice and quite particular new interface between classical and quantum mechanics, where trajectories do (sort of) exist but over complex-valued time and space, due to the presence of quantum tunnelling . It has also helped push the study of light-matter interaction past that same perturbative limit, giving us the tools to extract electrons from molecules and control them in very precise ways, thereby allowing for the creation of tools like e.g. laser-driven electron diffraction , which can be used to image the shapes of molecules as they undergo bending and other vibrations. CPA also underpins several breakthrough measurements which have been touched on previously on this site, including the observation of the time-dependent waveform of a light pulse , itself done using high-order harmonic radiation; the observation of charge oscillations when atoms are placed in excited states , again using HHG; or performing electron holography from an atomic target using electrons pulled from that same atom. Of course, all the cool laser-driven QED stuff at the top of that second diagram: if your laser is strong enough that, if you release an electron into the focus, the kinetic energy of its oscillations will exceed $m_e c^2$ , then you can start to have things like laser-driven pair creation, and all sorts of fun stuff. Some of it is already on the table, some of it is in achievable plans for the future, and all of it is made possible by CPA. CPA is also extremely useful in delivering sharply controlled bursts of power to materials. This is extremely useful in laser micromachining , for example, where it is routinely used in e.g. using short laser pulses to etch waveguides into dielectrics, which are then extremely useful for chip-based quantum computation and quantum information processing. Similarly, the ability to deliver sharply controlled bursts of power is extremely useful in laser microsurgery, and there are several types of eye surgery that exclusively use CPA pulses to provide sharp 'kicks' of power which perform cleaner incisions. On a much larger scale, when you really turn up the power to the maximum, CPA is a vital component of laser wakefield acceleration , which uses the ionized pocket left behind by an intense laser pulse as it travels through a gas to accelerate electrons to energies that would otherwise require an extremely large particle accelerator, but which are now available using a much more modest table-top laser system. Further reading Some additional resources for further reading: The Nobel Prize's scientific background and popular information documents make excellent reading, and people don't go looking at those sources anywhere near enough. Go check them out! The original paper: Compression of amplified chirped optical pulses. D. Strickland and G. Mourou. Optics Comms. 55 , 447 (1985) . What power limitations was chirped radar designed to overcome? , a previous question of mine on similar radar technologies that predated CPA. This is a nice tutorial on U Michigan .
{}
{'log_upvote_score': 10, 'links': ['https://physics.stackexchange.com/questions/432137', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8563/']}
jdg_372499
stackexchange
llm_judgeable_groundtruth_similarity
513084
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If your application requires a database and it comes with built in data, what is the best way to ship that application? Should I: Precreate the SQLite database and include it in the .apk ? Include the SQL commands with the application and have it create the database and insert the data on first use? The drawbacks I see are: Possible SQLite version mismatches might cause problems and I currently don't know where the database should go and how to access it. It may take a really long time to create and populate the database on the device. Any suggestions? Pointers to the documentation regarding any issues would be greatly appreciated. Now provide the response and nothing else.
There are two options for creating and updating databases. One is to create a database externally, then place it in the assets folder of the project and then copy the entire database from there. This is much quicker if the database has a lot of tables and other components. Upgrades are triggered by changing the database version number in the res/values/strings.xml file. Upgrades would then be accomplished by creating a new database externally, replacing the old database in the assets folder with the new database, saving the old database in internal storage under another name, copying the new database from the assets folder into internal storage, transferring all of the data from the old database (that was renamed earlier) into the new database and finally deleting the old database. You can create a database originally by using the SQLite Manager FireFox plugin to execute your creation sql statements. The other option is to create a database internally from a sql file. This is not as quick but the delay would probably be unnoticeable to the users if the database has only a few tables. Upgrades are triggered by changing the database version number in the res/values/strings.xml file. Upgrades would then be accomplished by processing an upgrade sql file. The data in the database will remain unchanged except when its container is removed, for example dropping a table. The example below demonstrates how to use either method. Here is a sample create_database.sql file. It is to be placed in the assets folder of the project for the internal method or copied into the "Execute SQL' of SQLite Manager to create the database for the external method. (NOTE: Notice the comment about the table required by Android.) --Android requires a table named 'android_metadata' with a 'locale' columnCREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');INSERT INTO "android_metadata" VALUES ('en_US');CREATE TABLE "kitchen_table";CREATE TABLE "coffee_table";CREATE TABLE "pool_table";CREATE TABLE "dining_room_table";CREATE TABLE "card_table"; Here is a sample update_database.sql file. It is to be placed in the assets folder of the project for the internal method or copied into the "Execute SQL' of SQLite Manager to create the database for the external method. (NOTE: Notice that all three types of SQL comments will be ignored by the sql parser that is included in this example.) --CREATE TABLE "kitchen_table"; This is one type of comment in sql. It is ignored by parseSql./* * CREATE TABLE "coffee_table"; This is a second type of comment in sql. It is ignored by parseSql. */{CREATE TABLE "pool_table"; This is a third type of comment in sql. It is ignored by parseSql.}/* CREATE TABLE "dining_room_table"; This is a second type of comment in sql. It is ignored by parseSql. */{ CREATE TABLE "card_table"; This is a third type of comment in sql. It is ignored by parseSql. }--DROP TABLE "picnic_table"; Uncomment this if picnic table was previously created and now is being replaced.CREATE TABLE "picnic_table" ("plates" TEXT);INSERT INTO "picnic_table" VALUES ('paper'); Here is an entry to add to the /res/values/strings.xml file for the database version number. <item type="string" name="databaseVersion" format="integer">1</item> Here is an activity that accesses the database and then uses it. ( Note: You might want to run the database code in a separate thread if it uses a lot of resources. ) package android.example;import android.app.Activity;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;/** * @author Danny Remington - MacroSolve * * Activity for demonstrating how to use a sqlite database. */public class Database extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DatabaseHelper myDbHelper; SQLiteDatabase myDb = null; myDbHelper = new DatabaseHelper(this); /* * Database must be initialized before it can be used. This will ensure * that the database exists and is the current version. */ myDbHelper.initializeDataBase(); try { // A reference to the database can be obtained after initialization. myDb = myDbHelper.getWritableDatabase(); /* * Place code to use database here. */ } catch (Exception ex) { ex.printStackTrace(); } finally { try { myDbHelper.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { myDb.close(); } } }} Here is the database helper class where the database is created or updated if necessary. (NOTE: Android requires that you create a class that extends SQLiteOpenHelper in order to work with a Sqlite database.) package android.example;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;/** * @author Danny Remington - MacroSolve * * Helper class for sqlite database. */public class DatabaseHelper extends SQLiteOpenHelper { /* * The Android's default system path of the application database in internal * storage. The package of the application is part of the path of the * directory. */ private static String DB_DIR = "/data/data/android.example/databases/"; private static String DB_NAME = "database.sqlite"; private static String DB_PATH = DB_DIR + DB_NAME; private static String OLD_DB_PATH = DB_DIR + "old_" + DB_NAME; private final Context myContext; private boolean createDatabase = false; private boolean upgradeDatabase = false; /** * Constructor Takes and keeps a reference of the passed context in order to * access to the application assets and resources. * * @param context */ public DatabaseHelper(Context context) { super(context, DB_NAME, null, context.getResources().getInteger( R.string.databaseVersion)); myContext = context; // Get the path of the database that is based on the context. DB_PATH = myContext.getDatabasePath(DB_NAME).getAbsolutePath(); } /** * Upgrade the database in internal storage if it exists but is not current. * Create a new empty database in internal storage if it does not exist. */ public void initializeDataBase() { /* * Creates or updates the database in internal storage if it is needed * before opening the database. In all cases opening the database copies * the database in internal storage to the cache. */ getWritableDatabase(); if (createDatabase) { /* * If the database is created by the copy method, then the creation * code needs to go here. This method consists of copying the new * database from assets into internal storage and then caching it. */ try { /* * Write over the empty data that was created in internal * storage with the one in assets and then cache it. */ copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } else if (upgradeDatabase) { /* * If the database is upgraded by the copy and reload method, then * the upgrade code needs to go here. This method consists of * renaming the old database in internal storage, create an empty * new database in internal storage, copying the database from * assets to the new database in internal storage, caching the new * database from internal storage, loading the data from the old * database into the new database in the cache and then deleting the * old database from internal storage. */ try { FileHelper.copyFile(DB_PATH, OLD_DB_PATH); copyDataBase(); SQLiteDatabase old_db = SQLiteDatabase.openDatabase(OLD_DB_PATH, null, SQLiteDatabase.OPEN_READWRITE); SQLiteDatabase new_db = SQLiteDatabase.openDatabase(DB_PATH,null, SQLiteDatabase.OPEN_READWRITE); /* * Add code to load data into the new database from the old * database and then delete the old database from internal * storage after all data has been transferred. */ } catch (IOException e) { throw new Error("Error copying database"); } } } /** * Copies your database from your local assets-folder to the just created * empty database in the system folder, from where it can be accessed and * handled. This is done by transfering bytestream. * */ private void copyDataBase() throws IOException { /* * Close SQLiteOpenHelper so it will commit the created empty database * to internal storage. */ close(); /* * Open the database in the assets folder as the input stream. */ InputStream myInput = myContext.getAssets().open(DB_NAME); /* * Open the empty db in interal storage as the output stream. */ OutputStream myOutput = new FileOutputStream(DB_PATH); /* * Copy over the empty db in internal storage with the database in the * assets folder. */ FileHelper.copyFile(myInput, myOutput); /* * Access the copied database so SQLiteHelper will cache it and mark it * as created. */ getWritableDatabase().close(); } /* * This is where the creation of tables and the initial population of the * tables should happen, if a database is being created from scratch instead * of being copied from the application package assets. Copying a database * from the application package assets to internal storage inside this * method will result in a corrupted database. * <P> * NOTE: This method is normally only called when a database has not already * been created. When the database has been copied, then this method is * called the first time a reference to the database is retrieved after the * database is copied since the database last cached by SQLiteOpenHelper is * different than the database in internal storage. */ @Override public void onCreate(SQLiteDatabase db) { /* * Signal that a new database needs to be copied. The copy process must * be performed after the database in the cache has been closed causing * it to be committed to internal storage. Otherwise the database in * internal storage will not have the same creation timestamp as the one * in the cache causing the database in internal storage to be marked as * corrupted. */ createDatabase = true; /* * This will create by reading a sql file and executing the commands in * it. */ // try { // InputStream is = myContext.getResources().getAssets().open( // "create_database.sql"); // // String[] statements = FileHelper.parseSqlFile(is); // // for (String statement : statements) { // db.execSQL(statement); // } // } catch (Exception ex) { // ex.printStackTrace(); // } } /** * Called only if version number was changed and the database has already * been created. Copying a database from the application package assets to * the internal data system inside this method will result in a corrupted * database in the internal data system. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /* * Signal that the database needs to be upgraded for the copy method of * creation. The copy process must be performed after the database has * been opened or the database will be corrupted. */ upgradeDatabase = true; /* * Code to update the database via execution of sql statements goes * here. */ /* * This will upgrade by reading a sql file and executing the commands in * it. */ // try { // InputStream is = myContext.getResources().getAssets().open( // "upgrade_database.sql"); // // String[] statements = FileHelper.parseSqlFile(is); // // for (String statement : statements) { // db.execSQL(statement); // } // } catch (Exception ex) { // ex.printStackTrace(); // } } /** * Called everytime the database is opened by getReadableDatabase or * getWritableDatabase. This is called after onCreate or onUpgrade is * called. */ @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); } /* * Add your public helper methods to access and get content from the * database. You could return cursors by doing * "return myDataBase.query(....)" so it'd be easy to you to create adapters * for your views. */} Here's the FileHelper class that contains methods for byte stream copying files and parsing sql files. package android.example;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import java.nio.channels.FileChannel;/** * @author Danny Remington - MacroSolve * * Helper class for common tasks using files. * */public class FileHelper { /** * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this * operation. * * @param fromFile * - InputStream for the file to copy from. * @param toFile * - InputStream for the file to copy to. */ public static void copyFile(InputStream fromFile, OutputStream toFile) throws IOException { // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; try { while ((length = fromFile.read(buffer)) > 0) { toFile.write(buffer, 0, length); } } // Close the streams finally { try { if (toFile != null) { try { toFile.flush(); } finally { toFile.close(); } } } finally { if (fromFile != null) { fromFile.close(); } } } } /** * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this * operation. * * @param fromFile * - String specifying the path of the file to copy from. * @param toFile * - String specifying the path of the file to copy to. */ public static void copyFile(String fromFile, String toFile) throws IOException { copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile)); } /** * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this * operation. * * @param fromFile * - File for the file to copy from. * @param toFile * - File for the file to copy to. */ public static void copyFile(File fromFile, File toFile) throws IOException { copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile)); } /** * Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy * of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then * it will be replaced with a copy of <i><b>fromFile</b></i>. The name and * path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both * <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this * operation. * * @param fromFile * - FileInputStream for the file to copy from. * @param toFile * - FileInputStream for the file to copy to. */ public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException { FileChannel fromChannel = fromFile.getChannel(); FileChannel toChannel = toFile.getChannel(); try { fromChannel.transferTo(0, fromChannel.size(), toChannel); } finally { try { if (fromChannel != null) { fromChannel.close(); } } finally { if (toChannel != null) { toChannel.close(); } } } } /** * Parses a file containing sql statements into a String array that contains * only the sql statements. Comments and white spaces in the file are not * parsed into the String array. Note the file must not contained malformed * comments and all sql statements must end with a semi-colon ";" in order * for the file to be parsed correctly. The sql statements in the String * array will not end with a semi-colon ";". * * @param sqlFile * - String containing the path for the file that contains sql * statements. * * @return String array containing the sql statements. */ public static String[] parseSqlFile(String sqlFile) throws IOException { return parseSqlFile(new BufferedReader(new FileReader(sqlFile))); } /** * Parses a file containing sql statements into a String array that contains * only the sql statements. Comments and white spaces in the file are not * parsed into the String array. Note the file must not contained malformed * comments and all sql statements must end with a semi-colon ";" in order * for the file to be parsed correctly. The sql statements in the String * array will not end with a semi-colon ";". * * @param sqlFile * - InputStream for the file that contains sql statements. * * @return String array containing the sql statements. */ public static String[] parseSqlFile(InputStream sqlFile) throws IOException { return parseSqlFile(new BufferedReader(new InputStreamReader(sqlFile))); } /** * Parses a file containing sql statements into a String array that contains * only the sql statements. Comments and white spaces in the file are not * parsed into the String array. Note the file must not contained malformed * comments and all sql statements must end with a semi-colon ";" in order * for the file to be parsed correctly. The sql statements in the String * array will not end with a semi-colon ";". * * @param sqlFile * - Reader for the file that contains sql statements. * * @return String array containing the sql statements. */ public static String[] parseSqlFile(Reader sqlFile) throws IOException { return parseSqlFile(new BufferedReader(sqlFile)); } /** * Parses a file containing sql statements into a String array that contains * only the sql statements. Comments and white spaces in the file are not * parsed into the String array. Note the file must not contained malformed * comments and all sql statements must end with a semi-colon ";" in order * for the file to be parsed correctly. The sql statements in the String * array will not end with a semi-colon ";". * * @param sqlFile * - BufferedReader for the file that contains sql statements. * * @return String array containing the sql statements. */ public static String[] parseSqlFile(BufferedReader sqlFile) throws IOException { String line; StringBuilder sql = new StringBuilder(); String multiLineComment = null; while ((line = sqlFile.readLine()) != null) { line = line.trim(); // Check for start of multi-line comment if (multiLineComment == null) { // Check for first multi-line comment type if (line.startsWith("/*")) { if (!line.endsWith("}")) { multiLineComment = "/*"; } // Check for second multi-line comment type } else if (line.startsWith("{")) { if (!line.endsWith("}")) { multiLineComment = "{"; } // Append line if line is not empty or a single line comment } else if (!line.startsWith("--") && !line.equals("")) { sql.append(line); } // Check for matching end comment } else if (multiLineComment.equals("/*")) { if (line.endsWith("*/")) { multiLineComment = null; } // Check for matching end comment } else if (multiLineComment.equals("{")) { if (line.endsWith("}")) { multiLineComment = null; } } } sqlFile.close(); return sql.toString().split(";"); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/513084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62596/']}
jdg_372500
stackexchange
llm_judgeable_groundtruth_similarity
1243952
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 getting performance problems when LIMIT ing a mysql SELECT with a large offset: SELECT * FROM table LIMIT m, n; If the offset m is, say, larger than 1,000,000, the operation is very slow. I do have to use limit m, n ; I can't use something like id > 1,000,000 limit n . How can I optimize this statement for better performance? Now provide the response and nothing else.
Perhaps you could create an indexing table which provides a sequential key relating to the key in your target table. Then you can join this indexing table to your target table and use a where clause to more efficiently get the rows you want. #create table to store sequencesCREATE TABLE seq ( seq_no int not null auto_increment, id int not null, primary key(seq_no), unique(id));#create the sequenceTRUNCATE seq;INSERT INTO seq (id) SELECT id FROM mytable ORDER BY id;#now get 1000 rows from offset 1000000SELECT mytable.* FROM mytable INNER JOIN seq USING(id)WHERE seq.seq_no BETWEEN 1000000 AND 1000999;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1243952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128070/']}
jdg_372501
stackexchange
llm_judgeable_groundtruth_similarity
379288
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to prove this equation:$$\sin\left(\frac{\pi}{n}\right)\cdot \sin\left(\frac{2\pi}{n}\right) \cdots \sin\left(\frac{(n-1)\pi}{n}\right)=\frac{2n}{2^n}$$There's a hint: Consider the product of $n-1$ non-zero roots of equation $(z+1)^n=1$, but I fail to understand it. Now provide the response and nothing else.
To explain the given hint: the roots of $x^n=1$ are$$x_k=e^{2ik\pi/n}\quad k=0,\ldots,n-1$$so the product of roots except $0$ of $(z+1)^n=1$ is$$\prod_{k=1}^{n-1} (x_k-1)=\prod_{k=1}^{n-1}e^{2ik\pi/n}-1=\prod_{k=1}^{n-1}e^{ik\pi/n}\prod_{k=1}^{n-1}(e^{ik\pi/n}-e^{-ik\pi/n})=\prod_{k=1}^{n-1}2ie^{ik\pi/n}\prod_{k=1}^{n-1}\sin({k\pi/n})$$ hence to find the desired result you have to calculate ( which isn't difficult )$$\prod_{k=1}^{n-1}(x_k-1)\quad\text{and}\quad \prod_{k=1}^{n-1}2ie^{ik\pi/n}$$ Hint for the first product you can use the Vieta's formulas and I trust you that you understand this second hint.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/379288', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71089/']}
jdg_372502
stackexchange
llm_judgeable_groundtruth_similarity
41017202
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a problem using the HammerJS with Angular2.I have a carousel (based on the bootstrap carousel with Angular2 event handlers) where I'm listening to the swipe left and swipe right events.The swipe itself works perfectly.The problem is that since I use the HammerJS I can not scroll up/down over my carousel component and since it's a full viewport sized item it's a huge issue. How can this issue be solved? Platform: Angular2 2.1.2 Samsung Galaxy S2 with Android 5.1.1 Google Chrome for Android: 54.0.2840.85 Now provide the response and nothing else.
Got it! In your AppModule: import { HAMMER_GESTURE_CONFIG, HammerGestureConfig } from '@angular/platform-browser';export class MyHammerConfig extends HammerGestureConfig { overrides = <any> { 'pinch': { enable: false }, 'rotate': { enable: false } }}@NgModule({ declarations: [ // ... ], imports: [ // ... ], providers: [ // ... { provide: HAMMER_GESTURE_CONFIG, useClass: MyHammerConfig } ], bootstrap: [ AppComponent ]})export class AppModule {} Now vertical scrolling works, after disabling pinch and rotate .Couldn't find any other way so far. I'm not sure what happens to the pinch and rotate events (I mean they would be disabled, I think). But even without this config, attaching a (pinch)="onPinch($event)" - didn't do anything anyway. Angular version in my project: 2.4.1 Tested on: Chrome for Windows (on a Surface, so real touchscreen - not just emulated) v 55.0.2883.87 m (64-bit) Chrome for Android - v 55.0.2883.91
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41017202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1511408/']}
jdg_372503
stackexchange
llm_judgeable_groundtruth_similarity
13065868
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 bind an action to the Go button of the keyboard in iOS ? Now provide the response and nothing else.
Objective-C Assuming you're using a UITextField, you could use the <UITextFieldDelegate> method textFieldShouldReturn . - (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; // Dismiss the keyboard. // Execute any additional code return YES;} Don't forget to assign the class you put this code in as the text field's delegate. self.someTextField.delegate = self; Or if you'd prefer to use UIControlEvents, you can do the following [someTextField addTarget:self action:@selector(textFieldDidReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];- (void)textFieldDidReturn:(UITextField *)textField{ // Execute additional code} See @Wojtek Rutkowski's answer to see how to do this in Interface Builder. Swift UITextFieldDelegate class SomeViewController: UIViewController, UITextFieldDelegate { let someTextField = UITextField() override func viewDidLoad() { super.viewDidLoad() someTextField.delegate = self } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() // Dismiss the keyboard // Execute additional code return true }} UIControlEvents class SomeViewController: UIViewController { let someTextField = UITextField() override func viewDidLoad() { super.viewDidLoad() // Action argument can be Selector("textFieldDidReturn:") or "textFieldDidReturn:" someTextField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: .EditingDidEndOnExit) } func textFieldDidReturn(textField: UITextField!) { textField.resignFirstResponder() // Execute additional code }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13065868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/507323/']}
jdg_372504
stackexchange
llm_judgeable_groundtruth_similarity
3014737
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: what is IEnumerable in .net? Now provide the response and nothing else.
It's ... something... that you can loop over. That might be a List or an Array or (almost) anything else that supports a foreach loop. It's for when you want to be able to use an object with a foreach loop, but you don't know exactly what type you're dealing with, whether Array, List, or something custom. So that's the first advantage there: if your methods accept an IEnumerable rather than an array or list they become more powerful because you can pass more different kinds of objects to them. Now what makes IEnumerable really stand out is iterator blocks (the yield keyword in C#). Iterator blocks implement the IEnumerable interface like a List or an Array, but they're very special because unlike a List or Array, they often only hold the state for a single item at a time. So if you want to loop over the lines in a very large file, for example, you can write an iterator block to handle the file input. Then you'll never have more than one line of the file in memory at a time, and if you finish the loop earlier (perhaps it was a search and you found what you needed) you might not need to read the whole file. Or if you're reading the results from a large SQL query you can limit your memory use to a single record. Another feature is that this evaluation is lazy , so if you're doing complicated work to evaluate the enumerable as you read from it, that work doesn't happen until it's asked for. This is extra beneficial, because often (say, for searches again) you'll find you might not need to do the work at all. You can think of IEnumerable as if it were a just-in-time List.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3014737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363493/']}
jdg_372505
stackexchange
llm_judgeable_groundtruth_similarity
20607746
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 incorporating AdMob into my app. I've followed the steps in the developers page. However AdRequest.Builder() is being underlined with red and it says: AdRequest cannot be resolved to a type and AdRequest.Builder cannot be resolved to a type. What could be the problem? import com.google.ads.AdRequest;import com.google.ads.AdView;public class FireRoomActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fire_room); // Look up the AdView as a resource and load a request. AdView adView = (AdView)this.findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } In xml I've shown admob as such: <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="bla bla" ads:adSize="BANNER"/> Now provide the response and nothing else.
Your code is mix for Admob SDK (Google Play) and Android (6.4.1 and earlier SDKs) Use import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.AdView;AdRequest adRequest = new AdRequest.Builder().build(); and <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="bla bla" ads:adSize="BANNER"/> if you use Admob SDK (Google Play) Or use import com.google.ads.AdRequest;import com.google.ads.AdView;AdRequest adRequest = new AdRequest(); and <com.google.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" ads:adUnitId="bla bla" ads:adSize="BANNER"/> if you use earlies SDK For Admob SDK (Google Play) not forget to change namespase xmlns:ads="http://schemas.android.com/apk/res-auto"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20607746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625483/']}
jdg_372506
stackexchange
llm_judgeable_groundtruth_similarity
69700
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I’ve read a book on these verses (Luke 1:1-4 that suggested the Greek wording in Luke 1:1-4 shows that “speedy writers” followed Jesus as “ministers of the spoken word” also being eyewitnesses of Christ Himself. My question is, does the Greek make it possible for such an interpretation? This goes along the bounds of the arguments for the “gospel of Q”. Especially knowing that the gospel of Luke was about Jesus: “Inasmuch as many have taken in hand to set in order a narrative of those things which have been fulfilled among us, just as those who from the beginning were eyewitnesses and ministers of the word delivered them to us, it seemed good to me also , having had perfect understanding of all things from the very first, to write to you an orderly account, most excellent Theophilus, that you may know the certainty of those things in which you were instructed.”Luke 1:1-4 Book: Jesus Stenographers by Ben Van Noort Now provide the response and nothing else.
The short answer to, Were there "speedy writers" that followed Jesus as implied in Luke 1:1-4? (see appendix below) No. We deduce thus from several considerations: Luke records what people saw according to the "eyewitnesses" and thus was as much about what happened as what was said. Luke's account is from the initial witnesses, not stenographers "servants of the word" means those obedient to the word and faith of the Apostles, James 1:22, Rom 15:18, Num 3:51, 1 Chron 21:19, Ps 103:20, etc, see also Acts 6:7. Luke records that he "carefully investigated", presumably by examining any written records and interviewing many people who had witnessed these things We must also allow for the miraculous working of the Holy Spirit in the Luke's contribution to the Canon of the NT, 2 Tim 3:16, 17, 2 Peter 1:19-21. See also 2 Sam 23:2, Neh 9:30, Eze 2:2, 11:5, 24, Micah 3:8, Zech 7:12, 2 Peter 1:19-21, Rom 1:2, 3:2, Heb 3:7, 5:12, 9:8, Mark 12:36, Acts 28:25, 1 Tim 4:1. Just how this might have worked, we are not specifically told, but may have included things like (a) prompting the memories of the eyewitnesses, (b) prompting Luke in what he recorded and wrote, (c) making some data available to Luke's research, (d) ensuring some things got recorded at all for Luke to later use, etc, etc. Thus, there is no evidence of "speedy writers". APPENDIX Luke 1:1-4 1 Many have undertaken to compose an account of the things that have been fulfilled among us, 2 just as they were handed down to us by the initial eyewitnesses and servants of the word. 3 Therefore, having carefully investigated everything from the beginning, it seemed good also to me to write an orderly account for you, most excellent Theophilus, 4 so that you may know the certainty of the things you have been taught.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/69700', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/44302/']}
jdg_372507
stackexchange
llm_judgeable_groundtruth_similarity
549408
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: What is a non-trivial example of an identifiable model whose MLE is consistent, but the MLE's asymptotic distribution is not normal? Parametric setting and IID sample would be desirable. Now provide the response and nothing else.
Hypothesis tests are still used because they are motivated by a different need in statistical inference than interval estimators are motivated by. The purpose of a hypothesis test is to make a decision as to whether there is evidence for the alternative hypothesis' expression of the population parameter. Confidence intervals serve a different purpose: they provide a plausible range of estimates of a population parameter. All the technical details about estimation (exact vs approximate, bootstrap vs non-probabilistic closed-form estimators, intervals, test statistics and p values, etc.) aside, the above represent fundamentally different motivations in statistical inference. Aside: sometimes confidence interval coverage has a pretty direct correspondence to a hypothesis tests ( a la does it cover the null or not), but this is not always the case, and habitually using confidence intervals for that purpose, in my opinion, obscures the above distinction between "let's make a decision about evidence for the alternative hypothesis" and "let's estimate a plausible range of values for a parameter."
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/549408', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9394/']}
jdg_372508
stackexchange
llm_judgeable_groundtruth_similarity
8516812
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 storing String into shared preferences, but I wasn't able to find out maximal length of string I can store. Do you know this value? Now provide the response and nothing else.
By Romain Guy From the Question Asked Here , Whatever the maximum length of a Java string is. So something like Integer.MAX_VALUE chars. I suppose while SharedPreference is an XML file stored with One Tag if you store only One Pair/Object.So there is no limit to write String in that if you think like you are writing in a file..(Theoretically) But Actually what happens is that, while you are assigning value to SharedPreference using put/get function at that time you Reading/Writting value in String Object ..so the limit becomes to store value at one time equal to Size limit of String Object of Java . So while writting the code: Limit of SharedPreference String Size = Java String Object Size Limit (Practically)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8516812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/513956/']}
jdg_372509
stackexchange
llm_judgeable_groundtruth_similarity
11742812
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working with a d3 force-directed layout with HTML node labels implemented with SVG foreignObject elements. I'd like to select these elements at various times to update their positions and other properties (and track them as they are created and destoryed with enter() and exit() ), but I don't seem to be able to select them like other SVG elements. Here is a compact example: HTML: <html> <head> <title>Cannot Select SVG Foreign Object</title> <script src="http://d3js.org/d3.v2.js"></script> <script src = "fo_select.js"></script> </head> <body> <svg id="example_svg" width="600" height="600"> <g> <circle r="40" cx = "80" cy="80"></circle> <foreignObject width = "100" height = "100" x = "200" y="200"> <body>Hello, world</body> </foreignObject> </g> </svg> <script>run()</script> </body></html> Javascript: function run() { svg = d3.select("#example_svg"); console.log(svg.selectAll("circle")); console.log(svg.selectAll("foreignObject"));} This is also up at http://bl.ocks.org/3217448 . The console output is: [Array[1]][Array[0]] where the first array contains the circle element, while the second one is empty. Why is the circle object selectable, but the foreignObject is not? I assume it has to do with the unusual nature of the foreignObject . How would I select it to manipulate it in my code? Thanks very much. Now provide the response and nothing else.
Strictly speaking, SVG is case sensitive so you should use <foreignObject> instead of <foreignobject> . More seriously though, is that there's an open bug in WebKit that prevents camelCase elements from being selected. One possible workaround is to use: .selectAll(function() { return this.getElementsByTagName("foreignObject"); }) (This may not work in older WebKit versions though; see the now-closed WebKit bug 46800 .) Alternatively, you can use CSS classes or IDs and select your elements that way instead. I would recommend this approach at the moment if possible, given the various aforementioned bugs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11742812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/413345/']}
jdg_372510
stackexchange
llm_judgeable_groundtruth_similarity
57455200
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to create my own Component Library for the past few weeks, everything is going smooth except from the fact that I can't get hooks to work. Whenever I import from the library a component that uses hooks I get "Hooks can only be called inside the body of a function component." https://reactjs.org/warnings/invalid-hook-call-warning.html I would expect it's something about React being duplicated which I don't see when I run npm ls react . This is my webpack.config.js const path = require('path');var nodeExternals = require('webpack-node-externals');module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', } }, { test: /\.scss$/, sideEffects: true, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, ], }, { test: /\.(png|gif|jpg|svg)$/, use: { loader: 'url-loader', options: { limit: 50000, }, }, }, { test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [ { loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'fonts/' } } ] } ], }, resolve: { extensions: ['.scss', '.ttf', '.js', '.json', '.png', '.gif', '.jpg', '.svg'], }, output: { path: path.resolve(__dirname, 'dist/'), publicPath: '', filename: 'index.js', libraryTarget: 'umd', }, target: 'node', externals: [ nodeExternals() ]}; This is my package-json { "name": "ui-components", "version": "1.1.1", "description": "componentes UI", "main": "dist/index.js", "scripts": { "test": "jest", "build": "webpack --mode production", "storybook": "start-storybook -p 9001", "docz:dev": "docz dev", "docz:build": "docz build" }, "repository": { "type": "git", "url": "..." }, "keywords": [ "react", "shared", "components", "botbit" ], "author": "Uriel Chami", "license": "MIT", "devDependencies": { "@babel/core": "^7.2.2", "@babel/preset-env": "^7.2.3", "@babel/preset-react": "^7.0.0", "@storybook/addon-actions": "^5.0.0", "@storybook/addon-storyshots": "^5.1.10", "@storybook/react": "^5.0.0", "@tulipjs/eslint-config": "^1.1.1", "babel-loader": "^8.0.1", "babel-plugin-macros": "^2.6.1", "css-loader": "^1.0.0", "docz": "^1.2.0", "docz-theme-default": "^1.2.0", "file-loader": "^4.1.0", "jest": "^24.8.0", "node-sass": "^4.9.3", "react": "^16.9.0", "react-dom": "^16.9.0", "react-router-dom": "^5.0.1", "react-test-renderer": "^16.8.6", "sass-loader": "^7.1.0", "style-loader": "^0.23.1", "url-loader": "^1.1.2", "webpack": "^4.28.3", "webpack-cli": "^3.2.0", "webpack-node-externals": "^1.7.2" }, "peerDependencies": { "react": "16.9.0", "react-dom": "16.9.0" }, "dependencies": { "mdbreact": "..." }} Im using npm link to test the functioning of the library but also I can deploy it to GitHub and npm update it. I've added window.React1 = require('react'); in node_modules/react-dom/index.js (in the App that uses my library).And require('react-dom'); window.React2 = require('react'); console.log(window.React1); console.log(window.React1 === window.React2); in my App.js (in the app that uses my library). And it throws true . I'm slowly getting clueless. Any ideas? Edit: The code where I'm trying to use Hooks is: import React, {useEffect} from 'react';export const Test = () => { useEffect(()=>{ console.log("component did mount"); } , []) return(<div>Hola!</div>);} Edit 2 When I build yarn webpack --mode development it throws 'require is not defined' . Here it goes a GitHub repo with my complete code if anyone wants to toy around: https://github.com/uchami/hooks-not-working Edit 3 I add the component library (ui-components) as so yarn add git+ssh:repository .The application where I import my library is simply a plain create-react-app. And I just implement the Test component (which is the one that uses Hooks) using import {Test} from 'ui-components' and I use it just like that <Test></Test> . The compilation of the ui-components project is just yarn build on the console. On the background what is doing is calling yarn webpack --mode production . If you call yarn webpack --mode development you will see extra verbose error output. Now provide the response and nothing else.
"Hooks can only be called inside the body of a function component." Let's rule out all possibilities according to React docs : You might have mismatching versions of React and React DOM. You might be breaking the Rules of Hooks . You might have more than one copy of React in the same app. 1.) If unsure, try to reinstall react and react-dom in the latest version in your app, so they 100% match (or look at your package-lock.json / yarn lock): npm i react@latest react-dom@latest 2.) Your useEffect Hook usage inside Test looks fine - Test is a function component and useEffect is called at the top-level . 3.) It would be my main guess for the error at hand. You are using npm link to link the library for local tests. npm link will add a symbolic link for the complete library working directory (including node_modules ) inside app project's node_modules . react is installed both as devDependencies in the library and as dependencies in the app project. Now, when Webpack bundles the app project, it will choose react either from library or app - whichever is included in the nearest node_modules folder relative to the importing module. Solution A fix is mentioned on the Invalid Hook Call Warning page: Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib . This should make the library use the application’s React copy. Alternative: Tell Webpack to always resolve to a single react package - the one in your app node_modules (credit goes to these two issues ). webpack.config.js : resolve: { ... alias: { // Needed when library is linked via `npm link` to app react: path.resolve("./node_modules/react") }} "require is not defined" This likely happens, when you run the web app bundled by a faulty Webpack config, where require calls are not dropped and replaced by the actual code modules. If the application project is based on create-react-app , you might import the library in app and just run start or build . Given a custom Webpack config (e.g. via eject ), run the build with target:web (or omit target ) and leave out externals: [ nodeExternals() ] .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57455200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7338046/']}
jdg_372511
stackexchange
llm_judgeable_groundtruth_similarity
7438386
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following function defined in .bash_aliases findphp () { find -name '*.php' -exec grep -H --color "$@" "{}" \;} It allows me to run something like findphp 'function x' to find all references to function x in php files Now I want to pass the file type to search, example js, css, ctp as a parameter in bash I defined the follwing function and sourced .bash_aliases myfind () { find -name '*.$1' -exec grep -H --color "$2" "{}" \;} But it's not working, I tried single quotes, double quotes around the positional parameterswith no avail. How could I define a function that takes the file extension and search string as arguments from the command line? Now provide the response and nothing else.
How about: list = context.Obj.Where(o => A == null || o.A == A) .ToList(); You can do it in one query but still using a condition: IEnumerable<O> query = context.Obj;if (A != null){ query = query.Where(o => o.A == A);}var list = query.ToList(); Or you could use a conditional operator to put the query in a single statement: var query = A is null ? context.Obj : context.Obj.Where(o => o.A == A);var list = query.ToList(); I would personally suggest either of the latter options, as they don't require that the LINQ provider is able to optimise away the filter in the case where A is null. (I'd expect most good LINQ providers / databases to be able to do that, but I'd generally avoid specifying a filter when it's not needed.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7438386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61327/']}
jdg_372512
stackexchange
llm_judgeable_groundtruth_similarity
8510335
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: can you have a layout with an imageview and textview for a row in a SimpleCursorAdapter with a listview? this would be the layout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"><ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /><TextView android:id="@+id/bowler_txt" android:paddingLeft="25dp" android:textSize="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bowler" android:textAppearance="?android:attr/textAppearanceLarge" /></LinearLayout> can it be done in SimpleCursorAdapter with a listview? when I needed images in a listview I always used a custom arrayadapter but never with a cursor. How would I set the image if it can be done? Now provide the response and nothing else.
When the view to bind is an ImageView and there is no existing ViewBinder associated SimpleCursorAdapter.bindView() calls setViewImage(ImageView, String) . By default, the value will be treated as an image resource . If the value cannot be used as an image resource, the value is used as an image Uri . If you need to filter in other ways the value retrieved from the database you need a ViewBinder to add to the ListAdapter as follow: listAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder(){ /** Binds the Cursor column defined by the specified index to the specified view */ public boolean setViewValue(View view, Cursor cursor, int columnIndex){ if(view.getId() == R.id.your_image_view_id){ //... ((ImageView)view).setImageDrawable(...); return true; //true because the data was bound to the view } return false; }});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8510335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/599346/']}
jdg_372513
stackexchange
llm_judgeable_groundtruth_similarity
45418523
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 find examples of WebClient use. My goal is to use Spring 5 WebClient to query a REST service using https and self signed certificate Any example? Now provide the response and nothing else.
See example of use insecure TrustManagerFactory that trusts all X.509 certificates (including self-signed) without any verification. The important note from documentation: Never use this TrustManagerFactory in production. It is purely for testing purposes, and thus it is very insecure. @Beanpublic WebClient createWebClient() throws SSLException { SslContext sslContext = SslContextBuilder .forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); ClientHttpConnector httpConnector = HttpClient.create().secure(t -> t.sslContext(sslContext) ) return WebClient.builder().clientConnector(httpConnector).build();}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45418523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3938606/']}
jdg_372514
stackexchange
llm_judgeable_groundtruth_similarity
634971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Simpler Example Let's try a simpler example, so people can wrap their heads around the concepts, and have a practical example that you can copy&paste into SQL Query Analizer: Imagine a Nodes table, with a heirarchy: A - B - C We can start testing in Query Analizer: CREATE TABLE ##Nodes( NodeID varchar(50) PRIMARY KEY NOT NULL, ParentNodeID varchar(50) NULL)INSERT INTO ##Nodes (NodeID, ParentNodeID) VALUES ('A', null)INSERT INTO ##Nodes (NodeID, ParentNodeID) VALUES ('B', 'A')INSERT INTO ##Nodes (NodeID, ParentNodeID) VALUES ('C', 'B') Desired output: ParentNodeID NodeID GenerationsRemoved============ ====== ==================NULL A 1NULL B 2NULL C 3A B 1A C 2B C 1 Now the suggested CTE expression, with it's incorrect output: WITH NodeChildren AS( --initialization SELECT ParentNodeID, NodeID, 1 AS GenerationsRemoved FROM ##Nodes WHERE ParentNodeID IS NULL UNION ALL --recursive execution SELECT P.ParentNodeID, N.NodeID, P.GenerationsRemoved + 1 FROM NodeChildren AS P INNER JOIN ##Nodes AS N ON P.NodeID = N.ParentNodeID)SELECT ParentNodeID, NodeID, GenerationsRemovedFROM NodeChildren Actual output : ParentNodeID NodeID GenerationsRemoved============ ====== ==================NULL A 1NULL B 2NULL C 3 Note: If SQL Server 2005† CTE cannot do what i was doing before in 2000‡, that's fine, and that's the answer. And whoever gives "it's not possible" as the answer will win the bounty. But i will wait a few days to make sure everyone concur's that it's not possible before i irrecovably give 250 reputation for a non-solution to my problem. Nitpickers Corner †not 2008 ‡without resorting to a UDF*, which is the solution already have *unless you can see a way to improve the performance of the UDF in the original question Original Question i have a table of Nodes, each with a parent that points to another Node (or to null). For illustration: 1 My Computer 2 Drive C 4 Users 5 Program Files 7 Windows 8 System32 3 Drive D 6 mp3 i want a table that returns all the parent-child relationships, and the number of generations between them For for all direct parent relationships: ParentNodeID ChildNodeID GenerationsRemoved============ =========== ===================(null) 1 11 2 12 4 12 5 12 7 11 3 13 6 17 8 1 But then there's the grandparent relationships: ParentNodeID ChildNodeID GenerationsRemoved============ =========== ===================(null) 2 2(null) 3 21 4 21 5 21 7 21 6 22 8 2 And the there's the great-grand-grandparent relationships: ParentNodeID ChildNodeID GenerationsRemoved============ =========== ===================(null) 4 3(null) 5 3(null) 7 3(null) 6 31 8 3 So i can figure out the basic CTE initialization: WITH (NodeChildren) AS{ --initialization SELECT ParentNodeID, NodeID AS ChildNodeID, 1 AS GenerationsRemoved FROM Nodes} The problem now is the recursive part. The obvious answer, of course, doesn't work: WITH (NodeChildren) AS{ --initialization SELECT ParentNodeID, ChildNodeID, 1 AS GenerationsRemoved FROM Nodes UNION ALL --recursive execution SELECT parents.ParentNodeID, children.NodeID, parents.Generations+1 FROM NodeChildren parents INNER JOIN NodeParents children ON parents.NodeID = children.ParentNodeID} Msg 253, Level 16, State 1, Line 1Recursive member of a common table expression 'NodeChildren' has multiple recursive references. All the information needed to generate the entire recursive list is present in the inital CTE table. But if that's not allowed i'll try: WITH (NodeChildren) AS{ --initialization SELECT ParentNodeID, NodeID, 1 AS GenerationsRemoved FROM Nodes UNION ALL --recursive execution SELECT parents.ParentNodeID, Nodes.NodeID, parents.Generations+1 FROM NodeChildren parents INNER JOIN Nodes ON parents.NodeID = nodes.ParentNodeID} But that fails because it's not only joining on the recursive elements, but keeps recursivly adding the same rows over and over: Msg 530, Level 16, State 1, Line 1The statement terminated. The maximum recursion 100 has been exhausted before statement completion. In SQL Server 2000 i simulated a CTE by using a User Defined Function (UDF): CREATE FUNCTION [dbo].[fn_NodeChildren] ()RETURNS @Result TABLE ( ParentNodeID int NULL, ChildNodeID int NULL, Generations int NOT NULL) AS /*This UDF returns all "ParentNode" - "Child Node" combinations ...even multiple levels separatedBEGIN DECLARE @Generations int SET @Generations = 1 --Insert into the Return table all "Self" entries INSERT INTO @Result SELECT ParentNodeID, NodeID, @Generations FROM Nodes WHILE @@rowcount > 0 BEGIN SET @Generations = @Generations + 1 --Add to the Children table: -- children of all nodes just added -- (i.e. Where @Result.Generation = CurrentGeneration-1) INSERT @Result SELECT CurrentParents.ParentNodeID, Nodes.NodeID, @Generations FROM Nodes INNER JOIN @Result CurrentParents ON Nodes.ParentNodeID = CurrentParents.ChildNodeID WHERE CurrentParents.Generations = @Generations - 1 END RETURNEND And the magic to keep it from blowing up was the limiting where clause: WHERE CurrentParents.Generations - @Generations-1 How do you prevent a recursive CTE from recursing forever? Now provide the response and nothing else.
Try this: WITH Nodes AS( --initialization SELECT ParentNodeID, NodeID, 1 AS GenerationsRemoved FROM ##Nodes UNION ALL ----recursive execution SELECT P.ParentNodeID, N.NodeID, P.GenerationsRemoved + 1 FROM Nodes AS P INNER JOIN ##Nodes AS N ON P.NodeID = N.ParentNodeID WHERE P.GenerationsRemoved <= 10)SELECT ParentNodeID, NodeID, GenerationsRemovedFROM NodesORDER BY ParentNodeID, NodeID, GenerationsRemoved Basically removing the "only show me absolute parents" from the initialization query; That way it generates the results starting from each of them and decending from there. I also added in the "WHERE P.GenerationsRemoved <= 10" as an infinite recursion catch(replace 10 with any number up to 100 to fit your needs). Then add the sort so it looks like the results you wanted.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/634971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12597/']}
jdg_372515
stackexchange
llm_judgeable_groundtruth_similarity
8861105
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 built GCC 4.7 on my x86 32-bit linux system. When I try to cross-compile with the -m64 flag I get the following: sorry, unimplemented: 64-bit mode not compiled in while the compiler provided by default by my Linux distribution can cross-compile with -m64. What do I have to pass to ./configure to enable the 64bit mode in GCC? These are the options I used to build GCC 4.7: $ /usr/local/bin/g++ -v Using built-in specs.COLLECT_GCC=/usr/local/bin/g++COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/i686-pc-linux-gnu/4.7.0/lto-wrapperTarget: i686-pc-linux-gnuConfigured with: ./configure --enable-multiarch --with-cloog=/usr/local/ --with-mpfr=/usr/local/ --with-ppl=/usr/local/ --verbose --enable-languages=c,c++Thread model: posix gcc version 4.7.0 20120113 (experimental) (GCC) EDIT: --enable-multilib and --enable-targets=i686-pc-linux-gnu,x86_64-pc-linux-gnu do not change the situation. The compiler still complains about 64 bit mode not compiled in: $ g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/i686-pc-linux-gnu/4.7.0/lto-wrapper Target: i686-pc-linux-gnu Configured with: ./configure --enable-multiarch --with-cloog=/usr/local/ --with-mpfr=/usr/local/ --with-ppl=/usr/local/ --verbose --enable-languages=c,c++ --enable-multilib --enable-targets=i686-pc-linux-gnu,x86_64-pc-linux-gnu Thread model: posix gcc version 4.7.0 20120113 (experimental) (GCC) $ g++ -m64 c.cpp c.cpp:1:0: sorry, unimplemented: 64-bit mode not compiled in Now provide the response and nothing else.
You will need both binutils and gcc configured with: --enable-multilib and probably: --enable-targets=i686-pc-linux-gnu,x86_64-pc-linux-gnu to support multilib (the -m64 and/or -m32 options). You'll also need two versions of stuff like glibc to be able to link and run the resulting binaries.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8861105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989331/']}
jdg_372516
stackexchange
llm_judgeable_groundtruth_similarity
12951453
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've noticed that a lot of good answers to MATLAB questions on Stack Overflow frequently use the function bsxfun . Why? Motivation: In the MATLAB documentation for bsxfun , the following example is provided: A = magic(5);A = bsxfun(@minus, A, mean(A)) Of course we could do the same operation using: A = A - (ones(size(A, 1), 1) * mean(A)); And in fact a simple speed test demonstrates the second method is about 20% faster. So why use the first method? I'm guessing there are some circumstances where using bsxfun will be much faster than the "manual" approach. I'd be really interested in seeing an example of such a situation and an explanation as to why it is faster. Also, one final element to this question, again from the MATLAB documentation for bsxfun : "C = bsxfun(fun,A,B) applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled.". What does the phrase "with singleton expansion enabled" mean? Now provide the response and nothing else.
There are three reasons I use bsxfun ( documentation , blog link ) bsxfun is faster than repmat (see below) bsxfun requires less typing Using bsxfun , like using accumarray , makes me feel good about my understanding of MATLAB. bsxfun will replicate the input arrays along their "singleton dimensions", i.e., the dimensions along which the size of the array is 1, so that they match the size of the corresponding dimension of the other array. This is what is called " singleton expansion ". As an aside, the singleton dimensions are the ones that will be dropped if you call squeeze . It is possible that for very small problems, the repmat approach is faster - but at that array size, both operations are so fast that it likely won't make any difference in terms of overall performance. There are two important reasons bsxfun is faster: (1) the calculation happens in compiled code, which means that the actual replication of the array never happens, and (2) bsxfun is one of the multithreaded MATLAB functions. I have run a speed comparison between repmat and bsxfun with MATLAB R2012b on my decently fast laptop. For me, bsxfun is about three times faster than repmat . The difference becomes more pronounced if the arrays get larger: The jump in runtime of repmat happens around an array size of 1 MB, which could have something to do with the size of my processor cache - bsxfun doesn't get as bad of a jump, because it only needs to allocate the output array. Below you find the code I used for timing: n = 300;k=1; %# k=100 for the second grapha = ones(10,1);rr = zeros(n,1);bb = zeros(n,1);ntt = 100;tt = zeros(ntt,1);for i=1:n; r = rand(1,i*k); for it=1:ntt; tic, x = bsxfun(@plus,a,r); tt(it) = toc; end; bb(i) = median(tt); for it=1:ntt; tic, y = repmat(a,1,i*k) + repmat(r,10,1); tt(it) = toc; end; rr(i) = median(tt);end
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12951453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1667895/']}
jdg_372517
stackexchange
llm_judgeable_groundtruth_similarity
10539268
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 currently doing a special xml layout of a landscape screen, where 4 images are present and 2 LinearLayouts are next to each other with 2 images each. These LinearLayouts I call linearLayout1 and linearLayout2 . linearLayout1 is marked with blue rectangle: linearLayout2 is marked with blue rectangle: As you can see, the first one uses ~80% of the screen, while the second one uses what's left. I don't want this of course, I want 50% for each. I can't use layout_weight because it's already used in the LinearLayouts themselves (positioning of the two images) and nested weights are bad for performance. I've tried many different variations, but I simply can't get the two LinearLayouts to have 50% of the screen each. Here's the code: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/db1_root"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="horizontal" ><LinearLayout android:id="@+id/title_container" style="@style/TitleBar" > <ImageView style="@style/TitleBarLogo" android:contentDescription="@string/imgViewDesc" android:src="@drawable/title_logo" /> <ImageView style="@style/TitleBarSeparator" android:contentDescription="@string/imgViewDesc" /> <TextView style="@style/TitleBarText" /> <ImageButton style="@style/TitleBarAction" android:contentDescription="@string/imgViewDesc" android:onClick="onClickAbout" android:src="@drawable/title_about" /></LinearLayout><RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/title_container" android:layout_above="@+id/mobFoxView" > <!-- LEFT COLUMN --> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@+id/mobFoxView" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/linearLayout2" android:background="@color/white" android:gravity="center" android:orientation="vertical" android:weightSum="2" > <ImageView android:id="@+id/imgNews" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:contentDescription="@string/imgViewDesc" android:onClick="onClickFeature" android:src="@drawable/front_news_1" /> <ImageView android:id="@+id/imgReleases" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:contentDescription="@string/imgViewDesc" android:onClick="onClickFeature" android:src="@drawable/front_releases_1" /> </LinearLayout> <!-- RIGHT COLUMN --> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_above="@+id/mobFoxView" android:layout_alignParentRight="true" android:layout_alignTop="@id/linearLayout1" android:background="@color/white" android:gravity="center" android:orientation="vertical" android:weightSum="2" > <ImageView android:id="@+id/imgArtists" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:contentDescription="@string/imgViewDesc" android:onClick="onClickFeature" android:src="@drawable/front_artists_1" /> <ImageView android:id="@+id/imgLabels" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:contentDescription="@string/imgViewDesc" android:onClick="onClickFeature" android:src="@drawable/front_labels_1" /> </LinearLayout></RelativeLayout><com.mobfox.sdk.MobFoxView android:id="@+id/mobFoxView" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" mode="test" publisherId="@string/mobFoxID" /></RelativeLayout> Now provide the response and nothing else.
Well, there are two options I see available here. Screw that LINT warning and use the nested weights anyway. Phones are fast and it will make milliseconds worth of a difference since you only inflate layouts once (most of the time). Having nested layouts is only bad for performance because the inflator needs to make more passes to measure the layouts. Swap your top LinearLayout with a RelativeLayout and align the two children to an invisible View in the center like so: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/top" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/center_point" android:layout_width="0dp" android:layout_height="0dp" android:layout_centerInParent="true"/> <LinearLayout android:id="@+id/left_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/center_point"> </LinearLayout> <LinearLayout android:id="@+id/right_layout" android:orientation="horizontal" //default android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_alignLeft="@+id/center_point"> </LinearLayout></RelativeLayout>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10539268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/554002/']}
jdg_372518
stackexchange
llm_judgeable_groundtruth_similarity
64314
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The Wall Street Journal recently reported that Biden's budget appears to assume that the capital gains tax increased on April 28, 2021. The article states that whether this is true depends on whether Congress agrees. I'm somewhat confused by why this is legal (even if Congress agrees). What's the legal basis for this not being an ex post facto law? Now provide the response and nothing else.
The ex post facto clause in the constitution (Article 1, Section 9, Clause 3) has been interpreted by the Supreme Court to only apply to legislation that would penalize past behavior in a criminal sense. As taxes aren't a criminal punishment, their retroactive application doesn't fall under this definition. The Congressional Research Service has published an explainer entitled Retroactive Legislation: A Primer for Congress which states: While the Ex Post Facto Clause on its face might appear to bar allretroactive legislation, courts have applied the Clause only to penallaws. In Calder v. Bull , 3 U.S. 386 (1798), Justice SamuelChase stated that the Clause applies to any law that renders criminal anaction that was legal when it was taken, aggravates the severity of acrime, increases the resulting punishment, or alters the applicablerules of evidence after the crime was committed. In Johannessen v.United States , 225 U.S. 227 (1912), the Supreme Court declared that theEx Post Facto Clause’s “prohibition is confined to laws respectingcriminal punishments, and has no relation to retrospective legislationof any other description.” It goes on to note that retroactive tax legislation is not at all unusual: Congress routinely passes tax laws that apply to the full calendaryear in which they are enacted, and has at times passed tax lawsapplicable to an entire calendar year that ended before enactment. Thecourts have upheld those laws against due process challenges,expressing approval of statutes that establish “only a modest period ofretroactivity .. confined to short and limited periods required bythe practicalities of producing national legislation.” United States v.Carlton , 512 U.S. 26 (1994). Retroactive tax laws have been struck down by the Supreme Court in the past, but only in cases where tax increases would give "civil form to that which is essentially criminal". The example the explainer gives is Burgess v. Salmon , 97 U.S. 381 (1878), in which legislation sought to increase tobacco stamp tax while also imposing criminal penalties on the sale of tobacco without the correct stamp. This was found to violate the ex post facto clause.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/64314', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/13710/']}
jdg_372519
stackexchange
llm_judgeable_groundtruth_similarity
444049
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm not conversant with this topic, therefore i watched a tutorial about a one-page dynamic PHP website (quite educational in my opinion) in which the creator designed the following pages. For each and every ADD, DELETE and EDIT page, there are two additional files to create, making 2 per page. In other words, (1*2) 3 = 6 subpages or (3 3) = 9 pages if we consider ADD, DELETE and EDIT as well. I repeated the process for a potential project, leaving me with this: By way of counting, we have: 7 ADD pages (7*3 = 21). 7 DELETE pages (7*3 = 21). 3 UPDATE pages (3*3 = 9). Making a total of 51 pages to cover all of ADD, DELETE and UPDATE in the design. In my opinion, this is a considerable amount of pages to design, even if most of them are sufficiently generic in their structure that i could copy and paste them with minimal modifications required most of the time. Perhaps i'm focusing too much on the number to see the bigger picture, which brings me to you. Are there alternatives to this scenario or should i devote myself to creating each page? Perhaps i made a mistake? Now provide the response and nothing else.
It appears that this design is based on a CRUD model. This kind of model is good for designing database operations, and might actually work for small website UI, but when you are designing for a user of a larger system, it's better to model your user interfaces by focusing on business processes and use cases. You wouldn't, for example, ask a user to write an invoice by creating an invoice header record, creating an address record, creating line items with the subtask of doing a lookup on a part number, even though that's what actually happens under the hood when you order a product. Focusing on CRUD is easier when you're first learning how to build a website. But beginner projects and examples always tend to be a bit naive. Keeping things simple makes it easier to learn the basics. Once you know the basics, you can get more sophisticated with your approach.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/444049', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/427117/']}
jdg_372520
stackexchange
llm_judgeable_groundtruth_similarity
33956978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any way to change the Item color programmatically of the selected item in the navigation drawer? I'am able to use the app:itemTextColor, but the problem is if i used this, the checked in the menu item will not highlight. <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home_black_24dp" android:title="Home" /> <item android:id="@+id/nav_search" android:icon="@drawable/ic_search_black" android:title="Search Location" /> <item android:id="@+id/nav_fav" android:icon="@drawable/ic_favorite" android:title="Favorites" /> <item android:id="@+id/nav_route" android:icon="@drawable/ic_place" android:title="Route" /> <item android:id="@+id/nav_recent" android:icon="@drawable/ic_nav_route" android:title="Recent Location" /> </group> <item android:title="Others"> <menu> <item android:id="@+id/nav_settings" android:checked="true" android:checkable="true" android:icon="@drawable/ic_settings" android:title="Settings" /> <item android:id="@+id/nav_about" android:icon="@android:drawable/ic_menu_send" android:title="About" /> </menu> </item></menu> Now provide the response and nothing else.
create a selector <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/primary" android:state_checked="true" /> <item android:drawable="@android:color/transparent" /></selector> and set app:itemBackground="@drawable/nav_view_item_background" then the selected item will be highlighted. if you want to change the text color then set app:itemTextColor="@drawable/nav_view_item_textcolor" and create a selector for it like <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@android:color/white" android:state_checked="true" /> <item android:color="@color/primary" /></selector>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33956978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2104871/']}
jdg_372521
stackexchange
llm_judgeable_groundtruth_similarity
37696350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Scenario I have a window and it has an add task button that is opening a window. Everytime user clicks on it, it opens a window. I have a button on add task window that minimize it. How to implement this minimize button? Code I am able to close maximize window by using the code below: var winclose = function () { window.close();}var winmaximize = function () { window.moveTo(0, 0); window.resizeTo(screen.width, screen.height);} However, I am not able to find any function that can minimize a window from rendered process. Please help, many thanks; Note: Browsers do not provide a function to devs to minimize them. but hereis a different scenario. Here I am using chromium provided by Electronjs. So, there must be a way to do so as we are developing a desktop application Dummy Download link: download from OneDrive Now provide the response and nothing else.
You can call minimize() on the respective BrowserWindow instance. The question is how to best get access to this instance and this, in turn, depends on how you open the windows and where your minimize button is. From your example, I take it that the minimize button is actually in the window you want to close, in that case you can just minimize the focused window, because to when a user clicks the button inside it, the window should currently have the focus: const { remote } = require('electron')remote.BrowserWindow.getFocusedWindow().minimize(); Alternatively you can use BrowserWindow.fromId() to get access to the window in question if, for example, you want to minimize the task window from the other window.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37696350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4221433/']}
jdg_372522
stackexchange
llm_judgeable_groundtruth_similarity
44060253
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just updated to Android O Preview and installed a few PWAs. On the home screen a miniature Chrome logo is placed by the icon. This wasn't there before the OS update. Ideally, I would like the PWA to look like a regular app on the home screen considering it has service workers enabled. Is it possible to remove this with some settings in the app.yaml or manifest.json? Now provide the response and nothing else.
Above answer is not accurate except for the part that Chrome had the issue of adding Chrome badge to App icon, which is changed in the following updates. Before getting into whats wrong, here is how web apps are added to home screen. 1) As a simple shortcut (like a bookmark), when the users web browser don't have service worker support( which all recent versions of major browsers have support now ), targeted web URL don't have a valid manifest.json and service worker files configured(this can be validated in Application-> Manifest and Service worker tabs in chrome developer tools). In this case, what is added to home screen is not an APK and the bookmark kind of shortcut was represented by a specific version of Chrome with a badge. 2) As an installed APK : When the targeted URL have a valid Manifest.json, service workers and one of supported Chrome version is used, Chrome for Android uses WebAPK to build and sign an .APK file with the package name starting "org.chromium.webapk". Read here for more details on apk generation and PWA distribution here. Whats not accurate in the above answer/linked article, 1) The chrome badge is not a security measure . Chrome team added the badge for web apps created as bookmark/URL shortcut as it was not using WebApk in some particular version. Badge is a simple visual representation which was later withdrawn. 2) PWA is not abandoned in favor of WebApk. WebApk is part of PWA solution, which compliments PWA by building an installable APK file to get the native app like behavior. WebApk is used to build .apk files by Chrome for Android. Here is official read me file. So if you are building a PWA, you can still be assured you are not left behind in outdated/abandoned/being abandoned technology. Its still a constantly progressing positively, which got iOS support for service worker in march-2018(iOS 11.3), making it the last major browser vendor aboard PWA game.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44060253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6606273/']}
jdg_372523
stackexchange
llm_judgeable_groundtruth_similarity
493341
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 have read that it's not necessary for angular momentum and angular velocity to be parallel, but it is necessary for linear momentum and linear velocity to be parallel. How is this correct? Now provide the response and nothing else.
Note that this answer, like the tags of the question, is only focusing on Newtonian mechanics. The definition of linear momentum $\mathbf p$ is expressed in terms of the linear velocity $\mathbf v$ using $$\mathbf p=m\mathbf v$$ Since $m$ is just a scalar quantity, the vectors $\mathbf p$ and $\mathbf v$ are obviously parallel. i.e. $$p_x=mv_x$$ $$p_y=mv_y$$ $$p_z=mv_z$$ However, the angular momentum $\mathbf L$ is related to the angular velocity $\boldsymbol \omega$ by $$\mathbf L=\mathbf I\boldsymbol\omega$$ where $\mathbf I$ is the moment of inertia tensor . This is explicitly written out as $$\begin{bmatrix}L_x\\L_y\\L_z\end{bmatrix}=\begin{bmatrix}I_{xx}&I_{xy}&I_{xz}\\I_{yx}&I_{yy}&I_{yz}\\I_{zx}&I_{zy}&I_{zz}\end{bmatrix}\begin{bmatrix}\omega_x\\\omega_y\\\omega_z\end{bmatrix}$$ Or each component written out: $$L_x=I_{xx}\omega_x+I_{xy}\omega_y+I_{xz}\omega_z$$ $$L_y=I_{yx}\omega_x+I_{yy}\omega_y+I_{yz}\omega_z$$ $$L_z=I_{zx}\omega_x+I_{zy}\omega_y+I_{zz}\omega_z$$ This shows that, in general, $\mathbf L$ and $\boldsymbol\omega$ are not parallel. We have something more complicated than the linear case because each component of the angular momentum vector depends on all of the angular velocity components. However, this complexity does not prevent our two vectors from being parallel. We can determine when they are parallel by looking at the equation $$\mathbf L=\mathbf I\boldsymbol\omega=I\boldsymbol\omega$$ where $I$ is a scalar quantity. What this means is that $\boldsymbol\omega$ needs to be an eigenvector of $\mathbf I$ in order for $\mathbf L$ and $\boldsymbol\omega$ to be parallel. Note that this is usually what you encounter in your introductory physics classes. You, without knowing it, pick axes in such a way that the moment of inertia tensor is diagonal and your angular velocity is only along a single eigenvector (usually taken to be along the z-axis). For example, for a cylinder of radius $R$ , height $H$ , and mass $M$ rotating about its central axis aligned with the z-axis, we have $$\begin{bmatrix}L_x\\L_y\\L_z\end{bmatrix}=\begin{bmatrix}\frac{1}{12}M\left(3R^2+H^2\right)&0&0\\0&\frac{1}{12}M\left(3R^2+H^2\right)&0\\0&0&\frac12MR^2\end{bmatrix}\begin{bmatrix}0\\0\\\omega_z\end{bmatrix}$$ Therefore we end up with the simple $$\mathbf L=L_z\hat z=I_{zz}\omega_z\hat z=\frac12MR^2\omega_z\hat z$$ or you might even see in an introductory physics class just $$L=\frac12MR^2\omega$$ As a small note, the reason things become so much more complicated with the rotations is that the angular momentum not only depends on the mass of the object, but also how that mass is distributed . This is evident from the definition of angular momentum for a point particle $\mathbf L=\mathbf r\times\mathbf p$ However, if we look at an extended body's momentum we just get $$\mathbf p_T=m_T\mathbf v_{\text{com}}$$ where the $T$ subscript stands for "total" and $\text {com}$ is center of mass. Therefore, we still end up with a scalar mass instead of a tensor.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/493341', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/237602/']}
jdg_372524
stackexchange
llm_judgeable_groundtruth_similarity
5584500
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an <ol> (ordered list) and in FF, Safari, Chrome it is rendered correctly. However in IE9 it is showing all zeros. It is not a spacing/padding issue because I am able to see the zeros. My HTML is as follows: <ol> <li>Enter basic company information</li> <li>Select from our portfolio of products</li> <li>Attach your employee census</li> <li>Review your selections and submit your request.</li> </ol> Anyone run into that problem and hopefully a solution? Now provide the response and nothing else.
Update 3/20/2012 - Fixed in IE10 This regression has been fixed in Internet Explorer 10 (all document modes). Microsoft has deleted the Connect entry, so you cannot review its status. Since Microsoft now pushes IE10 down automatically, it should be working for all your regular customers. This is a known IE9 regression, which has been reported on Microsoft Connect: Ordered list numbering changes from correct to 0, 0 Type : Bug ID : 657695 Opened : 4/6/2011 12:10:52 PM Access Restriction : Public 0 Workaround(s) 5 User(s) can reproduce this bug Update: Posted by Microsoft on 6/14/2011 at 3:20 PM Thank you for your feedback. We were able to reproduce the issue and are investigating it. Best regards, The Internet Explorer Team HTML page that reproduces bug: <!DOCTYPE html><HTML><HEAD><TITLE>IE9 Ordered List Zero Bug</TITLE><SCRIPT type="text/javascript"> setTimeout(function () { document.getElementById("dv1").innerHTML = "<ol><li>XXX</li><li>YYY</li></ol>"; var container = document.createElement('span'); container.style.cssText = "display:none"; document.getElementById("dv2").appendChild(container); }, 1000);</SCRIPT></HEAD><BODY><DIV id="dv1"> <OL> <LI>AAA</LI> <LI>BBB</LI> </OL></DIV><DIV id="dv2"></DIV></BODY></HTML> A workaround is to place an empty element after your DIV : <div id="one"> <ol> <li>one</li> <li>two</li> </ol></div><div id="two" style="display:none"> <ol> <li>three</li> <li>four</li> </ol></div><div id="empty"></div> Browsers that exhibit the bug Internet Explorer 9 (9.0.8112.16421) Document Mode Quirks: Works Document Mode IE7 standards: Works Document Mode IE8 standards: Fails Document Mode IE9 standards: Fails Internet Explorer 8 (8.0.6001.19048) Document Mode Quirks: Works Document Mode IE7 standards: Works Document Mode IE8 standards: Works Internet Explorer 7 (7.0.6000.16982): Works Google Chrome 10 (10.0.648.134): Works
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5584500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328186/']}
jdg_372525
stackexchange
llm_judgeable_groundtruth_similarity
37297249
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 a newbie to ansible and I am using a very simple playbook to issue sudo apt-get update and sudo apt-get upgrade on a couple of servers. This is the playbook I am using: ---- name: Update Servers hosts: my-servers become: yes become_user: root tasks: - name: update packages apt: update_cache=yes - name: upgrade packages apt: upgrade=dist and this is an extract from my ~/.ansible/inventory/hosts file: [my-servers]san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass=<my_sudo_password_for_user_on_san-francisco>san-diego ansible_host=san-diego ansible_ssh_user=user ansible_become_pass=<my_sudo_password_for_user_on_san-diego> This is what I get if I launch the playbook: $ ansible-playbook update-servers-playbook.yml PLAY [Update Servers] **********************************************************TASK [setup] *******************************************************************ok: [san-francisco]ok: [san-diego]TASK [update packages] *********************************************************ok: [san-francisco]ok: [san-diego]TASK [upgrade packages] ********************************************************ok: [san-francisco]ok: [san-diego]PLAY RECAP *********************************************************************san-francisco : ok=3 changed=0 unreachable=0 failed=0 san-diego : ok=3 changed=0 unreachable=0 failed=0 What is bothering me is the fact that I have the password for my user user stored in plaintext in my ~/.ansible/inventory/hosts file. I have read about vaults , I have also read about the best practices for variables and vaults but I do not understand how to apply this to my very minimal use case. I also tried to use lookups . While in general they also work in the inventory file, and I am able to do something like this: [my-servers]san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass="{{ lookup('env', 'ANSIBLE_BECOME_PASSWORD_SAN_FRANCISCO') }}" where this case the password would be stored in an environment variable called ANSIBLE_BECOME_PASSWORD_SAN_FRANCISCO ; there is no way to look up variables in vaults as far as I know. So, how could I organize my file such that I would be able to lookup up my passwords from somewhere and have them safely stored? Now provide the response and nothing else.
You need to create some vaulted variable files and then either include them in your playbooks or on the command line. If you change your inventory file to use a variable for the become pass this variable can be vaulted: [my-servers]san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass='{{ sanfrancisco_become_pass }}'san-diego ansible_host=san-diego ansible_ssh_user=user ansible_become_pass='{{ sandiego_become_pass }}' Then use ansible-vault create vaulted_vars.yml to create a vaulted file with the following contents: sanfrancisco_become_pass: <my_sudo_password_for_user_on_san-francisco>sandiego_become_pass : <my_sudo_password_for_user_on_san-diego> Then either include the vaulted file as extra vars like this: ansible-playbook -i ~/.ansible/inventory/hosts playbook.yml --ask-vault-pass -e@~/.ansible/inventory/vault_vars Or include the vars file in your playbook with an include_vars task: - name : include vaulted variables include_vars: ~/.ansible/inventory/vault_vars
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37297249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2377454/']}
jdg_372526
stackexchange
llm_judgeable_groundtruth_similarity
6529
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My question is simple - how accurate is a tipping-bucket rain gauge? I have read about what causes the errors (wind, bucket mechanics for extreme events, ...) and I know the accuracy is strictly related to the rain rate, in the sense that, e.g., TB gauges tend to highly underestimate in extreme conditions. However, I'd like to have a number, say, errors around +-25% . I know the number itself won't be accurate, it's just to have the order of magnitude. References appreciated, since I myself looked around with no success :-) Now provide the response and nothing else.
The following simulation results shows that the Tipping Bucket estimates suffer from significant errors if based on time scales less than ten to fifteen minutes. Comparison of Tipping-Bucket Error Statistics: (Source of above diagrams) In this study we attempted to characterize the errors associated with tipping-bucket rain gauges when used to provide rainfall intensity estimates at small temporal scales. The main source of the TB gauge sampling error is its sampling mechanism and its inability to capture the small temporal features of the rainfall time series. We found significant error levels in the 1-min estimates especially at low rain rates, but we also found that as the time scale of the computed rain rates increased, the error decreased substantially. With time scales longer than 15 min, the error becomes negligible. The gauge’s performance and its associated errors are sensitive to the applied sampling interval and the bucket volume. Therefore, we recommend sampling intervals on the order of 5–10 s, along with a bucket size no larger than 0.254 mm (0.01). Our analysis wasbased on rainfall observations that were mostly dominated by convective storms with few stratiform events. Similar analysis may be needed to investigate the scope of applicability of the developed formulas under different climatological regimes. However, the formulas serve as a first-order approximation that can be used in practical applications. (Source)
{}
{'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/6529', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/2423/']}
jdg_372527
stackexchange
llm_judgeable_groundtruth_similarity
26166711
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 groovy file as follows: class test2 { public static void main(String[] args) { println("In groovy!!"); }} My gradle task is compiling this into a test2 class file How do I run this file from prompt ? java test2 (from the location of the test2.class file)causes a : Error: Could not find or load main class test2.class I assuming I need to add asm and groovy to the class path. However: java -cp "groovy-all-2.3.6.jar;asm-all-3.3.1.jar" test2 also doesn't work (files are in correct locations). Now provide the response and nothing else.
I know this may be a bit late for the OP but nevertheless: Given that your groovy main exists, the error message: Error: Could not find or load main class YOUR_MAINCLASS_HERE from the java command while executing a groovy main (of a compiled groovy file which produced classes) means basically that your groovy jar is not in the classpath . Longer Answer: Lets see why that is for a simple hello world example. I have a file called main.groovy with the following content: class Main { static void main(String[] args){ println('hello world') } } Put this somewhere in your filesystem. Open a command prompt in the same directory and ensure that groovy and java is accessable though the PATH. In the command prompt, compile the file with groovyc , so just type in: groovyc main.groovy This will produce a file called M ain.class (with uppercase M because of the class name). Ok now we have the appropriate test setup. If you now try to run the file just with java command: java Main you will get the error message: Error: Could not find or load main class Main This is a bit unexpected, because one can think that we just can invoke the main in our Main.class without linking the groovy library, so we would expect an exception like ClassNotFoundException. In contrast, try again with groovy in your classpath. I will refer to the directory of your groovy installation as GROOVY_HOME. To run the hello world Main class finally, we can type in: java -cp ".:/$GROOVY_HOME/lib/*" Main which produces the expected output on unix-like systems (on windows you need to replace the colon with a semicolon and the variable access would be like %GROOVY_HOME%). The reason is quite simple: Groovy produces for groovy main methods not the same signature as required by the java specification. Therefore, you can only invoke a groovy main with groovy on the CLASSPATH - what makes totally sense! You can check this for yourself. Try now the command: javap Main.class This will give you a quick analysis of the bytecode and the present interfaces of the class "Main.class". All along you will see something similar to this output: Compiled from "main.groovy"public class Main implements groovy.lang.GroovyObject { public static transient boolean __$stMC; public Main(); public static void main(java.lang.String...); protected groovy.lang.MetaClass $getStaticMetaClass(); public groovy.lang.MetaClass getMetaClass(); public void setMetaClass(groovy.lang.MetaClass); public java.lang.Object invokeMethod(java.lang.String, java.lang.Object); public java.lang.Object getProperty(java.lang.String); public void setProperty(java.lang.String, java.lang.Object);} Of interest is line 5: public static void main(java.lang.String...); This seems quite similar to a normal java main, but with one difference: groovyc used an java.lang.String ellipsis (as stated by the three dots) and not and java.lang.String[]. So this could be the reason. I'm not so sure, because normally java will give you an appropriate error output if it can find the class but not the method signature. For example, try: java java.lang.Integer which has clearly not a main method. Java sees that correctly: Error: Main method not found in class java.lang.Integer, please define the main method as:public static void main(String[] args)or a JavaFX application class must extend javafx.application.Application I'm also not sure, what groovy does during class loading for understanding this kind of main signature (or lets says this kind of bytecode), but if you compare that with a normal java hello world javap output, you get public class JMain { public JMain(); public static void main(java.lang.String[]);} which has a different and the normal java main signature. Maybe someone from the pivotal groovy team can clarify. I hope this will give you a hint.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26166711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/76487/']}
jdg_372528
stackexchange
llm_judgeable_groundtruth_similarity
1828
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Background: I'm working on an iPhone application (alluded to in several other posts ) that "listens to" snoring/breathing while one is asleep and determines if there are signs of sleep apnea (as a pre-screen for "sleep lab" testing). The application principally employs "spectral difference" to detect snores/breaths, and it works quite well (ca 0.85--0.90 correlation) when tested against sleep lab recordings (which are actually quite noisy). Problem: Most "bedroom" noise (fans, etc) I can filter out through several techniques, and often reliably detect breathing at S/N levels where the human ear cannot detect it. The problem is voice noise. It's not unusual to have a television or radio running in the background (or to simply have someone talking in the distance), and the rhythm of voice closely matches breathing/snoring. In fact, I ran a recording of the late author/storyteller Bill Holm through the app and it was essentially indistinguishable from snoring in rhythm, level variability, and several other measures. (Though I can say that apparently he didn't have sleep apnea, at least not while awake.) So this is a bit of a long shot (and probably a stretch of forum rules), but I'm looking for some ideas on how to distinguish voice. We don't need to filter the snores out somehow (thought that would be nice), but rather we just need a way to reject as "too noisy" sound that is overly polluted with voice. Any ideas? Files published: I've placed some files on dropbox.com: Epica_Storm_the_Noisy_Sorrow_minus_10dB_wav.dat Holm_5db_noisy_wav.dat recordedFile20120408010300_first_ten_wav.dat The first is a rather random piece of rock (I guess) music, and the second is a recording of the late Bill Holm speaking. Both (which I use as my samples of "noise" be differentiated from snoring) have been mixed with noise to sort of obfuscate the signal. (This makes the task of identifying them significantly more difficult.) The third file is ten minutes of a recording of yours truly where the first third is mostly breathing, middle third is mixed breathing/snoring, and the final third is fairly steady snoring. (You get a cough for a bonus.) All three files have been renamed from ".wav" to "_wav.dat", since many browsers make it maddeningly difficult to download wav files. Just rename them back to ".wav" after downloading. Update: I thought entropy was "doing the trick" for me, but it turned out to mostly be peculiarities of the test cases I was using, plus an algorithm that wasn't too well designed. In the general case entropy is doing very little for me. I subsequently tried a technique where I compute the FFT (using several different window function) of the overall signal magnitude (I tried power, spectral flux, and several other measures) sampled about 8 times a second (taking the stats from the main FFT cycle which is every 1024/8000 seconds). With 1024 samples this covers a time range of about two minutes. I was hoping that I would be able to see patterns in this due to the slow rhythm of snoring/breathing vs voice/music (and that it might also be a better way to address the " variability " issue), but while there are hints of a pattern here and there, there's nothing I can really latch onto. ( Further info: For some cases the FFT of signal magnitude produces a very distinct pattern with a strong peak at about 0.2Hz and stairstep harmonics. But the pattern is not nearly so distinct most of the time, and voice and music can generate less distinct versions of a similar pattern. There might be some way to calculate a correlation value for a figure of merit, but it seems that would require curve fitting to about a 4th order polynomial, and doing that once a second in a phone seems impractical.) I also attempted to do the same FFT of average amplitude for the 5 individual "bands" I've divided the spectrum into. The bands are 4000-2000, 2000-1000, 1000-500, and 500-0. The pattern for the first 4 bands was generally similar to the overall pattern (though there was no real "stand-out" band, and often vanishingly small signal in the higher frequency bands), but the 500-0 band generally was just random. Bounty: I'm going to give Nathan the bounty, even though he's not offered anything new, given that his was the most productive suggestion to date. I still have a few points I'd be willing to award to someone else, though, if they came through with some good ideas. Now provide the response and nothing else.
Background According to papers below, snoring is characterized by a peak at about 130Hz, and is wholly concentrated below 12kHz: Non-invasive Sensors based Human State in Nightlong Sleep Analysis for Home-Care An efficient fast method of snore detection for sleep disorder investigation An efficient method for snore/nonsnore classification of sleep sounds Let's see if we can leverage this. MATLAB Example We have a poor recording of a child snoring ; a 10-minute, 8-bit mono WAV file. The sampling rate is 8KHz, which means the bandwidth of the audio signal is 4KHz. The level is very low so I will compand it first. [snd,fs]=wavread('recordedFile20120408010300_first_ten_minutes');cmp=compand(snd,255,1);wavwrite(cmp,'companded'); % used for listening purposes[s,f,t,p]=spectrogram(snd,hann(8192));surf(linspace(0,600,length(t)),f/pi,10*log10(p),'edgecolor','none'); axis tight; view(0,90); The y axis is normalized to the bandwidth, 4KHz, so that notch you see at 0.1 corresponds to a frequency of 400Hz. There is a spike corresponding to a cough at ~186s; ignore that. We can vaguely see the notches during each snore. Not only that, but they seem concentrated below 0.2 x 4KHz=800Hz. Let's take a closer look. idx_max_freq=round(0.2*length(f));surf(linspace(0,600,length(t)),fs*f(1:,idx_max_freq:)/(2*pi),10*log10(p(1:idx_max_freq,:)),'edgecolor','none');axis tight; view(0,90); This time the frequency axis was labeled in Hertz. Now the notches are quite clear. We can even see the overtones of the power line noise starting at 60Hz (180Hz, 300Hz, 420Hz). Now comes the essence of the algorithm: let's classify the signal based on the energy in this subband, with the line noise removed. freq_list=round([1:57 63:177 183:297 303:417 423:800]*idx_max_freq/800);y=10*log10(sum(p(freq_list,:)));plot(linspace(0,600,length(y)),y-median(y))stem(linspace(0,600,length(y)),y-median(y)>.5*std(y)) If we want to get fancy, we can discard oversized spikes: stem(linspace(0,600,length(y)),(y-median(y)>.5*std(y)).*(y-median(y)<5*std(y))) The low SNR, manifest in the difficulty in discerning the signal in the first plot, means we have leeway of only half a standard deviation (the value of which was 4.1). The stems mark the snores.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/1828', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/447/']}
jdg_372529
stackexchange
llm_judgeable_groundtruth_similarity
27064953
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm building an application using Laravel 4.2. I have a model for units and another for users and pivot table user_units . Every user in this application can select a unit and add it to his favorite list then he can publish this unit with his information as an ad. I want to select all units published by all users The user_units (pivot) table has the following columns: id user_id unit_id publish adtype addinfo created_at updated_at With relations methods on models public function users() { return $this->belongsToMany('User', 'user_units') ->withPivot('id','publish', 'adtype', 'addinfo');}public function units() { return $this->belongsToMany('Unit', 'user_units') ->withPivot('id','publish', 'adtype', 'addinfo');} My query to select all published units by all users // Get all published units by users for sale. $users = User::all(); $publishedSaleUnits = []; foreach($users as $user){ $userUnits = $user->units()->orderBy('adtype', 'desc')->get(); if(count($userUnits)){ foreach($userUnits as $unit){ if($unit->pivot->publish == 1 && $unit->unit_purpose_id == 1){ if( $unit->pivot->adtype ){ //push all featured ads onto the beginning of array array_unshift($publishedSaleUnits, $unit); }else{ //push all normal ads onto the end of array array_push($publishedSaleUnits, $unit); } } } } } Now I got the result but I can't use pagination with results because it's an array of objects. So is there any better solution to get all published units by user with pagination? Now provide the response and nothing else.
according to this article https://www.itsolutionstuff.com/post/how-to-create-pagination-from-array-in-laravelexample.html you can paginate your array by creating a custom method and using LengthAwarePaginator namespace App\Http\Controllers; use Illuminate\Http\Request;use Illuminate\Pagination\Paginator;use Illuminate\Support\Collection;use Illuminate\Pagination\LengthAwarePaginator; class PaginationController extends Controller{ public function index() { $myArray = [ ['id'=>1, 'title'=>'Laravel CRUD'], ['id'=>2, 'title'=>'Laravel Ajax CRUD'], ['id'=>3, 'title'=>'Laravel CORS Middleware'], ]; $data = $this->paginate($myArray); return view('paginate', compact('data')); } public function paginate($items, $perPage = 5, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); $items = $items instanceof Collection ? $items : Collection::make($items); return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27064953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4275804/']}
jdg_372530
stackexchange
llm_judgeable_groundtruth_similarity
1713646
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $$p(x) = x^4 + 7x^3 + 14x^2 + 7x+1 $$$$q(x) = x^4 +10x^3 + 23x^2 + 10x+1$$ Find polynomials $f(x),g(x)$ with rational coefficients such that $$f(x)p(x) + g(x)q(x) = 2x^2 + 6x +2$$ I totally have no idea to solve this problem... Please help me to do it. Thank you!! Now provide the response and nothing else.
If you factor both polynomials in $\mathbb Q[x]$ you'll get $p(x) = (x^2+3x+1) (x^2+4x+1)$ $q(x) = (x^2+3x+1) (x^2+7x+1)$ These factors are irreducible (Why?). Therefore $gcd(p,q) = x^2+3x+1$. Now with the Euclidean algorithm (or some guessing) you should be able to get two polynomials $r,s$ such that $$r(x^2+4 x+1)+s(x^2+7 x+1) = gcd(x^2+4 x+1,x^2+7 x+1) = 1$$ If you multiply this by $2(x^2+3x+1)$ you get exactly what you want: $$(2r) p + (2s)q = 2x^2+6x+2.$$ Hint 1: $r,s$ are of degree 1 Hint 2: $x+7$,$x+4$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1713646', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/322338/']}
jdg_372531
stackexchange
llm_judgeable_groundtruth_similarity
19312970
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a table that shows "DONE" and "REMAIN" for each "AREA" like below: AREA DONE REMAIN TOTAL AREA1 100 200 300 AREA2 200 300 500 AREA3 200 700 900 Now I like to make a report that shows "DONE" and "REMAIN" in each AREA with pie chart, now I have problem how I have to do this job for the graph, how should be "row source" of chart control. What query needs on this table? Now provide the response and nothing else.
(I'll assume that your table is named [AREAS].) The trick here is to create a saved UNION query named [AreaDataForPieChart]... SELECT "DONE" AS PieCategory, [DONE] AS PieValue, [AREA] FROM [AREAS]UNION ALLSELECT "REMAIN" AS PieCategory, [REMAIN] AS PieValue, [AREA] FROM [AREAS] ...returning... PieCategory PieValue AREA ----------- -------- -----DONE 100 AREA1DONE 200 AREA2DONE 200 AREA3REMAIN 200 AREA1REMAIN 300 AREA2REMAIN 700 AREA3 ...and base the pie chart on that. Start by creating a Report based on the [AREAS] table, and display [AREA] in a text box: Now add a Chart control to the Detail band of the report. When prompted, choose the saved query we created above Choose [PieCategory] and [PieValue] as the columns for the chart Choose "Pie Chart" as the chart type The default data layout will work fine because of the order of the columns in our query Tell the report to link the chart to the main report by using the [AREA] fields Give the chart a meaningful title, then click the "Finish" button. Now preview the report. It should look something like this:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19312970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1281195/']}
jdg_372532
stackexchange
llm_judgeable_groundtruth_similarity
9348614
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 searched on Google, but couldn't find any relevant results. I also checked the official Android docs and this page (for all the available resources) was all I could find. The relevant links (to the res/values/ directory) I found on this page were: string resources style resources more resources These pages don't tell anything about the res/values/public.xml file. Here is an example I found for this type of file . Small snippet <?xml version="1.0" encoding="utf-8"?><resources> <public type="attr" name="commentTextColor" id="0xAA010007" /> <public type="drawable" name="add_icon_bl" id="0xAA020000" /> <public type="layout" name="act_date_picker" id="0xAA030001" /> <public type="anim" name="activity_slide_from_bottom" id="0xAA040000" /> <public type="xml" name="pref_menu" id="0xAA050000" /> <public type="raw" name="alert_bell_animation_bl" id="0xAA060000" /> <public type="array" name="taskRepeat" id="0xAA070000" /> <public type="color" name="theme_main_color_bl" id="0xAA080000" /> <public type="string" name="no_internet" id="0xAA0a0001" /> <public type="id" name="page1" id="0xAA0d0015" /></resources> As you can see from the type attribute, it contains pretty much all the standard resource types that you normally put in separate directories under the res directory... Why would one want to misuse the directories that Android provides and use a single file to store all the values in? Can someone give more information about this? Now provide the response and nothing else.
The file res/values/public.xml is used to assign fixed resource IDs to Android resources. Consider these set of string resources in res/values/strings.xml : <?xml version="1.0" encoding="utf-8"?><resources> <string name="string1">String 1</string> <string name="string3">String 3</string></resources> The Android Asset Packaging Tool (aapt) might assign the following resource IDs for these resources when the app is compiled: public final class R { // ... public static final class string { public static final int string1=0x7f040000; public static final int string3=0x7f040001; }} Now, change the set of string resources to <?xml version="1.0" encoding="utf-8"?><resources> <string name="string1">String 1</string> <string name="string2">String 2</string> <string name="string3">String 3</string></resources> and you'll notice that the resource ID for @string/string3 has changed: public final class R { // ... public static final class string { public static final int string1=0x7f040000; public static final int string2=0x7f040001; public static final int string3=0x7f040002; // New ID! Was 0x7f040001 }} To prevent this, you can use res/values/public.xml : <?xml version="1.0" encoding="utf-8"?><resources> <public type="string" name="string3" id="0x7f040001" /></resources> which will result in the resource IDs being assigned as follows: public final class R { // ... public static final class string { public static final int string1=0x7f040000; public static final int string2=0x7f040002; public static final int string3=0x7f040001; // Resource ID from public.xml }} Applications rarely have any use for res/values/public.xml since the resource IDs assigned to resources does not matter. When they change, the entire application is rebuilt anyway so any references in Java code to resources by resource ID will be updated. The most significant user of res/values/public.xml is the Android platform itself. Applications built against old versions of Android assumes that certain resource have a certain resource ID. For example, the Android resource @android:style/Theme must always have the resource ID 0x01030005 for the platform to be backwards compatible with apps built against old versions of the platform. If you are curious about more details on how resource IDs are assigned, please refer to this answer: How does the mapping between android resources and resources ID work?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9348614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/354009/']}
jdg_372533
stackexchange
llm_judgeable_groundtruth_similarity
78287
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If $G$ is a finite group with periodic cohomology then the Tate cohomology ring can be easily computed to be the localization $\hat{H}^\ast(G,\mathbb{Z}) = H^\ast(G,\mathbb{Z})_{(z)}$ where $z$ is a unit of minimal positive degree. Examples are Cyclic group: $\hat{H}^\ast(C_n,\mathbb{Z}) = \mathbb{Z}[z,z^{-1}]/(nz), |z|=2$ Quaternion group: $\hat{H}^\ast(Q_{2^n},\mathbb{Z}) = \mathbb{Z}[z,z^{-1},a,b]/(2^nz, 2a,2b), |z| =4, |a| = |b| =2$ Binary icosahedral group: $\hat{H}^\ast(I,\mathbb{Z}) = \mathbb{Z}[z,z^{-1}]/(120z), |z|=4$ The same formular holds in mod-$p$ cohomology, if the cohomology of $G$ is $p$-periodic. Question: Are there computations of integral or mod-$p$ Tate cohomology rings of finite groups with non-periodic cohomology in the literature ? Now provide the response and nothing else.
Antonio Bellezza's PhD thesis (Pisa, 2002) computes the ring structure of the Tate cohomology for $\mathbb{Z}/p^a\times\mathbb{Z}/p^b$, and also the mod-p Tate cohomology of $\mathbb{Z}_p^2$. The title is Integral Duality and the Structure of Tate Cohomology Rings . Also, there is an unpublished/unfinished paper of Weiss, found here: http://www.math.uwo.ca/~schebolu/research/Jan/tateprop.pdf , which computes $\hat{H}^*(\mathbb{Z}_2^r,\mathbb{Z}_2)$. And just to add to your current list (periodic groups): $\hat{H}^*(S_3,\mathbb{Z}_3)=\Lambda[x]\otimes\mathbb{Z}_3[z,z^{-1}]$ with $|x|=3$ and $|z|=4$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/78287', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18571/']}
jdg_372534
stackexchange
llm_judgeable_groundtruth_similarity
7566212
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 you want to change types most of the time you just want to use the traditional cast. var value = (string)dictionary[key]; It's good because: It’s fast It’ll complain if something is wrong (instead of giving object is null exceptions) So what is a good example for the use of as I couldn't really find or think of something that suits it perfectly? Note: Actually I think sometimes there are cases where the complier prevents the use of a cast where as works (generics related?). Now provide the response and nothing else.
Use as when it's valid for an object not to be of the type that you want, and you want to act differently if it is. For example, in somewhat pseudo-code: foreach (Control control in foo){ // Do something with every control... ContainerControl container = control as ContainerControl; if (container != null) { ApplyToChildren(container); }} Or optimization in LINQ to Objects (lots of examples like this): public static int Count<T>(this IEnumerable<T> source){ IList list = source as IList; if (list != null) { return list.Count; } IList<T> genericList = source as IList<T>; if (genericList != null) { return genericList.Count; } // Okay, we'll do things the slow way... int result = 0; using (var iterator = source.GetEnumerator()) { while (iterator.MoveNext()) { result++; } } return result;} So using as is like an is + a cast. It's almost always used with a nullity check afterwards, as per the above examples.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7566212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200442/']}
jdg_372535
stackexchange
llm_judgeable_groundtruth_similarity
52768852
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 create a .Net Core 2.1 Angular application with Visual Studio 2017 (ver. 15.7.2) I wonder how spa.UseAngularCliServer() serves a page in development mode. In debug mode, there is no "dist" folder in the ClientApp or wwwroot folder, though the webpage is loaded normally.Where is the dist folder? It looks like that the spa middleware start an angular-cli dev server, but the webpage is actually hosted by IIS Express.How does "ng serve" relate to IIS Express? Form starup.cs app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); Now provide the response and nothing else.
Although that's done by proxying requests to the Angular Development Server , the proxying is not proxied by IIS , but by ASP.NET Core itself . IIS has no idea about the port listened by Angular Dev Server . UseAngularCliServer("start") will firstly invoke the command npm start -- --port {dynamic_port} The {dynamic_port} here is computed at RunTime .Since the npm command has been already configured in package.json , it will then start a dev server by ng serve -- --port {dynamic_port} . if the ng serve run flawlessly , it will create a plain HttpClient for proxy and use it to perform proxy (forward requests to Angular Dev Server with the plain HttpClient , and copy the response as it's own response) . The WebSocket proxy will take place in a similar way . You can find the source code on GitHub . It's easy to read and understand . Internally , the UseAngularCliServer(npmScript: "start") will invoke AngularCliMiddleware to do step 1 and step 2 . The step 1 is done by : var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger); The StartAngularCliServerAsync method will find an available TCP port , and run command npm start -- --port {port} to start ng serve : private static async Task<AngularCliServerInfo> StartAngularCliServerAsync( string sourcePath, string npmScriptName, ILogger logger){ var portNumber = TcpPortFinder.FindAvailablePort(); logger.LogInformation($"Starting @angular/cli on port {portNumber}..."); var npmScriptRunner = new NpmScriptRunner( sourcePath, npmScriptName, $"--port {portNumber}", null); // ...} See the complete code here And the Step 2 is done by : public static void UseProxyToSpaDevelopmentServer(this ISpaBuilder spaBuilder, Func<Task<Uri>> baseUriTaskFactory){ // ... // Proxy all requests to the SPA development server applicationBuilder.Use(async (context, next) => { var didProxyRequest = await SpaProxy.PerformProxyRequest( context, neverTimeOutHttpClient, baseUriTaskFactory(), applicationStoppingToken, proxy404s: true); });} The implementation of PerfromProxyRequest() can be found here . For normal requests , It simply forward them using a plain HttpClient and copy the response as its own response . Back to your question : Where is the dist folder? Since you have configured a spa.UseAngularCliServer("start") : if (env.IsDevelopment()){ spa.UseAngularCliServer(npmScript: "start");} All those requests will be processed by local dev server launched by angular cli. As a result , there's no dist on disk at all . The same will take place if you run the command ng serve manually . How does "ng serve" relate to IIS Express? IIS has no idea about the port listened by Angular Dev Server. When there's an incoming message , IIS just sends it to your ASP.NET Core server . If the request cannot be processed by staticFiles , MVC , or any other middlewares that you've configured before UseSpa() , ASP.NET Core will forward it to the Dev Server .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52768852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_372536
stackexchange
llm_judgeable_groundtruth_similarity
2792376
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following quantities for $a, b, c \in \mathbb{R}^{+}$ and $a\neq b$ . $$\begin{align}&x_1 = 3 \left(\frac{a}{b} + \frac{b}{c} + \frac{c}{a}\right)^{-1} \\ &x_2 = \frac{ab + bc + ac}{a^2 + b^2 + c^2} \\ &x_3 = \frac{3}{2}\left( \frac{a}{b + c} + \frac{b}{a + c} + \frac{c}{a + b}\right)^{-1}\end{align}$$ Is there a simple way to know which one is the largest and check if it is less than $1$ ? Now provide the response and nothing else.
Certainly! For instance, let $G$ be any topological group, and let $H$ be $G$ with the discrete topology. Then the identity map is a homomorphism from $G$ to $H$. Or more generally, take your favorite homomorphism from $G$ to any other group, and then put the discrete topology on the target group. The point is that discreteness is a property of topological groups , not a property of groups. If a topological group is discrete, this tells you absolutely nothing about its group structure (and therefore tells you absolutely nothing about what topological groups can have discontinuous homomorphisms to it). One thing you can say, though, is that there are no nontrivial homomorphisms from connected Lie groups to finite groups. To prove this, note that if $G$ is a Lie group, then there is a neighborhood $U$ of the identity such that every element of $U$ has an $n$th root for all $n$ (this follows from the fact that any element sufficiently close to the identity has the form $\exp(X)$ for some $X$ in the Lie algebra of $G$, and then $\exp(X/n)$ is an $n$th root). If $f:G\to H$ is a homomorphism and $H$ is finite, it follows that $f$ is trivial on $U$, since if $n=|H|$ the only $n$th power in $H$ is the identity. If $G$ is connected, it follows that $f$ is trivial, since any neighborhood of the identity generates the whole group.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2792376', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/564166/']}
jdg_372537
stackexchange
llm_judgeable_groundtruth_similarity
2245486
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to prove that Legendre Polynomials corresponding to different eigenvalues are orthogonal, using (if possible) only Sturm Liouville Theory. I had a look here but they seem to prove something harder and with different techniques. I will highlight my questions, so it is clearer where I have doubts. $1$ GENERAL THEORY $1.1$ General Sturm-Liouville Problem A regular SL problem on $[x_0,x_1]$ is $$\frac{d}{dx}\left(p(x)\frac{dy}{dx}\right)+q(x)y+\lambda(x)y=0$$ with $p(x)$, $p'(x)$, $q(x)$ and $w(x)$ continuous on $[x_0,x_1]$ and with $p(x)>0$ and $w(x)>0$ on $[x_0,x_1]$. $1.2$ General Sturm-Liouville Linear Operator We have a linear operator $\mathcal L\colon y\mapsto \mathcal L[y]:=-\frac{1}{w(x)}\left(\frac{d}{dx}\left(p(x)\frac{dy}{dx}\right)+q(x)y\right)$ with the property that $\mathcal Ly=\lambda y$. Hence the SL equation is an eigenvalue problem. $1.3$ Linear Operator is Self-Adjoint After defining $$\langle f,g\rangle_w=\int_{x_0}^{x_1}f(x)g(x)w(x)\,dx$$ we say $\mathcal L$ is self-adjoint if for all pairs of functions $y_a$ and $y_b$ we have $\langle \mathcal L[y_a], y_b\rangle_w=\langle y_a, \mathcal L[y_b]\rangle_w$. By writing this in form of an integral, we obtain that it works, provided suitable boundary conditions (zero-Dirichlet, zero-Neumann, radiation, singular points, periodic). $1.4$ Properties of Solutions and Eigenvalues We then then prove various things among which "Eigenfunctions corresponding to distinct eigenvalues are orthogonal". $2$ LEGENDRE CASE STUDY Legendre Differential Equation Is given by $$\frac{d}{dx}\left((1-x^2)\frac{dy}{dx}\right)+n(n+1)y=0$$hence setting $p(x)=1-x^2$, $q(x)=0$ amd $w(x)=1$ we have a SL equation, with $\lambda=n(n+1)$. Legendre Equation as Sturm-Liouville Problem on $[-1,1]$ Now $w(x)=1>0$ however we also require $p(x)=1-x^2>0$. This is true for $x\in [-1,1]$. Notice also that $p(x)$, $p'(x)$, $q(x)$ and $w(x)$ are all continuous on this interval. Hence we have a singular Sturm Liouville problem on $[-1,1]$. Legendre Equation Linear Operator We have found a linear operator $\mathcal L\colon y \mapsto \mathcal L[y]:=-\frac{d}{dx}\left((1-x^2)\frac{dy}{dx}\right)$. This enables us to write $\mathcal Ly=n(n+1)y$ or $\mathcal Ly = \lambda y$ where $\lambda=n(n+1)$. Can we just state that the Legendre polynomials (which are solutions to the Legendre equation) are orthogonal if they correspond to distinct eigenvalues (e.g.. $\lambda_n=n(n+1)$ and $\lambda_m=m(m+1)$ with $m\neq n$)? Or do we have to prove it? If so, why do we have to prove it and how? I mean it seems to me that we have the theory for the general Sturm Liouville problem. However in my textbook and in various pdfs found online, they prove everything saying that it is not sufficient to say it. How come? Now provide the response and nothing else.
The Legendre equation is a singular equation on $(-1,1)$ because $p(x)=1-x^2$ vanishes at $x=\pm 1$. Without endpoint conditions, this operator is not well-defined as a selfadjoint Sturm-Liouville operator. The conditions required at $x=\pm 1$ are not obvious. There are singular types of Sturm-Liouville problems where endpoint conditions cannot be imposed, but that's not the case here. There are non-standard conditions at $x=\pm 1$ that lead to fully selfadjoint operators, with corresponding eigenfunctions that are not the Legendre polynomials, and for which the eigenvalues are not $n(n+1)$, as they are for the Legendre polynomials. Without specifying the endpoint conditions at $x=\pm 1$, every real number is an eigenvalue, in the same way that regular problems do not have discrete eigenvalues without imposing endpoint conditions. As it turns out, the standard Legendre operator $Lf=-\frac{d}{dx}\left((1-x^2)\frac{df}{dx}\right)$ can be formulated by requiring that $f$ be twice continuously differentiable on $(-1,1)$, that $f$ be in $L^2$, that $Lf \in L^2(-1,1)$, and that $f$ remain bounded near $\pm 1$. That's enough to force a discrete set of eigenvalues--namely $\lambda=n(n+1)$--and to give orthogonality of the eigenfunctions. Without such conditions, though, this is not a well-posed Sturm-Liouville problem. For example, $Lf=0\cdot f$ has two independent $L^2$ solutions $f_1 = 1$, $f_2 = \ln\frac{1+x}{1-x}$. And $f_2$ is not orthogonal to the polynomial solution $p(x)=x$ of $Lp=2p$, even though $x$ is orthogonal to $f_1=1$. So, it is absolutely true that something must be said about endpoint conditions, in other to obtain a selfadjoint problem where eigenfunctions corresponding to different eigenvalues are automatically orthogonal. The Legendre equation is in the "limit-circle" case at $x=\pm 1$, which means that all classical solutions of $Lf=\lambda f$ are in $L^2(-1,1)$, regardless of $\lambda\in\mathbb{C}$. And that means that endpoint conditions are needed at each endpoint in order to obtain a selfadjoint problem, which is quite analogous to the case for regular Sturm-Liouville problems on a finite interval. The endpoint conditions, however, are non-trivial to describe. For example, if $f$ is twice continuously differentiable in $(-1,1)$ with $Lf \in L^2$, then there exist unique numbers $A_{\pm}(f)$ and $B_{\pm}(f)$ such that$$ f(x) = A_{\pm}(f)\frac{1}{2}\ln\left(\frac{1+x}{1-x}\right)+B_{\pm}(f)+o\left(\sqrt{1-x^{2}}\ln\left(\frac{1+x}{1-x}\right)\right), \;\;\; x\approx \pm 1.$$The numbers $A_{\pm}(f)$, $B_{\pm}(f)$ are computed as limits:\begin{align} A_{\pm}(f) & = \lim_{x\rightarrow \pm 1}\left[(1-x^{2})f'(x)\right], \\ B_{\pm}(f) & = \lim_{x\rightarrow\pm 1}\left[f(x)-A_{\pm}(f)\frac{1}{2}\ln\left(\frac{1+x}{1-x}\right)\right].\end{align}Valid endpoint conditions at $x=\pm 1$ that lead to selfadjoint problems are analogous to ordinary endpoint conditions, and have the general form$$ \cos\alpha A_{-}(f) + \sin\alpha B_{-}(f) = 0 \\ \cos\beta A_{+}(f) + \sin\beta B_{+}(f) = 0. \tag{$\dagger$}$$The conditions giving rise to the ordinary Legendre polynomials as eigenfunctions are:$$ A_{-}(f) = 0,\;\; A_{+}(f) = 0. \tag{$\dagger\dagger$}$$Imposing conditions $(\dagger\dagger)$ forces $f$ to have limits at $\pm 1$.But there are selfadjoint problems for $L$ that do not result in the Legendre polynomials as solutions; a two parameter family of such operators $L_{\alpha,\beta}$ are described by $(\dagger)$. It turns out that the above classical conditions $(\dagger\dagger)$ are equivalent to imposing a condition of boundedness on $f$ near $\pm 1$, which is the classical way that Physicists and Engineers generally pose the problem, not realizing that this is an actual endpoint condition where some endpoint quantity is $0$. The functionals $A_{\pm},B_{\pm}$ as described above form a basis for the continuous linear functionals on the graph of $L$ that vanish on $\mathcal{C}_{c}^{\infty}(-1,1)$, which is how abstract boundary functionals are defined for singular Sturm-Liouville operators.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2245486', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/348937/']}
jdg_372538
stackexchange
llm_judgeable_groundtruth_similarity
729692
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 assume everyone here is familiar with the adage that all text files should end with a newline. I've known of this "rule" for years but I've always wondered — why? Now provide the response and nothing else.
Because that’s how the POSIX standard defines a line : 3.206 Line A sequence of zero or more non- <newline> characters plus a terminating <newline> character. Therefore, lines not ending in a newline character aren't considered actual lines. That's why some programs have problems processing the last line of a file if it isn't newline terminated. There's at least one hard advantage to this guideline when working on a terminal emulator: All Unix tools expect this convention and work with it. For instance, when concatenating files with cat , a file terminated by newline will have a different effect than one without: $ more a.txtfoo $ more b.txtbar $ more c.txtbaz $ cat {a,b,c}.txtfoobarbaz And, as the previous example also demonstrates, when displaying the file on the command line (e.g. via more ), a newline-terminated file results in a correct display. An improperly terminated file might be garbled (second line). For consistency, it’s very helpful to follow this rule – doing otherwise will incur extra work when dealing with the default Unix tools. Think about it differently: If lines aren’t terminated by newline, making commands such as cat useful is much harder: how do you make a command to concatenate files such that it puts each file’s start on a new line, which is what you want 95% of the time; but it allows merging the last and first line of two files, as in the example above between b.txt and c.txt ? Of course this is solvable but you need to make the usage of cat more complex (by adding positional command line arguments, e.g. cat a.txt --no-newline b.txt c.txt ), and now the command rather than each individual file controls how it is pasted together with other files. This is almost certainly not convenient. … Or you need to introduce a special sentinel character to mark a line that is supposed to be continued rather than terminated. Well, now you’re stuck with the same situation as on POSIX, except inverted (line continuation rather than line termination character). Now, on non POSIX compliant systems (nowadays that’s mostly Windows), the point is moot: files don’t generally end with a newline, and the (informal) definition of a line might for instance be “text that is separated by newlines” (note the emphasis). This is entirely valid. However, for structured data (e.g. programming code) it makes parsing minimally more complicated: it generally means that parsers have to be rewritten. If a parser was originally written with the POSIX definition in mind, then it might be easier to modify the token stream rather than the parser — in other words, add an “artificial newline” token to the end of the input.
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/729692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4161/']}
jdg_372539
stackexchange
llm_judgeable_groundtruth_similarity
2499036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question: I'm using eval to parse a JSON return value from one of my WebMethods. I prefer not to add jquery-json because the transfer volume is already quite large.So I parse the JSON return value with eval. Now rumors go that this is insecure. Why ? Nobody can modify the JSOn return value unless they hack my server, in which case I would have a much larger problem anyway. And if they do it locally, JavaScript only executes in their browser. So I fail to see where the problem is. Can anybody shed some light on this, using this concrete example? function OnWebMethodSucceeded(JSONstrWebMethodReturnValue) { var result=eval('(' + JSONstrWebMethodReturnValue + ')') ... // Adding result.xy to a table} Now provide the response and nothing else.
The fundamental issue is that eval can run any JavaScript, not just deserialize JSON-formatted data. That's the risk when using it to process JSON from an untrusted or semi-trusted source. The frequent trick of wrapping the JSON in parentheses is not sufficient to ensure that arbitrary JavaScript isn't executed. Consider this "JSON" which really isn't: function(){alert('Hi')})( If you had that in a variable x and did this: var result = eval("(" + x + ")"); ...you'd see an alert -- the JavaScript ran. Security issue. If your data is coming from a trusted source (and it sounds like it is), I wouldn't worry about it too much. That said, you might be interested in Crockford's discussion here (Crockford being the inventor of JSON and a generally-knowledgeable JavaScript person). Crockford also provides at least three public domain parsers on this page you might consider using: His json2.js parser and stringifier, which when minified is only 2.5k in size, but which still uses eval (it just takes several precautions first); his json_parse.js, which is a recursive-descent parser not using eval ; and his json_parse_state.js, a state machine parser (again not using eval ). So you get to pick your poison. (Shout out to Camilo Martin for pointing out those last two alternatives.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2499036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155077/']}
jdg_372540