input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to drop a PostgreSQL database if there are active connections to it? <p>I need to write a script that will drop a PostgreSQL database. There may be a lot of connections to it, but the script should ignore that.</p> <p>The standard <code>DROP DATABASE db_name</code> query doesn't work when there are open connections. </p> <p>How can I solve the problem?</p>
<p>This will drop existing connections except for yours:</p> <p>Query <code>pg_stat_activity</code> and get the pid values you want to kill, then issue <code>SELECT pg_terminate_backend(pid int)</code> to them.</p> <p><strong>PostgreSQL 9.2 and above:</strong></p> <pre><code>SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB AND pid &lt;&gt; pg_backend_pid(); </code></pre> <p><strong>PostgreSQL 9.1 and below:</strong></p> <pre><code>SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB AND procpid &lt;&gt; pg_backend_pid(); </code></pre> <p>Once you disconnect everyone you will have to disconnect and issue the DROP DATABASE command from a connection from another database aka not the one your trying to drop.</p> <p>Note the renaming of the <code>procpid</code> column to <code>pid</code>. See <a href="http://archives.postgresql.org/pgsql-bugs/2012-08/msg00238.php" rel="noreferrer">this mailing list thread</a>.</p>
{ "question_id": 5408156, "question_date": "2011-03-23T16:03:36.430Z", "question_score": 777, "tags": "postgresql", "answer_id": 5408501, "answer_date": "2011-03-23T16:27:59.937Z", "answer_score": 1323 }
Please answer the following Stack Overflow question: Title: How do I prompt a user for confirmation in bash script? <p>I want to put a quick "are you sure?" prompt for confirmation at the top of a potentially dangerous bash script, what's the easiest/best way to do this?</p>
<pre class="lang-sh prettyprint-override"><code>read -p &quot;Are you sure? &quot; -n 1 -r echo # (optional) move to a new line if [[ $REPLY =~ ^[Yy]$ ]] then # do dangerous stuff fi </code></pre> <p>I incorporated <strong>levislevis85</strong>'s suggestion (thanks!) and added the <code>-n</code> option to <code>read</code> to accept one character without the need to press <kbd>Enter</kbd>. You can use one or both of these.</p> <p>Also, the negated form might look like this:</p> <pre class="lang-sh prettyprint-override"><code>read -p &quot;Are you sure? &quot; -n 1 -r echo # (optional) move to a new line if [[ ! $REPLY =~ ^[Yy]$ ]] then [[ &quot;$0&quot; = &quot;$BASH_SOURCE&quot; ]] &amp;&amp; exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell fi </code></pre> <p>However, as pointed out by Erich, under some circumstances such as a syntax error caused by the script being run in the wrong shell, the negated form could allow the script to continue to the &quot;dangerous stuff&quot;. The failure mode should favor the safest outcome so only the first, non-negated <code>if</code> should be used.</p> <h2>Explanation:</h2> <p>The <code>read</code> command outputs the prompt (<code>-p &quot;prompt&quot;</code>) then accepts one character (<code>-n 1</code>) and accepts backslashes literally (<code>-r</code>) (otherwise <code>read</code> would see the backslash as an escape and wait for a second character). The default variable for <code>read</code> to store the result in is <code>$REPLY</code> if you don't supply a name like this: <code>read -p &quot;my prompt&quot; -n 1 -r my_var</code></p> <p>The <code>if</code> statement uses a regular expression to check if the character in <code>$REPLY</code> matches (<code>=~</code>) an upper or lower case &quot;Y&quot;. The regular expression used here says &quot;a string starting (<code>^</code>) and consisting solely of one of a list of characters in a bracket expression (<code>[Yy]</code>) and ending (<code>$</code>)&quot;. The anchors (<code>^</code> and <code>$</code>) prevent matching longer strings. In this case they help reinforce the one-character limit set in the <code>read</code> command.</p> <p>The negated form uses the logical &quot;not&quot; operator (<code>!</code>) to match (<code>=~</code>) any character that is not &quot;Y&quot; or &quot;y&quot;. An alternative way to express this is less readable and doesn't as clearly express the intent in my opinion in this instance. However, this is what it would look like: <code>if [[ $REPLY =~ ^[^Yy]$ ]]</code></p>
{ "question_id": 1885525, "question_date": "2009-12-11T02:52:46.203Z", "question_score": 777, "tags": "bash", "answer_id": 1885534, "answer_date": "2009-12-11T02:56:30.220Z", "answer_score": 1293 }
Please answer the following Stack Overflow question: Title: When to use IMG vs. CSS background-image? <p>In what situations is it more appropriate to use an HTML <code>IMG</code> tag to display an image, as opposed to a CSS <code>background-image</code>, and vice-versa?</p> <p>Factors may include accessibility, browser support, dynamic content, or any kind of technical limits or usability principles.</p>
<h3>Proper uses of IMG</h3> <ol> <li>Use <code>IMG</code> if you intend to have people <a href="https://stackoverflow.com/questions/492809/when-to-use-img-instead-of-css-background-image/492835#492835">print your page</a> and you want the image to be included by default. &mdash;<a href="https://stackoverflow.com/users/20153/jaytee">JayTee</a></li> <li>Use <code>IMG</code> (with <code>alt</code> text) when the image has an important semantic meaning, such as <a href="http://24ways.org/2005/naughty-or-nice-css-background-images" rel="noreferrer">a warning icon</a>. This ensures that the meaning of the image can be communicated in all user-agents, including screen readers.</li> </ol> <h3>Pragmatic uses of IMG</h3> <ol> <li>Use <code>IMG</code> plus alt attribute if the image is <a href="http://stackoverflow.com/questions/492809/when-to-use-img-instead-of-css-background-image/492834#492834">part of the content</a> such as a logo or diagram or person (real person, not stock photo people). &mdash;<a href="http://stackoverflow.com/users/42147/sanchothefat">sanchothefat</a></li> <li>Use <code>IMG</code> if you rely on browser scaling to render an image in proportion to text size.</li> <li>Use <code>IMG</code> for <a href="http://blog.neatlysliced.com/2007/07/ie6-hides-css-images/" rel="noreferrer">multiple overlay images in IE6</a>.</li> <li><strike>Use <code>IMG</code> with a <code>z-index</code> in order to <a href="http://www.quackit.com/html/codes/html_stretch_background_image.cfm" rel="noreferrer">stretch a background image</a> to fill its entire window.</strike><br>Note, this is no longer true with CSS3 background-size; see #6 below.</li> <li>Using <code>img</code> instead of <code>background-image</code> can dramatically improve performance of animations over a background.</li> </ol> <h3>When to use CSS background-image</h3> <ol> <li>Use CSS background images if the image <a href="https://stackoverflow.com/questions/492809/when-to-use-img-instead-of-css-background-image/492834#492834">is not part of the content</a>. &mdash;<a href="https://stackoverflow.com/users/42147/sanchothefat">sanchothefat</a></li> <li>Use CSS background images when doing <a href="https://stackoverflow.com/questions/492809/when-to-use-img-instead-of-css-background-image/492834#492834">image-replacement of text</a> eg. paragraphs/headers. &mdash;<a href="https://stackoverflow.com/users/42147/sanchothefat">sanchothefat</a></li> <li>Use <code>background-image</code> if you intend to have people <a href="https://stackoverflow.com/questions/492809/when-to-use-img-instead-of-css-background-image/492835#492835">print your page</a> and you do not want the image to be included by default. &mdash;<a href="https://stackoverflow.com/users/20153/jaytee">JayTee</a></li> <li>Use <code>background-image</code> if you need to improve download times, as with <a href="http://css-tricks.com/css-sprites/" rel="noreferrer">CSS sprites</a>.</li> <li>Use <code>background-image</code> if you need for only a portion of the image to be visible, as with CSS sprites.</li> <li>Use <code>background-image</code> with <code>background-size:cover</code> in order to stretch a background image to fill its entire window.</li> </ol>
{ "question_id": 492809, "question_date": "2009-01-29T18:25:06.327Z", "question_score": 777, "tags": "html|css|image|background-image", "answer_id": 1469139, "answer_date": "2009-09-23T23:58:07.937Z", "answer_score": 896 }
Please answer the following Stack Overflow question: Title: getColor(int id) deprecated on Android 6.0 Marshmallow (API 23) <p>The <code>Resources.getColor(int id)</code> method has been deprecated.</p> <pre><code>@ColorInt @Deprecated public int getColor(@ColorRes int id) throws NotFoundException { return getColor(id, null); } </code></pre> <p>What should I do?</p>
<p>Starting from Android Support Library 23, <br>a new <a href="http://developer.android.com/reference/android/support/v4/content/ContextCompat.html#getColor(android.content.Context,%20int)" rel="noreferrer">getColor()</a> method has been added to <code>ContextCompat</code>.</p> <p>Its description from the official JavaDoc:</p> <blockquote> <p>Returns a color associated with a particular resource ID</p> <p>Starting in M, the returned color will be styled for the specified Context's theme.</p> </blockquote> <br> <p>So, <strong>just call</strong>:</p> <pre><code>ContextCompat.getColor(context, R.color.your_color); </code></pre> <br> <p>You can check the <code>ContextCompat.getColor()</code> <a href="https://github.com/aosp-mirror/platform_frameworks_support/blob/57f7e35572a20b6ff4bd99fb714e2efcbf8023bb/compat/src/main/java/android/support/v4/content/ContextCompat.java#L416" rel="noreferrer">source code on GitHub</a>.</p>
{ "question_id": 31590714, "question_date": "2015-07-23T14:44:08.327Z", "question_score": 777, "tags": "android|android-resources|android-6.0-marshmallow|android-mnc", "answer_id": 31590927, "answer_date": "2015-07-23T14:52:01.057Z", "answer_score": 1446 }
Please answer the following Stack Overflow question: Title: Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster? <p>I've been hearing a lot about the <a href="http://en.wikipedia.org/wiki/PyPy" rel="noreferrer">PyPy</a> project. They claim it is 6.3 times faster than the <a href="http://en.wikipedia.org/wiki/CPython" rel="noreferrer">CPython</a> interpreter on <a href="http://speed.pypy.org" rel="noreferrer">their site</a>.</p> <p>Whenever we talk about dynamic languages like Python, speed is one of the top issues. To solve this, they say PyPy is 6.3 times faster.</p> <p>The second issue is parallelism, the infamous <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock" rel="noreferrer">Global Interpreter Lock</a> (GIL). For this, PyPy says it <a href="http://pypy.org/tmdonate.html" rel="noreferrer">can give GIL-less Python</a>.</p> <p>If PyPy can solve these great challenges, what are its weaknesses that are preventing wider adoption? That is to say, what's preventing someone like me, a typical Python developer, from switching to PyPy <em>right now</em>? </p>
<blockquote> <p><strong>NOTE:</strong> PyPy is more mature and better supported now than it was in 2013, when this question was asked. Avoid drawing conclusions from out-of-date information.</p> </blockquote> <hr /> <ol> <li>PyPy, as others have been quick to mention, has tenuous support for C extensions. It has support, but typically at slower-than-Python speeds and it's iffy at best. Hence a lot of modules simply require CPython. <strike>PyPy doesn't support numpy</strike>. Some extensions are still not supported (<strike>Pandas</strike>, <strike>SciPy</strike>, etc.), take a look at <a href="http://packages.pypy.org" rel="noreferrer">the list of supported packages</a> before making the change. <strong>Note that many packages marked unsupported on the list are now supported.</strong></li> <li>Python 3 support <strike>is experimental at the moment.</strike> <strong>has just reached stable! As of 20th June 2014, <a href="http://morepypy.blogspot.co.uk/2014/06/pypy3-231-fulcrum.html" rel="noreferrer">PyPy3 2.3.1 - Fulcrum is out</a>!</strong></li> <li>PyPy sometimes isn't actually faster for &quot;scripts&quot;, which a lot of people use Python for. These are the short-running programs that do something simple and small. Because PyPy is a JIT compiler its main advantages come from long run times and simple types (such as numbers). PyPy's pre-JIT speeds can be bad compared to CPython.</li> <li><strong>Inertia</strong>. Moving to PyPy often requires retooling, which for some people and organizations is simply too much work.</li> </ol> <p>Those are the main reasons that affect me, I'd say.</p>
{ "question_id": 18946662, "question_date": "2013-09-22T17:24:13.663Z", "question_score": 777, "tags": "python|performance|jit|pypy|cpython", "answer_id": 18946824, "answer_date": "2013-09-22T17:40:36.580Z", "answer_score": 709 }
Please answer the following Stack Overflow question: Title: Why is [] faster than list()? <p>I recently compared the processing speeds of <code>[]</code> and <code>list()</code> and was surprised to discover that <code>[]</code> runs <em>more than three times faster</em> than <code>list()</code>. I ran the same test with <code>{}</code> and <code>dict()</code> and the results were practically identical: <code>[]</code> and <code>{}</code> both took around 0.128sec / million cycles, while <code>list()</code> and <code>dict()</code> took roughly 0.428sec / million cycles each.</p> <p>Why is this? Do <code>[]</code> and <code>{}</code> (and probably <code>()</code> and <code>''</code>, too) immediately pass back a copies of some empty stock literal while their explicitly-named counterparts (<code>list()</code>, <code>dict()</code>, <code>tuple()</code>, <code>str()</code>) fully go about creating an object, whether or not they actually have elements?</p> <p>I have no idea how these two methods differ but I'd love to find out. I couldn't find an answer in the docs or on SO, and searching for empty brackets turned out to be more problematic than I'd expected.</p> <p>I got my timing results by calling <code>timeit.timeit("[]")</code> and <code>timeit.timeit("list()")</code>, and <code>timeit.timeit("{}")</code> and <code>timeit.timeit("dict()")</code>, to compare lists and dictionaries, respectively. I'm running Python 2.7.9.</p> <p>I recently discovered "<a href="https://stackoverflow.com/questions/18123965/why-if-true-is-slower-than-if-1">Why is if True slower than if 1?</a>" that compares the performance of <code>if True</code> to <code>if 1</code> and seems to touch on a similar literal-versus-global scenario; perhaps it's worth considering as well.</p>
<p>Because <code>[]</code> and <code>{}</code> are <em>literal syntax</em>. Python can create bytecode just to create the list or dictionary objects:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile('[]', '', 'eval')) 1 0 BUILD_LIST 0 3 RETURN_VALUE &gt;&gt;&gt; dis.dis(compile('{}', '', 'eval')) 1 0 BUILD_MAP 0 3 RETURN_VALUE </code></pre> <p><code>list()</code> and <code>dict()</code> are separate objects. Their names need to be resolved, the stack has to be involved to push the arguments, the frame has to be stored to retrieve later, and a call has to be made. That all takes more time.</p> <p>For the empty case, that means you have at the very least a <a href="https://docs.python.org/library/dis.html#opcode-LOAD_NAME" rel="noreferrer"><code>LOAD_NAME</code></a> (which has to search through the global namespace as well as the <a href="https://docs.python.org/library/builtins.html" rel="noreferrer"><code>builtins</code> module</a>) followed by a <a href="https://docs.python.org/library/dis.html#opcode-CALL_FUNCTION" rel="noreferrer"><code>CALL_FUNCTION</code></a>, which has to preserve the current frame:</p> <pre><code>&gt;&gt;&gt; dis.dis(compile('list()', '', 'eval')) 1 0 LOAD_NAME 0 (list) 3 CALL_FUNCTION 0 6 RETURN_VALUE &gt;&gt;&gt; dis.dis(compile('dict()', '', 'eval')) 1 0 LOAD_NAME 0 (dict) 3 CALL_FUNCTION 0 6 RETURN_VALUE </code></pre> <p>You can time the name lookup separately with <a href="https://docs.python.org/library/timeit.html" rel="noreferrer"><code>timeit</code></a>:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit('list', number=10**7) 0.30749011039733887 &gt;&gt;&gt; timeit.timeit('dict', number=10**7) 0.4215109348297119 </code></pre> <p>The time discrepancy there is probably a dictionary hash collision. Subtract those times from the times for calling those objects, and compare the result against the times for using literals:</p> <pre><code>&gt;&gt;&gt; timeit.timeit('[]', number=10**7) 0.30478692054748535 &gt;&gt;&gt; timeit.timeit('{}', number=10**7) 0.31482696533203125 &gt;&gt;&gt; timeit.timeit('list()', number=10**7) 0.9991960525512695 &gt;&gt;&gt; timeit.timeit('dict()', number=10**7) 1.0200958251953125 </code></pre> <p>So having to call the object takes an additional <code>1.00 - 0.31 - 0.30 == 0.39</code> seconds per 10 million calls.</p> <p>You can avoid the global lookup cost by aliasing the global names as locals (using a <code>timeit</code> setup, everything you bind to a name is a local):</p> <pre><code>&gt;&gt;&gt; timeit.timeit('_list', '_list = list', number=10**7) 0.1866450309753418 &gt;&gt;&gt; timeit.timeit('_dict', '_dict = dict', number=10**7) 0.19016098976135254 &gt;&gt;&gt; timeit.timeit('_list()', '_list = list', number=10**7) 0.841480016708374 &gt;&gt;&gt; timeit.timeit('_dict()', '_dict = dict', number=10**7) 0.7233691215515137 </code></pre> <p>but you never can overcome that <code>CALL_FUNCTION</code> cost.</p>
{ "question_id": 30216000, "question_date": "2015-05-13T13:16:22.850Z", "question_score": 777, "tags": "python|performance|list|instantiation|literals", "answer_id": 30216156, "answer_date": "2015-05-13T13:21:57.137Z", "answer_score": 822 }
Please answer the following Stack Overflow question: Title: What are the differences between Visual Studio Code and Visual Studio? <p>Microsoft recently released <a href="https://code.visualstudio.com/" rel="noreferrer">Visual Studio Code</a> and I am a little confused about its usage, since <a href="https://www.visualstudio.com/" rel="noreferrer">Visual Studio</a> has lot of functional similarities with it.</p>
<p><strong>Visual Studio (full version)</strong> is a &quot;full-featured&quot; and &quot;convenient&quot; development environment.</p> <p><strong>Visual Studio (free &quot;Express&quot; versions - only until 2017)</strong> are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.</p> <p><strong>Visual Studio (free Community edition - since 2015)</strong> is a simplified version of the full version and replaces the separated express editions used before 2015.</p> <p><strong>Visual Studio Code (VSCode)</strong> is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.</p> <p>For example, if you want to <a href="https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-xplat/start-mvc?view=aspnetcore-2.1" rel="noreferrer">create an ASP.NET application using Visual Studio Code</a> you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.</p>
{ "question_id": 30527522, "question_date": "2015-05-29T10:41:39.273Z", "question_score": 776, "tags": "visual-studio|visual-studio-code", "answer_id": 33798601, "answer_date": "2015-11-19T08:25:45.943Z", "answer_score": 466 }
Please answer the following Stack Overflow question: Title: How can I force division to be floating point? Division keeps rounding down to 0? <p>I have two integer values <code>a</code> and <code>b</code>, but I need their ratio in floating point. I know that <code>a &lt; b</code> and I want to calculate <code>a / b</code>, so if I use integer division I'll always get 0 with a remainder of <code>a</code>.</p> <p>How can I force <code>c</code> to be a floating point number in Python 2 in the following?</p> <pre><code>c = a / b </code></pre>
<p>In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from <code>__future__</code>.</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; a = 4 &gt;&gt;&gt; b = 6 &gt;&gt;&gt; c = a / b &gt;&gt;&gt; c 0.66666666666666663 </code></pre>
{ "question_id": 1267869, "question_date": "2009-08-12T18:25:15.513Z", "question_score": 776, "tags": "python|floating-point|integer|division|python-2.x", "answer_id": 1267892, "answer_date": "2009-08-12T18:28:26.193Z", "answer_score": 846 }
Please answer the following Stack Overflow question: Title: How do you pass a function as a parameter in C? <p>I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?</p>
<p><strong>Declaration</strong></p> <p>A prototype for a function which takes a function parameter looks like the following:</p> <pre><code>void func ( void (*f)(int) ); </code></pre> <p>This states that the parameter <code>f</code> will be a pointer to a function which has a <code>void</code> return type and which takes a single <code>int</code> parameter. The following function (<code>print</code>) is an example of a function which could be passed to <code>func</code> as a parameter because it is the proper type:</p> <pre><code>void print ( int x ) { printf("%d\n", x); } </code></pre> <p><strong>Function Call</strong></p> <p>When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:</p> <pre><code>func(print); </code></pre> <p>would call <code>func</code>, passing the print function to it.</p> <p><strong>Function Body</strong></p> <p>As with any parameter, <code>func</code> can now use the parameter's name in the function body to access the value of the parameter. Let's say that <code>func</code> will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:</p> <pre><code>for ( int ctr = 0 ; ctr &lt; 5 ; ctr++ ) { print(ctr); } </code></pre> <p>Since <code>func</code>'s parameter declaration says that <code>f</code> is the name for a pointer to the desired function, we recall first that if <code>f</code> is a pointer then <code>*f</code> is the thing that <code>f</code> points to (i.e. the function <code>print</code> in this case). As a result, just replace every occurrence of print in the loop above with <code>*f</code>:</p> <pre><code>void func ( void (*f)(int) ) { for ( int ctr = 0 ; ctr &lt; 5 ; ctr++ ) { (*f)(ctr); } } </code></pre> <p><a href="http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html" rel="noreferrer">Source</a></p>
{ "question_id": 9410, "question_date": "2008-08-13T02:16:32.520Z", "question_score": 776, "tags": "c|function|pointers|syntax|parameters", "answer_id": 9413, "answer_date": "2008-08-13T02:22:24.007Z", "answer_score": 922 }
Please answer the following Stack Overflow question: Title: What's the difference between a Python module and a Python package? <p>What's the difference between a Python module and a Python package?</p> <p>See also: <a href="https://stackoverflow.com/questions/3680883/whats-the-difference-between-package-and-module">What&#39;s the difference between &quot;package&quot; and &quot;module&quot;</a> (for other languages)</p>
<p>A module is a single file (or files) that are imported under one import and used. e.g.</p> <pre><code>import my_module </code></pre> <p>A package is a collection of modules in directories that give a package hierarchy.</p> <pre><code>from my_package.timing.danger.internets import function_of_love </code></pre> <p><a href="http://docs.python.org/tutorial/modules.html" rel="noreferrer">Documentation for modules</a></p> <p><a href="https://realpython.com/python-modules-packages/#python-packages" rel="noreferrer">Introduction to packages</a></p>
{ "question_id": 7948494, "question_date": "2011-10-30T22:53:39.170Z", "question_score": 776, "tags": "python|module|package", "answer_id": 7948504, "answer_date": "2011-10-30T22:55:47.403Z", "answer_score": 440 }
Please answer the following Stack Overflow question: Title: Adding a favicon to a static HTML page <p>I have a few static pages that are just pure HTML, that we display when the server goes down. How can I put a favicon that I made (it's 16x16px and it's sitting in the same directory as the HTML file; it's called favicon.ico) as the "tab" icon as it were? I have read up on Wikipedia and looked at a few tutorials and have implemented the following:</p> <pre><code>&lt;link rel="icon" href="favicon.ico" type="image/x-icon"/&gt; &lt;link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/&gt; </code></pre> <p>But it still doesn't want to work. I am using Chrome to test the sites. According to Wikipedia .ico is the best picture format that runs on all browser types.</p> <h2>Update</h2> <p>I could not get this to work locally although the code checks out it will only really work properly once the server started serving the site. Just try pushing it up to the server and refresh your cache and it should work fine.</p>
<p>You can make a .png image and then use one of the following snippets between the <code>&lt;head&gt;</code> tags of your static HTML documents:</p> <pre><code>&lt;link rel="icon" type="image/png" href="/favicon.png"/&gt; &lt;link rel="icon" type="image/png" href="https://example.com/favicon.png"/&gt; </code></pre>
{ "question_id": 9943771, "question_date": "2012-03-30T13:17:49.620Z", "question_score": 775, "tags": "html|static|favicon", "answer_id": 9943801, "answer_date": "2012-03-30T13:19:25.250Z", "answer_score": 1176 }
Please answer the following Stack Overflow question: Title: How to export/import PuTTY sessions list? <p>Is there a way to do this?</p> <p>Or I have to take manually every record from Registry?</p>
<h1>Export</h1> <h2><code>cmd.exe</code>, <em>requires</em> elevated prompt due to regedit:</h2> <p>Only sessions (produces file <code>putty-sessions.reg</code> on the Desktop):</p> <pre><code>regedit /e &quot;%USERPROFILE%\Desktop\putty-sessions.reg&quot; HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions </code></pre> <p>All settings except ssh keys (produces file <code>putty.reg</code> on the Desktop):</p> <pre><code>regedit /e &quot;%USERPROFILE%\Desktop\putty.reg&quot; HKEY_CURRENT_USER\Software\SimonTatham </code></pre> <hr /> <h2>Powershell:</h2> <p>Only sessions (produces file <code>putty-sessions.reg</code> on the Desktop):</p> <pre><code>reg export HKCU\Software\SimonTatham\PuTTY\Sessions ([Environment]::GetFolderPath(&quot;Desktop&quot;) + &quot;\putty-sessions.reg&quot;) </code></pre> <p>All settings except ssh keys (produces file <code>putty.reg</code> on the Desktop):</p> <pre><code>reg export HKCU\Software\SimonTatham ([Environment]::GetFolderPath(&quot;Desktop&quot;) + &quot;\putty.reg&quot;) </code></pre> <hr /> <h1>Import</h1> <p>Double-click on the <code>*.reg</code> file and accept the import.</p> <h2>Alternative ways:</h2> <h3><code>cmd.exe</code>, <em>requires</em> elevated command prompt:</h3> <pre><code>regedit /i putty-sessions.reg regedit /i putty.reg </code></pre> <h3>PowerShell:</h3> <pre><code>reg import putty-sessions.reg reg import putty.reg </code></pre> <hr /> <p><em>Note</em>: <strong>do not replace</strong> <code>SimonTatham</code> with your username.</p> <p><em>Note</em>: These commands will <strong>not</strong> export the related SSH keys.</p>
{ "question_id": 13023920, "question_date": "2012-10-23T05:10:05.120Z", "question_score": 775, "tags": "windows|registry|putty", "answer_id": 13023979, "answer_date": "2012-10-23T05:16:19.480Z", "answer_score": 1433 }
Please answer the following Stack Overflow question: Title: How to deal with floating point number precision in JavaScript? <p>I have the following dummy test script:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function test() { var x = 0.1 * 0.2; document.write(x); } test();</code></pre> </div> </div> </p> <p>This will print the result <code>0.020000000000000004</code> while it should just print <code>0.02</code> (if you use your calculator). As far as I understood this is due to errors in the floating point multiplication precision.</p> <p>Does anyone have a good solution so that in such case I get the correct result <code>0.02</code>? I know there are functions like <code>toFixed</code> or rounding would be another possibility, but I'd like to really have the whole number printed without any cutting and rounding. Just wanted to know if one of you has some nice, elegant solution.</p> <p>Of course, otherwise I'll round to some 10 digits or so.</p>
<p>From the <a href="http://floating-point-gui.de/" rel="noreferrer">Floating-Point Guide</a>:</p> <blockquote> <p><strong>What can I do to avoid this problem?</strong></p> <p>That depends on what kind of calculations you’re doing.</p> <ul> <li>If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype.</li> <li>If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it.</li> <li>If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But this is more work and has some drawbacks.</li> </ul> </blockquote> <p>Note that the first point only applies if you really need specific precise <em>decimal</em> behaviour. Most people don't need that, they're just irritated that their programs don't work correctly with numbers like 1/10 without realizing that they wouldn't even blink at the same error if it occurred with 1/3.</p> <p>If the first point really applies to you, use <a href="https://github.com/royNiladri/js-big-decimal" rel="noreferrer">BigDecimal for JavaScript</a>, which is not elegant at all, but actually solves the problem rather than providing an imperfect workaround.</p>
{ "question_id": 1458633, "question_date": "2009-09-22T07:34:42.487Z", "question_score": 775, "tags": "javascript|floating-point", "answer_id": 3439981, "answer_date": "2010-08-09T12:30:57.953Z", "answer_score": 570 }
Please answer the following Stack Overflow question: Title: How to convert existing non-empty directory into a Git working directory and push files to a remote repository <ol> <li><p>I have a non-empty directory (eg /etc/something) with files that cannot be renamed, moved, or deleted.</p></li> <li><p>I want to check this directory into git in place.</p></li> <li><p>I want to be able to push the state of this repository to a remote repository (on another machine) using "git push" or something similar.</p></li> </ol> <p>This is trivial using Subversion (currently we do it using Subversion) using:</p> <pre><code>svn mkdir &lt;url&gt; -m &lt;msg&gt; cd &lt;localdir&gt; svn co &lt;url&gt; . svn add &lt;files etc&gt; svn commit -m &lt;msg&gt; </code></pre> <p>What is the git equivalent?</p> <p>Can I "git clone" into an empty directory and simply move the .git directory and have everything work?</p>
<p>Given you've set up a git daemon on <code>&lt;url&gt;</code> and an empty repository:</p> <pre><code>cd &lt;localdir&gt; git init git add . git commit -m 'message' git remote add origin &lt;url&gt; git push -u origin master </code></pre>
{ "question_id": 3311774, "question_date": "2010-07-22T17:48:35.853Z", "question_score": 775, "tags": "git", "answer_id": 3311824, "answer_date": "2010-07-22T17:53:05.107Z", "answer_score": 1229 }
Please answer the following Stack Overflow question: Title: Remove IE10's "clear field" X button on certain inputs? <p>It's a useful feature, to be sure, but is there any way to disable it?<br> For instance, if the form is a single text field and already has a "clear" button beside it, it's superfluous to also have the X. In this situation, it would be better to remove it.</p> <p>Can it be done, and if so, how?</p>
<p>Style the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh465740.aspx"><code>::-ms-clear</code> pseudo-element</a> for the box:</p> <pre class="lang-css prettyprint-override"><code>.someinput::-ms-clear { display: none; } </code></pre>
{ "question_id": 14007655, "question_date": "2012-12-23T00:07:48.787Z", "question_score": 775, "tags": "css|internet-explorer-10", "answer_id": 14007839, "answer_date": "2012-12-23T00:50:33.600Z", "answer_score": 1305 }
Please answer the following Stack Overflow question: Title: jQuery hasAttr checking to see if there is an attribute on an element <p>How do you check if there is an attribute on an element in jQuery? Similar to <code>hasClass</code>, but with <code>attr</code>?</p> <p>For example, </p> <pre><code>if ($(this).hasAttr("name")) { // ... } </code></pre>
<pre><code>var attr = $(this).attr('name'); // For some browsers, `attr` is undefined; for others, // `attr` is false. Check for both. if (typeof attr !== 'undefined' &amp;&amp; attr !== false) { // ... } </code></pre>
{ "question_id": 1318076, "question_date": "2009-08-23T08:38:52.990Z", "question_score": 774, "tags": "jquery", "answer_id": 1318091, "answer_date": "2009-08-23T08:42:49.393Z", "answer_score": 1214 }
Please answer the following Stack Overflow question: Title: What is size_t in C? <p>I am getting confused with <code>size_t</code> in C. I know that it is returned by the <code>sizeof</code> operator. But what exactly is it? Is it a data type?</p> <p>Let's say I have a <code>for</code> loop:</p> <pre><code>for(i = 0; i &lt; some_size; i++) </code></pre> <p>Should I use <code>int i;</code> or <code>size_t i;</code>?</p>
<p><a href="http://en.wikipedia.org/wiki/Size_t" rel="noreferrer">From Wikipedia</a>:</p> <blockquote> <p>According to the 1999 ISO C standard (C99), <code>size_t</code> is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3).</p> <p><code>size_t</code>is an unsigned data type defined by several C/C++ standards, e.g. the C99 ISO/IEC 9899 standard, that is defined in <code>stddef.h</code>.<a href="http://en.wikipedia.org/wiki/Size_t" rel="noreferrer">1</a> It can be further imported by inclusion of <code>stdlib.h</code> as this file internally sub includes <code>stddef.h</code>.</p> <p>This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of <code>size_t</code>. Further, the most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible with <code>size_t</code>.</p> </blockquote> <p>As an implication, <code>size_t</code> is a type guaranteed to hold any array index.</p>
{ "question_id": 2550774, "question_date": "2010-03-31T05:51:55.800Z", "question_score": 774, "tags": "c|int|size-t", "answer_id": 2550799, "answer_date": "2010-03-31T05:56:32.267Z", "answer_score": 545 }
Please answer the following Stack Overflow question: Title: Unlink of file Failed. Should I try again? <p>Something wrong is going on with one of the files in my local git repository. When I'm trying to change the branch it says:</p> <pre><code>Unlink of file 'templates/media/container.html' failed. Should I try again? (y/n) </code></pre> <p>What could that mean?</p>
<p>This could mean that another program is using the file, which is preventing git from "moving" the file into or out of the working directory when you are attempting to change branches. </p> <p>I have had this happen on Windows Vista where eclipse is the program "using" the file. The file may not be actually open in eclipse but may have been opened by a process run by eclipse. </p> <p>In this event, try closing the file in any applications that might have used it. If that doesn't work, completely exit any applications which may have opened the file. </p>
{ "question_id": 4389833, "question_date": "2010-12-08T16:32:40.123Z", "question_score": 774, "tags": "git|unlink", "answer_id": 6076796, "answer_date": "2011-05-20T19:35:51.147Z", "answer_score": 1041 }
Please answer the following Stack Overflow question: Title: Why use static_cast<int>(x) instead of (int)x? <p>I've heard that the <code>static_cast</code> function should be preferred to C-style or simple function-style casting. Is this true? Why?</p>
<p>The main reason is that classic C casts make no distinction between what we call <code>static_cast&lt;&gt;()</code>, <code>reinterpret_cast&lt;&gt;()</code>, <code>const_cast&lt;&gt;()</code>, and <code>dynamic_cast&lt;&gt;()</code>. These four things are completely different.</p> <p>A <code>static_cast&lt;&gt;()</code> is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A <code>dynamic_cast&lt;&gt;()</code> is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference). </p> <p>A <code>reinterpret_cast&lt;&gt;()</code> (or a <code>const_cast&lt;&gt;()</code>) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a <code>foo</code> (this looks as if it isn't mutable), but it is". </p> <p>The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.</p> <p>Let's assume these:</p> <pre><code>class CDerivedClass : public CMyBase {...}; class CMyOtherStuff {...} ; CMyBase *pSomething; // filled somewhere </code></pre> <p>Now, these two are compiled the same way:</p> <pre><code>CDerivedClass *pMyObject; pMyObject = static_cast&lt;CDerivedClass*&gt;(pSomething); // Safe; as long as we checked pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast&lt;&gt; // Safe; as long as we checked // but harder to read </code></pre> <p>However, let's see this almost identical code:</p> <pre><code>CMyOtherStuff *pOther; pOther = static_cast&lt;CMyOtherStuff*&gt;(pSomething); // Compiler error: Can't convert pOther = (CMyOtherStuff*)(pSomething); // No compiler error. // Same as reinterpret_cast&lt;&gt; // and it's wrong!!! </code></pre> <p>As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.</p> <p>The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast&lt;" or "reinterpret_cast&lt;".</p> <pre><code>pOther = reinterpret_cast&lt;CMyOtherStuff*&gt;(pSomething); // No compiler error. // but the presence of a reinterpret_cast&lt;&gt; is // like a Siren with Red Flashing Lights in your code. // The mere typing of it should cause you to feel VERY uncomfortable. </code></pre> <p>That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.</p>
{ "question_id": 103512, "question_date": "2008-09-19T16:33:58.100Z", "question_score": 774, "tags": "c++|casting|static-cast", "answer_id": 103868, "answer_date": "2008-09-19T17:23:59.680Z", "answer_score": 711 }
Please answer the following Stack Overflow question: Title: What is monkey patching? <p>I am trying to understand, what is monkey patching or a monkey patch? </p> <p>Is that something like methods/operators overloading or delegating? </p> <p>Does it have anything common with these things?</p>
<p>No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.</p> <p>For instance, consider a class that has a method <code>get_data</code>. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the <code>get_data</code> method with a stub that returns some fixed data.</p> <p>Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.</p> <p>But, as a <a href="https://stackoverflow.com/users/2810305/lutz-prechelt">commenter</a> pointed out, use caution when monkeypatching: </p> <ol> <li><p>If anything else besides your test logic calls <code>get_data</code> as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware. </p></li> <li><p>If some variable or attribute exists that also points to the <code>get_data</code> function by the time you replace it, this alias will not change its meaning and will continue to point to the original <code>get_data</code>. (Why? Python just rebinds the name <code>get_data</code> in your class to some other function object; other name bindings are not impacted at all.) </p></li> </ol>
{ "question_id": 5626193, "question_date": "2011-04-11T19:05:41.507Z", "question_score": 774, "tags": "python|terminology|monkeypatching", "answer_id": 5626250, "answer_date": "2011-04-11T19:10:57.340Z", "answer_score": 702 }
Please answer the following Stack Overflow question: Title: GitHub satanically messing with Markdown - changes 666 to DCLXVI <p><a href="https://github.com/aaronryank/Forked/tree/fa599eaee537e05657d6d73116ee8c177eeb2c50" rel="noreferrer">My GitHub repository</a> has nothing but a readme in it. In this readme, locally I wrote this:</p> <pre><code>Factoids: - There are about six different ways to do everything in Forked. - There are actually six different ways to enter loops. - There are six directionals and six I/O commands. - 666. ha. </code></pre> <p>Emphasis on the last line. What GitHub decided to show was <em>not</em> <code>666</code>.</p> <p><a href="https://i.stack.imgur.com/AVSsT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AVSsT.png" alt="dclxvi"></a></p> <p><code>DCLXVI</code> is the Roman Numeral number for <a href="https://en.wikipedia.org/wiki/666_(number)" rel="noreferrer">666</a>.</p> <p>This really creeped me out. My local file and <a href="https://raw.githubusercontent.com/aaronryank/Forked/fa599eaee537e05657d6d73116ee8c177eeb2c50/README.md" rel="noreferrer">the raw file</a> both show <code>666</code>.</p> <p>What is GitHub doing, and why is the indentation on the un-numbered list messed up? Is this an easter egg, or some satanic bug?</p>
<p>This seems to be followed by <a href="https://github.com/github/markup/issues/991" rel="noreferrer">github/markup issue 991</a>, where on ordered sub-list, decimal numerals automatically turns into roman numerals.</p> <blockquote> <p>I have found the cause of problem. It is CSS</p> <blockquote> <p>This is the expected way for nested ordered lists to render in HTML.</p> </blockquote> <p>This is not expected in HTML. <a href="https://jsfiddle.net/tf5jtv8s" rel="noreferrer">https://jsfiddle.net/tf5jtv8s</a></p> <blockquote> <p>We don't make any modifications to the default HTML behavior.</p> </blockquote> <pre><code>ol ol,ul ol{list-style-type:lower-roman} </code></pre> <p>I don't know CSS but my understanding is that this is the cause of problem. I can get expected result by disabling CSS. (I am from my mobile so I can't use browser inspector)</p> </blockquote> <p>As mentioned in &quot;<a href="https://githubengineering.com/a-formal-spec-for-github-markdown/" rel="noreferrer">A formal spec for GitHub Flavored Markdown</a>&quot;, GitHub markdown spec <a href="https://github.github.com/gfm/" rel="noreferrer">GFM: GitHub Flavored Markdown Spec</a> is built on top of the <a href="http://spec.commonmark.org/0.26" rel="noreferrer">CommonMark Spec</a>.</p> <p>And as <a href="https://stackoverflow.com/users/8132914/tommi-kaikkonen">Tommi Kaikkonen</a> mentioned in <a href="https://stackoverflow.com/a/44619303/6309">his answer</a>, the ordered list is because of the dot following 666. See <a href="https://github.github.com/gfm/#list-items" rel="noreferrer">GFM Spec section 5.2</a>.</p> <p>As mentioned in <a href="https://github.github.com/gfm/#backslash-escapes" rel="noreferrer">section 6.1</a>, any ASCII punctuation character may be backslash-escaped, to avoid this issue.<br /> That means:</p> <pre><code>- 666\. ha. </code></pre> <p>(as explicitly shown in <a href="https://stackoverflow.com/users/2684760/fornever">ForNeVeR</a>'s <a href="https://stackoverflow.com/a/44623878/6309">answer</a>)</p> <p>That is why that <code>666</code> number is changed to roman numerals in a GitHub <code>README</code> markdown.</p> <hr /> <p><a href="https://stackoverflow.com/users/2184226/mike-lippert">Mike Lippert</a> commented:</p> <blockquote> <p>the 1st element in that list so it should show as <code>i</code> not <code>dclxvi</code>.<br /> Markdown ordered lists ignore the actual number used and number sequentially, and I haven't seen a way to change that.</p> </blockquote> <p>However, no: it shows <code>dclxvi</code>, because the generated html code is <code>&lt;ol start=&quot;666&quot;&gt;</code>, which is consistent with <a href="https://github.github.com/gfm/#list-items" rel="noreferrer">the GFM specs</a>:</p> <blockquote> <p>If the list item is ordered, then it is also assigned a start number, based on the ordered list marker&quot;</p> </blockquote> <p>(here, '<code>666</code>' is the ordered list marker)</p> <p>Mike adds:</p> <blockquote> <blockquote> <p>@VonC For anyone else here's another useful excerpt from VonC's doc link:</p> </blockquote> <p>&quot;The start number of an ordered list is determined by the list number of its initial list item. The numbers of subsequent list items are disregarded.&quot;</p> </blockquote> <hr /> <blockquote> <p>Also, why is the spacing messed up? I didn't catch that in your answer</p> </blockquote> <p>You get an ordered list <code>&lt;ol&gt;</code> within an un-ordered list <em>item</em> <code>&lt;li&gt;</code>:</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;ol start=&quot;666&quot;&gt; &lt;li&gt;ha.&lt;/li&gt; &lt;/ol&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>GitHub CSS rules include:</p> <pre><code>.markdown-body ol { padding-left: 2em; } </code></pre> <p>If you put <code>3em</code>, you would get<br /> <a href="https://i.stack.imgur.com/zmUrx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zmUrx.png" alt="correct padding" /></a><br /> instead of<br /> <a href="https://i.stack.imgur.com/rKPZY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rKPZY.png" alt="wrong padding" /></a></p>
{ "question_id": 44619165, "question_date": "2017-06-18T20:18:00.613Z", "question_score": 774, "tags": "github|markdown", "answer_id": 44619272, "answer_date": "2017-06-18T20:31:11.193Z", "answer_score": 495 }
Please answer the following Stack Overflow question: Title: Vertically align text within a div <p>The code below (also available as <a href="http://jsfiddle.net/9Y7Cm/3/" rel="noreferrer">a demo on JS Fiddle</a>) does not position the text in the middle, as I ideally would like it to. I cannot find any way to vertically centre text in a <code>div</code>, even using the <code>margin-top</code> attribute. How can I do this?</p> <pre><code>&lt;div id=&quot;column-content&quot;&gt; &lt;img src=&quot;http://i.stack.imgur.com/12qzO.png&quot;&gt; &lt;strong&gt;1234&lt;/strong&gt; yet another text content that should be centered vertically &lt;/div&gt; </code></pre> <pre><code>#column-content { display: inline-block; border: 1px solid red; position:relative; } #column-content strong { color: #592102; font-size: 18px; } img { margin-top:-7px; vertical-align: middle; } </code></pre>
<p>Create a container for your text content, a <code>span</code> perhaps.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#column-content { display: inline-block; } img { vertical-align: middle; } span { display: inline-block; vertical-align: middle; } /* for visual purposes */ #column-content { border: 1px solid red; position: relative; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="column-content"&gt; &lt;img src="http://i.imgur.com/WxW4B.png"&gt; &lt;span&gt;&lt;strong&gt;1234&lt;/strong&gt; yet another text content that should be centered vertically&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/9Y7Cm/5/">JSFiddle</a></p>
{ "question_id": 9249359, "question_date": "2012-02-12T14:00:48.600Z", "question_score": 773, "tags": "css|vertical-alignment", "answer_id": 9249396, "answer_date": "2012-02-12T14:06:45.827Z", "answer_score": 486 }
Please answer the following Stack Overflow question: Title: What characters are allowed in an email address? <p>I'm not asking about full email validation.</p> <p>I just want to know what are allowed characters in <code>user-name</code> and <code>server</code> parts of email address. This may be oversimplified, maybe email adresses can take other forms, but I don't care. I'm asking about only this simple form: <code>user-name@server</code> (e.g. [email protected]) and allowed characters in both parts.</p>
<p>See <a href="https://www.rfc-editor.org/rfc/rfc5322" rel="noreferrer">RFC 5322: Internet Message Format</a> and, to a lesser extent, <a href="https://www.rfc-editor.org/rfc/rfc5321" rel="noreferrer">RFC 5321: Simple Mail Transfer Protocol</a>.</p> <p><a href="https://www.rfc-editor.org/rfc/rfc822#section-6.1" rel="noreferrer">RFC 822</a> also covers email addresses, but it deals mostly with its structure:</p> <pre><code> addr-spec = local-part &quot;@&quot; domain ; global address local-part = word *(&quot;.&quot; word) ; uninterpreted ; case-preserved domain = sub-domain *(&quot;.&quot; sub-domain) sub-domain = domain-ref / domain-literal domain-ref = atom ; symbolic reference </code></pre> <p>And as usual, Wikipedia has a decent <a href="https://en.wikipedia.org/wiki/Email_address#Local-part" rel="noreferrer">article on email addresses</a>:</p> <blockquote> <p>The local-part of the email address may use any of these ASCII characters:</p> <ul> <li>uppercase and lowercase Latin letters <code>A</code> to <code>Z</code> and <code>a</code> to <code>z</code>;</li> <li>digits <code>0</code> to <code>9</code>;</li> <li>special characters <code>!#$%&amp;'*+-/=?^_`{|}~</code>;</li> <li>dot <code>.</code>, provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. <code>[email protected]</code> is not allowed but <code>&quot;John..Doe&quot;@example.com</code> is allowed);</li> <li>space and <code>&quot;(),:;&lt;&gt;@[\]</code> characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);</li> <li>comments are allowed with parentheses at either end of the local-part; e.g. <code>john.smith(comment)@example.com</code> and <code>(comment)[email protected]</code> are both equivalent to <code>[email protected]</code>.</li> </ul> </blockquote> <p>In addition to ASCII characters, <a href="https://www.rfc-editor.org/rfc/rfc6531" rel="noreferrer">as of 2012</a> you can use international <a href="http://www.utf8-chartable.de/unicode-utf8-table.pl" rel="noreferrer">characters above</a> <code>U+007F</code>, encoded as UTF-8 as described in the <a href="https://www.rfc-editor.org/rfc/rfc6532#section-3.2" rel="noreferrer">RFC 6532 spec</a> and explained on <a href="https://en.wikipedia.org/wiki/UTF-8#Description" rel="noreferrer">Wikipedia</a>. Note that as of 2019, these standards are still marked as Proposed, but are being rolled out slowly. The changes in this spec essentially added international characters as valid alphanumeric characters (atext) without affecting the rules on allowed &amp; restricted special characters like <code>!#</code> and <code>@:</code>.</p> <p>For validation, see <a href="https://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address">Using a regular expression to validate an email address</a>.</p> <p>The <code>domain</code> part is defined <a href="https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames" rel="noreferrer">as follows</a>:</p> <blockquote> <p>The Internet standards (Request for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters <code>a</code> through <code>z</code> (in a case-insensitive manner), the digits <code>0</code> through <code>9</code>, and the hyphen (<code>-</code>). The original specification of hostnames in <a href="https://www.rfc-editor.org/rfc/rfc952" rel="noreferrer">RFC 952</a>, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (<a href="https://www.rfc-editor.org/rfc/rfc1123" rel="noreferrer">RFC 1123</a>) permitted hostname labels to start with digits. No other symbols, punctuation characters, or blank spaces are permitted.</p> </blockquote>
{ "question_id": 2049502, "question_date": "2010-01-12T14:13:57.580Z", "question_score": 773, "tags": "forms|email|email-validation|email-address", "answer_id": 2049510, "answer_date": "2010-01-12T14:15:23.660Z", "answer_score": 920 }
Please answer the following Stack Overflow question: Title: How can I delete all local Docker images? <p>I recently started using Docker and never realized that I should use <code>docker-compose down</code> instead of <code>ctrl-c</code> or <code>docker-compose stop</code> to get rid of my experiments. I now have a large number of unneeded docker images locally. </p> <p>Is there a flag I can run to delete all the local docker images &amp; containers?</p> <p>Something like <code>docker rmi --all --force</code> --all flag does not exist but I am looking for something with similar idea. </p>
<p><strong>Unix</strong></p> <p>To delete all containers including its volumes use,</p> <pre><code>docker rm -vf $(docker ps -aq) </code></pre> <p>To delete all the images,</p> <pre><code>docker rmi -f $(docker images -aq) </code></pre> <p>Remember, you should remove all the containers before removing all the images from which those containers were created.</p> <p><strong>Windows - Powershell</strong></p> <pre><code>docker images -a -q | % { docker image rm $_ -f } </code></pre> <p><strong>Windows - Command Line</strong></p> <pre><code>for /F %i in ('docker images -a -q') do docker rmi -f %i </code></pre>
{ "question_id": 44785585, "question_date": "2017-06-27T16:36:53.480Z", "question_score": 773, "tags": "python|docker|docker-compose", "answer_id": 44785784, "answer_date": "2017-06-27T16:48:46.380Z", "answer_score": 1629 }
Please answer the following Stack Overflow question: Title: What is 'Currying'? <p>I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)</p>
<p>Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:</p> <pre class="lang-js prettyprint-override"><code>function add (a, b) { return a + b; } add(3, 4); // returns 7 </code></pre> <p>This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:</p> <pre class="lang-js prettyprint-override"><code>function add (a) { return function (b) { return a + b; } } </code></pre> <p>This is a function that takes one argument, <code>a</code>, and returns a function that takes another argument, <code>b</code>, and that function returns their sum.</p> <pre class="lang-js prettyprint-override"><code>add(3)(4); var add3 = add(3); add3(4); </code></pre> <p>The first statement returns 7, like the <code>add(3, 4)</code> statement. The second statement defines a new function called <code>add3</code> that will add 3 to its argument. (This is what some may call a closure.) The third statement uses the <code>add3</code> operation to add 3 to 4, again producing 7 as a result.</p>
{ "question_id": 36314, "question_date": "2008-08-30T20:12:55.867Z", "question_score": 773, "tags": "javascript|functional-programming|terminology|definition|currying", "answer_id": 36321, "answer_date": "2008-08-30T20:19:51.187Z", "answer_score": 1032 }
Please answer the following Stack Overflow question: Title: What is Common Gateway Interface (CGI)? <p>CGI is a Common Gateway Interface. As the name says, it is a "common" gateway interface for everything. It is so trivial and naive from the name. I feel that I understood this and I felt this every time I encountered this word. But frankly, I didn't. I'm still confused. </p> <p>I am a PHP programmer with web development experience. </p> <blockquote> <p>user (client) request for page ---> webserver(->embedded PHP interpreter) ----> Server side(PHP) Script ---> MySQL Server.</p> </blockquote> <p>Now say my PHP Script can fetch results from MySQL server &amp; MATLAB server &amp; some other server.</p> <p>So, now PHP Script is the CGI? Because its interface for the between webserver &amp; All other servers? I don't know. Sometimes they call CGI, a technology &amp; other times they call CGI a program or some other server. </p> <ul> <li><p>What exactly is CGI?</p></li> <li><p>Whats the big deal with <code>/cgi-bin/*.cgi</code>? What's up with this? I don't know what is this <code>cgi-bin</code> directory on the server for. I don't know why they have *.cgi extensions.</p></li> <li><p>Why does Perl always comes in the way. CGI &amp; Perl (language). I also don't know what's up with these two. Almost all the time I keep hearing these two in combination "CGI &amp; Perl". This book is another great example <a href="https://rads.stackoverflow.com/amzn/click/com/1565924193" rel="noreferrer" rel="nofollow noreferrer">CGI Programming with Perl</a>. Why not "CGI Programming with PHP/JSP/ASP"? I never saw such things. </p></li> <li><p><strong>CGI Programming in C</strong>, confuses me a lot. "<strong>in C</strong>"?? Seriously?? I don't know what to say. I'm just confused. "<strong>in C</strong>"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB &amp; MySQL) using socket programming? I'm lost!!</p></li> <li><p>People say that CGI is deprecated and isn't in use anymore. Is that so? What is the latest update?</p></li> </ul> <blockquote> <p>Once, I ran into a situation where I had to give HTTP PUT request access to web server (Apache HTTPD). Its a long back. So, as far as I remember this is what I did:</p> <ol> <li><p>Edited the configuration file of Apache HTTPD to tell webserver to pass all HTTP PUT requests to some <code>put.php</code> ( I had to write this PHP script)</p></li> <li><p>Implement put.php to handle the request (save the file to the location mentioned)</p></li> </ol> <p>People said that I wrote a CGI Script. Seriously, I didn't have a clue what they were talking about.</p> </blockquote> <ul> <li>Did I really write CGI Script? </li> </ul> <p>I hope you understood what my confusion is. (Because I myself don't know where I'm confused). I request you guys to keep your answer as simple as possible. I really can't understand any fancy technical terminology. At least not in this case. </p> <p><strong>EDIT:</strong></p> <p>I found this amazing tutorial <a href="http://www.whizkidtech.redprince.net/cgi-bin/tutorial" rel="noreferrer">"CGI Programming Is Simple!" - CGI Tutorial</a>, which explains the concepts in <strong>simplest</strong> possible way. After reading this article you may want to read <a href="http://www.cs.tut.fi/~jkorpela/forms/cgic.html" rel="noreferrer">Getting Started with CGI Programming in C</a> to supplement your understanding with actual code samples. I've also added these links to this tutorial to Wikipedia's article: <a href="http://en.wikipedia.org/wiki/Common_Gateway_Interface" rel="noreferrer">http://en.wikipedia.org/wiki/Common_Gateway_Interface</a></p>
<p>CGI is an interface which tells the webserver how to pass data to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the request body is passed in via standard input, and how the response is passed out via standard output. You can refer to the <a href="http://www.ietf.org/rfc/rfc3875.txt" rel="noreferrer">CGI specification</a> for details.</p> <p>To use your image:</p> <p><code>user (client) request for page ---&gt; webserver ---[CGI]----&gt; Server side Program ---&gt; MySQL Server.</code></p> <p>Most if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.</p> <p>The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.</p> <p>In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.</p> <p>So, answering your questions:</p> <blockquote> <p>What exactly is CGI?</p> </blockquote> <p>See above.</p> <blockquote> <p>Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.</p> </blockquote> <p>That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.</p> <blockquote> <p>Why does Perl always comes in the way. CGI &amp; Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI &amp; Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.</p> </blockquote> <p>Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly <a href="http://perl.apache.org" rel="noreferrer">mod_perl</a>.</p> <blockquote> <p>CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB &amp; MySQL) using socket programming? I'm lost!!</p> </blockquote> <p>You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.</p> <blockquote> <p>They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?</p> </blockquote> <p>CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is <a href="http://www.fastcgi.com/" rel="noreferrer">FastCGI</a>. </p>
{ "question_id": 2089271, "question_date": "2010-01-18T21:15:48.867Z", "question_score": 773, "tags": "cgi", "answer_id": 2089297, "answer_date": "2010-01-18T21:20:13.210Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: How to "git pull" from master into the development branch <p>I have a branch called &quot;dmgr2&quot; in development, and I want to pull from the master branch (live site) and incorporate all the changes into my development branch. Is there a better way to do this?</p> <p>Here is what I had planned on doing, after committing changes:</p> <pre><code>git checkout dmgr2 git pull origin master </code></pre> <p>This should pull the live changes into my development branch, or do I have this wrong?</p>
<p>The steps you listed will work, but there's a longer way that gives you more options:</p> <pre><code>git checkout dmgr2 # gets you "on branch dmgr2" git fetch origin # gets you up to date with origin git merge origin/master </code></pre> <p>The <code>fetch</code> command can be done at any point before the <code>merge</code>, i.e., you can swap the order of the fetch and the checkout, because <code>fetch</code> just goes over to the named remote (<code>origin</code>) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named <code>origin/branch</code> for any branch named <code>branch</code> on the remote.</p> <p>At this point you can use any viewer (<code>git log</code>, <code>gitk</code>, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").</p> <p>Finally, the <code>merge</code> command takes the given commit, which you can name as <code>origin/master</code>, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the <code>merge</code>. You can insert <code>--no-ff</code> or <code>--ff-only</code> to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.</p> <p>When you use the sequence:</p> <pre><code>git checkout dmgr2 git pull origin master </code></pre> <p>the <code>pull</code> command instructs git to run <code>git fetch</code>, and then the moral equivalent of <code>git merge origin/master</code>. So this is <em>almost</em> the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the <code>fetch</code> step run by <code>pull</code> brings over <em>only</em> <code>origin/master</code>, and it does not update the ref in your repo:<sup>1</sup> any new commits winds up referred-to only by the special <code>FETCH_HEAD</code> reference.)</p> <p>If you use the more-explicit <code>git fetch origin</code> (then optionally look around) and then <code>git merge origin/master</code> sequence, you can also bring your own local <code>master</code> up to date with the remote, with only one <code>fetch</code> run across the network:</p> <pre><code>git fetch origin git checkout master git merge --ff-only origin/master git checkout dmgr2 git merge --no-ff origin/master </code></pre> <p>for instance.</p> <hr> <p><sup>1</sup>This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)</p>
{ "question_id": 20101994, "question_date": "2013-11-20T16:53:52.920Z", "question_score": 772, "tags": "git|branch|pull", "answer_id": 20103414, "answer_date": "2013-11-20T17:58:31.963Z", "answer_score": 1112 }
Please answer the following Stack Overflow question: Title: How to convert a byte array to a hex string in Java? <p>I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in the form of: <code>3a5f771c</code></p>
<p>From the discussion <a href="https://stackoverflow.com/q/332079/1284661">here</a>, and especially <a href="https://stackoverflow.com/a/2197650/1284661">this</a> answer, this is the function I currently use:</p> <pre><code>private static final char[] HEX_ARRAY = &quot;0123456789ABCDEF&quot;.toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j &lt; bytes.length; j++) { int v = bytes[j] &amp; 0xFF; hexChars[j * 2] = HEX_ARRAY[v &gt;&gt;&gt; 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v &amp; 0x0F]; } return new String(hexChars); } </code></pre> <p>My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)</p> <p>2k20 version, with respect to Java 9 compact strings:</p> <pre><code>private static final byte[] HEX_ARRAY = &quot;0123456789ABCDEF&quot;.getBytes(StandardCharsets.US_ASCII); public static String bytesToHex(byte[] bytes) { byte[] hexChars = new byte[bytes.length * 2]; for (int j = 0; j &lt; bytes.length; j++) { int v = bytes[j] &amp; 0xFF; hexChars[j * 2] = HEX_ARRAY[v &gt;&gt;&gt; 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v &amp; 0x0F]; } return new String(hexChars, StandardCharsets.UTF_8); } </code></pre>
{ "question_id": 9655181, "question_date": "2012-03-11T13:06:24Z", "question_score": 772, "tags": "java|bytearray|hex", "answer_id": 9855338, "answer_date": "2012-03-24T20:32:14.537Z", "answer_score": 1035 }
Please answer the following Stack Overflow question: Title: How can I capitalize the first letter of each word in a string? <pre><code>s = 'the brown fox' </code></pre> <p>...do something here...</p> <p><code>s</code> should be:</p> <pre><code>'The Brown Fox' </code></pre> <p>What's the easiest way to do this?</p>
<p>The <a href="http://docs.python.org/library/stdtypes.html#str.title" rel="noreferrer"><code>.title()</code></a> method of a string (either ASCII or Unicode is fine) does this:</p> <pre><code>&gt;&gt;&gt; &quot;hello world&quot;.title() 'Hello World' &gt;&gt;&gt; u&quot;hello world&quot;.title() u'Hello World' </code></pre> <p>However, look out for strings with embedded apostrophes, as noted in the docs.</p> <blockquote> <p>The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:</p> <pre><code>&gt;&gt;&gt; &quot;they're bill's friends from the UK&quot;.title() &quot;They'Re Bill'S Friends From The Uk&quot; </code></pre> </blockquote>
{ "question_id": 1549641, "question_date": "2009-10-11T02:03:54.417Z", "question_score": 772, "tags": "python|capitalization|capitalize", "answer_id": 1549644, "answer_date": "2009-10-11T02:04:35.680Z", "answer_score": 1259 }
Please answer the following Stack Overflow question: Title: How to set focus on input field? <p>What is the 'Angular way' to set focus on input field in AngularJS?</p> <p>More specific requirements:</p> <ol> <li>When a <a href="http://angular-ui.github.com/bootstrap/#modal" rel="nofollow noreferrer">Modal</a> is opened, set focus on a predefined <code>&lt;input&gt;</code> inside this Modal.</li> <li>Every time <code>&lt;input&gt;</code> becomes visible (e.g. by clicking some button), set focus on it.</li> </ol> <p><a href="http://plnkr.co/edit/XL1NP0?p=preview" rel="nofollow noreferrer">I tried to achieve the first requirement</a> with <code>autofocus</code>, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).</p>
<blockquote> <ol> <li>When a Modal is opened, set focus on a predefined &lt;input> inside this Modal.</li> </ol> </blockquote> <p>Define a directive and have it $watch a property/trigger so it knows when to focus the element:</p> <pre><code>Name: &lt;input type="text" focus-me="shouldBeOpen"&gt; </code></pre> <p></p> <pre><code>app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) { return { //scope: true, // optionally create a child scope link: function (scope, element, attrs) { var model = $parse(attrs.focusMe); scope.$watch(model, function (value) { console.log('value=', value); if (value === true) { $timeout(function () { element[0].focus(); }); } }); // to address @blesh's comment, set attribute value to 'false' // on blur event: element.bind('blur', function () { console.log('blur'); scope.$apply(model.assign(scope, false)); }); } }; }]); </code></pre> <p><a href="http://plnkr.co/edit/LbHRBB?p=preview" rel="noreferrer">Plunker</a></p> <p>The $timeout seems to be needed to give the modal time to render.</p> <blockquote> <p>'2.' Everytime &lt;input> becomes visible (e.g. by clicking some button), set focus on it.</p> </blockquote> <p>Create a directive essentially like the one above. Watch some scope property, and when it becomes true (set it in your ng-click handler), execute <code>element[0].focus()</code>. Depending on your use case, you may or may not need a $timeout for this one:</p> <pre><code>&lt;button class="btn" ng-click="showForm=true; focusInput=true"&gt;show form and focus input&lt;/button&gt; &lt;div ng-show="showForm"&gt; &lt;input type="text" ng-model="myInput" focus-me="focusInput"&gt; {{ myInput }} &lt;button class="btn" ng-click="showForm=false"&gt;hide form&lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code>app.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log('value=',value); //$timeout(function() { element[0].focus(); scope[attrs.focusMe] = false; //}); } }); } }; }); </code></pre> <p><a href="http://plnkr.co/edit/V8PSie?p=preview" rel="noreferrer">Plunker</a></p> <hr> <p><strong>Update 7/2013</strong>: I've seen a few people use my original isolate scope directives and then have problems with embedded input fields (i.e., an input field in the modal). A directive with no new scope (or possibly a new child scope) should alleviate some of the pain. So above I updated the answer to not use isolate scopes. Below is the original answer:</p> <p>Original answer for 1., using an isolate scope:</p> <pre><code>Name: &lt;input type="text" focus-me="{{shouldBeOpen}}"&gt; </code></pre> <p></p> <pre><code>app.directive('focusMe', function($timeout) { return { scope: { trigger: '@focusMe' }, link: function(scope, element) { scope.$watch('trigger', function(value) { if(value === "true") { $timeout(function() { element[0].focus(); }); } }); } }; }); </code></pre> <p><a href="http://plnkr.co/edit/6kHuj0?p=preview" rel="noreferrer">Plunker</a>.</p> <p>Original answer for 2., using an isolate scope:</p> <pre><code>&lt;button class="btn" ng-click="showForm=true; focusInput=true"&gt;show form and focus input&lt;/button&gt; &lt;div ng-show="showForm"&gt; &lt;input type="text" focus-me="focusInput"&gt; &lt;button class="btn" ng-click="showForm=false"&gt;hide form&lt;/button&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code>app.directive('focusMe', function($timeout) { return { scope: { trigger: '=focusMe' }, link: function(scope, element) { scope.$watch('trigger', function(value) { if(value === true) { //console.log('trigger',value); //$timeout(function() { element[0].focus(); scope.trigger = false; //}); } }); } }; }); </code></pre> <p><a href="http://plnkr.co/edit/gmaQCl?p=preview" rel="noreferrer">Plunker</a>.</p> <p>Since we need to reset the trigger/focusInput property in the directive, '=' is used for two-way databinding. In the first directive, '@' was sufficient. Also note that when using '@' we compare the trigger value to "true" since @ always results in a string.</p>
{ "question_id": 14833326, "question_date": "2013-02-12T13:08:52.773Z", "question_score": 772, "tags": "angularjs|angularjs-directive", "answer_id": 14837021, "answer_date": "2013-02-12T16:23:14.677Z", "answer_score": 591 }
Please answer the following Stack Overflow question: Title: How do you handle multiple submit buttons in ASP.NET MVC Framework? <p>Is there some easy way to handle multiple submit buttons from the same form? For example:</p> <pre><code>&lt;% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %&gt; &lt;input type="submit" value="Send" /&gt; &lt;input type="submit" value="Cancel" /&gt; &lt;% Html.EndForm(); %&gt; </code></pre> <p>Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them.</p>
<p>Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from <a href="http://blog.maartenballiauw.be/post/2009/11/26/supporting-multiple-submit-buttons-on-an-aspnet-mvc-view.aspx" rel="noreferrer">Maarten Balliauw</a>.</p> <pre><code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class MultipleButtonAttribute : ActionNameSelectorAttribute { public string Name { get; set; } public string Argument { get; set; } public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { var isValidName = false; var keyValue = string.Format("{0}:{1}", Name, Argument); var value = controllerContext.Controller.ValueProvider.GetValue(keyValue); if (value != null) { controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument; isValidName = true; } return isValidName; } } </code></pre> <p>razor:</p> <pre><code>&lt;form action="" method="post"&gt; &lt;input type="submit" value="Save" name="action:Save" /&gt; &lt;input type="submit" value="Cancel" name="action:Cancel" /&gt; &lt;/form&gt; </code></pre> <p>and controller:</p> <pre><code>[HttpPost] [MultipleButton(Name = "action", Argument = "Save")] public ActionResult Save(MessageModel mm) { ... } [HttpPost] [MultipleButton(Name = "action", Argument = "Cancel")] public ActionResult Cancel(MessageModel mm) { ... } </code></pre> <p><em>Update:</em> <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/#using-multiple-handlers" rel="noreferrer">Razor pages</a> looks to provide the same functionality out of the box. For new development, it may be preferable.</p>
{ "question_id": 442704, "question_date": "2009-01-14T11:58:36.140Z", "question_score": 772, "tags": "c#|html|asp.net-mvc|http-post|form-submit", "answer_id": 7111222, "answer_date": "2011-08-18T17:00:22.800Z", "answer_score": 661 }
Please answer the following Stack Overflow question: Title: How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)? <p>I have this in my package.json file (shortened version):</p> <pre><code>{ "name": "a-module", "version": "0.0.1", "dependencies": { "coffee-script": "&gt;= 1.1.3" }, "devDependencies": { "stylus": "&gt;= 0.17.0" } } </code></pre> <p>I am using NPM version 1.1.1 on Mac 10.6.8.</p> <p>When I run the following command from the project root, it installs both the <code>dependencies</code> <em>and</em> <code>devDependencies</code>:</p> <pre><code>npm install </code></pre> <p>I was under the impression that this command installed the <code>devDependencies</code>:</p> <pre><code>npm install --dev </code></pre> <p>How do I make it so <code>npm install</code> only installs <code>dependencies</code> (so production environment only gets those modules), while something like <code>npm install --dev</code> installs both <code>dependencies</code> and <code>devDependencies</code>?</p>
<p>The <code>npm install</code> command will install the <code>devDependencies</code> along other <code>dependencies</code> when run inside a package directory, in a development environment (the default).</p> <p>In version 8.x and above use <a href="https://docs.npmjs.com/cli/v8/commands/npm-install#omit" rel="noreferrer"><code>--omit=dev</code></a> flag to install only regular dependencies:</p> <pre><code>npm install --omit=dev </code></pre> <p>This will install <strong>only</strong> <code>dependencies</code>, and not <code>devDependencies</code>, regardless of the value of the <code>NODE_ENV</code> environment variable.</p> <p>If you use 6.x or an earlier version, you need to use the <code>--only=prod</code> flag instead.</p> <p><strong>Note:</strong><br /> Before v3.3.0 of npm (2015-08-13), the option was called <code>--production</code>, i.e.</p> <pre><code>npm install --production </code></pre> <p>You may also need <code>--no-optional</code> flag.</p>
{ "question_id": 9268259, "question_date": "2012-02-13T21:25:10.277Z", "question_score": 772, "tags": "node.js|npm", "answer_id": 9276112, "answer_date": "2012-02-14T11:33:28.260Z", "answer_score": 1167 }
Please answer the following Stack Overflow question: Title: What is the volatile keyword useful for? <p>At work today, I came across the <code>volatile</code> keyword in Java. Not being very familiar with it, I found <a href="http://web.archive.org/web/20210221170926/https://www.ibm.com/developerworks/java/library/j-jtp06197/" rel="noreferrer">this explanation</a>.</p> <p>Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?</p>
<p><code>volatile</code> has semantics for memory visibility. Basically, the value of a <code>volatile</code> field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without <code>volatile</code>, readers could see some non-updated value.</p> <p>To answer your question: Yes, I use a <code>volatile</code> variable to control whether some code continues a loop. The loop tests the <code>volatile</code> value and continues if it is <code>true</code>. The condition can be set to <code>false</code> by calling a "stop" method. The loop sees <code>false</code> and terminates when it tests the value after the stop method completes execution.</p> <p>The book "<a href="http://jcip.net" rel="noreferrer">Java Concurrency in Practice</a>," which I highly recommend, gives a good explanation of <code>volatile</code>. This book is written by the same person who wrote the IBM article that is referenced in the question (in fact, he cites his book at the bottom of that article). My use of <code>volatile</code> is what his article calls the "pattern 1 status flag."</p> <p>If you want to learn more about how <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.4" rel="noreferrer"><code>volatile</code></a> works under the hood, read up on <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html" rel="noreferrer">the Java memory model</a>. If you want to go beyond that level, check out a good computer architecture book like <a href="https://www.elsevier.com/books/computer-architecture/hennessy/978-0-12-383872-8" rel="noreferrer">Hennessy &amp; Patterson</a> and read about cache coherence and cache consistency.</p>
{ "question_id": 106591, "question_date": "2008-09-20T00:41:02.267Z", "question_score": 772, "tags": "java|multithreading|keyword|volatile", "answer_id": 106787, "answer_date": "2008-09-20T02:09:51.007Z", "answer_score": 837 }
Please answer the following Stack Overflow question: Title: Fixed position but relative to container <p>I am trying to fix a <code>div</code> so it always sticks to the top of the screen, using:</p> <pre><code>position: fixed; top: 0px; right: 0px; </code></pre> <p>However, the <code>div</code> is inside a centered container. When I use <code>position:fixed</code> it fixes the <code>div</code> relative to the browser window, such as it's up against the right side of the browser. Instead, it should be fixed relative to the container.</p> <p>I know that <code>position:absolute</code> can be used to fix an element relative to the <code>div</code>, but when you scroll down the page the element vanishes and doesn't stick to the top as with <code>position:fixed</code>.</p> <p>Is there a hack or workaround to achieve this?</p>
<p>Short answer: <s>no.</s> (It is now possible with CSS transform. See the edit below)</p> <p>Long answer: The problem with using &quot;fixed&quot; positioning is that it takes the element <strong>out of flow</strong>. thus it can't be re-positioned relative to its parent because it's as if it didn't have one. If, however, the container is of a fixed, known width, you can use something like:</p> <pre><code>#fixedContainer { position: fixed; width: 600px; height: 200px; left: 50%; top: 0%; margin-left: -300px; /*half the width*/ } </code></pre> <p><a href="http://jsfiddle.net/HFjU6/1/" rel="noreferrer">http://jsfiddle.net/HFjU6/1/</a></p> <h3>Edit (03/2015):</h3> <p>This is outdated information. It is now possible to center content of an dynamic size (horizontally and vertically) with the help of the magic of CSS3 transform. The same principle applies, but instead of using margin to offset your container, you can use <code>translateX(-50%)</code>. This doesn't work with the above margin trick because you don't know how much to offset it unless the width is fixed and you can't use relative values (like <code>50%</code>) because it will be relative to the parent and not the element it's applied to. <code>transform</code> behaves differently. Its values are relative to the element they are applied to. Thus, <code>50%</code> for <code>transform</code> means half the width of the element, while <code>50%</code> for margin is half of the parent's width. This is an <a href="http://caniuse.com/#feat=transforms2d" rel="noreferrer">IE9+ solution</a></p> <p>Using similar code to the above example, I recreated the same scenario using completely dynamic width and height:</p> <pre><code>.fixedContainer { background-color:#ddd; position: fixed; padding: 2em; left: 50%; top: 0%; transform: translateX(-50%); } </code></pre> <p>If you want it to be centered, you can do that too:</p> <pre><code>.fixedContainer { background-color:#ddd; position: fixed; padding: 2em; left: 50%; top: 50%; transform: translate(-50%, -50%); } </code></pre> <h3>Demos:</h3> <p><a href="http://jsfiddle.net/b2jz1yvr/" rel="noreferrer">jsFiddle: Centered horizontally only</a><br/> <a href="http://jsfiddle.net/b2jz1yvr/1/" rel="noreferrer">jsFiddle: Centered both horizontally and vertically</a> <br/>Original credit goes to user <a href="https://stackoverflow.com/users/1387396/aaronk6">aaronk6</a> for pointing it out to me in <a href="https://stackoverflow.com/a/28773941/854246">this answer</a></p>
{ "question_id": 6794000, "question_date": "2011-07-22T17:47:00.717Z", "question_score": 771, "tags": "css|position|css-position|fixed", "answer_id": 6794097, "answer_date": "2011-07-22T17:55:45.563Z", "answer_score": 478 }
Please answer the following Stack Overflow question: Title: Converting ISO 8601-compliant String to java.util.Date <p>I am trying to convert an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> formatted String to a <code>java.util.Date</code>. </p> <p>I found the pattern <code>yyyy-MM-dd'T'HH:mm:ssZ</code> to be ISO8601-compliant if used with a Locale (compare sample).</p> <p>However, using the <code>java.text.SimpleDateFormat</code>, I cannot convert the correctly formatted String <code>2010-01-01T12:00:00+01:00</code>. I have to convert it first to <code>2010-01-01T12:00:00+0100</code>, without the colon. </p> <p>So, the current solution is</p> <pre class="lang-java prettyprint-override"><code>SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY); String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100"); System.out.println(ISO8601DATEFORMAT.parse(date)); </code></pre> <p>which obviously isn't that nice. Am I missing something or is there a better solution?</p> <hr> <p><strong>Answer</strong></p> <p>Thanks to JuanZe's comment, I found the <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> magic, it is also <a href="http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html" rel="noreferrer">described here</a>.</p> <p>So, the solution is</p> <pre class="lang-java prettyprint-override"><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); String jtdate = "2010-01-01T12:00:00+01:00"; System.out.println(parser2.parseDateTime(jtdate)); </code></pre> <p>Or more simply, use the default parser via the constructor:</p> <pre class="lang-java prettyprint-override"><code>DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ; </code></pre> <p>To me, this is nice.</p>
<p>Unfortunately, the time zone formats available to <a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="nofollow noreferrer">SimpleDateFormat</a> (Java 6 and earlier) are not <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer">ISO 8601</a> compliant. SimpleDateFormat understands time zone strings like &quot;GMT+01:00&quot; or &quot;+0100&quot;, the latter according to <a href="http://www.ietf.org/rfc/rfc0822.txt" rel="nofollow noreferrer" title="STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES">RFC # 822</a>.</p> <p>Even if Java 7 added support for time zone descriptors according to ISO 8601, SimpleDateFormat is still not able to properly parse a complete date string, as it has no support for optional parts.</p> <p>Reformatting your input string using regexp is certainly one possibility, but the replacement rules are not as simple as in your question:</p> <ul> <li>Some time zones are not full hours off <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time" rel="nofollow noreferrer">UTC</a>, so the string does not necessarily end with &quot;:00&quot;.</li> <li>ISO8601 allows only the number of hours to be included in the time zone, so &quot;+01&quot; is equivalent to &quot;+01:00&quot;</li> <li>ISO8601 allows the usage of &quot;Z&quot; to indicate UTC instead of &quot;+00:00&quot;.</li> </ul> <p>The easier solution is possibly to use the data type converter in JAXB, since JAXB must be able to parse ISO8601 date string according to the XML Schema specification. <code>javax.xml.bind.DatatypeConverter.parseDateTime(&quot;2010-01-01T12:00:00Z&quot;)</code> will give you a <code>Calendar</code> object and you can simply use getTime() on it, if you need a <code>Date</code> object.</p> <p>You could probably use <a href="http://www.joda.org/joda-time/" rel="nofollow noreferrer">Joda-Time</a> as well, but I don't know why you should bother with that (Update 2022; maybe because the entire <code>javax.xml.bind</code> section is missing from Android's <code>javax.xml</code> package).</p>
{ "question_id": 2201925, "question_date": "2010-02-04T17:52:39.783Z", "question_score": 771, "tags": "java|date|iso8601", "answer_id": 2202300, "answer_date": "2010-02-04T18:51:52.583Z", "answer_score": 507 }
Please answer the following Stack Overflow question: Title: How can I temporarily disable a foreign key constraint in MySQL? <p>Is it possible to temporarily disable constraints in MySQL?</p> <p>I have two Django models, each with a foreign key to the other one. Deleting instances of a model returns an error because of the foreign key constraint:</p> <pre><code>cursor.execute(&quot;DELETE FROM myapp_item WHERE n = %s&quot;, n) transaction.commit_unless_managed() #a foreign key constraint fails here cursor.execute(&quot;DELETE FROM myapp_style WHERE n = %s&quot;, n) transaction.commit_unless_managed() </code></pre> <p>Is it possible to temporarily disable constraints and delete anyway?</p>
<p>Try <code>DISABLE KEYS</code> or</p> <pre><code>SET FOREIGN_KEY_CHECKS=0; </code></pre> <p>Make sure to</p> <pre><code>SET FOREIGN_KEY_CHECKS=1; </code></pre> <p>after.</p>
{ "question_id": 15501673, "question_date": "2013-03-19T14:03:58.643Z", "question_score": 771, "tags": "mysql|sql|django|django-models", "answer_id": 15501754, "answer_date": "2013-03-19T14:07:45.653Z", "answer_score": 1673 }
Please answer the following Stack Overflow question: Title: How to apply multiple transforms in CSS? <p>Using CSS, how can I apply more than one <code>transform</code>?</p> <p>Example: In the following, only the translation is applied, not the rotation.</p> <pre><code>li:nth-child(2) { transform: rotate(15deg); transform: translate(-20px,0px); } </code></pre>
<p>You have to put them on one line like this:</p> <pre><code>li:nth-child(2) { transform: rotate(15deg) translate(-20px,0px); } </code></pre> <p>When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.</p> <hr> <p>Keep in mind multiple transform one line directives are <strong><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform#Values" rel="noreferrer">applied from right to left</a></strong>.</p> <p>This: <code>transform: scale(1,1.5) rotate(90deg);</code><br> and: <code>transform: rotate(90deg) scale(1,1.5);</code></p> <p>will <strong>not</strong> produce the same result:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.orderOne, .orderTwo { font-family: sans-serif; font-size: 22px; color: #000; display: inline-block; } .orderOne { transform: scale(1, 1.5) rotate(90deg); } .orderTwo { transform: rotate(90deg) scale(1, 1.5); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="orderOne"&gt; A &lt;/div&gt; &lt;div class="orderTwo"&gt; A &lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 10765755, "question_date": "2012-05-26T11:15:52.880Z", "question_score": 771, "tags": "css|css-transforms", "answer_id": 10765771, "answer_date": "2012-05-26T11:17:42.260Z", "answer_score": 1285 }
Please answer the following Stack Overflow question: Title: What is the Python equivalent of static variables inside a function? <p>What is the idiomatic Python equivalent of this C/C++ code?</p> <pre class="lang-cpp prettyprint-override"><code>void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } </code></pre> <p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
<p>A bit reversed, but this should work:</p> <pre><code>def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 </code></pre> <p>If you want the counter initialization code at the top instead of the bottom, you can create a decorator:</p> <pre><code>def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate </code></pre> <p>Then use the code like this:</p> <pre><code>@static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter </code></pre> <p>It'll still require you to use the <code>foo.</code> prefix, unfortunately.</p> <p><sup>(Credit: <a href="https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586">@ony</a>)</sup></p>
{ "question_id": 279561, "question_date": "2008-11-10T23:33:36.373Z", "question_score": 771, "tags": "python|static", "answer_id": 279586, "answer_date": "2008-11-10T23:46:00.920Z", "answer_score": 813 }
Please answer the following Stack Overflow question: Title: How do I convert from int to String? <p>I'm working on a project where all conversions from <code>int</code> to <code>String</code> are done like this:</p> <pre><code>int i = 5; String strI = "" + i; </code></pre> <p>I'm not familiar with Java. </p> <p>Is this usual practice or is something wrong, as I suppose?</p>
<p>Normal ways would be <code>Integer.toString(i)</code> or <code>String.valueOf(i)</code>.</p> <p>The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).</p> <p>Java has special support for the + operator when used with strings (see <a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html" rel="noreferrer">the documentation</a>) which translates the code you posted into:</p> <pre><code>StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(i); String strI = sb.toString(); </code></pre> <p>at compile-time. It's slightly less efficient (<code>sb.append()</code> ends up calling <code>Integer.getChars()</code>, which is what <code>Integer.toString()</code> would've done anyway), but it works.</p> <p>To answer Grodriguez's comment: ** No, the compiler <em>doesn't</em> optimise out the empty string in this case - look:</p> <pre><code>simon@lucifer:~$ cat TestClass.java public class TestClass { public static void main(String[] args) { int i = 5; String strI = "" + i; } } simon@lucifer:~$ javac TestClass.java &amp;&amp; javap -c TestClass Compiled from "TestClass.java" public class TestClass extends java.lang.Object{ public TestClass(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."&lt;init&gt;":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_5 1: istore_1 </code></pre> <p>Initialise the StringBuilder:</p> <pre><code> 2: new #2; //class java/lang/StringBuilder 5: dup 6: invokespecial #3; //Method java/lang/StringBuilder."&lt;init&gt;":()V </code></pre> <p>Append the empty string:</p> <pre><code> 9: ldc #4; //String 11: invokevirtual #5; //Method java/lang/StringBuilder.append: (Ljava/lang/String;)Ljava/lang/StringBuilder; </code></pre> <p>Append the integer:</p> <pre><code> 14: iload_1 15: invokevirtual #6; //Method java/lang/StringBuilder.append: (I)Ljava/lang/StringBuilder; </code></pre> <p>Extract the final string:</p> <pre><code> 18: invokevirtual #7; //Method java/lang/StringBuilder.toString: ()Ljava/lang/String; 21: astore_2 22: return } </code></pre> <p>There's <a href="https://bugs.openjdk.java.net/browse/JDK-8085796" rel="noreferrer">a proposal</a> and ongoing work to change this behaviour, targetted for JDK&nbsp;9.</p>
{ "question_id": 4105331, "question_date": "2010-11-05T11:11:21.600Z", "question_score": 770, "tags": "java|string|type-conversion", "answer_id": 4105406, "answer_date": "2010-11-05T11:22:19.270Z", "answer_score": 975 }
Please answer the following Stack Overflow question: Title: How can I convert String to Int? <p>I have a <code>TextBoxD1.Text</code> and I want to convert it to an <code>int</code> to store it in a database. </p> <p>How can I do this?</p>
<p>Try this:</p> <pre><code>int x = Int32.Parse(TextBoxD1.Text); </code></pre> <p>or better yet:</p> <pre><code>int x = 0; Int32.TryParse(TextBoxD1.Text, out x); </code></pre> <p>Also, since <a href="http://msdn.microsoft.com/en-us/library/f02979c7.aspx" rel="noreferrer"><code>Int32.TryParse</code></a> returns a <code>bool</code> you can use its return value to make decisions about the results of the parsing attempt:</p> <pre><code>int x = 0; if (Int32.TryParse(TextBoxD1.Text, out x)) { // you know that the parsing attempt // was successful } </code></pre> <p>If you are curious, the difference between <code>Parse</code> and <code>TryParse</code> is best summed up like this:</p> <blockquote> <p>The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed. - <a href="http://msdn.microsoft.com/en-us/library/f02979c7.aspx" rel="noreferrer">MSDN</a></p> </blockquote>
{ "question_id": 1019793, "question_date": "2009-06-19T20:02:43.877Z", "question_score": 770, "tags": "c#|.net|string|int|type-conversion", "answer_id": 1019804, "answer_date": "2009-06-19T20:04:50.673Z", "answer_score": 1222 }
Please answer the following Stack Overflow question: Title: How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java? <p>The code below gives me the current time. But it does not tell anything about milliseconds.</p> <pre><code>public static String getCurrentTimeStamp() { SimpleDateFormat sdfDate = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;);//dd/MM/yyyy Date now = new Date(); String strDate = sdfDate.format(now); return strDate; } </code></pre> <p>I have a date in the format <code>YYYY-MM-DD HH:MM:SS</code> (<code>2009-09-22 16:47:08</code>).</p> <p>But I want to retrieve the current time in the format <code>YYYY-MM-DD HH:MM:SS.MS</code> (<code>2009-09-22 16:47:08.128</code>, where <code>128</code> are the milliseconds).</p> <p><code>SimpleTextFormat</code> will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?</p>
<pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); </code></pre>
{ "question_id": 1459656, "question_date": "2009-09-22T12:00:50.140Z", "question_score": 770, "tags": "java|date", "answer_id": 1459683, "answer_date": "2009-09-22T12:05:42.050Z", "answer_score": 1176 }
Please answer the following Stack Overflow question: Title: Fastest method to replace all instances of a character in a string <p>What is the fastest way to replace all instances of a string/character in a string in JavaScript? A <code>while</code>, a <code>for</code>-loop, a regular expression?</p>
<p>The easiest would be to use a regular expression with <code>g</code> flag to replace all instances:</p> <pre><code>str.replace(/foo/g, "bar") </code></pre> <p>This will replace all occurrences of <code>foo</code> with <code>bar</code> in the string <code>str</code>. If you just have a string, you can convert it to a RegExp object like this:</p> <pre><code>var pattern = "foobar", re = new RegExp(pattern, "g"); </code></pre>
{ "question_id": 2116558, "question_date": "2010-01-22T10:26:06.543Z", "question_score": 770, "tags": "javascript|string|replace", "answer_id": 2116614, "answer_date": "2010-01-22T10:33:38.540Z", "answer_score": 1264 }
Please answer the following Stack Overflow question: Title: Best practice for instantiating a new Android Fragment <p>I have seen two general practices to instantiate a new Fragment in an application:</p> <pre><code>Fragment newFragment = new MyFragment(); </code></pre> <p>and</p> <pre><code>Fragment newFragment = MyFragment.newInstance(); </code></pre> <p>The second option makes use of a static method <code>newInstance()</code> and <em>generally</em> contains the following method.</p> <pre><code>public static Fragment newInstance() { MyFragment myFragment = new MyFragment(); return myFragment; } </code></pre> <p>At first, I thought the main benefit was the fact that I could overload the newInstance() method to give flexibility when creating new instances of a Fragment - but I could also do this by creating an overloaded constructor for the Fragment.</p> <p>Did I miss something?</p> <p>What are the benefits of one approach over the other? Or is it just good practice?</p>
<p>If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.</p> <p>With that being said, the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the <code>setArguments</code> method.</p> <p>So, for example, if we wanted to pass an integer to the fragment we would use something like:</p> <pre><code>public static MyFragment newInstance(int someInt) { MyFragment myFragment = new MyFragment(); Bundle args = new Bundle(); args.putInt("someInt", someInt); myFragment.setArguments(args); return myFragment; } </code></pre> <p>And later in the Fragment <code>onCreate()</code> you can access that integer by using:</p> <pre><code>getArguments().getInt("someInt", 0); </code></pre> <p>This Bundle will be available even if the Fragment is somehow recreated by Android.</p> <p>Also note: <code>setArguments</code> can only be called before the Fragment is attached to the Activity.</p> <p>This approach is also documented in the android developer reference: <a href="https://developer.android.com/reference/android/app/Fragment.html" rel="noreferrer">https://developer.android.com/reference/android/app/Fragment.html</a></p>
{ "question_id": 9245408, "question_date": "2012-02-12T00:42:11.737Z", "question_score": 770, "tags": "android|android-fragments", "answer_id": 9245510, "answer_date": "2012-02-12T00:57:55.530Z", "answer_score": 1243 }
Please answer the following Stack Overflow question: Title: What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition? <p>I am going through some blogs on SpringSource and in one of the blogs, author is using <code>@Inject</code> and I suppose he can also use <code>@Autowired</code>.</p> <p>Here is the piece of code:</p> <p><code>@Inject private CustomerOrderService customerOrderService;</code></p> <p>I am not sure about the difference between <code>@Inject</code> and <code>@Autowired</code> and would appreciate it if someone explained their difference and which one to use under what situation?</p>
<p>Assuming here you're referring to the <a href="http://download.oracle.com/javaee/6/api/javax/inject/Inject.html" rel="noreferrer"><code>javax.inject.Inject</code></a> annotation. <code>@Inject</code> is part of the Java CDI (<a href="http://docs.oracle.com/javaee/6/tutorial/doc/giwhb.html" rel="noreferrer">Contexts and Dependency Injection</a>) standard introduced in Java EE 6 (JSR-299), <a href="http://www.oracle.com/technetwork/articles/javaee/javaee6overview-141808.html" rel="noreferrer">read more</a>. Spring has chosen to support using the <code>@Inject</code> annotation synonymously with their own <code>@Autowired</code> annotation.</p> <p>So, to answer your question, <code>@Autowired</code> is Spring's own annotation. <code>@Inject</code> is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.</p>
{ "question_id": 7142622, "question_date": "2011-08-22T02:30:42.117Z", "question_score": 770, "tags": "java|spring|dependency-injection|autowired|inject", "answer_id": 7144137, "answer_date": "2011-08-22T07:08:15.090Z", "answer_score": 801 }
Please answer the following Stack Overflow question: Title: How to grep Git commit diffs or contents for a certain word <p>In a Git code repository I want to list all commits that contain a certain word. I tried this</p> <pre class="lang-sh prettyprint-override"><code>git log -p | grep --context=4 &quot;word&quot; </code></pre> <p>but it does not necessarily give me back the filename (unless it's less that five lines away from the word I searched for. I also tried</p> <pre class="lang-sh prettyprint-override"><code>git grep &quot;word&quot; </code></pre> <p>but it gives me only present files and not the history.</p> <p>How do I search the entire history so I can follow changes on a particular word? I intend to search my codebase for occurrences of word to track down changes (search in files history).</p>
<p>If you want to find all commits where the <em>commit message</em> contains a given word, use</p> <pre><code>$ git log --grep=word </code></pre> <p>If you want to find all commits where &quot;word&quot; was added or removed in the <em>file contents</em> (to be more exact: where the number of occurrences of &quot;word&quot; changed), i.e., search the <em>commit contents</em>, use a so-called 'pickaxe' search with</p> <pre><code>$ git log -Sword </code></pre> <p>In modern Git there is also</p> <pre><code>$ git log -Gword </code></pre> <p>to look for <em>differences</em> whose added or removed line matches &quot;word&quot; (also <em>commit contents</em>).</p> <p>A few things to note:</p> <ul> <li><code>-G</code> by default accepts a regex, while <code>-S</code> accepts a string, but it can be modified to accept regexes using the <code>--pickaxe-regex</code>.</li> <li><code>-S</code> finds commits where the number of occurrences of &quot;word&quot; changed, while <code>-G</code> finds commits where &quot;word&quot; appears in the diff.</li> <li>This means that <code>-S&lt;regex&gt; --pickaxe-regex</code> and <code>-G&lt;regex&gt;</code> do not do exactly the same thing.</li> </ul> <p>The <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code> documentation</a> has <a href="https://github.com/git/git/blob/9299f84921e0bd076cf998aa852fadb73627756f/Documentation/diff-options.txt#L565-L577" rel="noreferrer">a nice explanation</a> of the difference:</p> <blockquote> <p>To illustrate the difference between <code>-S&lt;regex&gt; --pickaxe-regex</code> and <code>-G&lt;regex&gt;</code>, consider a commit with the following diff in the same file:</p> <pre><code>+ return frotz(nitfol, two-&gt;ptr, 1, 0); ... - hit = frotz(nitfol, mf2.ptr, 1, 0); </code></pre> <p>While <code>git log -G&quot;frotz\(nitfol&quot;</code> will show this commit, <code>git log -S&quot;frotz\(nitfol&quot; --pickaxe-regex</code> will not (because the number of occurrences of that string did not change).</p> </blockquote>
{ "question_id": 1337320, "question_date": "2009-08-26T20:34:55.617Z", "question_score": 770, "tags": "git|search|grep", "answer_id": 1340245, "answer_date": "2009-08-27T10:41:39.983Z", "answer_score": 1114 }
Please answer the following Stack Overflow question: Title: How to create a zip archive of a directory? <p>How can I create a zip archive of a directory structure in Python?</p>
<p>As others have pointed out, you should use <a href="http://docs.python.org/library/zipfile.html" rel="noreferrer">zipfile</a>. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:</p> <pre class="lang-py prettyprint-override"><code>import os import zipfile def zipdir(path, ziph): # ziph is zipfile handle for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..'))) with zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED) as zipf: zipdir('tmp/', zipf) </code></pre>
{ "question_id": 1855095, "question_date": "2009-12-06T11:12:53.907Z", "question_score": 769, "tags": "python|zip|archive|python-zipfile", "answer_id": 1855118, "answer_date": "2009-12-06T11:23:55.163Z", "answer_score": 680 }
Please answer the following Stack Overflow question: Title: In C#, should I use string.Empty or String.Empty or "" to intitialize a string? <p>In C#, I want to initialize a string value with an empty string.</p> <p>How should I do this? What is the right way, and why?</p> <pre><code>string willi = string.Empty; </code></pre> <p>or</p> <pre><code>string willi = String.Empty; </code></pre> <p>or</p> <pre><code>string willi = ""; </code></pre> <p>or what?</p>
<p><strong>Use whatever you and your team find the most readable.</strong></p> <p>Other answers have suggested that a new string is created every time you use <code>""</code>. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, <em>massively</em> insignificant.</p> <p>Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find <code>""</code> easier to read.</p> <p>The argument that <code>""</code> and <code>" "</code> are easily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with <em>any</em> developers who do) it's pretty easy to tell the difference.</p>
{ "question_id": 263191, "question_date": "2008-11-04T19:49:02.973Z", "question_score": 769, "tags": "c#|.net|string|initialization", "answer_id": 263257, "answer_date": "2008-11-04T20:07:39.567Z", "answer_score": 860 }
Please answer the following Stack Overflow question: Title: How to read all files in a folder from Java? <p>How to read all the files in a folder through Java? It doesn't matter which API.</p>
<pre><code>public void listFilesForFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { System.out.println(fileEntry.getName()); } } } final File folder = new File("/home/you/Desktop"); listFilesForFolder(folder); </code></pre> <p><a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-" rel="noreferrer">Files.walk</a> API is available from Java 8.</p> <pre><code>try (Stream&lt;Path&gt; paths = Files.walk(Paths.get("/home/you/Desktop"))) { paths .filter(Files::isRegularFile) .forEach(System.out::println); } </code></pre> <p>The example uses <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="noreferrer">try-with-resources</a> pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.</p>
{ "question_id": 1844688, "question_date": "2009-12-04T03:39:37.567Z", "question_score": 768, "tags": "java|file|io|directory", "answer_id": 1846349, "answer_date": "2009-12-04T11:21:06.897Z", "answer_score": 1109 }
Please answer the following Stack Overflow question: Title: Pushing to Git returning Error Code 403 fatal: HTTP request failed <p>I was able to clone a copy of this repo over HTTPS authenticated. I've made some commits and want to push back out to the GitHub server. Using Cygwin on Windows 7 x64.</p> <pre><code>C:\cygwin\home\XPherior\Code\lunch_call&gt;git push Password: error: The requested URL returned error: 403 while accessing https://MichaelDrog [email protected]/derekerdmann/lunch_call.git/info/refs fatal: HTTP request failed </code></pre> <p>Also set it up with verbose mode. I'm still pretty baffled.</p> <pre><code>C:\cygwin\home\XPherior\Code\lunch_call&gt;set GIT_CURL_VERBOSE=1 C:\cygwin\home\XPherior\Code\lunch_call&gt;git push Password: * Couldn't find host github.com in the _netrc file; using defaults * About to connect() to github.com port 443 (#0) * Trying 207.97.227.239... * 0x23cb740 is at send pipe head! * Connected to github.com (207.97.227.239) port 443 (#0) * successfully set certificate verify locations: * CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt CApath: none * SSL connection using AES256-SHA * Server certificate: * subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1. 3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L =San Francisco; O=GitHub, Inc.; CN=github.com * start date: 2011-05-27 00:00:00 GMT * expire date: 2013-07-29 12:00:00 GMT * subjectAltName: github.com matched * issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass urance EV CA-1 * SSL certificate verify ok. &gt; GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1 User-Agent: git/1.7.4.3282.g844cb Host: github.com Accept: */* Pragma: no-cache &lt; HTTP/1.1 401 Authorization Required &lt; Server: nginx/1.0.4 &lt; Date: Thu, 15 Sep 2011 22:44:41 GMT &lt; Content-Type: text/plain &lt; Connection: keep-alive &lt; Content-Length: 55 &lt; WWW-Authenticate: Basic realm="GitHub" &lt; * Ignoring the response-body * Expire cleared * Connection #0 to host github.com left intact * Issue another request to this URL: 'https://[email protected]/dereker dmann/lunch_call.git/info/refs?service=git-receive-pack' * Couldn't find host github.com in the _netrc file; using defaults * Re-using existing connection! (#0) with host github.com * Connected to github.com (207.97.227.239) port 443 (#0) * 0x23cb740 is at send pipe head! * Server auth using Basic with user 'MichaelDrogalis' &gt; GET /derekerdmann/lunch_call.git/info/refs?service=git-receive-pack HTTP/1.1 Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX User-Agent: git/1.7.4.3282.g844cb Host: github.com Accept: */* Pragma: no-cache &lt; HTTP/1.1 401 Authorization Required &lt; Server: nginx/1.0.4 &lt; Date: Thu, 15 Sep 2011 22:44:41 GMT &lt; Content-Type: text/plain &lt; Connection: keep-alive &lt; Content-Length: 55 * Authentication problem. Ignoring this. &lt; WWW-Authenticate: Basic realm="GitHub" * The requested URL returned error: 401 * Closing connection #0 * Couldn't find host github.com in the _netrc file; using defaults * About to connect() to github.com port 443 (#0) * Trying 207.97.227.239... * 0x23cb740 is at send pipe head! * Connected to github.com (207.97.227.239) port 443 (#0) * successfully set certificate verify locations: * CAfile: C:\Program Files (x86)\Git/bin/curl-ca-bundle.crt CApath: none * SSL re-using session ID * SSL connection using AES256-SHA * old SSL session ID is stale, removing * Server certificate: * subject: 2.5.4.15=Private Organization; 1.3.6.1.4.1.311.60.2.1.3=US; 1. 3.6.1.4.1.311.60.2.1.2=California; serialNumber=C3268102; C=US; ST=California; L =San Francisco; O=GitHub, Inc.; CN=github.com * start date: 2011-05-27 00:00:00 GMT * expire date: 2013-07-29 12:00:00 GMT * subjectAltName: github.com matched * issuer: C=US; O=DigiCert Inc; OU=www.digicert.com; CN=DigiCert High Ass urance EV CA-1 * SSL certificate verify ok. * Server auth using Basic with user 'MichaelDrogalis' &gt; GET /derekerdmann/lunch_call.git/info/refs HTTP/1.1 Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx User-Agent: git/1.7.4.3282.g844cb Host: github.com Accept: */* Pragma: no-cache * The requested URL returned error: 403 * Expire cleared * Closing connection #0 error: The requested URL returned error: 403 while accessing https://MichaelDrog [email protected]/derekerdmann/lunch_call.git/info/refs fatal: HTTP request failed </code></pre> <p>These are the versions of git and curl that I have:</p> <pre><code>C:\Users\XPherior&gt;git --version git version 1.7.4.msysgit.0 C:\Users\XPherior&gt;curl --version curl 7.21.7 (amd64-pc-win32) libcurl/7.21.7 OpenSSL/0.9.8r zlib/1.2.5 Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp smtp smtps telnet tftp Features: AsynchDNS GSS-Negotiate Largefile NTLM SSL SSPI libz </code></pre>
<p>I just got the same problem and just figured out what's cause.</p> <p>Github seems only supports ssh way to read&amp;write the repo, although https way also displayed 'Read&amp;Write'.</p> <p>So you need to change your repo config on your PC to ssh way:</p> <ol> <li>Edit <code>.git/config</code> file under your repo directory.</li> <li>Find <code>url=</code>entry under section <code>[remote &quot;origin&quot;]</code>.</li> <li>Change it from:<br /> <code>url=https://[email protected]/derekerdmann/lunch_call.git</code><br /> to:<br /> <code>url=ssh://[email protected]/derekerdmann/lunch_call.git</code><br /> That is, change all the texts before <code>@</code> symbol to <code>ssh://git</code></li> <li>Save <code>config</code> file and quit. now you could use <code>git push origin master</code> to sync your repo on GitHub.</li> </ol>
{ "question_id": 7438313, "question_date": "2011-09-15T22:45:59.773Z", "question_score": 768, "tags": "git|github|dvcs", "answer_id": 7771927, "answer_date": "2011-10-14T18:26:33.860Z", "answer_score": 948 }
Please answer the following Stack Overflow question: Title: MySQL Error 1093 - Can't specify target table for update in FROM clause <p>I have a table <code>story_category</code> in my database with corrupt entries. The next query returns the corrupt entries:</p> <pre><code>SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); </code></pre> <p>I tried to delete them executing:</p> <pre><code>DELETE FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); </code></pre> <p>But I get the next error: </p> <blockquote> <p>#1093 - You can't specify target table 'story_category' for update in FROM clause </p> </blockquote> <p>How can I overcome this?</p>
<p><em>Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question</em></p> <p>In MySQL, you can't modify the same table which you use in the SELECT part.<br> This behaviour is documented at: <a href="http://dev.mysql.com/doc/refman/5.6/en/update.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.6/en/update.html</a></p> <p><strong>Maybe you can just join the table to itself</strong></p> <p>If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.</p> <pre><code>UPDATE tbl AS a INNER JOIN tbl AS b ON .... SET a.col = b.col </code></pre> <p><strong>Alternatively, try nesting the subquery deeper into a from clause ...</strong></p> <p>If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance:</p> <pre><code>UPDATE tbl SET col = ( SELECT ... FROM (SELECT.... FROM) AS x); </code></pre> <p>The nested subquery in the FROM clause creates an <em>implicit temporary table</em>, so it doesn't count as the same table you're updating. </p> <p><strong>... but watch out for the query optimiser</strong></p> <p>However, beware that from <a href="http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html" rel="noreferrer">MySQL 5.7.6</a> and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the <code>optimizer_switch</code> variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.</p> <pre><code>SET optimizer_switch = 'derived_merge=off'; </code></pre> <p><em>Thanks to <a href="https://stackoverflow.com/users/345716/peter-v-m%C3%B8rch">Peter V. Mørch</a> for this advice in the comments.</em></p> <p>Example technique was from Baron Schwartz, <a href="http://grokbase.com/t/mysql/mysql/08259dm24b/error-you-cant-specify-target-table-for-update-in-from-clause" rel="noreferrer">originally published at Nabble</a>, paraphrased and extended here.</p>
{ "question_id": 45494, "question_date": "2008-09-05T10:03:46.590Z", "question_score": 768, "tags": "mysql|subquery|sql-delete|mysql-error-1093", "answer_id": 45498, "answer_date": "2008-09-05T10:07:48.143Z", "answer_score": 905 }
Please answer the following Stack Overflow question: Title: Call async/await functions in parallel <p>As far as I understand, in ES7/ES2016 putting multiple <code>await</code>'s in code will work similar to chaining <code>.then()</code> with promises, meaning that they will execute one after the other rather than in parallel. So, for example, we have this code:</p> <pre><code>await someCall(); await anotherCall(); </code></pre> <p>Do I understand it correctly that <code>anotherCall()</code> will be called only when <code>someCall()</code> is completed? What is the most elegant way of calling them in parallel?</p> <p>I want to use it in Node, so maybe there's a solution with async library?</p> <p>EDIT: I'm not satisfied with the solution provided in this question: <a href="https://stackoverflow.com/questions/24193595/slowdown-due-to-non-parallel-awaiting-of-promises-in-async-generators">Slowdown due to non-parallel awaiting of promises in async generators</a>, because it uses generators and I'm asking about a more general use case.</p>
<p>You can await on <code>Promise.all()</code>:</p> <pre><code>await Promise.all([someCall(), anotherCall()]); </code></pre> <p>To store the results:</p> <pre><code>let [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]); </code></pre> <p>Note that <code>Promise.all</code> fails fast, which means that as soon as one of the promises supplied to it rejects, then the entire thing rejects.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const happy = (v, ms) =&gt; new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(v), ms)) const sad = (v, ms) =&gt; new Promise((_, reject) =&gt; setTimeout(() =&gt; reject(v), ms)) Promise.all([happy('happy', 100), sad('sad', 50)]) .then(console.log).catch(console.log) // 'sad'</code></pre> </div> </div> </p> <p>If, instead, you want to wait for all the promises to either fulfill or reject, then you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled" rel="noreferrer"><code>Promise.allSettled</code></a>. Note that Internet Explorer does not natively support this method.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const happy = (v, ms) =&gt; new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(v), ms)) const sad = (v, ms) =&gt; new Promise((_, reject) =&gt; setTimeout(() =&gt; reject(v), ms)) Promise.allSettled([happy('happy', 100), sad('sad', 50)]) .then(console.log) // [{ "status":"fulfilled", "value":"happy" }, { "status":"rejected", "reason":"sad" }]</code></pre> </div> </div> </p> <blockquote> <p><strong>Note:</strong> If you use <code>Promise.all</code> actions that managed to finish before rejection happen are not rolled back, so you may need to take care of such situation. For example if you have 5 actions, 4 quick, 1 slow and slow rejects. Those 4 actions may be already executed so you may need to roll back. In such situation consider using <code>Promise.allSettled</code> while it will provide exact detail which action failed and which not.</p> </blockquote>
{ "question_id": 35612428, "question_date": "2016-02-24T20:28:46.920Z", "question_score": 768, "tags": "javascript|node.js|asynchronous|ecmascript-6|babeljs", "answer_id": 35612484, "answer_date": "2016-02-24T20:31:40.097Z", "answer_score": 1243 }
Please answer the following Stack Overflow question: Title: Show or hide element in React <p>I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for some native way using the React library. This is what I have so far. I would like to show the results div when the click event fires. </p> <pre class="lang-js prettyprint-override"><code>var Search= React.createClass({ handleClick: function (event) { console.log(this.prop); }, render: function () { return ( &lt;div className="date-range"&gt; &lt;input type="submit" value="Search" onClick={this.handleClick} /&gt; &lt;/div&gt; ); } }); var Results = React.createClass({ render: function () { return ( &lt;div id="results" className="search-results"&gt; Some Results &lt;/div&gt; ); } }); React.renderComponent(&lt;Search /&gt; , document.body); </code></pre>
<h2>React circa 2020</h2> <p>In the <code>onClick</code> callback, call the <a href="https://reactjs.org/docs/hooks-state.html" rel="noreferrer">state hook's</a> setter function to update the state and re-render:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const Search = () =&gt; { const [showResults, setShowResults] = React.useState(false) const onClick = () =&gt; setShowResults(true) return ( &lt;div&gt; &lt;input type="submit" value="Search" onClick={onClick} /&gt; { showResults ? &lt;Results /&gt; : null } &lt;/div&gt; ) } const Results = () =&gt; ( &lt;div id="results" className="search-results"&gt; Some Results &lt;/div&gt; ) ReactDOM.render(&lt;Search /&gt;, document.querySelector("#container"))</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"&gt;&lt;/script&gt; &lt;div id="container"&gt; &lt;!-- This element's contents will be replaced with your component. --&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://jsfiddle.net/khx30pnv/" rel="noreferrer">JSFiddle</a></p> <h2>React circa 2014</h2> <p>The key is to update the state of the component in the click handler using <code>setState</code>. When the state changes get applied, the <code>render</code> method gets called again with the new state:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var Search = React.createClass({ getInitialState: function() { return { showResults: false }; }, onClick: function() { this.setState({ showResults: true }); }, render: function() { return ( &lt;div&gt; &lt;input type="submit" value="Search" onClick={this.onClick} /&gt; { this.state.showResults ? &lt;Results /&gt; : null } &lt;/div&gt; ); } }); var Results = React.createClass({ render: function() { return ( &lt;div id="results" className="search-results"&gt; Some Results &lt;/div&gt; ); } }); ReactDOM.render( &lt;Search /&gt; , document.getElementById('container'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id="container"&gt; &lt;!-- This element's contents will be replaced with your component. --&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/kb3gN/15084/" rel="noreferrer">JSFiddle</a></p>
{ "question_id": 24502898, "question_date": "2014-07-01T05:17:00.377Z", "question_score": 767, "tags": "javascript|reactjs", "answer_id": 24534492, "answer_date": "2014-07-02T14:59:38.783Z", "answer_score": 788 }
Please answer the following Stack Overflow question: Title: Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch <p>I am using Git. I did a pull from a remote repo and got an error message:</p> <blockquote> <p>Please enter a commit message to explain why this merge is necessary,<br> especially if it merges an updated upstream into a topic branch. </p> </blockquote> <p>I try to type a message and press <KBD>Enter</KBD> but nothing happens.</p> <p><strong>How do I tell Git/Terminal I am done typing in my message?</strong></p> <p>I am using Terminal on OS X.</p>
<p>It's not a Git error message, it's the editor as git uses your default editor. </p> <p>To solve this:</p> <ol> <li>press "i" (i for insert)</li> <li>write your merge message </li> <li>press "esc" (escape) </li> <li>write ":wq" (write &amp; quit)</li> <li>then press enter</li> </ol>
{ "question_id": 19085807, "question_date": "2013-09-30T02:57:00.380Z", "question_score": 767, "tags": "macos|git-merge|git-commit|git", "answer_id": 19085954, "answer_date": "2013-09-30T03:17:20.763Z", "answer_score": 1819 }
Please answer the following Stack Overflow question: Title: Set up adb on Mac OS X <p>I spent quite sometime figuring how to set up adb on Mac, so I figure writing how to set it up might be useful to some people. adb is the command line tool to install and run android apps on your phone/emulator</p>
<p><em>Note: this was originally written on <a href="https://stackoverflow.com/questions/31374085/">Installing ADB on macOS</a> but that question was closed as a duplicate of this one.</em></p> <p><em>Note for <strong>zsh users</strong>: replace all references to <code>~/.bash_profile</code> with <code>~/.zshrc</code>.</em></p> <h1>Option 1 - Using Homebrew</h1> <p>This is the easiest way and will provide automatic updates.</p> <ol> <li><p>Install <a href="http://brew.sh/" rel="noreferrer">homebrew</a></p> <pre><code> /bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)&quot; </code></pre> </li> <li><p>Install adb</p> <pre><code> brew install android-platform-tools </code></pre> </li> </ol> <p>or try a cask install depending on your settings:</p> <pre><code> brew install --cask android-platform-tools </code></pre> <ol start="3"> <li><p>Start using adb</p> <pre><code> adb devices </code></pre> </li> </ol> <br> <h1>Option 2 - Manually (just the platform tools)</h1> <p>This is the easiest way to get a manual installation of ADB and Fastboot.</p> <ol> <li><p>Delete your old installation <em>(optional)</em></p> <pre><code> rm -rf ~/.android-sdk-macosx/ </code></pre> </li> <li><p>Navigate to <a href="https://developer.android.com/studio/releases/platform-tools.html" rel="noreferrer">https://developer.android.com/studio/releases/platform-tools.html</a> and click on the <code>SDK Platform-Tools for Mac</code> link.</p> </li> <li><p>Go to your Downloads folder</p> <pre><code> cd ~/Downloads/ </code></pre> </li> <li><p>Unzip the tools you downloaded</p> <pre><code> unzip platform-tools-latest*.zip </code></pre> </li> <li><p>Move them somewhere you won't accidentally delete them</p> <pre><code> mkdir ~/.android-sdk-macosx mv platform-tools/ ~/.android-sdk-macosx/platform-tools </code></pre> </li> <li><p>Add <code>platform-tools</code> to your path</p> <pre><code> echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' &gt;&gt; ~/.bash_profile </code></pre> </li> <li><p>Refresh your bash profile (or restart your terminal app)</p> <pre><code> source ~/.bash_profile </code></pre> </li> <li><p>Start using adb</p> <pre><code> adb devices </code></pre> </li> </ol> <h1>Option 3 - If you already have Android Studio installed</h1> <ol> <li><p>Add <code>platform-tools</code> to your path</p> <pre><code> echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' &gt;&gt; ~/.bash_profile echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' &gt;&gt; ~/.bash_profile </code></pre> </li> <li><p>Refresh your bash profile (or restart your terminal app)</p> <pre><code> source ~/.bash_profile </code></pre> </li> <li><p>Start using adb</p> <pre><code> adb devices </code></pre> </li> </ol> <h1>Option 4 - MacPorts</h1> <ol> <li><p>Install the Android SDK:</p> <pre><code> sudo port install android </code></pre> </li> <li><p>Run the SDK manager:</p> <pre><code> sh /opt/local/share/java/android-sdk-macosx/tools/android </code></pre> </li> <li><p>Uncheck everything but <code>Android SDK Platform-tools</code> <em>(optional)</em></p> </li> <li><p>Install the packages, accepting licenses. Close the SDK Manager.</p> </li> <li><p>Add <code>platform-tools</code> to your path; in MacPorts, they're in <code>/opt/local/share/java/android-sdk-macosx/platform-tools</code>. E.g., for bash:</p> <pre><code> echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' &gt;&gt; ~/.bash_profile </code></pre> </li> <li><p>Refresh your bash profile (or restart your terminal/shell):</p> <pre><code>source ~/.bash_profile </code></pre> </li> <li><p>Start using adb:</p> <pre><code>adb devices </code></pre> </li> </ol> <h1>Option 5 - Manually (with SDK Manager)</h1> <ol> <li><p>Delete your old installation <em>(optional)</em></p> <pre><code> rm -rf ~/.android-sdk-macosx/ </code></pre> </li> <li><p>Download the Mac SDK Tools from the Android developer site under <a href="http://developer.android.com/sdk/index.html#mac-tools" rel="noreferrer">&quot;Get just the command line tools&quot;</a>. Make sure you save them to your Downloads folder.</p> </li> <li><p>Go to your Downloads folder</p> <pre><code> cd ~/Downloads/ </code></pre> </li> <li><p>Unzip the tools you downloaded</p> <pre><code> unzip tools_r*-macosx.zip </code></pre> </li> <li><p>Move them somewhere you won't accidentally delete them</p> <pre><code> mkdir ~/.android-sdk-macosx mv tools/ ~/.android-sdk-macosx/tools </code></pre> </li> <li><p>Run the SDK Manager</p> <pre><code> sh ~/.android-sdk-macosx/tools/android </code></pre> </li> <li><p>Uncheck everything but <code>Android SDK Platform-tools</code> <em>(optional)</em></p> </li> </ol> <p><a href="https://i.stack.imgur.com/H2p4V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/H2p4V.png" alt="enter image description here" /></a></p> <ol start="8"> <li>Click <code>Install Packages</code>, accept licenses, click <code>Install</code>. Close the SDK Manager window.</li> </ol> <p><a href="https://i.stack.imgur.com/ojZVT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ojZVT.png" alt="enter image description here" /></a></p> <ol start="9"> <li><p>Add <code>platform-tools</code> to your path</p> <pre><code> echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' &gt;&gt; ~/.bash_profile </code></pre> </li> <li><p>Refresh your bash profile (or restart your terminal app)</p> <pre><code>source ~/.bash_profile </code></pre> </li> <li><p>Start using adb</p> <pre><code>adb devices </code></pre> </li> </ol>
{ "question_id": 17901692, "question_date": "2013-07-27T19:32:57.087Z", "question_score": 767, "tags": "android|macos|adb", "answer_id": 28208121, "answer_date": "2015-01-29T06:17:30.077Z", "answer_score": 1643 }
Please answer the following Stack Overflow question: Title: How to use double or single brackets, parentheses, curly braces <p>I am confused by the usage of brackets, parentheses, curly braces in Bash, as well as the difference between their double or single forms. Is there a clear explanation?</p>
<p>In Bash, <code>test</code> and <code>[</code> are shell builtins.</p> <p>The <a href="http://mywiki.wooledge.org/BashFAQ/031" rel="noreferrer">double bracket</a>, which is a shell keyword, enables additional functionality. For example, you can use <code>&amp;&amp;</code> and <code>||</code> instead of <code>-a</code> and <code>-o</code> and there's a regular expression matching operator <code>=~</code>.</p> <p>Also, in a simple test, double square brackets seem to evaluate quite a lot quicker than single ones.</p> <pre class="lang-bash prettyprint-override"><code>$ time for ((i=0; i&lt;10000000; i++)); do [[ "$i" = 1000 ]]; done real 0m24.548s user 0m24.337s sys 0m0.036s $ time for ((i=0; i&lt;10000000; i++)); do [ "$i" = 1000 ]; done real 0m33.478s user 0m33.478s sys 0m0.000s </code></pre> <p>The braces, in addition to delimiting a variable name are used for <a href="http://tiswww.case.edu/php/chet/bash/bashref.html#Brace-Expansion" rel="noreferrer">parameter expansion</a> so you can do things like:</p> <ul> <li><p>Truncate the contents of a variable</p> <pre><code>$ var="abcde"; echo ${var%d*} abc </code></pre></li> <li><p>Make substitutions similar to <code>sed</code></p> <pre><code>$ var="abcde"; echo ${var/de/12} abc12 </code></pre></li> <li><p>Use a default value</p> <pre><code>$ default="hello"; unset var; echo ${var:-$default} hello </code></pre></li> <li><p>and several more</p></li> </ul> <p>Also, brace expansions create lists of strings which are typically iterated over in loops:</p> <pre><code>$ echo f{oo,ee,a}d food feed fad $ mv error.log{,.OLD} (error.log is renamed to error.log.OLD because the brace expression expands to "mv error.log error.log.OLD") $ for num in {000..2}; do echo "$num"; done 000 001 002 $ echo {00..8..2} 00 02 04 06 08 $ echo {D..T..4} D H L P T </code></pre> <p>Note that the leading zero and increment features weren't available before Bash 4.</p> <p>Thanks to gboffi for reminding me about brace expansions.</p> <p>Double parentheses are used for <a href="http://tiswww.case.edu/php/chet/bash/bashref.html#Arithmetic-Expansion" rel="noreferrer">arithmetic operations</a>:</p> <pre><code>((a++)) ((meaning = 42)) for ((i=0; i&lt;10; i++)) echo $((a + b + (14 * c))) </code></pre> <p>and they enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability.</p> <p>Single brackets are also used for <a href="http://tiswww.case.edu/php/chet/bash/bashref.html#Arrays" rel="noreferrer">array</a> indices:</p> <pre><code>array[4]="hello" element=${array[index]} </code></pre> <p>Curly brace are required for (most/all?) array references on the right hand side.</p> <p><strong>ephemient's</strong> comment reminded me that parentheses are also used for subshells. And that they are used to create arrays.</p> <pre><code>array=(1 2 3) echo ${array[1]} 2 </code></pre>
{ "question_id": 2188199, "question_date": "2010-02-02T22:22:54.043Z", "question_score": 767, "tags": "bash|syntax", "answer_id": 2188369, "answer_date": "2010-02-02T22:48:42.233Z", "answer_score": 692 }
Please answer the following Stack Overflow question: Title: What is bootstrapping? <p>I keep seeing "bootstrapping" mentioned in discussions of application development. It seems both widespread and important, but I've yet to come across even a poor explanation of what bootstrapping actually is; rather, it seems as though everyone is just supposed to know what it means. I don't, though. Near as I can figure, it has something to do with initialization tasks required of an application upon launch, but I could be completely wrong about that. Can anyone help me to understand this idea?</p>
<p>"Bootstrapping" comes from the term "pulling yourself up by your own bootstraps." That much you can get from <a href="http://en.wikipedia.org/wiki/Bootstrap" rel="noreferrer">Wikipedia</a>.</p> <p>In computing, a bootstrap loader is the first piece of code that runs when a machine starts, and is responsible for loading the rest of the operating system. In modern computers it's stored in ROM, but I recall the bootstrap process on the PDP-11, where you would poke bits via the front-panel switches to load a particular disk segment into memory, and then run it. Needless to say, the bootstrap loader is normally pretty small.</p> <p>"Bootstrapping" is also used as a term for building a system using itself -- or more correctly, a predecessor version. For example, <a href="http://www.antlr.org/" rel="noreferrer">ANTLR</a> version 3 is written using a parser developed in ANTLR version 2.</p>
{ "question_id": 1254542, "question_date": "2009-08-10T12:16:29.490Z", "question_score": 766, "tags": "bootstrapping", "answer_id": 1254561, "answer_date": "2009-08-10T12:21:35.107Z", "answer_score": 375 }
Please answer the following Stack Overflow question: Title: Order of items in classes: Fields, Properties, Constructors, Methods <p>Is there an official C# guideline for the order of items in terms of class structure?</p> <p>Does it go:</p> <ul> <li>Public Fields</li> <li>Private Fields</li> <li>Properties</li> <li>Constructors</li> <li>Methods<br> ?</li> </ul> <p>I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere.</p> <p>The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor.</p> <p>Any tips/suggestions?</p>
<p>According to the <a href="https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1201.md" rel="noreferrer">StyleCop Rules Documentation</a> the ordering is as follows.</p> <p>Within a class, struct or interface: (SA1201 and SA1203)</p> <ul> <li>Constant Fields</li> <li>Fields</li> <li>Constructors</li> <li>Finalizers (Destructors)</li> <li>Delegates</li> <li>Events</li> <li>Enums</li> <li>Interfaces (<em>interface implementations</em>)</li> <li>Properties</li> <li>Indexers</li> <li>Methods</li> <li>Structs</li> <li>Classes</li> </ul> <p>Within each of these groups order by access: (SA1202)</p> <ul> <li>public</li> <li>internal</li> <li>protected internal</li> <li>protected</li> <li>private</li> </ul> <p>Within each of the access groups, order by static, then non-static: (SA1204)</p> <ul> <li>static</li> <li>non-static</li> </ul> <p>Within each of the static/non-static groups of fields, order by readonly, then non-readonly : (SA1214 and SA1215)</p> <ul> <li>readonly</li> <li>non-readonly</li> </ul> <p>An unrolled list is 130 lines long, so I won't unroll it here. The methods part unrolled is:</p> <ul> <li>public static methods</li> <li>public methods</li> <li>internal static methods</li> <li>internal methods</li> <li>protected internal static methods</li> <li>protected internal methods</li> <li>protected static methods</li> <li>protected methods</li> <li>private static methods</li> <li>private methods</li> </ul> <p>The documentation notes that if the prescribed order isn't suitable - say, multiple interfaces are being implemented, and the interface methods and properties should be grouped together - then use a partial class to group the related methods and properties together.</p>
{ "question_id": 150479, "question_date": "2008-09-29T20:23:21.793Z", "question_score": 766, "tags": "c#|.net|coding-style|code-cleanup|code-structure", "answer_id": 310967, "answer_date": "2008-11-22T06:41:49.557Z", "answer_score": 1192 }
Please answer the following Stack Overflow question: Title: What is the difference between GitHub and gist? <p>What is the purpose of gist and how is it different from regular code sharing/maintaining using GitHub?</p> <p><a href="https://i.stack.imgur.com/gTtGt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gTtGt.png" alt="enter image description here" /></a></p>
<p>GitHub is the entire site. Gists are a particular service offered on that site, namely code snippets akin to pastebin. However, everything is driven by git revision control, so gists also have complete revision histories. </p>
{ "question_id": 6767518, "question_date": "2011-07-20T19:41:51.083Z", "question_score": 766, "tags": "github|repository|gist", "answer_id": 6767547, "answer_date": "2011-07-20T19:44:55.393Z", "answer_score": 460 }
Please answer the following Stack Overflow question: Title: Text-align class for inside a table <p>Is there a set of classes in Twitter's Bootstrap framework that aligns text?</p> <p>For example, I have some tables with <code>$</code> totals that I want aligned to the right...</p> <pre><code>&lt;th class="align-right"&gt;Total&lt;/th&gt; </code></pre> <p>and</p> <pre><code>&lt;td class="align-right"&gt;$1,000,000.00&lt;/td&gt; </code></pre>
<h1>Bootstrap 3</h1> <p><a href="https://getbootstrap.com/docs/3.3/css/#type-alignment" rel="noreferrer">v3 Text Alignment Docs</a></p> <pre><code>&lt;p class=&quot;text-left&quot;&gt;Left aligned text.&lt;/p&gt; &lt;p class=&quot;text-center&quot;&gt;Center aligned text.&lt;/p&gt; &lt;p class=&quot;text-right&quot;&gt;Right aligned text.&lt;/p&gt; &lt;p class=&quot;text-justify&quot;&gt;Justified text.&lt;/p&gt; &lt;p class=&quot;text-nowrap&quot;&gt;No wrap text.&lt;/p&gt; </code></pre> <p><a href="https://i.stack.imgur.com/DZHMg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DZHMg.png" alt="Bootstrap 3 text align example" /></a></p> <hr /> <h1>Bootstrap 4</h1> <p><a href="https://getbootstrap.com/docs/4.0/utilities/text/#text-alignment" rel="noreferrer">v4 Text Alignment Docs</a></p> <pre><code>&lt;p class=&quot;text-xs-left&quot;&gt;Left aligned text on all viewport sizes.&lt;/p&gt; &lt;p class=&quot;text-xs-center&quot;&gt;Center aligned text on all viewport sizes.&lt;/p&gt; &lt;p class=&quot;text-xs-right&quot;&gt;Right aligned text on all viewport sizes.&lt;/p&gt; &lt;p class=&quot;text-sm-left&quot;&gt;Left aligned text on viewports sized SM (small) or wider.&lt;/p&gt; &lt;p class=&quot;text-md-left&quot;&gt;Left aligned text on viewports sized MD (medium) or wider.&lt;/p&gt; &lt;p class=&quot;text-lg-left&quot;&gt;Left aligned text on viewports sized LG (large) or wider.&lt;/p&gt; &lt;p class=&quot;text-xl-left&quot;&gt;Left aligned text on viewports sized XL (extra-large) or wider.&lt;/p&gt; </code></pre> <p><a href="https://i.stack.imgur.com/Qfi1K.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qfi1K.png" alt="Bootstrap 4 text align example" /></a></p> <hr /> <h1>Bootstrap 5</h1> <p><a href="https://getbootstrap.com/docs/5.0/utilities/text/#text-alignment" rel="noreferrer">v5 Text Alignment Docs</a></p> <p><code>text-left</code> has been replaced with <code>text-start</code>, <code>text-right</code> has been replaced with <code>text-end</code></p> <pre><code>&lt;p class=&quot;text-start&quot;&gt;Left aligned text.&lt;/p&gt; &lt;p class=&quot;text-center&quot;&gt;Center aligned text.&lt;/p&gt; &lt;p class=&quot;text-end&quot;&gt;Right aligned text.&lt;/p&gt; &lt;p class=&quot;text-justify&quot;&gt;Justified text.&lt;/p&gt; &lt;p class=&quot;text-nowrap&quot;&gt;No wrap text.&lt;/p&gt; </code></pre>
{ "question_id": 12829608, "question_date": "2012-10-10T22:45:40.893Z", "question_score": 765, "tags": "html|css|twitter-bootstrap|text-align", "answer_id": 15140080, "answer_date": "2013-02-28T16:03:10.433Z", "answer_score": 1507 }
Please answer the following Stack Overflow question: Title: HTML-encoding lost when attribute read from input field <p>I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.</p> <p>For example,</p> <pre class="lang-html prettyprint-override"><code>&lt;input id='hiddenId' type='hidden' value='chalk &amp;amp; cheese' /&gt; </code></pre> <p>gets pulled into</p> <pre class="lang-html prettyprint-override"><code>&lt;input type='text' value='chalk &amp;amp; cheese' /&gt; </code></pre> <p>via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):</p> <pre class="lang-js prettyprint-override"><code>$('#hiddenId').attr('value') </code></pre> <p>The problem is that when I read <code>chalk &amp;amp; cheese</code> from the hidden field, JavaScript seems to lose the encoding. I do not want the value to be <code>chalk &amp; cheese</code>. I want the literal <code>amp;</code> to be retained.</p> <p>Is there a JavaScript library or a jQuery method that will HTML-encode a string?</p>
<p><strong>EDIT:</strong> This answer was posted a long ago, and the <code>htmlDecode</code> function introduced a XSS vulnerability. It has been modified changing the temporary element from a <code>div</code> to a <code>textarea</code> reducing the XSS chance. But nowadays, I would encourage you to use the DOMParser API as suggested in <a href="https://stackoverflow.com/a/34064434/5445">other anwswer</a>.</p> <hr> <p>I use these functions:</p> <pre><code>function htmlEncode(value){ // Create a in-memory element, set its inner text (which is automatically encoded) // Then grab the encoded contents back out. The element never exists on the DOM. return $('&lt;textarea/&gt;').text(value).html(); } function htmlDecode(value){ return $('&lt;textarea/&gt;').html(value).text(); } </code></pre> <p>Basically a textarea element is created in memory, but it is never appended to the document.</p> <p>On the <code>htmlEncode</code> function I set the <code>innerText</code> of the element, and retrieve the encoded <code>innerHTML</code>; on the <code>htmlDecode</code> function I set the <code>innerHTML</code> value of the element and the <code>innerText</code> is retrieved.</p> <p>Check a running example <a href="http://jsbin.com/ejuru" rel="noreferrer">here</a>.</p>
{ "question_id": 1219860, "question_date": "2009-08-02T21:08:29.730Z", "question_score": 765, "tags": "javascript|jquery|html|escaping|html-escape-characters", "answer_id": 1219983, "answer_date": "2009-08-02T22:03:10.380Z", "answer_score": 1073 }
Please answer the following Stack Overflow question: Title: A component is changing an uncontrolled input of type text to be controlled error in ReactJS <blockquote> <p>Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.*</p> </blockquote> <p>Following is my code:</p> <pre><code>constructor(props) { super(props); this.state = { fields: {}, errors: {} } this.onSubmit = this.onSubmit.bind(this); } .... onChange(field, e){ let fields = this.state.fields; fields[field] = e.target.value; this.setState({fields}); } .... render() { return( &lt;div className="form-group"&gt; &lt;input value={this.state.fields["name"]} onChange={this.onChange.bind(this, "name")} className="form-control" type="text" refs="name" placeholder="Name *" /&gt; &lt;span style={{color: "red"}}&gt;{this.state.errors["name"]}&lt;/span&gt; &lt;/div&gt; ) } </code></pre>
<p>The reason is, in state you defined:</p> <pre><code>this.state = { fields: {} } </code></pre> <p>fields as a blank object, so during the first rendering <code>this.state.fields.name</code> will be <code>undefined</code>, and the input field will get its value as:</p> <pre><code>value={undefined} </code></pre> <p>Because of that, the input field will become uncontrolled. </p> <p>Once you enter any value in input, <code>fields</code> in state gets changed to:</p> <pre><code>this.state = { fields: {name: 'xyz'} } </code></pre> <p>And at that time the input field gets converted into a controlled component; that's why you are getting the error:</p> <blockquote> <p>A component is changing an uncontrolled input of type text to be controlled.</p> </blockquote> <p><strong>Possible Solutions:</strong></p> <p>1- Define the <code>fields</code> in state as:</p> <pre><code>this.state = { fields: {name: ''} } </code></pre> <p>2- Or define the value property by using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation" rel="noreferrer">Short-circuit evaluation</a> like this:</p> <pre><code>value={this.state.fields.name || ''} // (undefined || '') = '' </code></pre>
{ "question_id": 47012169, "question_date": "2017-10-30T09:47:10.447Z", "question_score": 765, "tags": "javascript|reactjs", "answer_id": 47012342, "answer_date": "2017-10-30T09:54:56.733Z", "answer_score": 1339 }
Please answer the following Stack Overflow question: Title: What killed my process and why? <p>My application runs as a background process on Linux. It is currently started at the command line in a Terminal window.</p> <p>Recently a user was executing the application for a while and it died mysteriously. The text:</p> <blockquote> <p>Killed</p> </blockquote> <p>was on the terminal. This happened two times. I asked if someone at a different Terminal used the kill command to kill the process? No.</p> <p>Under what conditions would Linux decide to kill my process? I believe the shell displayed "killed" because the process died after receiving the kill(9) signal. If Linux sent the kill signal should there be a message in a system log somewhere that explains why it was killed?</p>
<p>If the user or sysadmin did not kill the program the kernel may have. The kernel would only kill a process under exceptional circumstances such as extreme resource starvation (think mem+swap exhaustion).</p>
{ "question_id": 726690, "question_date": "2009-04-07T17:07:19.760Z", "question_score": 765, "tags": "linux|process|kill|signals", "answer_id": 726762, "answer_date": "2009-04-07T17:23:58.397Z", "answer_score": 480 }
Please answer the following Stack Overflow question: Title: When does Git refresh the list of remote branches? <p>Using <code>git branch --all</code> shows all <em>remote</em> and <em>local</em> branches. When does Git refresh this list?</p> <p>On pull/push? And how do I refresh it using <a href="https://superuser.com/questions/1053633">Git Bash</a>?</p>
<p>To update the local list of remote branches:</p> <pre><code>git remote update origin --prune </code></pre> <p>To show all local and remote branches that (local) Git knows about:</p> <pre><code>git branch -a </code></pre>
{ "question_id": 36358265, "question_date": "2016-04-01T13:58:41.077Z", "question_score": 765, "tags": "git|github|branch|remote-branch", "answer_id": 36358502, "answer_date": "2016-04-01T14:09:03.513Z", "answer_score": 1832 }
Please answer the following Stack Overflow question: Title: Are strongly-typed functions as parameters possible in TypeScript? <p>In TypeScript, I can declare a parameter of a function as a type Function. Is there a "type-safe" way of doing this that I am missing? For example, consider this:</p> <pre><code>class Foo { save(callback: Function) : void { //Do the save var result : number = 42; //We get a number from the save operation //Can I at compile-time ensure the callback accepts a single parameter of type number somehow? callback(result); } } var foo = new Foo(); var callback = (result: string) : void =&gt; { alert(result); } foo.save(callback); </code></pre> <p>The save callback is not type safe, I am giving it a callback function where the function's parameter is a string but I am passing it a number, and compiles with no errors. Can I make the result parameter in save a type-safe function?</p> <p>TL;DR version: is there an equivalent of a .NET delegate in TypeScript?</p>
<p>Sure. A function's <a href="https://www.typescriptlang.org/docs/handbook/functions.html#writing-the-function-type" rel="noreferrer">type</a> consists of the types of its argument and its return type. Here we specify that the <code>callback</code> parameter's type must be "function that accepts a number and returns type <code>any</code>":</p> <pre><code>class Foo { save(callback: (n: number) =&gt; any) : void { callback(42); } } var foo = new Foo(); var strCallback = (result: string) : void =&gt; { alert(result); } var numCallback = (result: number) : void =&gt; { alert(result.toString()); } foo.save(strCallback); // not OK foo.save(numCallback); // OK </code></pre> <p>If you want, you can define a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases" rel="noreferrer">type alias</a> to encapsulate this:</p> <pre><code>type NumberCallback = (n: number) =&gt; any; class Foo { // Equivalent save(callback: NumberCallback) : void { callback(42); } } </code></pre>
{ "question_id": 14638990, "question_date": "2013-02-01T02:56:27.053Z", "question_score": 765, "tags": "typescript", "answer_id": 14639219, "answer_date": "2013-02-01T03:25:19.147Z", "answer_score": 1048 }
Please answer the following Stack Overflow question: Title: How do I create delegates in Objective-C? <p>I know how delegates work, and I know how I can use them.</p> <p>But how do I create them?</p>
<p>An Objective-C delegate is an object that has been assigned to the <code>delegate</code> property another object. To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol.</p> <p>For example, suppose you have a <code>UIWebView</code>. If you'd like to implement its delegate's <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIWebViewDelegate/webViewDidStartLoad:" rel="noreferrer"><code>webViewDidStartLoad:</code></a> method, you could create a class like this:</p> <pre><code>@interface MyClass&lt;UIWebViewDelegate&gt; // ... @end @implementation MyClass - (void)webViewDidStartLoad:(UIWebView *)webView { // ... } @end </code></pre> <p>Then you could create an instance of MyClass and assign it as the web view's delegate:</p> <pre><code>MyClass *instanceOfMyClass = [[MyClass alloc] init]; myWebView.delegate = instanceOfMyClass; </code></pre> <p>On the <code>UIWebView</code> side, it probably has code similar to this to see if the delegate responds to the <code>webViewDidStartLoad:</code> message using <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/respondsToSelector:" rel="noreferrer"><code>respondsToSelector:</code></a> and send it if appropriate.</p> <pre><code>if([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { [self.delegate webViewDidStartLoad:self]; } </code></pre> <p>The delegate property itself is typically declared <code>weak</code> (in ARC) or <code>assign</code> (pre-ARC) to avoid retain loops, since the delegate of an object often holds a strong reference to that object. (For example, a view controller is often the delegate of a view it contains.)</p> <h2>Making Delegates for Your Classes</h2> <p>To define your own delegates, you'll have to declare their methods somewhere, as discussed in the <a href="http://www.google.ca/search?q=site:developer.apple.com+protocols+objective+c&amp;btnI" rel="noreferrer">Apple Docs on protocols</a>. You usually declare a formal protocol. The declaration, paraphrased from UIWebView.h, would look like this:</p> <pre><code>@protocol UIWebViewDelegate &lt;NSObject&gt; @optional - (void)webViewDidStartLoad:(UIWebView *)webView; // ... other methods here @end </code></pre> <p>This is analogous to an interface or abstract base class, as it creates a special type for your delegate, <code>UIWebViewDelegate</code> in this case. Delegate implementors would have to adopt this protocol:</p> <pre><code>@interface MyClass &lt;UIWebViewDelegate&gt; // ... @end </code></pre> <p>And then implement the methods in the protocol. For methods declared in the protocol as <code>@optional</code> (like most delegate methods), you need to check with <code>-respondsToSelector:</code> before calling a particular method on it. </p> <h3>Naming</h3> <p>Delegate methods are typically named starting with the delegating class name, and take the delegating object as the first parameter. They also often use a will-, should-, or did- form. So, <code>webViewDidStartLoad:</code> (first parameter is the web view) rather than <code>loadStarted</code> (taking no parameters) for example. </p> <h3>Speed Optimizations</h3> <p>Instead of checking whether a delegate responds to a selector every time we want to message it, you can cache that information when delegates are set. One very clean way to do this is to use a bitfield, as follows:</p> <pre><code>@protocol SomethingDelegate &lt;NSObject&gt; @optional - (void)something:(id)something didFinishLoadingItem:(id)item; - (void)something:(id)something didFailWithError:(NSError *)error; @end @interface Something : NSObject @property (nonatomic, weak) id &lt;SomethingDelegate&gt; delegate; @end @implementation Something { struct { unsigned int didFinishLoadingItem:1; unsigned int didFailWithError:1; } delegateRespondsTo; } @synthesize delegate; - (void)setDelegate:(id &lt;SomethingDelegate&gt;)aDelegate { if (delegate != aDelegate) { delegate = aDelegate; delegateRespondsTo.didFinishLoadingItem = [delegate respondsToSelector:@selector(something:didFinishLoadingItem:)]; delegateRespondsTo.didFailWithError = [delegate respondsToSelector:@selector(something:didFailWithError:)]; } } @end </code></pre> <p>Then, in the body, we can check that our delegate handles messages by accessing our <code>delegateRespondsTo</code> struct, rather than by sending <code>-respondsToSelector:</code> over and over again.</p> <h3>Informal Delegates</h3> <p>Before protocols existed, it was common to use a <a href="http://www.google.ca/search?q=site:developer.apple.com+category+objective+c&amp;btnI" rel="noreferrer">category</a> on <code>NSObject</code> to declare the methods a delegate could implement. For example, <code>CALayer</code> still does this:</p> <pre><code>@interface NSObject(CALayerDelegate) - (void)displayLayer:(CALayer *)layer; // ... other methods here @end </code></pre> <p>This tells the compiler that any object might implement <code>displayLayer:</code>.</p> <p>You would then use the same <code>-respondsToSelector:</code> approach as described above to call this method. Delegates implement this method and assign the <code>delegate</code> property, and that's it (there's no declaring you conform to a protocol). This method is common in Apple's libraries, but new code should use the more modern protocol approach above, since this approach pollutes <code>NSObject</code> (which makes autocomplete less useful) and makes it hard for the compiler to warn you about typos and similar errors.</p>
{ "question_id": 626898, "question_date": "2009-03-09T16:06:14.197Z", "question_score": 765, "tags": "ios|objective-c|cocoa|callback|delegates", "answer_id": 626946, "answer_date": "2009-03-09T16:16:24.233Z", "answer_score": 917 }
Please answer the following Stack Overflow question: Title: Eliminate extra separators below UITableView <p>When I set up a table view with 4 rows, there are still extra separators lines (or extra blank cells) below the filled rows.</p> <p>How would I remove these cells?</p> <p><a href="https://i.stack.imgur.com/cFbz5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cFbz5.png" alt="image for extra separator lines in UITableView"></a></p>
<h1>Interface builder (iOS 9+)</h1> <p>Just drag a UIView to the table. In storyboard, it will sit at the top below your custom cells. You may prefer to name it "footer".</p> <p>Here it is shown in green for clarity, you'd probably want clear color.</p> <p>Note that by adjusting the height, you can affect how the "bottom bounce" of the table is handled, as you prefer. (Height zero is usually fine).</p> <p><a href="https://i.stack.imgur.com/OOwGA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OOwGA.png" alt="enter image description here"></a></p> <hr> <p>To do it programmatically: </p> <h1>Swift</h1> <pre><code>override func viewDidLoad() { super.viewDidLoad() self.tableView.tableFooterView = UIView() } </code></pre> <h1>Objective-C</h1> <h2>iOS 6.1+</h2> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; // This will remove extra separators from tableview self.tableView.tableFooterView = [UIView new]; } </code></pre> <p>or if you prefer,</p> <pre><code> self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; </code></pre> <h2>Historically in iOS:</h2> <p>Add to the table view controller...</p> <pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { // This will create a "invisible" footer return CGFLOAT_MIN; } </code></pre> <p>and if necessary...</p> <pre><code>- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { return [UIView new]; // If you are not using ARC: // return [[UIView new] autorelease]; } </code></pre>
{ "question_id": 1369831, "question_date": "2009-09-02T20:05:15.670Z", "question_score": 765, "tags": "ios|uitableview|cocoa-touch", "answer_id": 5377569, "answer_date": "2011-03-21T12:28:15.360Z", "answer_score": 1565 }
Please answer the following Stack Overflow question: Title: IndentationError: unindent does not match any outer indentation level <p>When I compile the Python code below, I get</p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr /> <pre><code>import sys def Factorial(n): # Return factorial result = 1 for i in range (1,n): result = result * i print &quot;factorial is &quot;,result return result </code></pre> <p>Why?</p>
<p>Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search &amp; replace to replace all tabs with a few spaces.</p> <p>Try this:</p> <pre><code>import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print &quot;factorial is &quot;,result return result print Factorial(10) </code></pre>
{ "question_id": 492387, "question_date": "2009-01-29T16:34:46.893Z", "question_score": 764, "tags": "python|indentation", "answer_id": 492399, "answer_date": "2009-01-29T16:37:18.510Z", "answer_score": 835 }
Please answer the following Stack Overflow question: Title: SQL update query using joins <p>I have to update a field with a value which is returned by a join of 3 tables.</p> <p>Example: </p> <pre><code>select im.itemid ,im.sku as iSku ,gm.SKU as GSKU ,mm.ManufacturerId as ManuId ,mm.ManufacturerName ,im.mf_item_number ,mm.ManufacturerID from item_master im, group_master gm, Manufacturer_Master mm where im.mf_item_number like 'STA%' and im.sku=gm.sku and gm.ManufacturerID = mm.ManufacturerID and gm.manufacturerID=34 </code></pre> <p>I want to update the <code>mf_item_number</code> field values of table <code>item_master</code> with some other value which is joined in the above condition.</p> <p>How can I do this in MS SQL Server?</p>
<pre><code>UPDATE im SET mf_item_number = gm.SKU --etc FROM item_master im JOIN group_master gm ON im.sku = gm.sku JOIN Manufacturer_Master mm ON gm.ManufacturerID = mm.ManufacturerID WHERE im.mf_item_number like 'STA%' AND gm.manufacturerID = 34 </code></pre> <p>To make it clear... The <code>UPDATE</code> clause can refer to an table alias specified in the <code>FROM</code> clause. So <code>im</code> in this case is valid</p> <h3>Generic example</h3> <pre><code>UPDATE A SET foo = B.bar FROM TableA A JOIN TableB B ON A.col1 = B.colx WHERE ... </code></pre>
{ "question_id": 982919, "question_date": "2009-06-11T18:49:33.633Z", "question_score": 764, "tags": "sql|sql-server|tsql|sql-server-2005|sql-update", "answer_id": 982947, "answer_date": "2009-06-11T18:55:52.570Z", "answer_score": 1390 }
Please answer the following Stack Overflow question: Title: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 <p>I have recently installed tensorflow (Windows CPU version) and received the following message:</p> <blockquote> <p>Successfully installed tensorflow-1.4.0 tensorflow-tensorboard-0.4.0rc2</p> </blockquote> <p>Then when I tried to run</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() sess.run(hello) 'Hello, TensorFlow!' a = tf.constant(10) b = tf.constant(32) sess.run(a + b) 42 sess.close() </code></pre> <p>(which I found through <a href="https://github.com/tensorflow/tensorflow" rel="noreferrer">https://github.com/tensorflow/tensorflow</a>)</p> <p>I received the following message:</p> <blockquote> <p>2017-11-02 01:56:21.698935: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2</p> </blockquote> <p>But when I ran</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) </code></pre> <p>it ran as it should and output <code>Hello, TensorFlow!</code>, which indicates that the installation was successful indeed but there is something else that is wrong.</p> <p>Do you know what the problem is and how to fix it?</p>
<h2>What is this warning about?</h2> <p>Modern CPUs provide a lot of low-level instructions, besides the usual arithmetic and logic, known as extensions, e.g. SSE2, SSE4, AVX, etc. From the <a href="https://en.wikipedia.org/wiki/Advanced_Vector_Extensions" rel="noreferrer">Wikipedia</a>:</p> <blockquote> <p><strong>Advanced Vector Extensions</strong> (<strong>AVX</strong>) are extensions to the x86 instruction set architecture for microprocessors from Intel and AMD proposed by Intel in March 2008 and first supported by Intel with the Sandy Bridge processor shipping in Q1 2011 and later on by AMD with the Bulldozer processor shipping in Q3 2011. AVX provides new features, new instructions and a new coding scheme.</p> </blockquote> <p>In particular, AVX introduces <a href="https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation#Fused_multiply.E2.80.93add" rel="noreferrer">fused multiply-accumulate</a> (FMA) operations, which speed up linear algebra computation, namely dot-product, matrix multiply, convolution, etc. Almost every machine-learning training involves a great deal of these operations, hence will be faster on a CPU that supports AVX and FMA (up to 300%). The warning states that your CPU does support AVX (hooray!).</p> <p>I'd like to stress here: it's all about <strong>CPU only</strong>.</p> <h2>Why isn't it used then?</h2> <p>Because tensorflow default distribution is built <a href="https://github.com/tensorflow/tensorflow/issues/7778" rel="noreferrer">without CPU extensions</a>, such as SSE4.1, SSE4.2, AVX, AVX2, FMA, etc. The default builds (ones from <code>pip install tensorflow</code>) are intended to be compatible with as many CPUs as possible. Another argument is that even with these extensions CPU is a lot slower than a GPU, and it's expected for medium- and large-scale machine-learning training to be performed on a GPU.</p> <h2>What should you do?</h2> <p><strong>If you have a GPU</strong>, you shouldn't care about AVX support, because most expensive ops will be dispatched on a GPU device (unless explicitly set not to). In this case, you can simply ignore this warning by</p> <pre><code># Just disables the warning, doesn't take advantage of AVX/FMA to run faster import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' </code></pre> <p>... or by setting <code>export TF_CPP_MIN_LOG_LEVEL=2</code> if you're on Unix. Tensorflow is working fine anyway, but you won't see these annoying warnings.</p> <hr /> <p><strong>If you don't have a GPU</strong> and want to utilize CPU as much as possible, <strong>you should build tensorflow from the source optimized for <em>your</em> CPU</strong> with AVX, AVX2, and FMA enabled if your CPU supports them. It's been discussed in <a href="https://stackoverflow.com/q/41293077/712995">this question</a> and also <a href="https://github.com/tensorflow/tensorflow/issues/8037" rel="noreferrer">this GitHub issue</a>. Tensorflow uses an ad-hoc build system called <a href="https://bazel.build/" rel="noreferrer">bazel</a> and building it is not that trivial, but is certainly doable. After this, not only will the warning disappear, tensorflow performance should also improve.</p>
{ "question_id": 47068709, "question_date": "2017-11-02T06:10:46.210Z", "question_score": 764, "tags": "python|tensorflow|cpu|avx", "answer_id": 47227886, "answer_date": "2017-11-10T17:07:34.190Z", "answer_score": 938 }
Please answer the following Stack Overflow question: Title: Volatile vs. Interlocked vs. lock <p>Let's say that a class has a <code>public int counter</code> field that is accessed by multiple threads. This <code>int</code> is only incremented or decremented.</p> <p>To increment this field, which approach should be used, and why?</p> <ul> <li><code>lock(this.locker) this.counter++;</code>,</li> <li><code>Interlocked.Increment(ref this.counter);</code>,</li> <li>Change the access modifier of <code>counter</code> to <code>public volatile</code>.</li> </ul> <p>Now that I've discovered <code>volatile</code>, I've been removing many <code>lock</code> statements and the use of <code>Interlocked</code>. But is there a reason not to do this?</p>
<h3>Worst (won't actually work)</h3> <blockquote> <p>Change the access modifier of <code>counter</code> to <code>public volatile</code></p> </blockquote> <p>As other people have mentioned, this on its own isn't actually safe at all. The point of <code>volatile</code> is that multiple threads running on multiple CPUs can and will cache data and re-order instructions.</p> <p>If it is <strong>not</strong> <code>volatile</code>, and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems.</p> <p>If it is <code>volatile</code>, this just ensures the two CPUs see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid.</p> <h3>Second Best:</h3> <blockquote> <p><code>lock(this.locker) this.counter++</code>;</p> </blockquote> <p>This is safe to do (provided you remember to <code>lock</code> everywhere else that you access <code>this.counter</code>). It prevents any other threads from executing any other code which is guarded by <code>locker</code>. Using locks also, prevents the multi-CPU reordering problems as above, which is great.</p> <p>The problem is, locking is slow, and if you re-use the <code>locker</code> in some other place which is not really related then you can end up blocking your other threads for no reason.</p> <h3>Best</h3> <blockquote> <p><code>Interlocked.Increment(ref this.counter);</code></p> </blockquote> <p>This is safe, as it effectively does the read, increment, and write in 'one hit' which can't be interrupted. Because of this, it won't affect any other code, and you don't need to remember to lock elsewhere either. It's also very fast (as MSDN says, on modern CPUs, this is often literally a single CPU instruction).</p> <p><s> I'm not entirely sure however if it gets around other CPUs reordering things, or if you also need to combine volatile with the increment.</s></p> <p>InterlockedNotes:</p> <ol> <li>INTERLOCKED METHODS ARE CONCURRENTLY SAFE ON ANY NUMBER OF COREs OR CPUs.</li> <li>Interlocked methods apply a full fence around instructions they execute, so reordering does not happen.</li> <li>Interlocked methods <strong>do not need or even do not support access to a volatile field</strong>, as volatile is placed a half fence around operations on given field and interlocked is using the full fence.</li> </ol> <h3>Footnote: What volatile is actually good for.</h3> <p>As <code>volatile</code> doesn't prevent these kinds of multithreading issues, what's it for? A good example is saying you have two threads, one which always writes to a variable (say <code>queueLength</code>), and one which always reads from that same variable.</p> <p>If <code>queueLength</code> is not volatile, thread A may write five times, but thread B may see those writes as being delayed (or even potentially in the wrong order).</p> <p>A solution would be to lock, but you could also use volatile in this situation. This would ensure that thread B will always see the most up-to-date thing that thread A has written. Note however that this logic <em>only</em> works if you have writers who never read, and readers who never write, <em>and</em> if the thing you're writing is an atomic value. As soon as you do a single read-modify-write, you need to go to Interlocked operations or use a Lock.</p>
{ "question_id": 154551, "question_date": "2008-09-30T19:25:06.760Z", "question_score": 764, "tags": "c#|multithreading|locking|volatile|interlocked", "answer_id": 154803, "answer_date": "2008-09-30T20:13:08.237Z", "answer_score": 966 }
Please answer the following Stack Overflow question: Title: Rename column SQL Server 2008 <p>I am using SQL Server 2008 and Navicat. I need to rename a column in a table using SQL.</p> <pre><code>ALTER TABLE table_name RENAME COLUMN old_name to new_name; </code></pre> <p>This statement doesn't work.</p>
<p>Use <code>sp_rename</code></p> <pre><code>EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN' </code></pre> <p>See: <a href="http://blog.sqlauthority.com/2008/08/26/sql-server-how-to-rename-a-column-name-or-table-name/" rel="noreferrer">SQL SERVER – How to Rename a Column Name or Table Name</a></p> <p>Documentation: <a href="https://docs.microsoft.com/de-de/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql" rel="noreferrer"><strong>sp_rename</strong> (Transact-SQL)</a></p> <p>For your case it would be:</p> <pre><code>EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN' </code></pre> <p>Remember to use single quotes to enclose your values. </p>
{ "question_id": 16296622, "question_date": "2013-04-30T09:34:48.440Z", "question_score": 763, "tags": "sql|sql-server|sql-server-2008|alter-table", "answer_id": 16296669, "answer_date": "2013-04-30T09:37:16.023Z", "answer_score": 1391 }
Please answer the following Stack Overflow question: Title: How can I access my localhost from my Android device? <p>I'm able to access my laptop web server using the Android emulator, I'm using <code>10.0.2.2:portno</code> works well.</p> <p>But when I connect my real Android phone, the phone browser can't connect to the same web server on my laptop. The phone is connected to the laptop using a USB cable. If I run the adb devices command, I can see my phone.</p> <p>What am I missing?</p>
<p>USB doesn't provide network to mobile device. </p> <p><strong>If both your desktop and phone are connected to the same WiFi</strong> (or any other local network), then use your desktop IP address assigned by the router (not <code>localhost</code> and not <code>127.0.0.1</code>). </p> <p>To find out the IP address of your desktop: </p> <ul> <li>type into the command line <code>ipconfig</code> (Windows) or <code>ifconfig</code> (Unix) <ul> <li>on Linux the one-liner <code>ifconfig | grep "inet " | grep -v 127.0.0.1</code> will yield only the important stuff</li> <li>there's a <a href="https://superuser.com/questions/19992/ipconfig-for-one-network-adaptor-only">bunch of suggestions</a> on how to have a similar output on Windows</li> </ul></li> <li>there's going to be a bunch of IP's</li> <li>try all of them (except the forementioned <code>localhost</code> and <code>127.0.0.1</code>)</li> </ul> <p><strong>If your phone is connected to the mobile network</strong>, then things are going to be harder. </p> <p>Either go hardcore:</p> <ul> <li>first find out your router external IP address (<a href="https://www.google.de/search?q=myip" rel="noreferrer">https://www.google.de/search?q=myip</a>)</li> <li>then, on the router, forward some port to <code>&lt;your desktop IP&gt;:&lt;server port number&gt;</code></li> <li>finally use the external IP address and forwarded port</li> </ul> <p>Otherwise use something like <a href="http://xip.io/" rel="noreferrer">xip.io</a> or <a href="https://ngrok.com/" rel="noreferrer">ngrok</a>.</p> <p><strong>NOTE</strong>: The <code>ifconfig</code> command has been deprecated and thus missing by default on Debian Linux, starting from Debian stretch. The new and recommended alternative for examining a network configuration on Debian Linux is ip command. For example to use ip command to display a network configuration run the following:</p> <pre><code>ip address </code></pre> <p>The above ip command can be abbreviated to:</p> <pre><code>ip a </code></pre> <p>If you still prefer to use <code>ifconfig</code> as part of your daily sys admin routine, you can easily install it as part of the <code>net-tools</code> package.</p> <pre><code>apt-get install net-tools </code></pre> <p>Reference is <a href="https://linuxconfig.org/how-to-install-missing-ifconfig-command-on-debian-linux" rel="noreferrer">here</a></p>
{ "question_id": 4779963, "question_date": "2011-01-24T08:27:52.753Z", "question_score": 763, "tags": "android", "answer_id": 4779992, "answer_date": "2011-01-24T08:35:22.543Z", "answer_score": 578 }
Please answer the following Stack Overflow question: Title: What is the difference between dict.items() and dict.iteritems() in Python2? <p>Are there any applicable differences between <a href="http://docs.python.org/library/stdtypes.html#dict.items" rel="noreferrer"><code>dict.items()</code></a> and <a href="http://docs.python.org/library/stdtypes.html#dict.iteritems" rel="noreferrer"><code>dict.iteritems()</code></a>?</p> <p>From the <a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="noreferrer">Python docs</a>:</p> <blockquote> <p><code>dict.items()</code>: Return a <strong>copy</strong> of the dictionary’s list of (key, value) pairs.</p> <p><code>dict.iteritems()</code>: Return an <strong>iterator</strong> over the dictionary’s (key, value) pairs.</p> </blockquote> <p>If I run the code below, each seems to return a reference to the same object. Are there any subtle differences that I am missing?</p> <pre><code>#!/usr/bin/python d={1:'one',2:'two',3:'three'} print 'd.items():' for k,v in d.items(): if d[k] is v: print '\tthey are the same object' else: print '\tthey are different' print 'd.iteritems():' for k,v in d.iteritems(): if d[k] is v: print '\tthey are the same object' else: print '\tthey are different' </code></pre> <p>Output:</p> <pre><code>d.items(): they are the same object they are the same object they are the same object d.iteritems(): they are the same object they are the same object they are the same object </code></pre>
<p>It's part of an evolution.</p> <p>Originally, Python <code>items()</code> built a real list of tuples and returned that. That could potentially take a lot of extra memory.</p> <p>Then, generators were introduced to the language in general, and that method was reimplemented as an iterator-generator method named <code>iteritems()</code>. The original remains for backwards compatibility.</p> <p>One of Python 3’s changes is that <code>items()</code> now return views, and a <code>list</code> is never fully built. The <code>iteritems()</code> method is also gone, since <code>items()</code> in Python 3 works like <code>viewitems()</code> in Python 2.7.</p>
{ "question_id": 10458437, "question_date": "2012-05-05T02:58:27.393Z", "question_score": 763, "tags": "python|dictionary|python-2.x", "answer_id": 10458567, "answer_date": "2012-05-05T03:26:27.157Z", "answer_score": 928 }
Please answer the following Stack Overflow question: Title: How do I get NuGet to install/update all the packages in the packages.config? <p>I have a solution with multiple projects in it. Most of the third party references are missing, yet there are <code>packages.config</code> file for each project. <strong>How do I get NuGet to install/update all the packages needed?</strong> Does this need to be done via command line for each project?</p>
<p>You can use <a href="https://github.com/nuget/home" rel="noreferrer">nuget.exe</a> to restore your packages or with NuGet 2.7, or above, installed you can simply compile your solution in Visual Studio, which will also restore the missing packages.</p> <p>For NuGet.exe you can run the following command for each project.</p> <pre><code>nuget install packages.config </code></pre> <p>Or with <a href="https://docs.microsoft.com/en-au/nuget/tools/cli-ref-restore" rel="noreferrer">NuGet 2.7 you can restore all packages in the solution</a> using the command line.</p> <pre><code>nuget restore YourSolution.sln </code></pre> <p>Both of these will pull down the packages. Your project files will not be modified however when running this command so the project should already have a reference to the NuGet packages. If this is not the case then you can use Visual Studio to install the packages.</p> <p>With NuGet 2.7, and above, Visual Studio will automatically restore missing NuGet packages when you build your solution so there is no need to use NuGet.exe.</p> <p>To update all the packages in your solution, first restore them, and then you can either use NuGet.exe to update the packages or from within Visual Studio you can update the packages from the Package Manager Console window, or finally you can use the Manage Packages dialog.</p> <p>From the command line you can update packages in the solution to the latest version available from nuget.org.</p> <pre><code>nuget update YourSolution.sln </code></pre> <p>Note that this will not run any PowerShell scripts in any NuGet packages.</p> <p>From within Visual Studio you can use the <a href="http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference" rel="noreferrer">Package Manager Console</a> to also update the packages. This has the benefit that any PowerShell scripts will be run as part of the update where as using NuGet.exe will not run them. The following command will update all packages in every project to the latest version available from nuget.org.</p> <pre><code>Update-Package </code></pre> <p>You can also restrict this down to one project.</p> <pre><code>Update-Package -Project YourProjectName </code></pre> <p>If you want to reinstall the packages to the same versions as were previously installed then you can use the <code>-reinstall</code> argument with <code>Update-Package</code> command.</p> <pre><code>Update-Package -reinstall </code></pre> <p>You can also restrict this down to one project.</p> <pre><code>Update-Package -reinstall -Project YourProjectName </code></pre> <p>The <code>-reinstall</code> option will first uninstall and then install the package back again into a project.</p> <p>Or, you can update the packages using the <code>Manage Packages</code> dialog.</p> <p><strong>Updates:</strong></p> <ul> <li><strong>2013/07/10</strong> - Updated with information about nuget restore in NuGet 2.7</li> <li><strong>2014/07/06</strong> - Updated with information about automatic package restore in Visual Studio and brought the answer up to date with other changes to NuGet.</li> <li><strong>2014/11/21</strong> - Updated with information about <code>-reinstall</code></li> </ul>
{ "question_id": 6876732, "question_date": "2011-07-29T17:23:42.013Z", "question_score": 763, "tags": "nuget", "answer_id": 6882750, "answer_date": "2011-07-30T11:11:23.433Z", "answer_score": 959 }
Please answer the following Stack Overflow question: Title: What is a stack trace, and how can I use it to debug my application errors? <p>Sometimes when I run my application it gives me an error that looks like:</p> <pre><code>Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) </code></pre> <p>People have referred to this as a "stack trace". <strong>What is a stack trace?</strong> What can it tell me about the error that's happening in my program?</p> <hr/> <p><em>About this question - quite often I see a question come through where a novice programmer is "getting an error", and they simply paste their stack trace and some random block of code without understanding what the stack trace is or how they can use it. This question is intended as a reference for novice programmers who might need help understanding the value of a stack trace.</em></p>
<p>In simple terms, a <strong>stack trace</strong> is a list of the method calls that the application was in the middle of when an Exception was thrown.</p> <p><strong>Simple Example</strong></p> <p>With the example given in the question, we can determine exactly where the exception was thrown in the application. Let's have a look at the stack trace:</p> <pre><code>Exception in thread &quot;main&quot; java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) </code></pre> <p>This is a very simple stack trace. If we start at the beginning of the list of &quot;at ...&quot;, we can tell where our error happened. What we're looking for is the <strong>topmost</strong> method call that is part of our application. In this case, it's:</p> <pre><code>at com.example.myproject.Book.getTitle(Book.java:16) </code></pre> <p>To debug this, we can open up <code>Book.java</code> and look at line <code>16</code>, which is:</p> <pre><code>15 public String getTitle() { 16 System.out.println(title.toString()); 17 return title; 18 } </code></pre> <p>This would indicate that something (probably <code>title</code>) is <code>null</code> in the above code.</p> <p><strong>Example with a chain of exceptions</strong></p> <p>Sometimes applications will catch an Exception and re-throw it as the cause of another Exception. This typically looks like:</p> <pre><code>34 public void getBookIds(int id) { 35 try { 36 book.getId(id); // this method it throws a NullPointerException on line 22 37 } catch (NullPointerException e) { 38 throw new IllegalStateException(&quot;A book has a null property&quot;, e) 39 } 40 } </code></pre> <p>This might give you a stack trace that looks like:</p> <pre><code>Exception in thread &quot;main&quot; java.lang.IllegalStateException: A book has a null property at com.example.myproject.Author.getBookIds(Author.java:38) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) Caused by: java.lang.NullPointerException at com.example.myproject.Book.getId(Book.java:22) at com.example.myproject.Author.getBookIds(Author.java:36) ... 1 more </code></pre> <p>What's different about this one is the &quot;Caused by&quot;. Sometimes exceptions will have multiple &quot;Caused by&quot; sections. For these, you typically want to find the &quot;root cause&quot;, which will be one of the lowest &quot;Caused by&quot; sections in the stack trace. In our case, it's:</p> <pre><code>Caused by: java.lang.NullPointerException &lt;-- root cause at com.example.myproject.Book.getId(Book.java:22) &lt;-- important line </code></pre> <p>Again, with this exception we'd want to look at line <code>22</code> of <code>Book.java</code> to see what might cause the <code>NullPointerException</code> here.</p> <p><strong>More daunting example with library code</strong></p> <p>Usually stack traces are much more complex than the two examples above. Here's an example (it's a long one, but demonstrates several levels of chained exceptions):</p> <pre><code>javax.servlet.ServletException: Something bad happened at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Caused by: com.example.myproject.MyProjectServletException at com.example.myproject.MyServlet.doPost(MyServlet.java:169) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30) ... 27 more Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [com.example.myproject.MyEntity] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2822) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344) at $Proxy19.save(Unknown Source) at com.example.myproject.MyEntityService.save(MyEntityService.java:59) &lt;-- relevant call (see notes below) at com.example.myproject.MyServlet.doPost(MyServlet.java:164) ... 32 more Caused by: java.sql.SQLException: Violation of unique constraint MY_ENTITY_UK_1: duplicate value(s) for column(s) MY_COLUMN in statement [...] at org.hsqldb.jdbc.Util.throwError(Unknown Source) at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105) at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57) ... 54 more </code></pre> <p>In this example, there's a lot more. What we're mostly concerned about is looking for methods that are from <em>our code</em>, which would be anything in the <code>com.example.myproject</code> package. From the second example (above), we'd first want to look down for the root cause, which is:</p> <pre><code>Caused by: java.sql.SQLException </code></pre> <p>However, all the method calls under that are library code. So we'll <strong>move up</strong> to the <strong>&quot;Caused by&quot; above</strong> it, and in that &quot;Caused by&quot; block, look for the <strong>first method call originating from our code</strong>, which is:</p> <pre><code>at com.example.myproject.MyEntityService.save(MyEntityService.java:59) </code></pre> <p>Like in previous examples, we should look at <code>MyEntityService.java</code> on line <code>59</code>, because that's where this error originated (this one's a bit obvious what went wrong, since the SQLException states the error, but the debugging procedure is what we're after).</p>
{ "question_id": 3988788, "question_date": "2010-10-21T14:52:24.783Z", "question_score": 763, "tags": "java|debugging|stack-trace", "answer_id": 3988794, "answer_date": "2010-10-21T14:52:43.160Z", "answer_score": 718 }
Please answer the following Stack Overflow question: Title: How to squash commits in git after they have been pushed? <p>This gives a good explanation of squashing multiple commits:</p> <p><a href="http://git-scm.com/book/en/Git-Branching-Rebasing" rel="noreferrer">http://git-scm.com/book/en/Git-Branching-Rebasing</a></p> <p>but it does not work for commits that have already been pushed. How do I squash the most recent few commits both in my local and remote repos?</p> <p>When I do <code>git rebase -i origin/master~4 master</code>, keep the first one as <code>pick</code>, set the other three as <code>squash</code>, and then exit (via c-x c-c in emacs), I get:</p> <pre><code>$ git rebase -i origin/master~4 master # Not currently on any branch. nothing to commit (working directory clean) Could not apply 2f40e2c... Revert &quot;issue 4427: bpf device permission change option added&quot; $ git rebase -i origin/master~4 master Interactive rebase already started </code></pre> <p>where 2f40 is the <code>pick</code> commit. And now none of the 4 commits appear in <code>git log</code>. I expected my editor to be restarted so that I could enter a commit message. What am I doing wrong?</p>
<p>Squash commits locally with </p> <pre><code>git rebase -i origin/master~4 master </code></pre> <p>and then force push with </p> <pre><code>git push origin +master </code></pre> <hr> <h3>Difference between <code>--force</code> and <code>+</code></h3> <p>From the documentation of <a href="https://git-scm.com/docs/git-push#Documentation/git-push.txt---force" rel="noreferrer"><code>git push</code></a>: </p> <blockquote> <p>Note that <code>--force</code> applies to all the refs that are pushed, hence using it with <code>push.default</code> set to <code>matching</code> or with multiple push destinations configured with <code>remote.*.push</code> may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a <code>+</code> in front of the refspec to push (e.g <code>git push origin +master</code> to force a push to the <code>master</code> branch).</p> </blockquote>
{ "question_id": 5667884, "question_date": "2011-04-14T18:31:50.637Z", "question_score": 763, "tags": "git|squash", "answer_id": 5668050, "answer_date": "2011-04-14T18:43:54.973Z", "answer_score": 1032 }
Please answer the following Stack Overflow question: Title: Include another HTML file in a HTML file <p>I have 2 HTML files, suppose <code>a.html</code> and <code>b.html</code>. In <code>a.html</code> I want to include <code>b.html</code>.</p> <p>In JSF I can do it like that:</p> <pre><code>&lt;ui:include src="b.xhtml" /&gt; </code></pre> <p>It means that inside <code>a.xhtml</code> file, I can include <code>b.xhtml</code>.</p> <p>How can we do it in <code>*.html</code> file?</p>
<p>In my opinion the best solution uses jQuery:</p> <p><code>a.html</code>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $(function(){ $("#includedContent").load("b.html"); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="includedContent"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><code>b.html</code>:</p> <pre><code>&lt;p&gt;This is my include file&lt;/p&gt; </code></pre> <p>This method is a simple and clean solution to my problem.</p> <p>The jQuery <code>.load()</code> documentation is <a href="http://api.jquery.com/load/">here</a>.</p>
{ "question_id": 8988855, "question_date": "2012-01-24T14:51:16.640Z", "question_score": 762, "tags": "javascript|html|dom|include", "answer_id": 9003363, "answer_date": "2012-01-25T13:17:19.010Z", "answer_score": 792 }
Please answer the following Stack Overflow question: Title: Differences between Emacs and Vim <p>Without getting into a religious argument about why one is better than the other, what are the <strong>practical</strong> differences between Emacs and Vim? I'm looking to learn one or the other, but I realize the learning curve for each is high and I can't decide. I have never used an editor of this type (I've always used IDEs), so anything that helps a newbie is a plus.</p> <hr> <p>Before a flame war starts: I'm not asking which is better, I'm asking the differences between the two. I would like an <strong>objective</strong> comparison.</p>
<p><em>(the text below is my opinion, it should not be taken as fact or an insult)</em></p> <p>With Emacs you are expected to have it open 24/7 and live inside the program, almost everything you do can be done from there. You write your own extensions, use it for note-taking, organization, games, programming, shell access, file access, listening to music, web browsing. It takes weeks and weeks till you will be happy with it and then you will learn new stuff all the time. You will be annoyed when you don't have access to it and constantly change your config. You won't be able to use other peoples emacs versions easily and it won't just be installed. It uses Lisp, which is great. You can make it into anything you want it to be. (anything, at all)</p> <p>With Vim, it's almost always pre-installed. It's fast. You open up a file do a quick edit and then quit. You can work with the basic setup if you are on someone else's machine. It's not quite so editable, but it's still far better than most text editors. It recognizes that most of the time you are reading/editing not typing and makes that portion faster. You don't suffer from <em><a href="https://en.wikipedia.org/wiki/Emacs#Emacs_pinky" rel="noreferrer">emacs pinkie</a></em>. It's not so infuriating. It's easier to learn. </p> <p><em>Even though I use Emacs all day every day (and love it) unless you intend to spend a lot of time in the program you choose I would pick vim</em></p>
{ "question_id": 1430164, "question_date": "2009-09-15T23:32:15.240Z", "question_score": 762, "tags": "vim|emacs|editor", "answer_id": 1433315, "answer_date": "2009-09-16T14:26:35.550Z", "answer_score": 554 }
Please answer the following Stack Overflow question: Title: Convert all strings in a list to int <p>How do I convert all strings in a list to integers?</p> <pre><code>['1', '2', '3'] ⟶ [1, 2, 3] </code></pre>
<p>Given:</p> <pre><code>xs = ['1', '2', '3'] </code></pre> <p>Use <a href="https://docs.python.org/3/library/functions.html#map" rel="noreferrer"><code>map</code></a> then <code>list</code> to obtain a list of integers:</p> <pre><code>list(map(int, xs)) </code></pre> <p>In Python 2, <code>list</code> was unnecessary since <a href="https://docs.python.org/2/library/functions.html#map" rel="noreferrer"><code>map</code></a> returned a list:</p> <pre><code>map(int, xs) </code></pre>
{ "question_id": 7368789, "question_date": "2011-09-10T00:28:08.950Z", "question_score": 761, "tags": "python|list|integer", "answer_id": 7368801, "answer_date": "2011-09-10T00:30:17.100Z", "answer_score": 1424 }
Please answer the following Stack Overflow question: Title: Remove ALL white spaces from text <pre><code>$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current"); </code></pre> <p>This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters. </p> <p>I would like the white spaces removed. I have tried <code>TRIM()</code>and <code>REPLACE()</code> but this only partially works. The <code>REPLACE()</code> only removes the 1st space.</p>
<p>You have to tell replace() to repeat the regex:</p> <pre><code>.replace(/ /g,'') </code></pre> <p>The <strong>g</strong> character makes it a &quot;global&quot; match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript <a href="http://www.w3schools.com/jsref/jsref_obj_regexp.asp" rel="noreferrer">here</a>.</p> <p>If you want to match all whitespace, and not just the literal space character, use <code>\s</code> instead:</p> <pre><code>.replace(/\s/g,'') </code></pre> <p>You can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll" rel="noreferrer"><code>.replaceAll</code></a> if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching <em>all</em> whitespace requires a regex, and when using a regex with <code>.replaceAll</code>, it must be global, so you just end up with extra typing:</p> <pre><code>.replaceAll(/\s/g,'') </code></pre>
{ "question_id": 6623231, "question_date": "2011-07-08T10:33:09.847Z", "question_score": 761, "tags": "javascript|jquery", "answer_id": 6623263, "answer_date": "2011-07-08T10:36:19.347Z", "answer_score": 1724 }
Please answer the following Stack Overflow question: Title: How do I clear my local working directory in Git? <p>How can I clear my working directory in Git?</p>
<p>To reset a specific file to the last-committed state (to discard uncommitted changes in a specific file):</p> <pre><code>git checkout thefiletoreset.txt </code></pre> <p>This is mentioned in the <code>git status</code> output:</p> <pre><code>(use "git checkout -- &lt;file&gt;..." to discard changes in working directory) </code></pre> <p>To reset the entire repository to the last committed state:</p> <pre><code>git reset --hard </code></pre> <p>To remove untracked files, I usually just delete all files in the working copy (but <strong>not</strong> the <code>.git/</code> folder!), then do <code>git reset --hard</code> which leaves it with only committed files.</p> <p>A better way is to use <code>git clean</code> (<strong>warning</strong>: using the <code>-x</code> flag as below will cause Git to delete ignored files): </p> <pre><code>git clean -d -x -f </code></pre> <p>will remove untracked files, including directories (<code>-d</code>) and files ignored by git (<code>-x</code>). Replace the <code>-f</code> argument with <code>-n</code> to perform a dry-run or <code>-i</code> for interactive mode, and it will tell you what will be removed.</p> <p>Relevant links:</p> <ul> <li><a href="http://git-scm.com/docs/git-reset" rel="noreferrer">git-reset man page</a></li> <li><a href="http://www.kernel.org/pub/software/scm/git/docs/git-clean.html" rel="noreferrer">git-clean man page</a></li> <li><a href="http://www.gitready.com/beginner/2009/01/16/cleaning-up-untracked-files.html" rel="noreferrer">git ready "cleaning up untracked files"</a> (as Marko posted)</li> <li>Stack Overflow question <em><a href="https://stackoverflow.com/questions/61212/how-to-remove-local-untracked-files-from-the-current-git-working-tree">"How to remove local (untracked) files from the current Git working tree"</a></em>)</li> </ul>
{ "question_id": 673407, "question_date": "2009-03-23T13:43:19.223Z", "question_score": 761, "tags": "git", "answer_id": 675797, "answer_date": "2009-03-24T00:57:22.787Z", "answer_score": 1148 }
Please answer the following Stack Overflow question: Title: How can I turn a List of Lists into a List in Java 8? <p>If I have a <code>List&lt;List&lt;Object&gt;&gt;</code>, how can I turn that into a <code>List&lt;Object&gt;</code> that contains all the objects in the same iteration order by using the features of Java 8?</p>
<p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#flatMap-java.util.function.Function-" rel="noreferrer"><code>flatMap</code></a> to flatten the internal lists (after converting them to Streams) into a single Stream, and then collect the result into a list:</p> <pre><code>List&lt;List&lt;Object&gt;&gt; list = ... List&lt;Object&gt; flat = list.stream() .flatMap(List::stream) .collect(Collectors.toList()); </code></pre>
{ "question_id": 25147094, "question_date": "2014-08-05T19:48:00.293Z", "question_score": 761, "tags": "java|collections|java-8", "answer_id": 25147125, "answer_date": "2014-08-05T19:50:04.910Z", "answer_score": 1338 }
Please answer the following Stack Overflow question: Title: How to include files outside of Docker's build context? <p>How can I include files from outside of Docker's build context using the "ADD" command in the Docker file?</p> <p>From the Docker documentation:</p> <blockquote> <p>The path must be inside the context of the build; you cannot ADD ../something/something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon.</p> </blockquote> <p>I do not want to restructure my whole project just to accommodate Docker in this matter. I want to keep all my Docker files in the same sub-directory.</p> <p>Also, it appears Docker does not yet (and may not ever) support symlinks: <a href="https://github.com/docker/docker/issues/1676" rel="noreferrer">Dockerfile ADD command does not follow symlinks on host #1676.</a> </p> <p>The only other thing I can think of is to include a pre-build step to copy the files into the Docker build context (and configure my version control to ignore those files). Is there a better workaround for than that?</p>
<p>The best way to work around this is to specify the Dockerfile independently of the build context, using -f.</p> <p>For instance, this command will give the ADD command access to anything in your current directory.</p> <pre><code>docker build -f docker-files/Dockerfile . </code></pre> <p><strong>Update</strong>: Docker now allows having the Dockerfile outside the build context (fixed in 18.03.0-ce). So you can also do something like</p> <pre><code>docker build -f ../Dockerfile . </code></pre>
{ "question_id": 27068596, "question_date": "2014-11-21T19:11:28.247Z", "question_score": 761, "tags": "docker", "answer_id": 34392052, "answer_date": "2015-12-21T09:02:47.807Z", "answer_score": 641 }
Please answer the following Stack Overflow question: Title: MySQL Query GROUP BY day / month / year <p>Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a <code>TIMESTAMP</code> field, like: </p> <pre><code>SELECT COUNT(id) FROM stats WHERE record_date.YEAR = 2009 GROUP BY record_date.YEAR </code></pre> <p>Or even:</p> <pre><code>SELECT COUNT(id) FROM stats GROUP BY record_date.YEAR, record_date.MONTH </code></pre> <p>To have a monthly statistic. </p> <p>Thanks!</p>
<pre><code>GROUP BY YEAR(record_date), MONTH(record_date) </code></pre> <p>Check out the <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_month" rel="noreferrer">date and time functions</a> in MySQL.</p>
{ "question_id": 508791, "question_date": "2009-02-03T20:29:19.177Z", "question_score": 760, "tags": "mysql|sql|date|datetime|group-by", "answer_id": 508806, "answer_date": "2009-02-03T20:33:38.717Z", "answer_score": 1174 }
Please answer the following Stack Overflow question: Title: Saving UTF-8 texts with json.dumps as UTF-8, not as a \u escape sequence <p>Sample code (in a <a href="https://en.wikipedia.org/wiki/Read-eval-print_loop" rel="noreferrer">REPL</a>):</p> <pre><code>import json json_string = json.dumps(&quot;ברי צקלה&quot;) print(json_string) </code></pre> <p>Output:</p> <pre><code>&quot;\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4&quot; </code></pre> <p>The problem: it's not human readable. My (smart) users want to verify or even edit text files with JSON dumps (and I’d rather not use XML).</p> <p>Is there a way to serialize objects into UTF-8 JSON strings (instead of <code>\uXXXX</code>)?</p>
<p>Use the <code>ensure_ascii=False</code> switch to <code>json.dumps()</code>, then encode the value to UTF-8 manually:</p> <pre><code>&gt;&gt;&gt; json_string = json.dumps("ברי צקלה", ensure_ascii=False).encode('utf8') &gt;&gt;&gt; json_string b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"' &gt;&gt;&gt; print(json_string.decode()) "ברי צקלה" </code></pre> <p>If you are writing to a file, just use <code>json.dump()</code> and leave it to the file object to encode:</p> <pre><code>with open('filename', 'w', encoding='utf8') as json_file: json.dump("ברי צקלה", json_file, ensure_ascii=False) </code></pre> <p><strong>Caveats for Python 2</strong></p> <p>For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use <a href="https://docs.python.org/2/library/io.html#io.open" rel="noreferrer"><code>io.open()</code></a> instead of <code>open()</code> to produce a file object that encodes Unicode values for you as you write, then use <code>json.dump()</code> instead to write to that file:</p> <pre><code>with io.open('filename', 'w', encoding='utf8') as json_file: json.dump(u"ברי צקלה", json_file, ensure_ascii=False) </code></pre> <p>Do note that there is a <a href="http://bugs.python.org/issue13769" rel="noreferrer">bug in the <code>json</code> module</a> where the <code>ensure_ascii=False</code> flag can produce a <em>mix</em> of <code>unicode</code> and <code>str</code> objects. The workaround for Python 2 then is:</p> <pre><code>with io.open('filename', 'w', encoding='utf8') as json_file: data = json.dumps(u"ברי צקלה", ensure_ascii=False) # unicode(data) auto-decodes data to unicode if str json_file.write(unicode(data)) </code></pre> <p>In Python 2, when using byte strings (type <code>str</code>), encoded to UTF-8, make sure to also set the <code>encoding</code> keyword:</p> <pre><code>&gt;&gt;&gt; d={ 1: "ברי צקלה", 2: u"ברי צקלה" } &gt;&gt;&gt; d {1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'} &gt;&gt;&gt; s=json.dumps(d, ensure_ascii=False, encoding='utf8') &gt;&gt;&gt; s u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}' &gt;&gt;&gt; json.loads(s)['1'] u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4' &gt;&gt;&gt; json.loads(s)['2'] u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4' &gt;&gt;&gt; print json.loads(s)['1'] ברי צקלה &gt;&gt;&gt; print json.loads(s)['2'] ברי צקלה </code></pre>
{ "question_id": 18337407, "question_date": "2013-08-20T14:18:18.580Z", "question_score": 760, "tags": "python|json|unicode|utf-8|escaping", "answer_id": 18337754, "answer_date": "2013-08-20T14:33:20.163Z", "answer_score": 1092 }
Please answer the following Stack Overflow question: Title: MongoDB vs. Cassandra <p>I am evaluating what might be the best migration option.</p> <p>Currently, I am on a sharded MySQL (horizontal partition), with most of my data stored in JSON blobs. I do not have any complex SQL queries (already migrated away after since I partitioned my db).</p> <p>Right now, it seems like both MongoDB and Cassandra would be likely options. My situation:</p> <ul> <li>Lots of reads in every query, less regular writes</li> <li>Not worried about "massive" scalability</li> <li>More concerned about simple setup, maintenance and code</li> <li>Minimize hardware/server cost</li> </ul>
<p><strong>Lots of reads in every query, fewer regular writes</strong></p> <p>Both databases perform well on reads where the hot data set fits in memory. Both also emphasize join-less data models (and encourage denormalization instead), and both provide indexes on <a href="http://www.mongodb.org/display/DOCS/Indexes" rel="noreferrer">documents</a> or <a href="http://www.datastax.com/dev/blog/whats-new-cassandra-07-secondary-indexes" rel="noreferrer">rows</a>, although MongoDB's indexes are currently more flexible.</p> <p>Cassandra's storage engine provides constant-time writes no matter how big your data set grows. Writes are more problematic in MongoDB, partly because of the b-tree based storage engine, but more because of the <a href="http://www.mongodb.org/display/DOCS/How+does+concurrency+work" rel="noreferrer">multi-granularity locking</a> it does.</p> <p>For analytics, MongoDB provides a custom map/reduce implementation; Cassandra provides native Hadoop support, including for <a href="http://hive.apache.org" rel="noreferrer">Hive</a> (a SQL data warehouse built on Hadoop map/reduce) and <a href="http://pig.apache.org" rel="noreferrer">Pig</a> (a Hadoop-specific analysis language that many think is a better fit for map/reduce workloads than SQL). Cassandra also supports use of <a href="https://github.com/datastax/spark-cassandra-connector/blob/master/doc/0_quick_start.md" rel="noreferrer">Spark</a>.</p> <p><strong>Not worried about "massive" scalability</strong></p> <p>If you're looking at a single server, MongoDB is probably a better fit. For those more concerned about scaling, Cassandra's no-single-point-of-failure architecture will be easier to set up and more reliable. (MongoDB's global write lock tends to become more painful, too.) Cassandra also gives a lot more control over how your replication works, including support for multiple data centers.</p> <p><strong>More concerned about simple setup, maintenance and code</strong></p> <p>Both are trivial to set up, with reasonable out-of-the-box defaults for a single server. Cassandra is simpler to set up in a multi-server configuration since there are no special-role nodes to worry about.</p> <p>If you're presently using JSON blobs, MongoDB is an insanely good match for your use case, given that it uses BSON to store the data. You'll be able to have richer and more queryable data than you would in your present database. This would be the most significant win for Mongo.</p>
{ "question_id": 2892729, "question_date": "2010-05-23T17:39:56.540Z", "question_score": 760, "tags": "mongodb|database-design|cassandra|database", "answer_id": 2894665, "answer_date": "2010-05-24T03:58:46.430Z", "answer_score": 599 }
Please answer the following Stack Overflow question: Title: Solr vs. ElasticSearch <p>What are the core architectural differences between these technologies? </p> <p>Also, what use cases are generally more appropriate for each?</p>
<h2>Update</h2> <p>Now that the question scope has been corrected, I might add something in this regard as well:</p> <p>There are many comparisons between <a href="http://lucene.apache.org/solr/" rel="noreferrer">Apache Solr</a> and <a href="https://www.elastic.co/" rel="noreferrer">ElasticSearch</a> available, so I'll reference those I found most useful myself, i.e. covering the most important aspects:</p> <ul> <li><p>Bob Yoplait already linked kimchy's answer to <a href="https://stackoverflow.com/a/2288211/45773">ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?</a>, which summarizes the reasons why he <em>went ahead and created ElasticSearch</em>, which in his opinion <em>provides a much superior distributed model and ease of use</em> in comparison to Solr.</p></li> <li><p>Ryan Sonnek's <a href="http://blog.socialcast.com/realtime-search-solr-vs-elasticsearch/" rel="noreferrer">Realtime Search: Solr vs Elasticsearch</a> provides an insightful analysis/comparison and explains why he switched from Solr to ElasticSeach, despite being a happy Solr user already - he summarizes this as follows: </p> <blockquote> <p><strong>Solr</strong> may be the weapon of choice when building <strong>standard search applications</strong>, but <strong>Elasticsearch</strong> takes it to the next level with an <strong>architecture for creating modern realtime search applications</strong>. Percolation is an exciting and innovative feature that singlehandedly blows Solr right out of the water. <strong>Elasticsearch is scalable, speedy and a dream to integrate with</strong>. Adios Solr, it was nice knowing you. <em>[emphasis mine]</em></p> </blockquote></li> <li><p>The Wikipedia article on ElasticSearch quotes a <a href="http://en.wikipedia.org/wiki/ElasticSearch#Comparison_to_other_software" rel="noreferrer">comparison</a> from the reputed German iX magazine, listing advantages and disadvantages, which pretty much summarize what has been said above already: </p> <blockquote> <p><strong>Advantages</strong>:</p> <ul> <li>ElasticSearch is distributed. No separate project required. Replicas are near real-time too, which is called "Push replication".</li> <li>ElasticSearch fully supports the near real-time search of Apache Lucene.</li> <li>Handling multitenancy is not a special configuration, where with Solr a more advanced setup is necessary.</li> <li>ElasticSearch introduces the concept of the Gateway, which makes full backups easier.</li> </ul> <p><strong>Disadvantages</strong>:</p> <ul> <li><strike>Only one main developer</strike> <em>[not applicable anymore according to the current <a href="https://github.com/elastic" rel="noreferrer">elasticsearch GitHub organization</a>, besides having a pretty active committer base in the first place]</em></li> <li><strike>No autowarming feature</strike> <em>[not applicable anymore according to the new <a href="https://github.com/elastic/elasticsearch/issues/1913" rel="noreferrer">Index Warmup API</a>]</em></li> </ul> </blockquote></li> </ul> <hr> <h2>Initial Answer</h2> <p>They are completely different technologies addressing completely different use cases, thus cannot be compared at all in any meaningful way:</p> <ul> <li><p><a href="http://lucene.apache.org/solr/" rel="noreferrer">Apache Solr</a> - <em>Apache Solr offers Lucene's capabilities in an easy to use, fast <strong>search server</strong> with additional features like faceting, scalability and much more</em></p></li> <li><p><a href="http://aws.amazon.com/elasticache/" rel="noreferrer">Amazon ElastiCache</a> - <em>Amazon ElastiCache is a web service that makes it easy to deploy, operate, and scale an <strong>in-memory cache</strong> in the cloud.</em></p> <ul> <li>Please note that <em>Amazon ElastiCache is protocol-compliant with Memcached, a widely adopted memory object caching system, so code, applications, and popular tools that you use today with existing Memcached environments will work seamlessly with the service</em> (see <a href="http://memcached.org/" rel="noreferrer">Memcached</a> for details).</li> </ul></li> </ul> <p><em>[emphasis mine]</em></p> <p>Maybe this has been confused with the following two related technologies one way or another:</p> <ul> <li><p><a href="https://www.elastic.co/" rel="noreferrer">ElasticSearch</a> - <em>It is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.</em></p></li> <li><p><a href="http://aws.amazon.com/cloudsearch/" rel="noreferrer">Amazon CloudSearch</a> - <em>Amazon CloudSearch is a fully-managed search service in the cloud that allows customers to easily integrate fast and highly scalable search functionality into their applications.</em></p></li> </ul> <p>The <em>Solr</em> and <em>ElasticSearch</em> offerings sound strikingly similar at first sight, and both use the same backend search engine, namely <a href="http://lucene.apache.org/core/" rel="noreferrer">Apache Lucene</a>.</p> <p>While <em>Solr</em> is older, quite versatile and mature and widely used accordingly, <em>ElasticSearch</em> has been developed specifically to address <em>Solr</em> shortcomings with scalability requirements in modern cloud environments, which are hard(er) to address with <em>Solr</em>.</p> <p>As such it would probably be most useful to compare <em>ElasticSearch</em> with the recently introduced <em>Amazon CloudSearch</em> (see the introductory post <a href="http://aws.typepad.com/aws/2012/04/amazon-cloudsearch-start-searching-in-one-hour.html" rel="noreferrer">Start Searching in One Hour for Less Than $100 / Month</a>), because both claim to cover the same use cases in principle.</p>
{ "question_id": 10213009, "question_date": "2012-04-18T15:42:24.880Z", "question_score": 760, "tags": "search|solr|lucene|elasticsearch", "answer_id": 10213568, "answer_date": "2012-04-18T16:15:50.433Z", "answer_score": 575 }
Please answer the following Stack Overflow question: Title: Are 'Arrow Functions' and 'Functions' equivalent / interchangeable? <p>Arrow functions in ES2015 provide a more concise syntax. </p> <ul> <li>Can I replace all my function declarations / expressions with arrow functions now? </li> <li>What do I have to look out for?</li> </ul> <p>Examples:</p> <p>Constructor function</p> <pre><code>function User(name) { this.name = name; } // vs const User = name =&gt; { this.name = name; }; </code></pre> <p>Prototype methods</p> <pre><code>User.prototype.getName = function() { return this.name; }; // vs User.prototype.getName = () =&gt; this.name; </code></pre> <p>Object (literal) methods</p> <pre><code>const obj = { getName: function() { // ... } }; // vs const obj = { getName: () =&gt; { // ... } }; </code></pre> <p>Callbacks</p> <pre><code>setTimeout(function() { // ... }, 500); // vs setTimeout(() =&gt; { // ... }, 500); </code></pre> <p>Variadic functions</p> <pre><code>function sum() { let args = [].slice.call(arguments); // ... } // vs const sum = (...args) =&gt; { // ... }; </code></pre>
<p><strong>tl;dr:</strong> <strong>No!</strong> Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.<br /> If the function you want to replace does <em>not</em> use <code>this</code>, <code>arguments</code> and is not called with <code>new</code>, then yes.</p> <hr /> <p>As so often: <strong>it depends</strong>. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:</p> <p><strong>1. Lexical <code>this</code> and <code>arguments</code></strong></p> <p>Arrow functions don't have their own <code>this</code> or <code>arguments</code> binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, <code>this</code> and <code>arguments</code> refer to the values of <code>this</code> and <code>arguments</code> in the environment the arrow function is <em>defined</em> in (i.e. &quot;outside&quot; the arrow function):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Example using a function expression function createObject() { console.log('Inside `createObject`:', this.foo); return { foo: 42, bar: function() { console.log('Inside `bar`:', this.foo); }, }; } createObject.call({foo: 21}).bar(); // override `this` inside createObject</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Example using a arrow function function createObject() { console.log('Inside `createObject`:', this.foo); return { foo: 42, bar: () =&gt; console.log('Inside `bar`:', this.foo), }; } createObject.call({foo: 21}).bar(); // override `this` inside createObject</code></pre> </div> </div> </p> <p>In the function expression case, <code>this</code> refers to the object that was created inside the <code>createObject</code>. In the arrow function case, <code>this</code> refers to <code>this</code> of <code>createObject</code> itself.</p> <p>This makes arrow functions useful if you need to access the <code>this</code> of the current environment:</p> <pre><code>// currently common pattern var that = this; getData(function(data) { that.data = data; }); // better alternative with arrow functions getData(data =&gt; { this.data = data; }); </code></pre> <p><strong>Note</strong> that this also means that is <em>not</em> possible to set an arrow function's <code>this</code> with <code>.bind</code> or <code>.call</code>.</p> <p>If you are not very familiar with <code>this</code>, consider reading</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" rel="noreferrer">MDN - this</a></li> <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20&amp;%20object%20prototypes/README.md#you-dont-know-js-this--object-prototypes" rel="noreferrer">YDKJS - this &amp; Object prototypes</a></li> </ul> <p><strong>2. Arrow functions cannot be called with <code>new</code></strong></p> <p>ES2015 distinguishes between functions that are <em>call</em>able and functions that are <em>construct</em>able. If a function is constructable, it can be called with <code>new</code>, i.e. <code>new User()</code>. If a function is callable, it can be called without <code>new</code> (i.e. normal function call).</p> <p>Functions created through function declarations / expressions are both constructable and callable.<br /> Arrow functions (and methods) are only callable. <code>class</code> constructors are only constructable.</p> <p>If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.</p> <hr /> <p>Knowing this, we can state the following.</p> <p>Replaceable:</p> <ul> <li>Functions that don't use <code>this</code> or <code>arguments</code>.</li> <li>Functions that are used with <code>.bind(this)</code></li> </ul> <p><em>Not</em> replaceable:</p> <ul> <li>Constructor functions</li> <li>Function / methods added to a prototype (because they usually use <code>this</code>)</li> <li>Variadic functions (if they use <code>arguments</code> (see below))</li> <li>Generator functions, which require the <code>function*</code> notation</li> </ul> <hr /> <p>Lets have a closer look at this using your examples:</p> <p><strong>Constructor function</strong></p> <p>This won't work because arrow functions cannot be called with <code>new</code>. Keep using a function declaration / expression or use <code>class</code>.</p> <p><strong>Prototype methods</strong></p> <p>Most likely not, because prototype methods usually use <code>this</code> to access the instance. If they don't use <code>this</code>, then you can replace it. However, if you primarily care for concise syntax, use <code>class</code> with its concise method syntax:</p> <pre><code>class User { constructor(name) { this.name = name; } getName() { return this.name; } } </code></pre> <p><strong>Object methods</strong></p> <p>Similarly for methods in an object literal. If the method wants to reference the object itself via <code>this</code>, keep using function expressions, or use the new method syntax:</p> <pre><code>const obj = { getName() { // ... }, }; </code></pre> <p><strong>Callbacks</strong></p> <p>It depends. You should definitely replace it if you are aliasing the outer <code>this</code> or are using <code>.bind(this)</code>:</p> <pre><code>// old setTimeout(function() { // ... }.bind(this), 500); // new setTimeout(() =&gt; { // ... }, 500); </code></pre> <p><strong>But:</strong> If the code which calls the callback explicitly sets <code>this</code> to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses <code>this</code> (or <code>arguments</code>), you <em>cannot</em> use an arrow function!</p> <p><strong>Variadic functions</strong></p> <p>Since arrow functions don't have their own <code>arguments</code>, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using <code>arguments</code>: the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters" rel="noreferrer">rest parameter</a>.</p> <pre><code>// old function sum() { let args = [].slice.call(arguments); // ... } // new const sum = (...args) =&gt; { // ... }; </code></pre> <hr /> <p>Related question:</p> <ul> <li><a href="https://stackoverflow.com/q/22939130/218196">When should I use arrow functions in ECMAScript 6?</a></li> <li><a href="https://stackoverflow.com/q/33288998/1048572">Do ES6 arrow functions have their own arguments or not?</a></li> <li><a href="https://stackoverflow.com/q/32535110/1048572">What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?</a></li> <li><a href="https://stackoverflow.com/q/31362292/1048572">How to use arrow functions (public class fields) as class methods?</a></li> </ul> <p>Further resources:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">MDN - Arrow functions</a></li> <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/es6%20&amp;%20beyond/ch2.md#arrow-functions" rel="noreferrer">YDKJS - Arrow functions</a></li> </ul>
{ "question_id": 34361379, "question_date": "2015-12-18T17:58:00.580Z", "question_score": 760, "tags": "javascript|ecmascript-6|arrow-functions", "answer_id": 34361380, "answer_date": "2015-12-18T17:58:00.580Z", "answer_score": 1033 }
Please answer the following Stack Overflow question: Title: Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM <p>I have a computer with 1 MB of RAM and no other local storage. I must use it to accept 1 million 8-digit decimal numbers over a TCP connection, sort them, and then send the sorted list out over another TCP connection. </p> <p>The list of numbers may contain duplicates, which I must not discard. The code will be placed in ROM, so I need not subtract the size of my code from the 1&nbsp;MB. I already have code to drive the Ethernet port and handle TCP/IP connections, and it requires 2&nbsp;KB for its state data, including a 1&nbsp;KB buffer via which the code will read and write data. Is there a solution to this problem?</p> <p><strong>Sources Of Question And Answer:</strong></p> <p><a href="http://tech.slashdot.org/comments.pl?sid=232757&amp;cid=18925745" rel="noreferrer">slashdot.org</a></p> <p><a href="https://web.archive.org/web/20160309195130/http://nick.cleaton.net/ramsort.html" rel="noreferrer">cleaton.net</a></p>
<p>A solution is possible only because of the difference between 1 megabyte and 1 million bytes. There are about 2 to the power 8093729.5 different ways to choose 1 million 8-digit numbers with duplicates allowed and order unimportant, so a machine with only 1 million bytes of RAM doesn't have enough states to represent all the possibilities. But 1M (less 2k for TCP/IP) is 1022*1024*8 = 8372224 bits, so a solution is possible.</p> <p><strong>Part 1, initial solution</strong></p> <p>This approach needs a little more than 1M, I'll refine it to fit into 1M later.</p> <p>I'll store a compact sorted list of numbers in the range 0 to 99999999 as a sequence of sublists of 7-bit numbers. The first sublist holds numbers from 0 to 127, the second sublist holds numbers from 128 to 255, etc. 100000000/128 is exactly 781250, so 781250 such sublists will be needed.</p> <p>Each sublist consists of a 2-bit sublist header followed by a sublist body. The sublist body takes up 7 bits per sublist entry. The sublists are all concatenated together, and the format makes it possible to tell where one sublist ends and the next begins. The total storage required for a fully populated list is 2*781250 + 7*1000000 = 8562500 bits, which is about 1.021 M-bytes.</p> <p>The 4 possible sublist header values are:</p> <p><strong>00</strong> Empty sublist, nothing follows.</p> <p><strong>01</strong> Singleton, there is only one entry in the sublist and and next 7 bits hold it.</p> <p><strong>10</strong> The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).</p> <p><strong>11</strong> The sublist holds 2 or more repetitions of a single number. The next 7 bits give the number. Then come zero or more 7-bit entries with the value 1, followed by a 7-bit entry with the value 0. The length of the sublist body dictates the number of repetitions. For example, the numbers 12,12 would be stored as (12,0), the numbers 12,12,12 would be stored as (12,1,0), 12,12,12,12 would be (12,1,1,0) and so on.</p> <p>I start off with an empty list, read a bunch of numbers in and store them as 32 bit integers, sort the new numbers in place (using heapsort, probably) and then merge them into a new compact sorted list. Repeat until there are no more numbers to read, then walk the compact list once more to generate the output.</p> <p>The line below represents memory just before the start of the list merge operation. The "O"s are the region that hold the sorted 32-bit integers. The "X"s are the region that hold the old compact list. The "=" signs are the expansion room for the compact list, 7 bits for each integer in the "O"s. The "Z"s are other random overhead.</p> <pre><code>ZZZOOOOOOOOOOOOOOOOOOOOOOOOOO==========XXXXXXXXXXXXXXXXXXXXXXXXXX </code></pre> <p>The merge routine starts reading at the leftmost "O" and at the leftmost "X", and starts writing at the leftmost "=". The write pointer doesn't catch the compact list read pointer until all of the new integers are merged, because both pointers advance 2 bits for each sublist and 7 bits for each entry in the old compact list, and there is enough extra room for the 7-bit entries for the new numbers.</p> <p><strong>Part 2, cramming it into 1M</strong></p> <p>To Squeeze the solution above into 1M, I need to make the compact list format a bit more compact. I'll get rid of one of the sublist types, so that there will be just 3 different possible sublist header values. Then I can use "00", "01" and "1" as the sublist header values and save a few bits. The sublist types are:</p> <p>A Empty sublist, nothing follows.</p> <p>B Singleton, there is only one entry in the sublist and and next 7 bits hold it.</p> <p>C The sublist holds at least 2 distinct numbers. The entries are stored in non-decreasing order, except that the last entry is less than or equal to the first. This allows the end of the sublist to be identified. For example, the numbers 2,4,6 would be stored as (4,6,2). The numbers 2,2,3,4,4 would be stored as (2,3,4,4,2).</p> <p>D The sublist consists of 2 or more repetitions of a single number.</p> <p>My 3 sublist header values will be "A", "B" and "C", so I need a way to represent D-type sublists.</p> <p>Suppose I have the C-type sublist header followed by 3 entries, such as "C[17][101][58]". This can't be part of a valid C-type sublist as described above, since the third entry is less than the second but more than the first. I can use this type of construct to represent a D-type sublist. In bit terms, anywhere I have "C{00?????}{1??????}{01?????}" is an impossible C-type sublist. I'll use this to represent a sublist consisting of 3 or more repetitions of a single number. The first two 7-bit words encode the number (the "N" bits below) and are followed by zero or more {0100001} words followed by a {0100000} word.</p> <pre><code>For example, 3 repetitions: "C{00NNNNN}{1NN0000}{0100000}", 4 repetitions: "C{00NNNNN}{1NN0000}{0100001}{0100000}", and so on. </code></pre> <p>That just leaves lists that hold exactly 2 repetitions of a single number. I'll represent those with another impossible C-type sublist pattern: "C{0??????}{11?????}{10?????}". There's plenty of room for the 7 bits of the number in the first 2 words, but this pattern is longer than the sublist that it represents, which makes things a bit more complex. The five question-marks at the end can be considered not part of the pattern, so I have: "C{0NNNNNN}{11N????}10" as my pattern, with the number to be repeated stored in the "N"s. That's 2 bits too long.</p> <p>I'll have to borrow 2 bits and pay them back from the 4 unused bits in this pattern. When reading, on encountering "C{0NNNNNN}{11N00AB}10", output 2 instances of the number in the "N"s, overwrite the "10" at the end with bits A and B, and rewind the read pointer by 2 bits. Destructive reads are ok for this algorithm, since each compact list gets walked only once.</p> <p>When writing a sublist of 2 repetitions of a single number, write "C{0NNNNNN}11N00" and set the borrowed bits counter to 2. At every write where the borrowed bits counter is non-zero, it is decremented for each bit written and "10" is written when the counter hits zero. So the next 2 bits written will go into slots A and B, and then the "10" will get dropped onto the end.</p> <p>With 3 sublist header values represented by "00", "01" and "1", I can assign "1" to the most popular sublist type. I'll need a small table to map sublist header values to sublist types, and I'll need an occurrence counter for each sublist type so that I know what the best sublist header mapping is.</p> <p>The worst case minimal representation of a fully populated compact list occurs when all the sublist types are equally popular. In that case I save 1 bit for every 3 sublist headers, so the list size is 2*781250 + 7*1000000 - 781250/3 = 8302083.3 bits. Rounding up to a 32 bit word boundary, thats 8302112 bits, or 1037764 bytes.</p> <p>1M minus the 2k for TCP/IP state and buffers is 1022*1024 = 1046528 bytes, leaving me 8764 bytes to play with.</p> <p>But what about the process of changing the sublist header mapping ? In the memory map below, "Z" is random overhead, "=" is free space, "X" is the compact list.</p> <pre><code>ZZZ=====XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </code></pre> <p>Start reading at the leftmost "X" and start writing at the leftmost "=" and work right. When it's done the compact list will be a little shorter and it will be at the wrong end of memory:</p> <pre><code>ZZZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX======= </code></pre> <p>So then I'll need to shunt it to the right:</p> <pre><code>ZZZ=======XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </code></pre> <p>In the header mapping change process, up to 1/3 of the sublist headers will be changing from 1-bit to 2-bit. In the worst case these will all be at the head of the list, so I'll need at least 781250/3 bits of free storage before I start, which takes me back to the memory requirements of the previous version of the compact list :(</p> <p>To get around that, I'll split the 781250 sublists into 10 sublist groups of 78125 sublists each. Each group has its own independent sublist header mapping. Using the letters A to J for the groups:</p> <pre><code>ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ </code></pre> <p>Each sublist group shrinks or stays the same during a sublist header mapping change:</p> <pre><code>ZZZ=====AAAAAABBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAA=====BBCCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABB=====CCCCDDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCC======DDDDDEEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDD======EEEFFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEE======FFFGGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEEFFF======GGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGG=======HHIJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHH=======IJJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHI=======JJJJJJJJJJJJJJJJJJJJ ZZZAAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ======= ZZZ=======AAAAAABBCCCDDDDDEEEFFFGGGGGGGGGGHHIJJJJJJJJJJJJJJJJJJJJ </code></pre> <p>The worst case temporary expansion of a sublist group during a mapping change is 78125/3 = 26042 bits, under 4k. If I allow 4k plus the 1037764 bytes for a fully populated compact list, that leaves me 8764 - 4096 = 4668 bytes for the "Z"s in the memory map.</p> <p>That should be plenty for the 10 sublist header mapping tables, 30 sublist header occurrence counts and the other few counters, pointers and small buffers I'll need, and space I've used without noticing, like stack space for function call return addresses and local variables.</p> <p><strong>Part 3, how long would it take to run?</strong></p> <p>With an empty compact list the 1-bit list header will be used for an empty sublist, and the starting size of the list will be 781250 bits. In the worst case the list grows 8 bits for each number added, so 32 + 8 = 40 bits of free space are needed for each of the 32-bit numbers to be placed at the top of the list buffer and then sorted and merged. In the worst case, changing the sublist header mapping results in a space usage of 2*781250 + 7*entries - 781250/3 bits.</p> <p>With a policy of changing the sublist header mapping after every fifth merge once there are at least 800000 numbers in the list, a worst case run would involve a total of about 30M of compact list reading and writing activity.</p> <p><strong>Source:</strong></p> <p><strong><a href="http://nick.cleaton.net/ramsortsol.html" rel="noreferrer">http://nick.cleaton.net/ramsortsol.html</a></strong></p>
{ "question_id": 12748246, "question_date": "2012-10-05T14:17:12.867Z", "question_score": 760, "tags": "algorithm|sorting|embedded|ram", "answer_id": 12978097, "answer_date": "2012-10-19T16:00:13.923Z", "answer_score": 187 }
Please answer the following Stack Overflow question: Title: What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for? <p>I've just noticed that the long, convoluted Facebook URLs that we're used to now look like this:</p> <p><code>http://www.facebook.com/example.profile#!/pages/Another-Page/123456789012345</code></p> <p>As far as I can recall, earlier this year it was just a normal URL-fragment-like string (starting with <code>#</code>), without the exclamation mark. But now it's a shebang or hashbang (<code>#!</code>), which I've previously only seen in shell scripts and Perl scripts.</p> <p>The <a href="http://blog.twitter.com/2010/09/better-twitter.html" rel="noreferrer">new Twitter</a> URLs now also feature the <code>#!</code> symbols. A Twitter profile URL, for example, now looks like this:</p> <p><code>http://twitter.com/#!/BoltClock</code></p> <p>Does <code>#!</code> now play some special role in URLs, like for a certain Ajax framework or something since the new Facebook and Twitter interfaces are now largely Ajaxified?<br> Would using this in my URLs benefit my Web application in any way?</p>
<p><strong>This technique is <a href="http://googlewebmastercentral.blogspot.com/2015/10/deprecating-our-ajax-crawling-scheme.html" rel="noreferrer">now deprecated</a>.</strong></p> <p>This <strong>used to</strong> tell Google how to index the page.</p> <p><a href="https://developers.google.com/webmasters/ajax-crawling/" rel="noreferrer">https://developers.google.com/webmasters/ajax-crawling/</a></p> <p>This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like <code>www.example.com/ajax.html#!key=value</code>, Google will check the URL <code>www.example.com/ajax.html?_escaped_fragment_=key=value</code> to fetch a non-AJAX version of the contents.</p>
{ "question_id": 3009380, "question_date": "2010-06-09T19:49:42.320Z", "question_score": 760, "tags": "facebook|url|twitter|fragment-identifier|hashbang", "answer_id": 3009501, "answer_date": "2010-06-09T20:07:25.070Z", "answer_score": 493 }
Please answer the following Stack Overflow question: Title: Check/Uncheck checkbox with JavaScript <p>How can a checkbox be checked/unchecked using JavaScript?</p>
<p>Javascript:</p> <pre><code>// Check document.getElementById("checkbox").checked = true; // Uncheck document.getElementById("checkbox").checked = false; </code></pre> <p>jQuery (1.6+):</p> <pre><code>// Check $("#checkbox").prop("checked", true); // Uncheck $("#checkbox").prop("checked", false); </code></pre> <p>jQuery (1.5-):</p> <pre><code>// Check $("#checkbox").attr("checked", true); // Uncheck $("#checkbox").attr("checked", false); </code></pre>
{ "question_id": 8206565, "question_date": "2011-11-21T02:12:16.823Z", "question_score": 759, "tags": "javascript|checkbox", "answer_id": 8206573, "answer_date": "2011-11-21T02:14:11.190Z", "answer_score": 1322 }
Please answer the following Stack Overflow question: Title: RGB to hex and hex to RGB <p>How to convert colors in RGB format to hex format and vice versa?</p> <p>For example, convert <code>'#0080C0'</code> to <code>(0, 128, 192)</code>.</p>
<p><strong>Note</strong>: both versions of <code>rgbToHex</code> expect integer values for <code>r</code>, <code>g</code> and <code>b</code>, so you'll need to do your own rounding if you have non-integer values.</p> <p>The following will do to the RGB to hex conversion and add any required zero padding:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function componentToHex(c) { var hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } alert(rgbToHex(0, 51, 255)); // #0033ff</code></pre> </div> </div> </p> <p>Converting the other way:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51";</code></pre> </div> </div> </p> <p>Finally, an alternative version of <code>rgbToHex()</code>, as discussed in <a href="https://stackoverflow.com/a/5623914/2849127">@casablanca's answer</a> and suggested in the comments by @cwolves:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function rgbToHex(r, g, b) { return "#" + ((1 &lt;&lt; 24) + (r &lt;&lt; 16) + (g &lt;&lt; 8) + b).toString(16).slice(1); } alert(rgbToHex(0, 51, 255)); // #0033ff</code></pre> </div> </div> </p> <h2>Update 3 December 2012</h2> <p>Here's a version of <code>hexToRgb()</code> that also parses a shorthand hex triplet such as &quot;#03F&quot;:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } alert(hexToRgb("#0033ff").g); // "51"; alert(hexToRgb("#03f").g); // "51";</code></pre> </div> </div> </p>
{ "question_id": 5623838, "question_date": "2011-04-11T15:42:53.310Z", "question_score": 759, "tags": "javascript|colors|hex|rgb", "answer_id": 5624139, "answer_date": "2011-04-11T16:04:10.673Z", "answer_score": 1557 }
Please answer the following Stack Overflow question: Title: decompiling DEX into Java sourcecode <p>How can one decompile Android DEX (VM bytecode) files into corresponding Java sourcecode?</p>
<h1>It's easy</h1> <p>Get these tools:</p> <ol> <li><p><a href="https://github.com/pxb1988/dex2jar" rel="noreferrer">dex2jar</a> to translate dex files to jar files</p> </li> <li><p><a href="http://jd.benow.ca/" rel="noreferrer">jd-gui</a> to view the java files in the jar</p> </li> </ol> <p>The source code is quite readable as dex2jar makes some optimizations.</p> <h2>Procedure:</h2> <p>And here's the procedure on how to decompile:</p> <h3>Step 1:</h3> <p>Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar</p> <pre><code>d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk d2j-dex2jar.sh -f -o output_jar.jar dex_to_decompile.dex </code></pre> <blockquote> <p><strong>Note 1:</strong> In the Windows machines all the <code>.sh</code> scripts are replaced by <code>.bat</code> scripts</p> </blockquote> <blockquote> <p><strong>Note 2:</strong> On linux/mac don't forget about <code>sh</code> or <code>bash</code>. The full command should be:</p> </blockquote> <pre><code>sh d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk </code></pre> <blockquote> <p><strong>Note 3:</strong> Also, remember to add execute permission to <code>dex2jar-X.X</code> directory e.g. <code>sudo chmod -R +x dex2jar-2.0</code></p> </blockquote> <p><a href="http://code.google.com/p/dex2jar/wiki/ModifyApkWithDexTool" rel="noreferrer">dex2jar documentation</a></p> <h3>Step 2:</h3> <p>Open the jar in JD-GUI</p> <p><img src="https://i.stack.imgur.com/PWJIX.png" alt="The decompiled source" /></p>
{ "question_id": 1249973, "question_date": "2009-08-08T21:39:45.463Z", "question_score": 759, "tags": "java|android|reverse-engineering|decompiler|dex", "answer_id": 4177581, "answer_date": "2010-11-14T13:02:54.133Z", "answer_score": 954 }
Please answer the following Stack Overflow question: Title: Fixed digits after decimal with f-strings <p>Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)</p> <p>For example, let's say I want to display 2 digits after the decimal place. </p> <p>How do I do that? Let's say that</p> <pre><code>a = 10.1234 </code></pre>
<p>Include the type specifier in your format expression:</p> <pre><code>&gt;&gt;&gt; a = 10.1234 &gt;&gt;&gt; f'{a:.2f}' '10.12' </code></pre>
{ "question_id": 45310254, "question_date": "2017-07-25T17:41:20.697Z", "question_score": 759, "tags": "python|python-3.x|f-string", "answer_id": 45310389, "answer_date": "2017-07-25T17:50:11.203Z", "answer_score": 1177 }
Please answer the following Stack Overflow question: Title: How to check if a "lateinit" variable has been initialized? <p>I wonder if there is a way to check if a <code>lateinit</code> variable has been initialized. For example:</p> <pre><code>class Foo() { private lateinit var myFile: File fun bar(path: String?) { path?.let { myFile = File(it) } } fun bar2() { myFile.whateverMethod() // May crash since I don't know whether myFile has been initialized } } </code></pre>
<p>There is a <code>lateinit</code> improvement in Kotlin 1.2 that allows to check the initialization state of <code>lateinit</code> variable directly:</p> <pre><code>lateinit var file: File if (this::file.isInitialized) { ... } </code></pre> <p>See the annoucement on <a href="https://blog.jetbrains.com/kotlin/2017/09/kotlin-1-2-beta-is-out/" rel="noreferrer">JetBrains blog</a> or the <a href="https://github.com/Kotlin/KEEP/pull/73" rel="noreferrer">KEEP proposal</a>.</p> <p><strong>UPDATE:</strong> Kotlin 1.2 has been released. You can find <code>lateinit</code> enhancements here:</p> <ul> <li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#checking-whether-a-lateinit-var-is-initialized" rel="noreferrer">Checking whether a lateinit var is initialized</a></li> <li><a href="http://kotlinlang.org/docs/reference/whatsnew12.html#lateinit-top-level-properties-and-local-variables" rel="noreferrer">Lateinit top-level properties and local variables</a></li> </ul>
{ "question_id": 37618738, "question_date": "2016-06-03T15:53:56.913Z", "question_score": 759, "tags": "kotlin", "answer_id": 46584412, "answer_date": "2017-10-05T11:23:26.657Z", "answer_score": 1523 }
Please answer the following Stack Overflow question: Title: How do I preview stash contents in Git? <p>I want to inspect a stash and find out what changes it would make if I applied it to working tree in its current state.</p> <p>I know I can do a git diff on the stash, but this shows me all the differences between the working tree and the stash, whereas I'm just interested to know what the stash apply is going to change.</p>
<p><code>git stash show</code> will show you the files that changed in your most recent stash. You can add the <code>-p</code> option to show the diff.</p> <pre><code>git stash show -p </code></pre> <p>If the stash you are interested in is not the most recent one, then add the name of the stash to the end of the command:</p> <pre><code>git stash show -p stash@{2} </code></pre>
{ "question_id": 3573623, "question_date": "2010-08-26T09:08:05.830Z", "question_score": 759, "tags": "git|git-stash", "answer_id": 3579474, "answer_date": "2010-08-26T21:01:08.450Z", "answer_score": 995 }
Please answer the following Stack Overflow question: Title: How to get URL parameter using jQuery or plain JavaScript? <p>I have seen lots of jQuery examples where parameter size and name are unknown.</p> <p>My URL is only going to ever have 1 string:</p> <pre><code>http://example.com?sent=yes </code></pre> <p>I just want to detect:</p> <ol> <li>Does <code>sent</code> exist?</li> <li>Is it equal to "yes"?</li> </ol>
<p>Best solution <a href="http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery" rel="noreferrer">here</a>.</p> <pre><code>var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), sURLVariables = sPageURL.split('&amp;'), sParameterName, i; for (i = 0; i &lt; sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } return false; }; </code></pre> <p>And this is how you can use this function assuming the URL is,<br /> <code>http://dummy.com/?technology=jquery&amp;blog=jquerybyexample</code>.</p> <pre><code>var tech = getUrlParameter('technology'); var blog = getUrlParameter('blog'); </code></pre>
{ "question_id": 19491336, "question_date": "2013-10-21T09:55:33.790Z", "question_score": 758, "tags": "jquery|url|parameters|query-string|querystringparameter", "answer_id": 21903119, "answer_date": "2014-02-20T09:12:50.447Z", "answer_score": 1412 }
Please answer the following Stack Overflow question: Title: How can I make Flexbox children 100% height of their parent? <p>I'm trying to fill the vertical space of a flex item inside a Flexbox.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { height: 200px; width: 500px; display: flex; flex-direction: row; } .flex-1 { width: 100px; background-color: blue; } .flex-2 { position: relative; flex: 1; background-color: red; } .flex-2-child { height: 100%; width: 100%; background-color: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="flex-1"&gt;&lt;/div&gt; &lt;div class="flex-2"&gt; &lt;div class="flex-2-child"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>And here's the <a href="https://jsfiddle.net/2ZDuE/" rel="noreferrer">JSFiddle</a></p> <p><code>flex-2-child</code> doesn't fill the required height except in the two cases where:</p> <ol> <li><code>flex-2</code> has a height of 100% (which is weird because a flex item has a 100% by default + it is buggy in Chrome)</li> <li><code>flex-2-child</code> has a position absolute which is also inconvenient</li> </ol> <p>This doesn't work in Chrome or Firefox currently.</p>
<h2>Use <code>align-items: stretch</code></h2> <p>Similar to David Storey's answer, my workaround is:</p> <pre><code>.flex-2 { display: flex; align-items: stretch; } </code></pre> <p>Note that <code>height: 100%</code> should be removed from the child component (see comments).</p> <p>Alternatively to <code>align-items</code>, you can use <code>align-self</code> just on the <code>.flex-2-child</code> item you want stretched.</p>
{ "question_id": 15381172, "question_date": "2013-03-13T09:19:00.423Z", "question_score": 758, "tags": "css|flexbox", "answer_id": 32466333, "answer_date": "2015-09-08T20:04:03.010Z", "answer_score": 675 }
Please answer the following Stack Overflow question: Title: How to add local .jar file dependency to build.gradle file? <p>So I have tried to add my local .jar file dependency to my build.gradle file:</p> <pre><code>apply plugin: 'java' sourceSets { main { java { srcDir 'src/model' } } } dependencies { runtime files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar') runtime fileTree(dir: 'libs', include: '*.jar') } </code></pre> <p>And you can see that I added the .jar files into the referencedLibraries folder here: <a href="https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1/referencedLibraries">https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1/referencedLibraries</a></p> <p>But the problem is that when I run the command: gradle build on the command line I get the following error:</p> <pre><code>error: package com.google.gson does not exist import com.google.gson.Gson; </code></pre> <p>Here is my entire repo: <a href="https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1">https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1</a></p>
<p>If you really need to take that .jar from a local directory, </p> <p>Add next to your module gradle (Not the app gradle file):</p> <pre><code>repositories { flatDir { dirs 'libs' } } dependencies { implementation name: 'gson-2.2.4' } </code></pre> <p>However, being a standard .jar in an actual maven repository, why don't you try this?</p> <pre><code>repositories { mavenCentral() } dependencies { implementation 'com.google.code.gson:gson:2.2.4' } </code></pre>
{ "question_id": 20700053, "question_date": "2013-12-20T09:14:44.133Z", "question_score": 758, "tags": "java|gradle|dependency-management|build.gradle|gradle-eclipse", "answer_id": 20700183, "answer_date": "2013-12-20T09:21:49.007Z", "answer_score": 539 }
Please answer the following Stack Overflow question: Title: How can I revert a single file to a previous version? <p>Is there a way to go through different commits on a file. Say I modified a file 5 times and I want to go back to change 2, after I already committed and pushed to a repository.</p> <p>In my understanding the only way is to keep many branches, have I got that right? If I'm right I'm gonna have hundreds of branches in a few days, so I'm probably not understanding it really.</p> <p>Could anyone clear that up please?</p>
<p>Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)</p> <p>So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:</p> <pre><code>git log path/to/file </code></pre> <p>If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the <code>-p/--patch</code> option:</p> <pre><code>git log -p path/to/file </code></pre> <p>Or, if you prefer the graphical view of gitk</p> <pre><code>gitk path/to/file </code></pre> <p>You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.</p> <p>Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:</p> <pre><code># get the version of the file from the given commit git checkout &lt;commit&gt; path/to/file # and commit this modification git commit </code></pre> <p>(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use <code>git add</code> to add it to the index in preparation for committing.)</p> <p>If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. <code>git</code> can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.</p>
{ "question_id": 2733873, "question_date": "2010-04-28T23:44:58.960Z", "question_score": 758, "tags": "git|revert", "answer_id": 2734035, "answer_date": "2010-04-29T00:26:36.583Z", "answer_score": 1058 }