input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: Extract file name from path, no matter what the os/path format <p>Which Python library can I use to extract filenames from paths, no matter what the operating system or path format could be?</p> <p>For example, I'd like all of these paths to return me <code>c</code>:</p> <pre><code>a/b/c/ a/b/c \a\b\c \a\b\c\ a\b\c a/b/../../a/b/c/ a/b/../../a/b/c </code></pre>
<p>Using <code>os.path.split</code> or <code>os.path.basename</code> as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.</p> <p>Windows paths can use either backslash or forward slash as path separator. Therefore, the <code>ntpath</code> module (which is equivalent to os.path when running on windows) will work for all<sup>(1)</sup> paths on all platforms.</p> <pre><code>import ntpath ntpath.basename("a/b/c") </code></pre> <p>Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:</p> <pre><code>def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) </code></pre> <p>Verification:</p> <pre><code>&gt;&gt;&gt; paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', ... 'a/b/../../a/b/c/', 'a/b/../../a/b/c'] &gt;&gt;&gt; [path_leaf(path) for path in paths] ['c', 'c', 'c', 'c', 'c', 'c', 'c'] </code></pre> <p><br></p> <p><sup>(1) There's one caveat: Linux filenames <em>may contain backslashes</em>. So on linux, <code>r'a/b\c'</code> always refers to the file <code>b\c</code> in the <code>a</code> folder, while on Windows, it always refers to the <code>c</code> file in the <code>b</code> subfolder of the <code>a</code> folder. So when both forward and backward slashes are used in a path, you <em>need</em> to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.</sup></p>
{ "question_id": 8384737, "question_date": "2011-12-05T11:39:49.827Z", "question_score": 1177, "tags": "python", "answer_id": 8384788, "answer_date": "2011-12-05T11:45:25.963Z", "answer_score": 1026 }
Please answer the following Stack Overflow question: Title: How do I rename both a Git local and remote branch name? <p>I have four branches like master -> origin/regacy, FeatureA -> origin/FeatureA. As you can see, I typed the wrong name.</p> <p>So I want to rename a remote branch name (origin/regacy → origin/legacy or origin/master)</p> <p>I try the command below:</p> <pre><code>git remote rename regacy legacy </code></pre> <p>But Git console returned an error message to me.</p> <pre><code> error : Could not rename config section 'remote.regacy' to 'remote.legacy' </code></pre> <p>How can I solve this problem?</p>
<p><a href="https://i.stack.imgur.com/YeBYR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YeBYR.jpg" alt="schematic, cute git remote graph" /></a></p> <hr /> <p>There are a few ways to accomplish that:</p> <ol> <li>Change your local branch and then push your changes</li> <li>Push the branch to remote with the new name while keeping the original name locally</li> </ol> <h3>Renaming local and remote</h3> <pre class="lang-sh prettyprint-override"><code># Rename the local branch to the new name git branch -m &lt;old_name&gt; &lt;new_name&gt; # Delete the old branch on remote - where &lt;remote&gt; is, for example, origin git push &lt;remote&gt; --delete &lt;old_name&gt; # Or shorter way to delete remote branch [:] git push &lt;remote&gt; :&lt;old_name&gt; # Prevent git from using the old name when pushing in the next step. # Otherwise, git will use the old upstream name instead of &lt;new_name&gt;. git branch --unset-upstream &lt;new_name&gt; # Push the new branch to remote git push &lt;remote&gt; &lt;new_name&gt; # Reset the upstream branch for the new_name local branch git push &lt;remote&gt; -u &lt;new_name&gt; </code></pre> <p><a href="https://i.stack.imgur.com/YOHON.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YOHON.png" alt="console screenshot" /></a></p> <hr /> <h3>Renaming Only remote branch</h3> <p>Credit: <a href="https://stackoverflow.com/questions/30590083/how-do-i-rename-both-a-git-local-and-remote-branch-name/30590238#42173564">ptim</a></p> <pre class="lang-sh prettyprint-override"><code># In this option, we will push the branch to the remote with the new name # While keeping the local name as is git push &lt;remote&gt; &lt;remote&gt;/&lt;old_name&gt;:refs/heads/&lt;new_name&gt; :&lt;old_name&gt; </code></pre> <hr /> <h3>Important note:</h3> <p>When you use the <code>git branch -m</code> (move), Git is also <strong>updating</strong> your tracking branch with the new name.</p> <blockquote> <p><code>git remote rename legacy legacy</code></p> </blockquote> <p><code>git remote rename</code> is trying to update your remote section in your configuration file. It will rename the remote with the given name to the new name, but in your case, it did not find any, so the renaming failed.</p> <p><strong>But</strong> it will not do what you think; it will rename your <strong>local</strong> configuration remote name and <strong>not</strong> the remote branch. </p> <hr /> <p><strong>Note</strong> Git servers might allow you to rename Git branches using the web interface or external programs (like Sourcetree, etc.), but you have to keep in mind that in Git all the work is done locally, so it's recommended to use the above commands to the work.</p>
{ "question_id": 30590083, "question_date": "2015-06-02T07:36:30.570Z", "question_score": 1176, "tags": "git|repository|rename|git-branch", "answer_id": 30590238, "answer_date": "2015-06-02T07:44:38.690Z", "answer_score": 1925 }
Please answer the following Stack Overflow question: Title: How do I turn a C# object into a JSON string in .NET? <p>I have classes like these:</p> <pre><code>class MyDate { int year, month, day; } class Lad { string firstName; string lastName; MyDate dateOfBirth; } </code></pre> <p>And I would like to turn a <code>Lad</code> object into a <strong>JSON</strong> string like this:</p> <pre><code>{ &quot;firstName&quot;:&quot;Markoff&quot;, &quot;lastName&quot;:&quot;Chaney&quot;, &quot;dateOfBirth&quot;: { &quot;year&quot;:&quot;1901&quot;, &quot;month&quot;:&quot;4&quot;, &quot;day&quot;:&quot;30&quot; } } </code></pre> <p>(Without the formatting). I found <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx" rel="noreferrer">this link</a>, but it uses a namespace that's not in <strong>.NET 4</strong>. I also heard about <a href="http://james.newtonking.com/projects/json-net.aspx" rel="noreferrer">JSON.NET</a>, but their site seems to be down at the moment, and I'm not keen on using external DLL files.</p> <p>Are there other options besides manually creating a <strong>JSON</strong> string writer?</p>
<h2>Please Note</h2> <p><strong>Microsoft recommends that you DO NOT USE JavaScriptSerializer</strong></p> <p>See the header of the documentation page:</p> <blockquote> <p>For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.</p> </blockquote> <hr /> <h4>Original answer:</h4> <p>You could use the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer" rel="noreferrer"><code>JavaScriptSerializer</code></a> class (add reference to <code>System.Web.Extensions</code>):</p> <pre><code>using System.Web.Script.Serialization; </code></pre> <pre><code>var json = new JavaScriptSerializer().Serialize(obj); </code></pre> <p>A full example:</p> <pre><code>using System; using System.Web.Script.Serialization; public class MyDate { public int year; public int month; public int day; } public class Lad { public string firstName; public string lastName; public MyDate dateOfBirth; } class Program { static void Main() { var obj = new Lad { firstName = &quot;Markoff&quot;, lastName = &quot;Chaney&quot;, dateOfBirth = new MyDate { year = 1901, month = 4, day = 30 } }; var json = new JavaScriptSerializer().Serialize(obj); Console.WriteLine(json); } } </code></pre>
{ "question_id": 6201529, "question_date": "2011-06-01T12:59:21.500Z", "question_score": 1174, "tags": "c#|.net|json|serialization", "answer_id": 6201609, "answer_date": "2011-06-01T13:05:38.227Z", "answer_score": 1013 }
Please answer the following Stack Overflow question: Title: How to have 'git log' show filenames like 'svn log -v' <p>SVN's log has a &quot;-v&quot; mode that outputs filenames of files changed in each commit, like so:</p> <pre>jes5199$ svn log -v ------------------------------------------------------------------------ r1 | jes5199 | 2007-01-03 14:39:41 -0800 (Wed, 03 Jan 2007) | 1 line Changed paths: A /AUTHORS A /COPYING A /ChangeLog A /EVOLUTION A /INSTALL A /MacOSX </pre> <p>Is there a quick way to get a list of changed files in each commit in Git?</p>
<p>For full path names of changed files:</p> <pre><code>git log --name-only </code></pre> <p>For full path names and status of changed files:</p> <pre><code>git log --name-status </code></pre> <p>For abbreviated pathnames and a diffstat of changed files:</p> <pre><code>git log --stat </code></pre> <p>There are a lot more options. <a href="https://git-scm.com/docs/git-log" rel="noreferrer">Check out the documentation</a>.</p>
{ "question_id": 1230084, "question_date": "2009-08-04T21:46:36.827Z", "question_score": 1174, "tags": "svn|git|logging", "answer_id": 1230094, "answer_date": "2009-08-04T21:48:33.047Z", "answer_score": 1822 }
Please answer the following Stack Overflow question: Title: How to echo shell commands as they are executed <p>In a shell script, how do I echo all shell commands called and expand any variable names?</p> <p>For example, given the following line:</p> <pre><code>ls $DIRNAME </code></pre> <p>I would like the script to run the command and display the following</p> <pre><code>ls /full/path/to/some/dir </code></pre> <p>The purpose is to save a log of all shell commands called and their arguments. Is there perhaps a better way of generating such a log?</p>
<p><code>set -x</code> or <code>set -o xtrace</code> expands variables and prints a little + sign before the line.</p> <p><code>set -v</code> or <code>set -o verbose</code> does not expand the variables before printing.</p> <p>Use <code>set +x</code> and <code>set +v</code> to turn off the above settings.</p> <p>On the first line of the script, one can put <code>#!/bin/sh -x</code> (or <code>-v</code>) to have the same effect as <code>set -x</code> (or <code>-v</code>) later in the script.</p> <p>The above also works with <code>/bin/sh</code>.</p> <p>See the bash-hackers' wiki on <a href="https://wiki.bash-hackers.org/commands/builtin/set#attributes" rel="noreferrer"><code>set</code> attributes</a>, and on <a href="https://wiki.bash-hackers.org/scripting/debuggingtips" rel="noreferrer">debugging</a>.</p> <pre><code>$ cat shl #!/bin/bash DIR=/tmp/so ls $DIR $ bash -x shl + DIR=/tmp/so + ls /tmp/so $ </code></pre>
{ "question_id": 2853803, "question_date": "2010-05-18T00:03:09.807Z", "question_score": 1173, "tags": "bash|shell|sh|posix|trace", "answer_id": 2853811, "answer_date": "2010-05-18T00:06:07.993Z", "answer_score": 1339 }
Please answer the following Stack Overflow question: Title: You need to use a Theme.AppCompat theme (or descendant) with this activity <p>Android Studio 0.4.5</p> <p>Android documentation for creating custom dialog boxes: <a href="http://developer.android.com/guide/topics/ui/dialogs.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/dialogs.html</a></p> <p>If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the <code>&lt;activity&gt;</code> manifest element:</p> <pre><code>&lt;activity android:theme="@android:style/Theme.Holo.Dialog" &gt; </code></pre> <p>However, when I tried this I get the following exception:</p> <pre><code>java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity </code></pre> <p>I am supporting the following, and I can't using something greater than 10 for the min:</p> <pre><code>minSdkVersion 10 targetSdkVersion 19 </code></pre> <p>In my styles I have the following:</p> <pre><code>&lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; </code></pre> <p>And in my manifest I have this for the activity:</p> <pre><code> &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:theme="@android:style/Theme.Holo.Light.Dialog" android:name="com.ssd.register.Dialog_update" android:label="@string/title_activity_dialog_update" &gt; &lt;/activity&gt; </code></pre> <p>Creating the dialog box like this was something I was hopping to do, as I have already completed the layout.</p> <p>Can anyone tell me how I can get around this problem?</p>
<p>The reason you are having this problem is because the activity you are trying to apply the dialog theme to is extending <code>ActionBarActivity</code> which requires the <code>AppCompat</code> theme to be applied. </p> <p><strong>Update</strong>: Extending <code>AppCompatActivity</code> would also have this problem </p> <p>In this case, change the Java inheritance from <code>ActionBarActivity</code> to <code>Activity</code> and leave the dialog theme in the manifest as it is, a non <code>Theme.AppCompat</code> value </p> <hr> <p>The general rule is that if you want your code to support older versions of Android, it should have the <code>AppCompat</code> theme and the java code should extend <code>AppCompatActivity</code>. If you have *an activity that doesn't need this support, such as you only care about the latest versions and features of Android, you can apply any theme to it but the java code must extend plain old <code>Activity</code>.</p> <hr> <p>NOTE: When change from <code>AppCompatActivity</code> (or a subclass, <code>ActionBarActivity</code>), to <code>Activity</code>, must also change the various calls with "support" to the corresponding call <em>without</em> "support". So, instead of <code>getSupportFragmentManager</code>, call <code>getFragmentManager</code>.</p>
{ "question_id": 21814825, "question_date": "2014-02-16T17:34:08.660Z", "question_score": 1172, "tags": "android|android-layout", "answer_id": 21815015, "answer_date": "2014-02-16T17:48:55.987Z", "answer_score": 1201 }
Please answer the following Stack Overflow question: Title: Are there constants in JavaScript? <p>Is there a way to use constants in <strong>JavaScript</strong>?</p> <p>If not, what's the common practice for specifying variables that are used as constants?</p>
<p>Since <a href="https://www.ecma-international.org/ecma-262/6.0/" rel="noreferrer">ES2015</a>, JavaScript has a notion of <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations" rel="noreferrer"><code>const</code></a>:</p> <pre><code>const MY_CONSTANT = "some-value"; </code></pre> <p>This will work in <a href="https://caniuse.com/#search=const" rel="noreferrer">pretty much all browsers except IE 8, 9 and 10</a>. Some may also need <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" rel="noreferrer">strict mode</a> enabled.</p> <p>You can use <code>var</code> with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:</p> <pre><code>var MY_CONSTANT = "some-value"; </code></pre>
{ "question_id": 130396, "question_date": "2008-09-24T22:45:05.233Z", "question_score": 1172, "tags": "javascript|constants", "answer_id": 130399, "answer_date": "2008-09-24T22:46:03.687Z", "answer_score": 1036 }
Please answer the following Stack Overflow question: Title: What are POD types in C++? <p>I've come across this term POD-type a few times.<br> What does it mean? </p>
<p><em>POD</em> stands for <em>Plain Old Data</em> - that is, a class (whether defined with the keyword <code>struct</code> or the keyword <code>class</code>) without constructors, destructors and virtual members functions. <a href="http://en.wikipedia.org/wiki/Plain_Old_Data_Structures" rel="noreferrer">Wikipedia's article on POD</a> goes into a bit more detail and defines it as:</p> <blockquote> <p>A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.</p> </blockquote> <p>Greater detail can be found in <a href="https://stackoverflow.com/a/4178176/734069">this answer for C++98/03</a>. C++11 changed the rules surrounding POD, relaxing them greatly, thus <a href="https://stackoverflow.com/a/7189821/734069">necessitating a follow-up answer here</a>.</p>
{ "question_id": 146452, "question_date": "2008-09-28T18:36:09.563Z", "question_score": 1172, "tags": "c++|types|c++-faq", "answer_id": 146454, "answer_date": "2008-09-28T18:37:31.977Z", "answer_score": 818 }
Please answer the following Stack Overflow question: Title: Set select option 'selected', by value <p>I have a <code>select</code> field with some options in it. Now I need to select one of those <code>options</code> with jQuery. But how can I do that when I only know the <code>value</code> of the <code>option</code> that must be selected?</p> <p>I have the following HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class=&quot;id_100&quot;&gt; &lt;select&gt; &lt;option value=&quot;val1&quot;&gt;Val 1&lt;/option&gt; &lt;option value=&quot;val2&quot;&gt;Val 2&lt;/option&gt; &lt;option value=&quot;val3&quot;&gt;Val 3&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>I need to select the option with value <code>val2</code>. How can this be done?</p> <p>Here's a demo page: <a href="http://jsfiddle.net/9Stxb/" rel="nofollow noreferrer">http://jsfiddle.net/9Stxb/</a></p>
<p>There's an easier way that doesn't require you to go into the options tag:</p> <pre><code>$(&quot;div.id_100 select&quot;).val(&quot;val2&quot;); </code></pre> <p>Check out this <a href="http://api.jquery.com/val/" rel="nofollow noreferrer">jQuery method</a>.</p> <p><em><strong>Note</strong></em>: The above code does not trigger the change event. You need to call it like this for full compatibility:</p> <pre><code>$(&quot;div.id_100 select&quot;).val(&quot;val2&quot;).change(); </code></pre>
{ "question_id": 13343566, "question_date": "2012-11-12T12:16:17.003Z", "question_score": 1170, "tags": "jquery|jquery-selectors|html-select", "answer_id": 16979926, "answer_date": "2013-06-07T08:49:48.027Z", "answer_score": 1851 }
Please answer the following Stack Overflow question: Title: How can I pad an integer with zeros on the left? <p>How do you left pad an <code>int</code> with zeros when converting to a <code>String</code> in java?</p> <p>I'm basically looking to pad out integers up to <code>9999</code> with leading zeros (e.g. 1 = <code>0001</code>).</p>
<p>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-" rel="noreferrer"><code>java.lang.String.format(String,Object...)</code></a> like this:</p> <pre><code>String.format("%05d", yournumber); </code></pre> <p>for zero-padding with a length of 5. For hexadecimal output replace the <code>d</code> with an <code>x</code> as in <code>"%05x"</code>.</p> <p>The full formatting options are documented as part of <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html" rel="noreferrer"><code>java.util.Formatter</code></a>.</p>
{ "question_id": 473282, "question_date": "2009-01-23T15:21:24.670Z", "question_score": 1170, "tags": "java|formatting|zero-pad", "answer_id": 473309, "answer_date": "2009-01-23T15:26:04.287Z", "answer_score": 1903 }
Please answer the following Stack Overflow question: Title: Difference between del, remove, and pop on lists <p>Is there any difference between these three methods to remove an element from a list?</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; a.remove(2) &gt;&gt;&gt; a [1, 3] &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; del a[1] &gt;&gt;&gt; a [1, 3] &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; a.pop(1) 2 &gt;&gt;&gt; a [1, 3] </code></pre>
<p>The effects of the three different methods to remove an element from a list:</p> <p><code>remove</code> removes the <em>first</em> matching <em>value</em>, not a specific index:</p> <pre><code>&gt;&gt;&gt; a = [0, 2, 3, 2] &gt;&gt;&gt; a.remove(2) &gt;&gt;&gt; a [0, 3, 2] </code></pre> <p><code>del</code> removes the item at a specific index:</p> <pre><code>&gt;&gt;&gt; a = [9, 8, 7, 6] &gt;&gt;&gt; del a[1] &gt;&gt;&gt; a [9, 7, 6] </code></pre> <p>and <code>pop</code> removes the item at a specific index and returns it.</p> <pre><code>&gt;&gt;&gt; a = [4, 3, 5] &gt;&gt;&gt; a.pop(1) 3 &gt;&gt;&gt; a [4, 5] </code></pre> <p>Their error modes are different too:</p> <pre><code>&gt;&gt;&gt; a = [4, 5, 6] &gt;&gt;&gt; a.remove(7) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ValueError: list.remove(x): x not in list &gt;&gt;&gt; del a[7] Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; IndexError: list assignment index out of range &gt;&gt;&gt; a.pop(7) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; IndexError: pop index out of range </code></pre>
{ "question_id": 11520492, "question_date": "2012-07-17T10:21:41.260Z", "question_score": 1169, "tags": "python|list", "answer_id": 11520540, "answer_date": "2012-07-17T10:24:09.450Z", "answer_score": 1634 }
Please answer the following Stack Overflow question: Title: How do I get a list of locally installed Python modules? <p>How do I get a list of Python modules installed on my computer?</p>
<h2>Solution</h2> <h1>Do not use with pip > 10.0!</h1> <p>My 50 cents for getting a <code>pip freeze</code>-like list from a Python script:</p> <pre class="lang-python prettyprint-override"><code>import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) </code></pre> <p>As a (too long) one liner:</p> <pre class="lang-python prettyprint-override"><code>sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) </code></pre> <p>Giving:</p> <pre class="lang-js prettyprint-override"><code>['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0', 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 'werkzeug==0.9.4'] </code></pre> <h2>Scope</h2> <p>This solution applies to the system scope or to a virtual environment scope, and covers packages installed by <code>setuptools</code>, <code>pip</code> and (<a href="https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install">god forbid</a>) <code>easy_install</code>.</p> <h2>My use case</h2> <p>I added the result of this call to my flask server, so when I call it with <code>http://example.com/exampleServer/environment</code> I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.</p> <h2>Caveats</h2> <p>I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a <code>setup.py</code> file, it does not list the package installed by <code>setup.py</code>.</p> <h3>Steps to reproduce:</h3> Create a virtual environment <pre><code>$ cd /tmp $ virtualenv test_env New python executable in test_env/bin/python Installing setuptools, pip...done. $ source test_env/bin/activate (test_env) $ </code></pre> Clone a git repo with <code>setup.py</code> <pre><code>(test_env) $ git clone https://github.com/behave/behave.git Cloning into 'behave'... remote: Reusing existing pack: 4350, done. remote: Total 4350 (delta 0), reused 0 (delta 0) Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done. Resolving deltas: 100% (2388/2388), done. Checking connectivity... done. </code></pre> <p>We have behave's <code>setup.py</code> in <code>/tmp/behave</code>:</p> <pre><code>(test_env) $ ls /tmp/behave/setup.py /tmp/behave/setup.py </code></pre> Install the python package from the git repo <pre><code>(test_env) $ cd /tmp/behave &amp;&amp; pip install . running install ... Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg Finished processing dependencies for behave==1.2.5a1 </code></pre> <h3>If we run the aforementioned solution from <code>/tmp</code></h3> <pre><code>&gt;&gt;&gt; import pip &gt;&gt;&gt; sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/private/tmp' </code></pre> <h3>If we run the aforementioned solution from <code>/tmp/behave</code></h3> <pre><code>&gt;&gt;&gt; import pip &gt;&gt;&gt; sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/private/tmp/behave' </code></pre> <p><code>behave==1.2.5a1</code> is missing from the second example, because the working directory contains <code>behave</code>'s <code>setup.py</code> file.</p> <p>I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.</p>
{ "question_id": 739993, "question_date": "2009-04-11T12:34:18.360Z", "question_score": 1167, "tags": "python|module|pip", "answer_id": 23885252, "answer_date": "2014-05-27T09:05:42.540Z", "answer_score": 654 }
Please answer the following Stack Overflow question: Title: How to determine if Javascript array contains an object with an attribute that equals a given value? <p>I have an array like</p> <pre><code>vendors = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' } // and so on... ]; </code></pre> <p>How do I check this array to see if &quot;Magenic&quot; exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.</p>
<p><strong>2018 edit</strong>: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at <a href="https://stackoverflow.com/a/8217584/104999">CAFxX's answer</a>.</p> <p>There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.</p> <pre><code>var found = false; for(var i = 0; i &lt; vendors.length; i++) { if (vendors[i].Name == 'Magenic') { found = true; break; } } </code></pre>
{ "question_id": 8217419, "question_date": "2011-11-21T19:30:40.910Z", "question_score": 1167, "tags": "javascript|arrays", "answer_id": 8217466, "answer_date": "2011-11-21T19:34:29.033Z", "answer_score": 373 }
Please answer the following Stack Overflow question: Title: Remove a symlink to a directory <p>I have a symlink to an important directory. I want to get rid of that symlink, while keeping the directory behind it. </p> <p>I tried <code>rm</code> and get back <code>rm: cannot remove 'foo'</code>.<br> I tried <code>rmdir</code> and got back <code>rmdir: failed to remove 'foo': Directory not empty</code><br> I then progressed through <code>rm -f</code>, <code>rm -rf</code> and <code>sudo rm -rf</code></p> <p>Then I went to find my back-ups.</p> <p>Is there a way to get rid of the symlink with out throwing away the baby with the bathwater? </p>
<pre><code># this works: rm foo # versus this, which doesn't: rm foo/ </code></pre> <p>Basically, you need to tell it to delete a <em>file</em>, not delete a <em>directory</em>. I believe the difference between <code>rm</code> and <code>rmdir</code> exists because of differences in the way the C library treats each.</p> <p>At any rate, the first should work, while the second should complain about foo being a directory.</p> <p>If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.</p>
{ "question_id": 210120, "question_date": "2008-10-16T20:18:22.453Z", "question_score": 1167, "tags": "linux|file|symlink", "answer_id": 210133, "answer_date": "2008-10-16T20:22:41.180Z", "answer_score": 1410 }
Please answer the following Stack Overflow question: Title: Fastest way to check if a value exists in a list <p>What is the fastest way to check if a value exists in a very large list?</p>
<pre><code>7 in a </code></pre> <p>Clearest and fastest way to do it.</p> <p>You can also consider using a <code>set</code>, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)</p>
{ "question_id": 7571635, "question_date": "2011-09-27T15:23:26.843Z", "question_score": 1166, "tags": "python|performance|list", "answer_id": 7571665, "answer_date": "2011-09-27T15:25:11.663Z", "answer_score": 2085 }
Please answer the following Stack Overflow question: Title: "Large data" workflows using pandas <p>I have tried to puzzle out an answer to this question for many months while learning pandas. I use SAS for my day-to-day work and it is great for it's out-of-core support. However, SAS is horrible as a piece of software for numerous other reasons.</p> <p>One day I hope to replace my use of SAS with python and pandas, but I currently lack an out-of-core workflow for large datasets. I'm not talking about "big data" that requires a distributed network, but rather files too large to fit in memory but small enough to fit on a hard-drive.</p> <p>My first thought is to use <code>HDFStore</code> to hold large datasets on disk and pull only the pieces I need into dataframes for analysis. Others have mentioned MongoDB as an easier to use alternative. My question is this:</p> <p>What are some best-practice workflows for accomplishing the following:</p> <ol> <li>Loading flat files into a permanent, on-disk database structure</li> <li>Querying that database to retrieve data to feed into a pandas data structure</li> <li>Updating the database after manipulating pieces in pandas</li> </ol> <p>Real-world examples would be much appreciated, especially from anyone who uses pandas on "large data".</p> <p>Edit -- an example of how I would like this to work:</p> <ol> <li>Iteratively import a large flat-file and store it in a permanent, on-disk database structure. These files are typically too large to fit in memory.</li> <li>In order to use Pandas, I would like to read subsets of this data (usually just a few columns at a time) that can fit in memory.</li> <li>I would create new columns by performing various operations on the selected columns.</li> <li>I would then have to append these new columns into the database structure.</li> </ol> <p>I am trying to find a best-practice way of performing these steps. Reading links about pandas and pytables it seems that appending a new column could be a problem.</p> <p>Edit -- Responding to Jeff's questions specifically:</p> <ol> <li>I am building consumer credit risk models. The kinds of data include phone, SSN and address characteristics; property values; derogatory information like criminal records, bankruptcies, etc... The datasets I use every day have nearly 1,000 to 2,000 fields on average of mixed data types: continuous, nominal and ordinal variables of both numeric and character data. I rarely append rows, but I do perform many operations that create new columns.</li> <li>Typical operations involve combining several columns using conditional logic into a new, compound column. For example, <code>if var1 &gt; 2 then newvar = 'A' elif var2 = 4 then newvar = 'B'</code>. The result of these operations is a new column for every record in my dataset.</li> <li>Finally, I would like to append these new columns into the on-disk data structure. I would repeat step 2, exploring the data with crosstabs and descriptive statistics trying to find interesting, intuitive relationships to model.</li> <li>A typical project file is usually about 1GB. Files are organized into such a manner where a row consists of a record of consumer data. Each row has the same number of columns for every record. This will always be the case.</li> <li>It's pretty rare that I would subset by rows when creating a new column. However, it's pretty common for me to subset on rows when creating reports or generating descriptive statistics. For example, I might want to create a simple frequency for a specific line of business, say Retail credit cards. To do this, I would select only those records where the line of business = retail in addition to whichever columns I want to report on. When creating new columns, however, I would pull all rows of data and only the columns I need for the operations.</li> <li>The modeling process requires that I analyze every column, look for interesting relationships with some outcome variable, and create new compound columns that describe those relationships. The columns that I explore are usually done in small sets. For example, I will focus on a set of say 20 columns just dealing with property values and observe how they relate to defaulting on a loan. Once those are explored and new columns are created, I then move on to another group of columns, say college education, and repeat the process. What I'm doing is creating candidate variables that explain the relationship between my data and some outcome. At the very end of this process, I apply some learning techniques that create an equation out of those compound columns.</li> </ol> <p>It is rare that I would ever add rows to the dataset. I will nearly always be creating new columns (variables or features in statistics/machine learning parlance).</p>
<p>I routinely use tens of gigabytes of data in just this fashion e.g. I have tables on disk that I read via queries, create data and append back.</p> <p>It's worth reading <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#hdf5-pytables" rel="noreferrer">the docs</a> and <a href="https://groups.google.com/forum/m/?fromgroups#!topic/pydata/cmw1F3OFJSc" rel="noreferrer">late in this thread</a> for several suggestions for how to store your data.</p> <p>Details which will affect how you store your data, like:<br> <em>Give as much detail as you can; and I can help you develop a structure.</em></p> <ol> <li>Size of data, # of rows, columns, types of columns; are you appending rows, or just columns? </li> <li>What will typical operations look like. E.g. do a query on columns to select a bunch of rows and specific columns, then do an operation (in-memory), create new columns, save these.<br> (Giving a toy example could enable us to offer more specific recommendations.)</li> <li>After that processing, then what do you do? Is step 2 ad hoc, or repeatable?</li> <li>Input flat files: how many, rough total size in Gb. How are these organized e.g. by records? Does each one contains different fields, or do they have some records per file with all of the fields in each file?</li> <li>Do you ever select subsets of rows (records) based on criteria (e.g. select the rows with field A > 5)? and then do something, or do you just select fields A, B, C with all of the records (and then do something)?</li> <li>Do you 'work on' all of your columns (in groups), or are there a good proportion that you may only use for reports (e.g. you want to keep the data around, but don't need to pull in that column explicity until final results time)?</li> </ol> <h2>Solution</h2> <p><em>Ensure you have <a href="http://pandas.pydata.org/getpandas.html" rel="noreferrer">pandas at least <code>0.10.1</code></a> installed.</em></p> <p>Read <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#iterating-through-files-chunk-by-chunk" rel="noreferrer">iterating files chunk-by-chunk</a> and <a href="http://pandas-docs.github.io/pandas-docs-travis/io.html#multiple-table-queries" rel="noreferrer">multiple table queries</a>.</p> <p>Since pytables is optimized to operate on row-wise (which is what you query on), we will create a table for each group of fields. This way it's easy to select a small group of fields (which will work with a big table, but it's more efficient to do it this way... I think I may be able to fix this limitation in the future... this is more intuitive anyhow):<br> (The following is pseudocode.)</p> <pre><code>import numpy as np import pandas as pd # create a store store = pd.HDFStore('mystore.h5') # this is the key to your storage: # this maps your fields to a specific group, and defines # what you want to have as data_columns. # you might want to create a nice class wrapping this # (as you will want to have this map and its inversion) group_map = dict( A = dict(fields = ['field_1','field_2',.....], dc = ['field_1',....,'field_5']), B = dict(fields = ['field_10',...... ], dc = ['field_10']), ..... REPORTING_ONLY = dict(fields = ['field_1000','field_1001',...], dc = []), ) group_map_inverted = dict() for g, v in group_map.items(): group_map_inverted.update(dict([ (f,g) for f in v['fields'] ])) </code></pre> <p>Reading in the files and creating the storage (essentially doing what <code>append_to_multiple</code> does):</p> <pre><code>for f in files: # read in the file, additional options may be necessary here # the chunksize is not strictly necessary, you may be able to slurp each # file into memory in which case just eliminate this part of the loop # (you can also change chunksize if necessary) for chunk in pd.read_table(f, chunksize=50000): # we are going to append to each table by group # we are not going to create indexes at this time # but we *ARE* going to create (some) data_columns # figure out the field groupings for g, v in group_map.items(): # create the frame for this group frame = chunk.reindex(columns = v['fields'], copy = False) # append it store.append(g, frame, index=False, data_columns = v['dc']) </code></pre> <p>Now you have all of the tables in the file (actually you could store them in separate files if you wish, you would prob have to add the filename to the group_map, but probably this isn't necessary).</p> <p>This is how you get columns and create new ones:</p> <pre><code>frame = store.select(group_that_I_want) # you can optionally specify: # columns = a list of the columns IN THAT GROUP (if you wanted to # select only say 3 out of the 20 columns in this sub-table) # and a where clause if you want a subset of the rows # do calculations on this frame new_frame = cool_function_on_frame(frame) # to 'add columns', create a new group (you probably want to # limit the columns in this new_group to be only NEW ones # (e.g. so you don't overlap from the other tables) # add this info to the group_map store.append(new_group, new_frame.reindex(columns = new_columns_created, copy = False), data_columns = new_columns_created) </code></pre> <p>When you are ready for post_processing:</p> <pre><code># This may be a bit tricky; and depends what you are actually doing. # I may need to modify this function to be a bit more general: report_data = store.select_as_multiple([groups_1,groups_2,.....], where =['field_1&gt;0', 'field_1000=foo'], selector = group_1) </code></pre> <p>About data_columns, you don't actually need to define <strong>ANY</strong> data_columns; they allow you to sub-select rows based on the column. E.g. something like:</p> <pre><code>store.select(group, where = ['field_1000=foo', 'field_1001&gt;0']) </code></pre> <p>They may be most interesting to you in the final report generation stage (essentially a data column is segregated from other columns, which might impact efficiency somewhat if you define a lot).</p> <p>You also might want to:</p> <ul> <li>create a function which takes a list of fields, looks up the groups in the groups_map, then selects these and concatenates the results so you get the resulting frame (this is essentially what select_as_multiple does). <em>This way the structure would be pretty transparent to you.</em></li> <li>indexes on certain data columns (makes row-subsetting much faster).</li> <li>enable compression.</li> </ul> <p>Let me know when you have questions!</p>
{ "question_id": 14262433, "question_date": "2013-01-10T16:20:32.017Z", "question_score": 1166, "tags": "python|mongodb|pandas|hdf5|large-data", "answer_id": 14268804, "answer_date": "2013-01-10T22:57:22.433Z", "answer_score": 708 }
Please answer the following Stack Overflow question: Title: Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS? <p>I'm a beginner RoR programmer who's planning to deploy my app using Heroku. Word from my other advisor friends says that Heroku is really easy, good to use. The only problem is that I still have no idea what Heroku does...</p> <p>I've looked at their <a href="http://www.heroku.com/how/command" rel="noreferrer">website</a> and in a nutshell, what Heroku does is help with scaling but... why does that even matter? How does Heroku help with:</p> <ol> <li><p>Speed - My research implied that deploying AWS on the US East Coast would be the fastest if I am targeting a US/Asia-based audience.</p></li> <li><p>Security - How secure are they?</p></li> <li><p>Scaling - How does it actually work?</p></li> <li><p>Cost efficiency - There's something like a dyno that makes it easy to scale.</p></li> <li><p>How do they fare against their competitors? For example, <a href="http://www.engineyard.com/" rel="noreferrer">Engine Yard</a> and <a href="http://www.bluebox.net/" rel="noreferrer">bluebox</a>?</p></li> </ol> <p>Please use layman English terms to explain... I'm a beginner programmer.</p>
<p><strong>AWS / Heroku</strong> are both free for small hobby projects (to start with). </p> <p>If you want to start an app right away, without much customization of the architecture, then choose <strong>Heroku</strong>.</p> <p>If you want to focus on the architecture and to be able to use different web servers, then choose <strong>AWS</strong>. AWS is more time-consuming based on what service/product you choose, but can be worth it. AWS also comes with many plugin services and products.</p> <hr> <p><strong>Heroku</strong></p> <ul> <li>Platform as a Service (PAAS)</li> <li>Good documentation</li> <li>Has built-in tools and architecture.</li> <li>Limited control over architecture while designing the app.</li> <li>Deployment is taken care of (automatic via GitHub or manual via git commands or CLI).</li> <li>Not time consuming.</li> </ul> <hr> <p><strong>AWS</strong></p> <ul> <li>Infrastructure as a Service (IAAS)</li> <li>Versatile - has many products such as EC2, LAMBDA, EMR, etc.</li> <li>Can use a Dedicated instance for more control over the architecture, such as choosing the OS, software version, etc. There is more than one backend layer.</li> <li>Elastic Beanstalk is a feature similar to Heroku's PAAS. </li> <li>Can use the automated deployment, or roll your own.</li> </ul>
{ "question_id": 9802259, "question_date": "2012-03-21T10:00:53.853Z", "question_score": 1166, "tags": "ruby-on-rails|heroku|amazon-web-services", "answer_id": 32944469, "answer_date": "2015-10-05T08:46:12.887Z", "answer_score": 283 }
Please answer the following Stack Overflow question: Title: Shortcuts in Objective-C to concatenate NSStrings <p>Are there any shortcuts to (<code>stringByAppendingString:</code>) string concatenation in Objective-C, or shortcuts for working with <code>NSString</code> in general?</p> <p>For example, I'd like to make:</p> <pre><code>NSString *myString = @"This"; NSString *test = [myString stringByAppendingString:@" is just a test"]; </code></pre> <p>something more like:</p> <pre><code>string myString = "This"; string test = myString + " is just a test"; </code></pre>
<p>Two answers I can think of... neither is particularly as pleasant as just having a concatenation operator.</p> <p>First, use an <code>NSMutableString</code>, which has an <code>appendString</code> method, removing some of the need for extra temp strings.</p> <p>Second, use an <code>NSArray</code> to concatenate via the <code>componentsJoinedByString</code> method.</p>
{ "question_id": 510269, "question_date": "2009-02-04T06:26:19.240Z", "question_score": 1165, "tags": "objective-c|nsstring|string-concatenation", "answer_id": 510311, "answer_date": "2009-02-04T06:44:42.353Z", "answer_score": 631 }
Please answer the following Stack Overflow question: Title: How do I iterate through two lists in parallel? <p>I have two iterables, and I want to go over them in pairs:</p> <pre class="lang-py prettyprint-override"><code>foo = [1, 2, 3] bar = [4, 5, 6] for (f, b) in iterate_together(foo, bar): print(&quot;f:&quot;, f, &quot; | b:&quot;, b) </code></pre> <p>That should result in:</p> <pre class="lang-none prettyprint-override"><code>f: 1 | b: 4 f: 2 | b: 5 f: 3 | b: 6 </code></pre> <p><em>One</em> way to do it is to iterate over the indices:</p> <pre class="lang-py prettyprint-override"><code>for i in range(len(foo)): print(&quot;f:&quot;, foo[i], &quot; | b:&quot;, bar[i]) </code></pre> <p>But that seems somewhat unpythonic to me. Is there a better way to do it?</p>
<h2>Python 3</h2> <pre><code>for f, b in zip(foo, bar): print(f, b) </code></pre> <p><code>zip</code> stops when the shorter of <code>foo</code> or <code>bar</code> stops.</p> <p>In <strong>Python 3</strong>, <a href="https://docs.python.org/3/library/functions.html#zip" rel="noreferrer"><code>zip</code></a> returns an iterator of tuples, like <code>itertools.izip</code> in Python2. To get a list of tuples, use <code>list(zip(foo, bar))</code>. And to zip until both iterators are exhausted, you would use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest" rel="noreferrer">itertools.zip_longest</a>.</p> <h2>Python 2</h2> <p>In <strong>Python 2</strong>, <a href="https://docs.python.org/2/library/functions.html#zip" rel="noreferrer"><code>zip</code></a> returns a list of tuples. This is fine when <code>foo</code> and <code>bar</code> are not massive. If they are both massive then forming <code>zip(foo,bar)</code> is an unnecessarily massive temporary variable, and should be replaced by <code>itertools.izip</code> or <code>itertools.izip_longest</code>, which returns an iterator instead of a list.</p> <pre><code>import itertools for f,b in itertools.izip(foo,bar): print(f,b) for f,b in itertools.izip_longest(foo,bar): print(f,b) </code></pre> <p><code>izip</code> stops when either <code>foo</code> or <code>bar</code> is exhausted. <code>izip_longest</code> stops when both <code>foo</code> and <code>bar</code> are exhausted. When the shorter iterator(s) are exhausted, <code>izip_longest</code> yields a tuple with <code>None</code> in the position corresponding to that iterator. You can also set a different <code>fillvalue</code> besides <code>None</code> if you wish. See here for the <a href="http://docs.python.org/library/itertools.html#itertools.izip_longest" rel="noreferrer">full story</a>.</p> <hr> <p>Note also that <code>zip</code> and its <code>zip</code>-like brethen can accept an arbitrary number of iterables as arguments. For example,</p> <pre><code>for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], ['red', 'blue', 'green']): print('{} {} {}'.format(num, color, cheese)) </code></pre> <p>prints</p> <pre><code>1 red manchego 2 blue stilton 3 green brie </code></pre>
{ "question_id": 1663807, "question_date": "2009-11-02T21:26:24.273Z", "question_score": 1164, "tags": "python|list|for-loop|iterator", "answer_id": 1663826, "answer_date": "2009-11-02T21:28:27.880Z", "answer_score": 1818 }
Please answer the following Stack Overflow question: Title: Convert a string to an enum in C# <p>What's the best way to convert a string to an enumeration value in C#?</p> <p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.</p> <p>In an ideal world, I could do something like this:</p> <pre><code>StatusEnum MyStatus = StatusEnum.Parse(&quot;Active&quot;); </code></pre> <p>but that isn't a valid code.</p>
<p>In .NET Core and .NET Framework ≥4.0 <a href="https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx" rel="noreferrer">there is a generic parse method</a>:</p> <pre><code>Enum.TryParse(&quot;Active&quot;, out StatusEnum myStatus); </code></pre> <p>This also includes C#7's new inline <code>out</code> variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the <code>myStatus</code> variable.</p> <p>If you have access to C#7 and the latest .NET this is the best way.</p> <h2>Original Answer</h2> <p>In .NET it's rather ugly (until 4 or above):</p> <pre><code>StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), &quot;Active&quot;, true); </code></pre> <p>I tend to simplify this with:</p> <pre><code>public static T ParseEnum&lt;T&gt;(string value) { return (T) Enum.Parse(typeof(T), value, true); } </code></pre> <p>Then I can do:</p> <pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum&lt;StatusEnum&gt;(&quot;Active&quot;); </code></pre> <p>One option suggested in the comments is to add an extension, which is simple enough:</p> <pre><code>public static T ToEnum&lt;T&gt;(this string value) { return (T) Enum.Parse(typeof(T), value, true); } StatusEnum MyStatus = &quot;Active&quot;.ToEnum&lt;StatusEnum&gt;(); </code></pre> <p>Finally, you may want to have a default enum to use if the string cannot be parsed:</p> <pre><code>public static T ToEnum&lt;T&gt;(this string value, T defaultValue) { if (string.IsNullOrEmpty(value)) { return defaultValue; } T result; return Enum.TryParse&lt;T&gt;(value, true, out result) ? result : defaultValue; } </code></pre> <p>Which makes this the call:</p> <pre><code>StatusEnum MyStatus = &quot;Active&quot;.ToEnum(StatusEnum.None); </code></pre> <p>However, I would be careful adding an extension method like this to <code>string</code> as (without namespace control) it will appear on all instances of <code>string</code> whether they hold an enum or not (so <code>1234.ToString().ToEnum(StatusEnum.None)</code> would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.</p>
{ "question_id": 16100, "question_date": "2008-08-19T12:51:55.043Z", "question_score": 1163, "tags": "c#|string|enums", "answer_id": 16104, "answer_date": "2008-08-19T12:54:28.533Z", "answer_score": 1936 }
Please answer the following Stack Overflow question: Title: Check if a variable is of function type <p>Suppose I have any variable, which is defined as follows:</p> <pre><code>var a = function() {/* Statements */}; </code></pre> <p>I want a function which checks if the type of the variable is function-like. i.e. :</p> <pre><code>function foo(v) {if (v is function type?) {/* do something */}}; foo(a); </code></pre> <p>How can I check if the variable <code>a</code> is of type <code>Function</code> in the way defined above?</p>
<p>Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.</p> <p>Inspired by underscore, the final isFunction function is as follows:</p> <pre><code>function isFunction(functionToCheck) { return functionToCheck &amp;&amp; {}.toString.call(functionToCheck) === '[object Function]'; } </code></pre> <p><strong>Note</strong>: This solution doesn't work for async functions, generators or proxied functions. Please see other answers for more up to date solutions.</p>
{ "question_id": 5999998, "question_date": "2011-05-14T05:27:47.243Z", "question_score": 1163, "tags": "javascript", "answer_id": 7356528, "answer_date": "2011-09-09T02:24:20.707Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: What is the difference between statically typed and dynamically typed languages? <p>What does it mean when we say a language is dynamically typed versus statically typed?</p>
<h3 id="statically-typed-languages-pajo">Statically typed languages</h3> <p>A language is statically typed if the type of a variable is known at compile time. For some languages this means that you as the programmer must specify what type each variable is; other languages (e.g.: Java, C, C++) offer some form of <em>type inference</em>, the capability of the type system to deduce the type of a variable (e.g.: OCaml, Haskell, Scala, Kotlin).</p> <p>The main advantage here is that all kinds of checking can be done by the compiler, and therefore a lot of trivial bugs are caught at a very early stage.</p> <p>Examples: C, C++, Java, Rust, Go, Scala</p> <h3 id="dynamically-typed-languages-17fp">Dynamically typed languages</h3> <p>A language is dynamically typed if the type is associated with run-time values, and not named variables/fields/etc. This means that you as a programmer can write a little quicker because you do not have to specify types every time (unless using a statically-typed language with <em>type inference</em>).</p> <p>Examples: Perl, Ruby, Python, PHP, JavaScript, Erlang</p> <p>Most scripting languages have this feature as there is no compiler to do static type-checking anyway, but you may find yourself searching for a bug that is due to the interpreter misinterpreting the type of a variable. Luckily, scripts tend to be small so bugs have not so many places to hide.</p> <p>Most dynamically typed languages do allow you to provide type information, but do not require it. One language that is currently being developed, <a href="http://www.rascal-mpl.org/" rel="noreferrer">Rascal</a>, takes a hybrid approach allowing dynamic typing within functions but enforcing static typing for the function signature.</p>
{ "question_id": 1517582, "question_date": "2009-10-04T22:36:10.520Z", "question_score": 1163, "tags": "programming-languages|computer-science|static-typing|dynamic-typing", "answer_id": 1517670, "answer_date": "2009-10-04T23:11:04.030Z", "answer_score": 1036 }
Please answer the following Stack Overflow question: Title: Convert character to ASCII code in JavaScript <p>How can I convert a character to its ASCII code using JavaScript?</p> <p>For example:</p> <blockquote> <p>get 10 from &quot;\n&quot;.</p> </blockquote>
<pre><code>"\n".charCodeAt(0); </code></pre>
{ "question_id": 94037, "question_date": "2008-09-18T16:13:48.010Z", "question_score": 1162, "tags": "javascript", "answer_id": 94049, "answer_date": "2008-09-18T16:15:24.823Z", "answer_score": 1720 }
Please answer the following Stack Overflow question: Title: How to reload .bash_profile from the command line <p>How can I reload file <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example" rel="noreferrer">.bash_profile</a> from the <em>command line</em>?</p> <p>I can get the shell to recognize changes to <em>.bash_profile</em> by exiting and logging back in, but I would like to be able to do it on demand.</p>
<p>Simply type <code>source ~/.bash_profile</code>.</p> <p>Alternatively, if you like saving keystrokes, you can type <code>. ~/.bash_profile</code>.</p>
{ "question_id": 4608187, "question_date": "2011-01-05T19:09:07.910Z", "question_score": 1162, "tags": "bash|shell|command-line", "answer_id": 4608197, "answer_date": "2011-01-05T19:10:03.910Z", "answer_score": 2183 }
Please answer the following Stack Overflow question: Title: Use a list of values to select rows from a Pandas dataframe <p>Let’s say I have the following Pandas dataframe:</p> <pre><code>df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) df A B 0 5 1 1 6 2 2 3 3 3 4 5 </code></pre> <p>I can subset based on a specific value:</p> <pre><code>x = df[df['A'] == 3] x A B 2 3 3 </code></pre> <p>But how can I subset based on a list of values? - something like this:</p> <pre><code>list_of_values = [3,6] y = df[df['A'] in list_of_values] </code></pre> <p>To get:</p> <pre><code> A B 1 6 2 2 3 3 </code></pre>
<p>You can use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="noreferrer"><code>isin</code></a> method:</p> <pre><code>In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]}) In [2]: df Out[2]: A B 0 5 1 1 6 2 2 3 3 3 4 5 In [3]: df[df['A'].isin([3, 6])] Out[3]: A B 1 6 2 2 3 3 </code></pre> <p>And to get the opposite use <code>~</code>:</p> <pre><code>In [4]: df[~df['A'].isin([3, 6])] Out[4]: A B 0 5 1 3 4 5 </code></pre>
{ "question_id": 12096252, "question_date": "2012-08-23T16:31:12.237Z", "question_score": 1161, "tags": "python|pandas|dataframe", "answer_id": 12098586, "answer_date": "2012-08-23T19:20:12.243Z", "answer_score": 1951 }
Please answer the following Stack Overflow question: Title: What is the maximum length of a valid email address? <p>What is the maximum length of a valid email address? Is it defined by any standard?</p>
<p>An email address must not exceed <strong>254</strong> characters.</p> <p>This was accepted by the IETF following <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696&amp;eid=1690" rel="noreferrer">submitted erratum</a>. A full diagnosis of any given address is available <a href="http://isemail.info/" rel="noreferrer">online</a>. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as</p> <pre><code>Path = &quot;&lt;&quot; [ A-d-l &quot;:&quot; ] Mailbox &quot;&gt;&quot; </code></pre> <p>So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.</p> <p>The maximum length specified in <a href="https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3" rel="noreferrer">RFC 5321</a> states:</p> <blockquote> <p>The maximum total length of a reverse-path or forward-path is 256 characters.</p> </blockquote> <p>RFC 3696 was corrected <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696" rel="noreferrer">here</a>.</p> <p>People should be aware of the <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696" rel="noreferrer">errata against RFC 3696</a> in particular. Three of the canonical examples are in fact invalid addresses.</p> <p>I've collated a couple hundred test addresses, which you can find at <a href="http://www.dominicsayers.com/isemail" rel="noreferrer">http://www.dominicsayers.com/isemail</a></p>
{ "question_id": 386294, "question_date": "2008-12-22T13:57:54.060Z", "question_score": 1161, "tags": "validation|email|max|email-address", "answer_id": 574698, "answer_date": "2009-02-22T10:28:47.640Z", "answer_score": 1388 }
Please answer the following Stack Overflow question: Title: How to prune local tracking branches that do not exist on remote anymore <p>With <code>git remote prune origin</code> I can remove the local branches that are not on the remote any more.</p> <p>But I also want to remove local branches that were created from those remote branches (a check if they are unmerged would be nice).</p> <p>How can I do this?</p>
<p>After pruning, you can get the list of remote branches with <code>git branch -r</code>. The list of branches with their remote tracking branch can be retrieved with <code>git branch -vv</code>. So using these two lists you can find the remote tracking branches that are not in the list of remotes.</p> <p>This line should do the trick (requires <code>bash</code> or <code>zsh</code>, won't work with standard Bourne shell):</p> <pre class="lang-sh prettyprint-override"><code>git fetch -p ; git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 &lt;(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d </code></pre> <p>This string gets the list of remote branches and passes it into <code>egrep</code> through the standard input. And filters the branches that have a remote tracking branch (using <code>git branch -vv</code> and filtering for those that have <code>origin</code>) then getting the first column of that output which will be the branch name. Finally passing all the branch names into the delete branch command.</p> <p>Since it is using the <code>-d</code> option, it will not delete branches that have not been merged into the branch that you are on when you run this command.</p>
{ "question_id": 13064613, "question_date": "2012-10-25T08:31:13.090Z", "question_score": 1160, "tags": "git", "answer_id": 17029936, "answer_date": "2013-06-10T17:54:00.810Z", "answer_score": 1277 }
Please answer the following Stack Overflow question: Title: What is an example of the Liskov Substitution Principle? <p>I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?</p>
<p>A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.</p> <p>In mathematics, a <code>Square</code> is a <code>Rectangle</code>. Indeed it is a specialization of a rectangle. The &quot;is a&quot; makes you want to model this with inheritance. However if in code you made <code>Square</code> derive from <code>Rectangle</code>, then a <code>Square</code> should be usable anywhere you expect a <code>Rectangle</code>. This makes for some strange behavior.</p> <p>Imagine you had <code>SetWidth</code> and <code>SetHeight</code> methods on your <code>Rectangle</code> base class; this seems perfectly logical. However if your <code>Rectangle</code> reference pointed to a <code>Square</code>, then <code>SetWidth</code> and <code>SetHeight</code> doesn't make sense because setting one would change the other to match it. In this case <code>Square</code> fails the Liskov Substitution Test with <code>Rectangle</code> and the abstraction of having <code>Square</code> inherit from <code>Rectangle</code> is a bad one.</p> <p><a href="https://i.stack.imgur.com/ilxzO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ilxzO.jpg" alt="enter image description here" /></a></p> <p>Y'all should check out the other priceless <a href="https://www.globalnerdy.com/2009/07/15/the-solid-principles-explained-with-motivational-posters/" rel="noreferrer">SOLID Principles Explained With Motivational Posters</a>.</p>
{ "question_id": 56860, "question_date": "2008-09-11T15:17:38.983Z", "question_score": 1160, "tags": "oop|definition|solid-principles|design-principles|liskov-substitution-principle", "answer_id": 584732, "answer_date": "2009-02-25T04:44:31.487Z", "answer_score": 1152 }
Please answer the following Stack Overflow question: Title: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException <p>I have some code that uses JAXB API classes which have been provided as a part of the JDK in Java 6/7/8. When I run the same code with Java 9, at runtime I get errors indicating that JAXB classes can not be found.</p> <p>The JAXB classes have been provided as a part of the JDK since Java 6, so why can Java 9 no longer find these classes?</p>
<p>The JAXB APIs are considered to be Java EE APIs and therefore are no longer contained on the default classpath in Java SE 9. In Java 11, they are completely removed from the JDK.</p> <p>Java 9 introduces the concepts of modules, and by default, the <code>java.se</code> aggregate module is available on the classpath (or rather, module-path). As the name implies, the <code>java.se</code> aggregate module does <em>not</em> include the Java EE APIs that have been traditionally bundled with Java 6/7/8.</p> <p>Fortunately, these Java EE APIs that were provided in JDK 6/7/8 are still in the JDK, but they just aren't on the classpath by default. The extra Java EE APIs are provided in the following modules:</p> <pre><code>java.activation java.corba java.transaction java.xml.bind &lt;&lt; This one contains the JAXB APIs java.xml.ws java.xml.ws.annotation </code></pre> <p><strong>Quick and dirty solution: (JDK 9/10 only)</strong></p> <p>To make the JAXB APIs available at runtime, specify the following command-line option:</p> <p><code>--add-modules java.xml.bind</code></p> <p><strong>But I still need this to work with Java 8!!!</strong></p> <p>If you try specifying <code>--add-modules</code> with an older JDK, it will blow up because it's an unrecognized option. I suggest one of two options:</p> <ol> <li>You can set any Java 9+ only options using the <code>JDK_JAVA_OPTIONS</code> environment variable. This environment variable is <a href="https://www.oracle.com/technetwork/java/javase/9-new-features-3745613.html#JDK-8170832" rel="noreferrer">automatically read</a> by the <code>java</code> launcher for Java 9+.</li> <li>You can add the <code>-XX:+IgnoreUnrecognizedVMOptions</code> to make the JVM silently ignore unrecognized options, instead of blowing up. But beware! Any other command-line arguments you use will no longer be validated for you by the JVM. This option works with Oracle/OpenJDK as well as IBM JDK (as of JDK 8sr4).</li> </ol> <hr /> <p><strong>Alternate quick solution: (JDK 9/10 only)</strong></p> <p>Note that you can make all of the above Java EE modules available at run time by specifying the <code>--add-modules java.se.ee</code> option. The <code>java.se.ee</code> module is an aggregate module that includes <code>java.se.ee</code> as well as the above Java EE API modules. Note, this <strong>doesn't work on Java 11</strong> because <code>java.se.ee</code> was removed in Java 11.</p> <hr /> <h2>Proper long-term solution: (JDK 9 and beyond)</h2> <p>The Java EE API modules listed above are all marked <code>@Deprecated(forRemoval=true)</code> because they are <a href="http://openjdk.java.net/jeps/320" rel="noreferrer">scheduled for removal</a> in <a href="http://openjdk.java.net/projects/jdk/11/" rel="noreferrer">Java 11</a>. So the <code>--add-module</code> approach will no longer work in Java 11 out-of-the-box.</p> <p>What you will need to do in Java 11 and forward is include your own copy of the Java EE APIs on the classpath or module path. For example, you can add the JAX-B APIs as a Maven dependency like this:</p> <pre><code>&lt;!-- API, java.xml.bind module --&gt; &lt;dependency&gt; &lt;groupId&gt;jakarta.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jakarta.xml.bind-api&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Runtime, com.sun.xml.bind module --&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jaxb&lt;/groupId&gt; &lt;artifactId&gt;jaxb-runtime&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>See the <a href="https://eclipse-ee4j.github.io/jaxb-ri/" rel="noreferrer">JAXB Reference Implementation page</a> for more details on JAXB.</p> <p>For full details on Java modularity, see <a href="http://openjdk.java.net/jeps/261" rel="noreferrer">JEP 261: Module System</a></p> <p>As of July 2022, the latest version of the bind-api and jaxb-runtime is 4.0.0. So you can also use</p> <pre><code> &lt;version&gt;4.0.0&lt;/version&gt; </code></pre> <p>...within those dependency clauses. But if you do so, the package names have changed from <code>javax.xml.bind...</code> to <code>jakarta.xml.bind...</code>. You will need to modify your source code to use these later versions of the JARs.</p> <p><strong>For Gradle or Android Studio developer: (JDK 9 and beyond)</strong></p> <p>Add the following dependencies to your <code>build.gradle</code> file:</p> <pre><code>dependencies { // JAX-B dependencies for JDK 9+ implementation &quot;jakarta.xml.bind:jakarta.xml.bind-api:2.3.2&quot; implementation &quot;org.glassfish.jaxb:jaxb-runtime:2.3.2&quot; } </code></pre>
{ "question_id": 43574426, "question_date": "2017-04-23T17:40:23.460Z", "question_score": 1158, "tags": "java|jaxb|java-9|java-11|java-10", "answer_id": 43574427, "answer_date": "2017-04-23T17:40:23.460Z", "answer_score": 1664 }
Please answer the following Stack Overflow question: Title: Can't create handler inside thread that has not called Looper.prepare() <p>What does the following exception mean; how can I fix it?</p> <p>This is the code:</p> <pre><code>Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT); </code></pre> <p>This is the exception:</p> <pre class="lang-none prettyprint-override"><code>java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.&lt;init&gt;(Handler.java:121) at android.widget.Toast.&lt;init&gt;(Toast.java:68) at android.widget.Toast.makeText(Toast.java:231) </code></pre>
<p>You're calling it from a worker thread. You need to call <code>Toast.makeText()</code> (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example.</p> <p>Look up <a href="https://developer.android.com/training/multiple-threads/communicate-ui.html" rel="noreferrer">Communicating with the UI Thread</a> in the documentation. In a nutshell:</p> <pre><code>// Set this up in the UI thread. mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message message) { // This is where you do your work in the UI thread. // Your worker tells you in the message what to do. } }; void workerThread() { // And this is how you call it from the worker thread: Message message = mHandler.obtainMessage(command, parameter); message.sendToTarget(); } </code></pre> <p><strong>Other options:</strong></p> <p>You could use <a href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)" rel="noreferrer"><code>Activity.runOnUiThread()</code></a>. Straightforward if you have an <code>Activity</code>:</p> <pre class="lang-java prettyprint-override"><code>@WorkerThread void workerThread() { myActivity.runOnUiThread(() -&gt; { // This is where your UI code goes. } } </code></pre> <p>You could also post to the main looper. This works great if all you have is a <code>Context</code>.</p> <pre class="lang-java prettyprint-override"><code>@WorkerThread void workerThread() { ContextCompat.getMainExecutor(context).execute(() -&gt; { // This is where your UI code goes. } } </code></pre> <p><strong>Deprecated:</strong></p> <p>You could use an <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="noreferrer">AsyncTask</a>, that works well for most things running in the background. It has hooks that you can call to indicate the progress, and when it's done.</p> <p>It's convenient, but can leak contexts if not used correctly. It's been officially deprecated, and you shouldn't use it anymore.</p>
{ "question_id": 3875184, "question_date": "2010-10-06T17:18:26.680Z", "question_score": 1158, "tags": "android|ui-thread|android-toast", "answer_id": 3875204, "answer_date": "2010-10-06T17:20:58.807Z", "answer_score": 809 }
Please answer the following Stack Overflow question: Title: Filename too long in Git for Windows <p>I'm using <code>Git-1.9.0-preview20140217</code> for Windows. As I know, this release should fix the issue with too long filenames. But not for me.</p> <p>Surely I'm doing something wrong: I did <code>git config core.longpaths true</code> and <code>git add .</code> and then <code>git commit</code>. Everything went well. But when I now do a <code>git status</code>, I get a list of files with <code>Filename too long</code>, for example:</p> <blockquote> <p><code>node_modules/grunt-contrib-imagemin/node_modules/pngquant-bin/node_modules/bin-wrapper/node_modules/download/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/test/integration/test-handle-source-errors.js: Filename too long</code></p> </blockquote> <p>It is quite simple to reproduce for me: just create a <a href="https://en.wikipedia.org/wiki/Yeoman_(software)" rel="noreferrer">Yeoman</a> web application with the Angular generator (&quot;yo angular&quot;) and remove <code>node_modules</code> from the <code>.gitignore</code> file. Then repeat the aforementioned Git commands.</p> <p>What am I missing here?</p>
<p>Git has a limit of 4096 characters for a filename, except on Windows when Git is compiled with msys. It uses an older version of the Windows API and there's a limit of 260 characters for a filename.</p> <p>So as far as I understand this, it's a limitation of msys and not of Git. You can read the details here: <a href="https://github.com/msysgit/git/pull/110" rel="noreferrer">https://github.com/msysgit/git/pull/110</a></p> <p>You can circumvent this by using another Git client on Windows or set <code>core.longpaths</code> to <code>true</code> as explained in other answers.</p> <pre><code>git config --system core.longpaths true </code></pre> <p>Git is build as a combination of scripts and compiled code. With the above change some of the scripts might fail. That's the reason for core.longpaths not to be enabled by default.</p> <p>The windows documentation at <a href="https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later" rel="noreferrer">https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later</a> has some more information:</p> <blockquote> <p>Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.</p> <p>A registry key allows you to enable or disable the new long path behavior. To enable long path behavior set the registry key at HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled (Type: REG_DWORD)</p> </blockquote>
{ "question_id": 22575662, "question_date": "2014-03-22T09:14:24.297Z", "question_score": 1158, "tags": "windows|git", "answer_id": 22575737, "answer_date": "2014-03-22T09:24:15.500Z", "answer_score": 1531 }
Please answer the following Stack Overflow question: Title: How to compare strings in Bash <p>How do I compare a variable to a string (and do something if they match)?</p>
<h1>Using variables in if statements</h1> <pre><code>if [ "$x" = "valid" ]; then echo "x has the value 'valid'" fi </code></pre> <p>If you want to do something when they don't match, replace <code>=</code> with <code>!=</code>. You can read more about <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.1" rel="noreferrer">string operations</a> and <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-11.html#ss11.3" rel="noreferrer">arithmetic operations</a> in their respective documentation.</p> <h3>Why do we use quotes around <code>$x</code>?</h3> <p>You want the quotes around <code>$x</code>, because if it is empty, your Bash script encounters a syntax error as seen below:</p> <pre><code>if [ = "valid" ]; then </code></pre> <hr> <h3>Non-standard use of <code>==</code> operator</h3> <p>Note that Bash allows <code>==</code> to be used for equality with <code>[</code>, but <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html" rel="noreferrer">this is not standard</a>.</p> <p>Use either the first case wherein the quotes around <code>$x</code> are optional:</p> <pre><code>if [[ "$x" == "valid" ]]; then </code></pre> <p>or use the second case:</p> <pre><code>if [ "$x" = "valid" ]; then </code></pre>
{ "question_id": 2237080, "question_date": "2010-02-10T13:31:18.520Z", "question_score": 1157, "tags": "string|bash", "answer_id": 2237103, "answer_date": "2010-02-10T13:34:55.860Z", "answer_score": 1641 }
Please answer the following Stack Overflow question: Title: Why not use Double or Float to represent currency? <p>I've always been told <em>never</em> to represent money with <code>double</code> or <code>float</code> types, and this time I pose the question to you: why? </p> <p>I'm sure there is a very good reason, I simply do not know what it is.</p>
<p>Because floats and doubles cannot accurately represent the base 10 multiples that we use for money. This issue isn't just for Java, it's for any programming language that uses base 2 floating-point types.</p> <p>In base 10, you can write 10.25 as 1025 * 10<sup>-2</sup> (an integer times a power of 10). <a href="http://en.wikipedia.org/wiki/IEEE_floating_point" rel="noreferrer">IEEE-754 floating-point numbers</a> are different, but a very simple way to think about them is to multiply by a power of two instead. For instance, you could be looking at 164 * 2<sup>-4</sup> (an integer times a power of two), which is also equal to 10.25. That's not how the numbers are represented in memory, but the math implications are the same.</p> <p>Even in base 10, this notation cannot accurately represent most simple fractions. For instance, you can't represent 1/3: the decimal representation is repeating (0.3333...), so there is no finite integer that you can multiply by a power of 10 to get 1/3. You could settle on a long sequence of 3's and a small exponent, like 333333333 * 10<sup>-10</sup>, but it is not accurate: if you multiply that by 3, you won't get 1.</p> <p>However, for the purpose of counting money, at least for countries whose money is valued within an order of magnitude of the US dollar, usually all you need is to be able to store multiples of 10<sup>-2</sup>, so it doesn't really matter that 1/3 can't be represented.</p> <p>The problem with floats and doubles is that the <em>vast majority</em> of money-like numbers don't have an exact representation as an integer times a power of 2. In fact, the only multiples of 0.01 between 0 and 1 (which are significant when dealing with money because they're integer cents) that can be represented exactly as an IEEE-754 binary floating-point number are 0, 0.25, 0.5, 0.75 and 1. All the others are off by a small amount. As an analogy to the 0.333333 example, if you take the floating-point value for 0.01 and you multiply it by 10, you won't get 0.1. Instead you will get something like 0.099999999786...</p> <p>Representing money as a <code>double</code> or <code>float</code> will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, errors will compound and you'll end up with values that are visibly not accurate. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required.</p> <p>A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25. Several languages also have built-in types to deal with money. Among others, Java has the <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html" rel="noreferrer"><code>BigDecimal</code></a> class, and Rust has the <a href="https://docs.rs/rust_decimal/latest/rust_decimal/" rel="noreferrer"><code>rust_decimal</code></a> crate, and C# has the <a href="http://msdn.microsoft.com/en-us/library/364x0z75.aspx" rel="noreferrer"><code>decimal</code></a> type.</p>
{ "question_id": 3730019, "question_date": "2010-09-16T19:23:57.087Z", "question_score": 1157, "tags": "floating-point|currency", "answer_id": 3730040, "answer_date": "2010-09-16T19:26:02.517Z", "answer_score": 1197 }
Please answer the following Stack Overflow question: Title: Maximum request length exceeded. <p>I am getting the error <strong>Maximum request length exceeded</strong> when I am trying to upload a video in my site. </p> <p>How do I fix this?</p>
<p>If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your <code>web.config</code> -</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;httpRuntime maxRequestLength="1048576" /&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>For IIS7 and above, you also need to add the lines below:</p> <pre><code> &lt;system.webServer&gt; &lt;security&gt; &lt;requestFiltering&gt; &lt;requestLimits maxAllowedContentLength="1073741824" /&gt; &lt;/requestFiltering&gt; &lt;/security&gt; &lt;/system.webServer&gt; </code></pre> <p><strong>Note</strong>: </p> <ul> <li><strong><code>maxRequestLength</code></strong> is measured in <strong>kilobytes</strong></li> <li><strong><code>maxAllowedContentLength</code></strong> is measured in <strong>bytes</strong> </li> </ul> <p>which is why the values differ in this config example. (Both are equivalent to 1 GB.)</p>
{ "question_id": 3853767, "question_date": "2010-10-04T08:48:28.683Z", "question_score": 1156, "tags": "asp.net|iis|file-upload", "answer_id": 3853785, "answer_date": "2010-10-04T08:52:08.603Z", "answer_score": 2147 }
Please answer the following Stack Overflow question: Title: What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? <p>I have tried reading some articles, but I am not very clear on the concepts yet.</p> <p>Would someone like to take a shot at explaining to me what these technologies are:</p> <ol> <li>Long Polling</li> <li>Server-Sent Events</li> <li>Websockets</li> <li>Comet</li> </ol> <p>One thing that I came across every time was, the server keeps a connection open and pushes data to the client. How is the connection kept open, and how does the client get the pushed data? (How does the client use the data, maybe some code might help?)</p> <p>Now, which one of them should I use for a real-time app. I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP?</p>
<p><em>In the examples below the client is the browser and the server is the webserver hosting the website.</em></p> <p>Before you can understand these technologies, you have to understand <em>classic</em> HTTP web traffic first.</p> <h2>Regular HTTP:</h2> <ol> <li>A client requests a webpage from a server.</li> <li>The server calculates the response</li> <li>The server sends the response to the client. </li> </ol> <p><img src="https://i.stack.imgur.com/TK1ZG.png" alt="HTTP"></p> <h2>Ajax Polling:</h2> <ol> <li>A client requests a webpage from a server using regular HTTP (see HTTP above).</li> <li>The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).</li> <li>The server calculates each response and sends it back, just like normal HTTP traffic.</li> </ol> <p><img src="https://i.stack.imgur.com/qlMEU.png" alt="Ajax Polling"></p> <h2>Ajax Long-Polling:</h2> <ol> <li>A client requests a webpage from a server using regular HTTP (see HTTP above).</li> <li>The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.</li> <li>The server does not immediately respond with the requested information but waits until there's <strong>new</strong> information available.</li> <li>When there's new information available, the server responds with the new information.</li> <li>The client receives the new information and immediately sends another request to the server, re-starting the process. </li> </ol> <p><img src="https://i.stack.imgur.com/zLnOU.png" alt="Ajax Long-Polling"></p> <h2>HTML5 Server Sent Events (SSE) / EventSource:</h2> <ol> <li>A client requests a webpage from a server using regular HTTP (see HTTP above).</li> <li>The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.</li> <li><p>The server sends an event to the client when there's new information available. </p> <ul> <li>Real-time traffic from server to client, mostly that's what you'll need</li> <li>You'll want to use a server that has an event loop</li> <li>Connections with servers from other domains are only possible <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource" rel="noreferrer">with correct CORS settings</a></li> <li>If you want to read more, I found these very useful: <a href="https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events" rel="noreferrer">(article)</a>, <a href="http://html5doctor.com/server-sent-events/#api" rel="noreferrer">(article)</a>, <a href="http://www.html5rocks.com/en/tutorials/eventsource/basics/" rel="noreferrer">(article)</a>, <a href="http://jaxenter.com/tutorial-jsf-2-and-html5-server-sent-events-42932.html" rel="noreferrer">(tutorial)</a>.</li> </ul></li> </ol> <p><img src="https://i.stack.imgur.com/ziR5h.png" alt="HTML5 SSE"></p> <h2>HTML5 Websockets:</h2> <ol> <li>A client requests a webpage from a server using regular http (see HTTP above).</li> <li>The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.</li> <li><p>The server and the client can now send each other messages when new data (on either side) is available.</p> <ul> <li>Real-time traffic from the server to the client <strong>and</strong> from the client to the server</li> <li>You'll want to use a server that has an event loop</li> <li>With WebSockets it is possible to connect with a server from another domain.</li> <li>It is also possible to use a third party hosted websocket server, for example <a href="http://pusher.com/" rel="noreferrer">Pusher</a> or <a href="http://www.leggetter.co.uk/real-time-web-technologies-guide" rel="noreferrer">others</a>. This way you'll only have to implement the client side, which is very easy!</li> <li>If you want to read more, I found these very useful: (<a href="http://www.developerfusion.com/article/143158/an-introduction-to-websockets/" rel="noreferrer">article</a>), <a href="https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications" rel="noreferrer">(article)</a> (<a href="http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/" rel="noreferrer">tutorial</a>).</li> </ul></li> </ol> <p><img src="https://i.stack.imgur.com/CgDlc.png" alt="HTML5 WebSockets"></p> <h2>Comet:</h2> <p>Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on <a href="http://en.wikipedia.org/wiki/Comet_%28programming%29" rel="noreferrer">wikipedia</a> or <a href="http://www.ibm.com/developerworks/web/library/wa-reverseajax1/index.html" rel="noreferrer">this</a> article.</p> <hr> <blockquote> <p>Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?</p> </blockquote> <p>You can use PHP with WebSockets, check out <a href="http://socketo.me/" rel="noreferrer">Ratchet</a>. </p>
{ "question_id": 11077857, "question_date": "2012-06-18T06:28:08.643Z", "question_score": 1155, "tags": "php|websocket|comet|long-polling|server-sent-events", "answer_id": 12855533, "answer_date": "2012-10-12T08:57:44.533Z", "answer_score": 2239 }
Please answer the following Stack Overflow question: Title: Selecting element by data attribute with jQuery <p>Is there an easy and straight-forward method to select elements based on their <code>data</code> attribute? For example, select all anchors that has data attribute named <code>customerID</code> which has value of <code>22</code>. </p> <p>I am kind of hesitant to use <code>rel</code> or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.</p>
<pre><code>$('*[data-customerID="22"]'); </code></pre> <p>You should be able to omit the <code>*</code>, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.</p> <p>Note that for compatibility with the Selectors API (<code>document.querySelector{,all}</code>), the quotes around the attribute value (<code>22</code>) <a href="http://mothereff.in/unquoted-attributes#22" rel="noreferrer">may not be omitted in this case</a>.</p> <p>Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the <a href="http://github.com/mathiasbynens/HTML5-custom-data-attributes-plugin-for-jQuery" rel="noreferrer">HTML5 custom data attributes plugin</a>. This allows you to write even more readable code by using <code>.dataAttr('foo')</code>, and results in a smaller file size after minification (compared to using <code>.attr('data-foo')</code>).</p>
{ "question_id": 2487747, "question_date": "2010-03-21T16:13:15.993Z", "question_score": 1154, "tags": "jquery|html|custom-data-attribute", "answer_id": 2487751, "answer_date": "2010-03-21T16:14:45.657Z", "answer_score": 1631 }
Please answer the following Stack Overflow question: Title: Fling gesture detection on grid layout <p>I want to get <code>fling</code> gesture detection working in my Android application.</p> <p>What I have is a <code>GridLayout</code> that contains 9 <code>ImageView</code>s. The source can be found here: <a href="https://github.com/selmanon/apps-for-android/blob/master/Photostream/src/com/google/android/photostream/GridLayout.java" rel="noreferrer">Romain Guys's Grid Layout</a>.</p> <p>That file I take is from Romain Guy's <a href="http://code.google.com/p/apps-for-android/" rel="noreferrer">Photostream application</a> and has only been slightly adapted.</p> <p>For the simple click situation I need only set the <code>onClickListener</code> for each <code>ImageView</code> I add to be the main <code>activity</code> which implements <code>View.OnClickListener</code>. It seems infinitely more complicated to implement something that recognizes a <code>fling</code>. I presume this is because it may span <code>views</code>?</p> <ul> <li><p>If my activity implements <code>OnGestureListener</code> I don't know how to set that as the gesture listener for the <code>Grid</code> or the <code>Image</code> views that I add.</p> <pre><code>public class SelectFilterActivity extends Activity implements View.OnClickListener, OnGestureListener { ... </code></pre></li> <li><p>If my activity implements <code>OnTouchListener</code> then I have no <code>onFling</code> method to <code>override</code> (it has two events as parameters allowing me to determine if the fling was noteworthy).</p> <pre><code>public class SelectFilterActivity extends Activity implements View.OnClickListener, OnTouchListener { ... </code></pre></li> <li><p>If I make a custom <code>View</code>, like <code>GestureImageView</code> that extends <code>ImageView</code> I don't know how to tell the activity that a <code>fling</code> has occurred from the view. In any case, I tried this and the methods weren't called when I touched the screen.</p></li> </ul> <p>I really just need a concrete example of this working across views. What, when and how should I attach this <code>listener</code>? I need to be able to detect single clicks also.</p> <pre><code>// Gesture detection mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { int dx = (int) (e2.getX() - e1.getX()); // don't accept the fling if it's too short // as it may conflict with a button push if (Math.abs(dx) &gt; MAJOR_MOVE &amp;&amp; Math.abs(velocityX) &gt; Math.absvelocityY)) { if (velocityX &gt; 0) { moveRight(); } else { moveLeft(); } return true; } else { return false; } } }); </code></pre> <p>Is it possible to lay a transparent view over the top of my screen to capture flings?</p> <p>If I choose not to <code>inflate</code> my child image views from XML can I pass the <code>GestureDetector</code> as a constructor parameter to a new subclass of <code>ImageView</code> that I create?</p> <p>This is the very simple activity that I'm trying to get the <code>fling</code> detection to work for: <a href="http://code.google.com/p/miffed/source/browse/GUI/src/uk/ac/ic/doc/gea05/miffed/gui/SelectFilterActivity.java?r=210" rel="noreferrer">SelectFilterActivity (Adapted from photostream)</a>.</p> <p>I've been looking at these sources:</p> <ul> <li><p><a href="http://www.anddev.org/gesturedetector_and_gesturedetectorongesturelistener-t3204.html" rel="noreferrer">Detect Gestures - Tutorial</a></p></li> <li><p><a href="http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html" rel="noreferrer">SDK docs</a></p></li> <li><p><a href="http://www.google.co.in/codesearch/p?hl=en#RzGvLIykRFs/src/com/android/calculator2/PanelSwitcher.java&amp;q=android%20package:git://android.git.kernel.org%20Calculator2" rel="noreferrer">Calculator Code</a></p></li> </ul> <p>Nothing has worked for me so far and I was hoping for some pointers.</p>
<p>Thanks to <a href="https://web.archive.org/web/20090503094429/http://www.codeshogun.com/blog/2009/04/16/how-to-implement-swipe-action-in-android/" rel="noreferrer">Code Shogun</a>, whose code I adapted to my situation.</p> <p>Let your activity implement<code>OnClickListener</code> as usual:</p> <pre><code>public class SelectFilterActivity extends Activity implements OnClickListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* ... */ // Gesture detection gestureDetector = new GestureDetector(this, new MyGestureDetector()); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }; } class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) &gt; SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(SelectFilterActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); } else if (e2.getX() - e1.getX() &gt; SWIPE_MIN_DISTANCE &amp;&amp; Math.abs(velocityX) &gt; SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(SelectFilterActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // nothing } return false; } @Override public boolean onDown(MotionEvent e) { return true; } } } </code></pre> <p>Attach your gesture listener to all the views you add to the main layout;</p> <pre><code>// Do this for each view added to the grid imageView.setOnClickListener(SelectFilterActivity.this); imageView.setOnTouchListener(gestureListener); </code></pre> <p>Watch in awe as your overridden methods are hit, both the <code>onClick(View v)</code> of the activity and the <code>onFling</code> of the gesture listener.</p> <pre><code>public void onClick(View v) { Filter f = (Filter) v.getTag(); FilterFullscreenActivity.show(this, input, f); } </code></pre> <p>The post 'fling' dance is optional but encouraged. </p>
{ "question_id": 937313, "question_date": "2009-06-01T23:35:31.800Z", "question_score": 1154, "tags": "android|listener|gesture-recognition", "answer_id": 938657, "answer_date": "2009-06-02T09:30:55.207Z", "answer_score": 840 }
Please answer the following Stack Overflow question: Title: Defining a variable with or without export <p>What is <code>export</code> for?</p> <p>What is the difference between:</p> <pre><code>export name=value </code></pre> <p>and</p> <pre><code>name=value </code></pre>
<p><code>export</code> makes the variable available to sub-processes.</p> <p>That is,</p> <pre><code>export name=value </code></pre> <p>means that the variable name is available to <em>any process</em> you run from that shell process. If you want a process to make use of this variable, use <code>export</code>, and run the process from that shell.</p> <pre><code>name=value </code></pre> <p>means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.</p> <p>It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.</p>
{ "question_id": 1158091, "question_date": "2009-07-21T09:09:57.080Z", "question_score": 1153, "tags": "linux|bash|shell", "answer_id": 1158231, "answer_date": "2009-07-21T09:45:52.530Z", "answer_score": 1264 }
Please answer the following Stack Overflow question: Title: How to create a checkbox with a clickable label? <p>How can I create an HTML checkbox with a label that is clickable (this means that clicking on the label turns the checkbox on/off)?</p>
<h2>Method 1: Wrap Label Tag</h2> <p>Wrap the checkbox within a <code>label</code> tag:</p> <pre><code>&lt;label&gt;&lt;input type=&quot;checkbox&quot; name=&quot;checkbox&quot; value=&quot;value&quot;&gt;Text&lt;/label&gt; </code></pre> <h2>Method 2: Use the <code>for</code> Attribute</h2> <p>Use the <code>for</code> attribute (match the checkbox <code>id</code>):</p> <pre><code>&lt;input type=&quot;checkbox&quot; name=&quot;checkbox&quot; id=&quot;checkbox_id&quot; value=&quot;value&quot;&gt; &lt;label for=&quot;checkbox_id&quot;&gt;Text&lt;/label&gt; </code></pre> <p><strong>NOTE</strong>: ID must be unique on the page!</p> <h2>Explanation</h2> <p>Since the other answers don't mention it, a label can include up to 1 input and omit the <code>for</code> attribute, and it will be assumed that it is for the input within it.</p> <p>Excerpt from <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1" rel="noreferrer">w3.org</a> (with my emphasis):</p> <blockquote> <p>[The for attribute] explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. <strong>When absent, the label being defined is associated with the element's contents.</strong></p> <p>To associate a label with another control implicitly, <strong>the control element must be within the contents of the LABEL element</strong>. In this case, the LABEL may only contain <strong>one</strong> control element. The label itself may be positioned before or after the associated control.</p> </blockquote> <p>Using this method has some advantages over <code>for</code>:</p> <ul> <li><p>No need to assign an <code>id</code> to every checkbox (great!).</p> </li> <li><p>No need to use the extra attribute in the <code>&lt;label&gt;</code>.</p> </li> <li><p>The input's clickable area is also the label's clickable area, so there aren't two separate places to click that can control the checkbox - only one, no matter how far apart the <code>&lt;input&gt;</code> and actual label text are, and no matter what kind of CSS you apply to it.</p> </li> </ul> <p>Demo with some CSS:</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>label { border:1px solid #ccc; padding:10px; margin:0 0 10px; display:block; } label:hover { background:#eee; cursor:pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label&gt;&lt;input type="checkbox" /&gt;Option 1&lt;/label&gt; &lt;label&gt;&lt;input type="checkbox" /&gt;Option 2&lt;/label&gt; &lt;label&gt;&lt;input type="checkbox" /&gt;Option 3&lt;/label&gt;</code></pre> </div> </div> </p>
{ "question_id": 6293588, "question_date": "2011-06-09T13:33:46.463Z", "question_score": 1152, "tags": "html|checkbox|click|label", "answer_id": 6293626, "answer_date": "2011-06-09T13:36:01.493Z", "answer_score": 2133 }
Please answer the following Stack Overflow question: Title: git undo all uncommitted or unsaved changes <p>I'm trying to undo all changes since my last commit. I tried <code>git reset --hard</code> and <code>git reset --hard HEAD</code> after viewing <a href="https://stackoverflow.com/questions/7999259/git-how-to-perform-the-tfs-equivalent-of-undo-pending-changes">this post</a>. I responds with head is now at 18c3773... but when I look at my local source all the files are still there. What am I missing?</p>
<ul> <li><p>This will unstage all files you might have staged with <code>git add</code>:</p> <pre><code>git reset </code></pre></li> <li><p>This will revert all local uncommitted changes (should be executed in repo root):</p> <pre><code>git checkout . </code></pre> <p>You can also revert uncommitted changes only to particular file or directory:</p> <pre><code>git checkout [some_dir|file.txt] </code></pre> <p>Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):</p> <pre><code>git reset --hard HEAD </code></pre></li> <li><p>This will remove all local untracked files, so <em>only</em> git tracked files remain:</p> <pre><code>git clean -fdx </code></pre> <blockquote> <p><strong>WARNING:</strong> <code>-x</code> will also remove all ignored files, including ones specified by <code>.gitignore</code>! You may want to use <code>-n</code> for preview of files to be deleted.</p> </blockquote></li> </ul> <hr> <p>To sum it up: executing commands below is basically equivalent to fresh <code>git clone</code> from original source (but it does not re-download anything, so is much faster):</p> <pre><code>git reset git checkout . git clean -fdx </code></pre> <p>Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.</p>
{ "question_id": 14075581, "question_date": "2012-12-28T20:46:53.067Z", "question_score": 1151, "tags": "git|command-line|undo|git-reset", "answer_id": 14075772, "answer_date": "2012-12-28T21:04:38.177Z", "answer_score": 2215 }
Please answer the following Stack Overflow question: Title: What is the difference between 'typedef' and 'using' in C++11? <p>I know that in C++11 we can now use <code>using</code> to write type alias, like <code>typedef</code>s:</p> <pre><code>typedef int MyInt; </code></pre> <p>Is, from what I understand, equivalent to:</p> <pre><code>using MyInt = int; </code></pre> <p>And that new syntax emerged from the effort to have a way to express &quot;template typedef&quot;:</p> <pre><code>template&lt; class T &gt; using MyType = AnotherType&lt; T, MyAllocatorType &gt;; </code></pre> <p>But, with the first two non-template examples, are there any other subtle differences in the standard? For example, <code>typedef</code>s do aliasing in a &quot;weak&quot; way. That is it does not create a new type but only a new name (conversions are implicit between those names).</p> <p>Is it the same with <code>using</code> or does it generate a new type? Are there any differences?</p>
<p><sub><em>All standard references below refers to <a href="https://timsong-cpp.github.io/cppwp/n4659/" rel="noreferrer">N4659: March 2017 post-Kona working draft/C++17 DIS</a>.</em></sub></p> <hr /> <h2>Typedef declarations can, whereas alias declarations cannot<sup>(+)</sup>, be used as initialization statements</h2> <blockquote> <p>But, with the first two non-template examples, are there any other subtle differences in the standard?</p> </blockquote> <ul> <li>Differences <strong>in semantics</strong>: none.</li> <li>Differences <strong>in allowed contexts</strong>: some<sup>(++)</sup>.</li> </ul> <p><sup>(+) <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2360r0.html" rel="noreferrer">P2360R0</a> (<em>Extend init-statement to allow alias-declaration</em>) <a href="https://github.com/cplusplus/papers/issues/1034" rel="noreferrer">has been approved by CWG</a> and as of C++23, this inconsistency between typedef declarations and alias declarations will have been removed.</sup> <br> <sup>(++) In addition to the examples of <em>alias templates</em>, which has already been mentioned in the original post.</sup></p> <h3>Same semantics</h3> <p>As governed by <a href="https://timsong-cpp.github.io/cppwp/n4659/dcl.typedef#2" rel="noreferrer">[dcl.typedef]/2</a> [extract, <strong>emphasis</strong> mine]</p> <blockquote> <p><strong>[dcl.typedef]/2</strong> A <a href="https://timsong-cpp.github.io/cppwp/n4659/dcl.typedef#nt:typedef-name" rel="noreferrer"><em>typedef-name</em></a> can also be introduced by an <a href="https://timsong-cpp.github.io/cppwp/n4659/dcl.dcl#nt:alias-declaration" rel="noreferrer"><em>alias-declaration</em></a>. The <em>identifier</em> following the <code>using</code> keyword becomes a <em>typedef-name</em> and the optional <em>attribute-specifier-seq</em> following the <em>identifier</em> appertains to that <em>typedef-name</em>. <strong>Such a <em>typedef-name</em> has the same semantics as if it were introduced by the <code>typedef</code> specifier.</strong> [...]</p> </blockquote> <p>a <em>typedef-name</em> introduced by an <em>alias-declaration</em> has <strong>the same semantics</strong> as if it were introduced by the <code>typedef</code> declaration.</p> <h3>Subtle difference in allowed contexts</h3> <p>However, this does <strong>not</strong> imply that the two variations have the same restrictions with regard to <strong>the contexts</strong> in which they may be used. And indeed, albeit a corner case, a <a href="https://timsong-cpp.github.io/cppwp/n4659/dcl.typedef#1" rel="noreferrer"><em>typedef declaration</em></a> is an <a href="https://timsong-cpp.github.io/cppwp/n4659/gram.stmt" rel="noreferrer"><em>init-statement</em></a> and may thus be used in contexts which allow initialization statements</p> <pre><code>// C++11 (C++03) (init. statement in for loop iteration statements). for (typedef int Foo; Foo{} != 0;) // ^^^^^^^^^^^^^^^ init-statement { } // C++17 (if and switch initialization statements). if (typedef int Foo; true) // ^^^^^^^^^^^^^^^ init-statement { (void)Foo{}; } switch (typedef int Foo; 0) // ^^^^^^^^^^^^^^^ init-statement { case 0: (void)Foo{}; } // C++20 (range-based for loop initialization statements). std::vector&lt;int&gt; v{1, 2, 3}; for (typedef int Foo; Foo f : v) // ^^^^^^^^^^^^^^^ init-statement { (void)f; } for (typedef struct { int x; int y;} P; auto [x, y] : {P{1, 1}, {1, 2}, {3, 5}}) // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ init-statement { (void)x; (void)y; } </code></pre> <p>whereas an <a href="https://timsong-cpp.github.io/cppwp/n4659/dcl.dcl#nt:alias-declaration" rel="noreferrer"><em>alias-declaration</em></a> is <strong>not</strong> an <em>init-statement</em>, and thus <strong>may not</strong> be used in contexts which allows initialization statements</p> <pre><code>// C++ 11. for (using Foo = int; Foo{} != 0;) {} // ^^^^^^^^^^^^^^^ error: expected expression // C++17 (initialization expressions in switch and if statements). if (using Foo = int; true) { (void)Foo{}; } // ^^^^^^^^^^^^^^^ error: expected expression switch (using Foo = int; 0) { case 0: (void)Foo{}; } // ^^^^^^^^^^^^^^^ error: expected expression // C++20 (range-based for loop initialization statements). std::vector&lt;int&gt; v{1, 2, 3}; for (using Foo = int; Foo f : v) { (void)f; } // ^^^^^^^^^^^^^^^ error: expected expression </code></pre>
{ "question_id": 10747810, "question_date": "2012-05-25T02:39:51.960Z", "question_score": 1151, "tags": "c++|c++11|typedef|using-declaration", "answer_id": 62196340, "answer_date": "2020-06-04T13:50:18.650Z", "answer_score": 134 }
Please answer the following Stack Overflow question: Title: How do I get the value of text input field using JavaScript? <p>I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:</p> <pre class="lang-html prettyprint-override"><code>&lt;input name=&quot;searchTxt&quot; type=&quot;text&quot; maxlength=&quot;512&quot; id=&quot;searchTxt&quot; class=&quot;searchField&quot;/&gt; </code></pre> <p>And this is my JavaScript code:</p> <pre class="lang-js prettyprint-override"><code>&lt;script type=&quot;text/javascript&quot;&gt; function searchURL(){ window.location = &quot;http://www.myurl.com/search/&quot; + (input text value); } &lt;/script&gt; </code></pre> <p>How do I get the value from the text field into JavaScript?</p>
<p>There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):</p> <h2>Method 1</h2> <p><code>document.getElementById('textbox_id').value</code> to get the value of desired box</p> <h3>For example</h3> <p><code>document.getElementById(&quot;searchTxt&quot;).value;</code></p> <p>  <strong>Note:</strong> Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use <code>[0]</code>, for the second one use <code>[1]</code>, and so on...</p> <h2>Method 2</h2> <p>Use <code>document.getElementsByClassName('class_name')[whole_number].value</code> which returns a Live HTMLCollection</p> <h3>For example</h3> <p><code>document.getElementsByClassName(&quot;searchField&quot;)[0].value;</code> if this is the first textbox in your page.</p> <h2>Method 3</h2> <p>Use <code>document.getElementsByTagName('tag_name')[whole_number].value</code> which also returns a live HTMLCollection</p> <h3>For example</h3> <p><code>document.getElementsByTagName(&quot;input&quot;)[0].value;</code>, if this is the first textbox in your page.</p> <h2>Method 4</h2> <p><code>document.getElementsByName('name')[whole_number].value</code> which also &gt;returns a live NodeList</p> <h3>For example</h3> <p><code>document.getElementsByName(&quot;searchTxt&quot;)[0].value;</code> if this is the first textbox with name 'searchtext' in your page.</p> <h2>Method 5</h2> <p>Use the powerful <code>document.querySelector('selector').value</code> which uses a CSS selector to select the element</p> <h3>For example</h3> <ul> <li><code>document.querySelector('#searchTxt').value;</code> selected by id</li> <li><code>document.querySelector('.searchField').value;</code> selected by class</li> <li><code>document.querySelector('input').value;</code> selected by tagname</li> <li><code>document.querySelector('[name=&quot;searchTxt&quot;]').value;</code> selected by name</li> </ul> <h2>Method 6</h2> <p><code>document.querySelectorAll('selector')[whole_number].value</code> which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.</p> <h3>For example</h3> <ul> <li><code>document.querySelectorAll('#searchTxt')[0].value;</code> selected by id</li> <li><code>document.querySelectorAll('.searchField')[0].value;</code> selected by class</li> <li><code>document.querySelectorAll('input')[0].value;</code> selected by tagname</li> <li><code>document.querySelectorAll('[name=&quot;searchTxt&quot;]')[0].value;</code> selected by name</li> </ul> <p>Support</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Browser</th> <th>Method1</th> <th>Method2</th> <th>Method3</th> <th>Method4</th> <th>Method5/6</th> </tr> </thead> <tbody> <tr> <td>IE6</td> <td>Y(Buggy)</td> <td>N</td> <td>Y</td> <td>Y(Buggy)</td> <td>N</td> </tr> <tr> <td>IE7</td> <td>Y(Buggy)</td> <td>N</td> <td>Y</td> <td>Y(Buggy)</td> <td>N</td> </tr> <tr> <td>IE8</td> <td>Y</td> <td>N</td> <td>Y</td> <td>Y(Buggy)</td> <td>Y</td> </tr> <tr> <td>IE9</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y(Buggy)</td> <td>Y</td> </tr> <tr> <td>IE10</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <td>FF3.0</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>N IE=Internet Explorer</td> </tr> <tr> <td>FF3.5/FF3.6</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y FF=Mozilla Firefox</td> </tr> <tr> <td>FF4b1</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y GC=Google Chrome</td> </tr> <tr> <td>GC4/GC5</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y Y=YES,N=NO</td> </tr> <tr> <td>Safari4/Safari5</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> <tr> <td>Opera10.10/</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Opera10.53/</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y(Buggy)</td> <td>Y</td> </tr> <tr> <td>Opera10.60</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>Opera 12</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> <td>Y</td> </tr> </tbody> </table> </div> <p><strong>Useful links</strong></p> <ol> <li><a href="http://www.quirksmode.org/dom/w3c_core.html" rel="noreferrer"><strong>To see the support of these methods with all the bugs including more details click here</strong></a></li> <li><a href="http://www.nczonline.net/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/" rel="noreferrer"><strong>Difference Between Static collections and Live collections click Here</strong></a></li> <li><a href="http://xahlee.info/js/js_array_vs_nodelist_vs_html_collection.html" rel="noreferrer"><strong>Difference Between NodeList and HTMLCollection click Here</strong></a></li> </ol>
{ "question_id": 11563638, "question_date": "2012-07-19T15:00:28.073Z", "question_score": 1150, "tags": "javascript|dom|html-input", "answer_id": 11563667, "answer_date": "2012-07-19T15:02:14.223Z", "answer_score": 2198 }
Please answer the following Stack Overflow question: Title: How do I expire a PHP session after 30 minutes? <p>I need to keep a session alive for 30 minutes and then destroy it. </p>
<p>You should implement a session timeout of your own. Both options mentioned by others (<a href="http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime" rel="noreferrer"><em>session.gc_maxlifetime</em></a> and <a href="http://php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime" rel="noreferrer"><em>session.cookie_lifetime</em></a>) are not reliable. I'll explain the reasons for that.</p> <p><strong>First:</strong></p> <blockquote> <p><strong>session.gc_maxlifetime</strong><br> <em>session.gc_maxlifetime</em> specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.</p> </blockquote> <p>But the garbage collector is only started with a probability of <a href="http://php.net/manual/en/session.configuration.php#ini.session.gc-probability" rel="noreferrer"><em>session.gc_probability</em></a> divided by <a href="http://php.net/manual/en/session.configuration.php#ini.session.gc-divisor" rel="noreferrer"><em>session.gc_divisor</em></a>. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.</p> <p>Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.</p> <p>Furthermore, when using PHP's default <a href="http://php.net/manual/en/session.configuration.php#ini.session.save-handler" rel="noreferrer"><em>session.save_handler</em></a> files, the session data is stored in files in a path specified in <a href="http://php.net/manual/en/session.configuration.php#ini.session.save-path" rel="noreferrer"><em>session.save_path</em></a>. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:</p> <blockquote> <p><strong>Note:</strong> If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.</p> </blockquote> <p>So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.</p> <p><strong>And second:</strong></p> <blockquote> <p><strong>session.cookie_lifetime</strong><br> <em>session.cookie_lifetime</em> specifies the lifetime of the cookie in seconds which is sent to the browser. […]</p> </blockquote> <p>Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having <em>session.cookie_lifetime</em> set to <code>0</code> would make the session’s cookie a real <a href="http://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie" rel="noreferrer">session cookie</a> that is only valid until the browser is closed.</p> <p><strong>Conclusion / best solution:</strong></p> <p>The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:</p> <pre><code>if (isset($_SESSION['LAST_ACTIVITY']) &amp;&amp; (time() - $_SESSION['LAST_ACTIVITY'] &gt; 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage } $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp </code></pre> <p>Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.</p> <p>You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like <a href="http://www.owasp.org/index.php/Session_fixation" rel="noreferrer">session fixation</a>:</p> <pre><code>if (!isset($_SESSION['CREATED'])) { $_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] &gt; 1800) { // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time } </code></pre> <p><strong>Notes:</strong></p> <ul> <li><code>session.gc_maxlifetime</code> should be at least equal to the lifetime of this custom expiration handler (1800 in this example);</li> <li>if you want to expire the session after 30 minutes of <em>activity</em> instead of after 30 minutes <em>since start</em>, you'll also need to use <code>setcookie</code> with an expire of <code>time()+60*30</code> to keep the session cookie active.</li> </ul>
{ "question_id": 520237, "question_date": "2009-02-06T13:14:14.497Z", "question_score": 1150, "tags": "php|session|cookies", "answer_id": 1270960, "answer_date": "2009-08-13T09:24:39.330Z", "answer_score": 1759 }
Please answer the following Stack Overflow question: Title: Get the data received in a Flask request <p>I want to be able to get the data sent to my Flask app. I've tried accessing <code>request.data</code> but it is an empty string. How do you access request data?</p> <pre class="lang-py prettyprint-override"><code>from flask import request @app.route('/', methods=['GET', 'POST']) def parse_request(): data = request.data # data is empty # need posted data here </code></pre> <hr> <p>The answer to this question led me to ask <a href="https://stackoverflow.com/q/10999990">Get raw POST body in Python Flask regardless of Content-Type header</a> next, which is about getting the raw data rather than the parsed data.</p>
<p>The <a href="https://flask.palletsprojects.com/api/#flask.Request" rel="noreferrer">docs</a> describe the attributes available on the <code>request</code> object (<code>from flask import request</code>) during a request. In most common cases <code>request.data</code> will be empty because it's used as a fallback:</p> <blockquote> <p><code>request.data</code> Contains the incoming request data as string in case it came with a mimetype Flask does not handle.</p> </blockquote> <ul> <li><a href="https://flask.palletsprojects.com/api/#flask.Request.args" rel="noreferrer"><code>request.args</code></a>: the key/value pairs in the URL query string</li> <li><a href="https://flask.palletsprojects.com/api/#flask.Request.form" rel="noreferrer"><code>request.form</code></a>: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded</li> <li><a href="https://flask.palletsprojects.com/api/#flask.Request.files" rel="noreferrer"><code>request.files</code></a>: the files in the body, which Flask keeps separate from <code>form</code>. HTML forms must use <code>enctype=multipart/form-data</code> or files will not be uploaded.</li> <li><a href="https://flask.palletsprojects.com/api/#flask.Request.values" rel="noreferrer"><code>request.values</code></a>: combined <code>args</code> and <code>form</code>, preferring <code>args</code> if keys overlap</li> <li><a href="https://flask.palletsprojects.com/api/#flask.Request.json" rel="noreferrer"><code>request.json</code></a>: parsed JSON data. The request must have the <code>application/json</code> content type, or use <a href="https://flask.palletsprojects.com/api/#flask.Request.get_json" rel="noreferrer"><code>request.get_json(force=True)</code></a> to ignore the content type.</li> </ul> <p>All of these are <a href="https://werkzeug.palletsprojects.com/datastructures/#werkzeug.datastructures.MultiDict" rel="noreferrer"><code>MultiDict</code></a> instances (except for <code>json</code>). You can access values using:</p> <ul> <li><code>request.form['name']</code>: use indexing if you know the key exists</li> <li><code>request.form.get('name')</code>: use <code>get</code> if the key might not exist</li> <li><code>request.form.getlist('name')</code>: use <code>getlist</code> if the key is sent multiple times and you want a list of values. <code>get</code> only returns the first value.</li> </ul>
{ "question_id": 10434599, "question_date": "2012-05-03T15:31:26.760Z", "question_score": 1149, "tags": "python|flask|werkzeug", "answer_id": 16664376, "answer_date": "2013-05-21T07:25:07.400Z", "answer_score": 2013 }
Please answer the following Stack Overflow question: Title: Get difference between two lists <p>I have two lists in Python:</p> <pre><code>temp1 = ['One', 'Two', 'Three', 'Four'] temp2 = ['One', 'Two'] </code></pre> <p>I want to create a third list with items from the first list which aren't in the second list:</p> <pre><code>temp3 = ['Three', 'Four'] </code></pre> <p>Are there any fast ways without cycles and checking?</p>
<p>To get elements which are in <code>temp1</code> but not in <code>temp2</code> :</p> <pre><code>In [5]: list(set(temp1) - set(temp2)) Out[5]: ['Four', 'Three'] </code></pre> <p>Beware that it is asymmetric :</p> <pre><code>In [5]: set([1, 2]) - set([2, 3]) Out[5]: set([1]) </code></pre> <p>where you might expect/want it to equal <code>set([1, 3])</code>. If you do want <code>set([1, 3])</code> as your answer, you can use <code>set([1, 2]).symmetric_difference(set([2, 3]))</code>.</p>
{ "question_id": 3462143, "question_date": "2010-08-11T19:38:10.443Z", "question_score": 1149, "tags": "python|performance|list|set|set-difference", "answer_id": 3462160, "answer_date": "2010-08-11T19:40:00.620Z", "answer_score": 1671 }
Please answer the following Stack Overflow question: Title: How to replace innerHTML of a div using jQuery? <p>How could I achieve the following:</p> <pre><code>document.all.regTitle.innerHTML = 'Hello World'; </code></pre> <p>Using jQuery where <code>regTitle</code> is my <code>div</code> id?</p>
<pre><code>$("#regTitle").html("Hello World"); </code></pre>
{ "question_id": 1309452, "question_date": "2009-08-20T23:51:36.783Z", "question_score": 1148, "tags": "javascript|jquery|innerhtml", "answer_id": 1309454, "answer_date": "2009-08-20T23:52:40.197Z", "answer_score": 1742 }
Please answer the following Stack Overflow question: Title: What is (functional) reactive programming? <p>I've read the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Reactive_programming" rel="noreferrer">reactive programming</a>. I've also read the small article on <a href="http://en.wikipedia.org/wiki/Functional_reactive_programming" rel="noreferrer">functional reactive programming</a>. The descriptions are quite abstract.</p> <ol> <li>What does functional reactive programming (FRP) mean in practice? </li> <li>What does reactive programming (as opposed to non-reactive programming?) consist of? </li> </ol> <p>My background is in imperative/OO languages, so an explanation that relates to this paradigm would be appreciated.</p>
<p>If you want to get a feel for FRP, you could start with the old <a href="http://conal.net/fran/tutorial.htm" rel="noreferrer">Fran tutorial</a> from 1998, which has animated illustrations. For papers, start with <a href="http://conal.net/papers/icfp97/" rel="noreferrer"><em>Functional Reactive Animation</em></a> and then follow up on links on the publications link on my home page and the <a href="http://haskell.org/haskellwiki/FRP" rel="noreferrer">FRP</a> link on the <a href="http://haskell.org/haskellwiki/Haskell" rel="noreferrer">Haskell wiki</a>.</p> <p>Personally, I like to think about what FRP <em>means</em> before addressing how it might be implemented. (Code without a specification is an answer without a question and thus "not even wrong".) So I don't describe FRP in representation/implementation terms as Thomas K does in another answer (graphs, nodes, edges, firing, execution, etc). There are many possible implementation styles, but no implementation says what FRP <em>is</em>.</p> <p>I do resonate with Laurence G's simple description that FRP is about "datatypes that represent a value 'over time' ". Conventional imperative programming captures these dynamic values only indirectly, through state and mutations. The complete history (past, present, future) has no first class representation. Moreover, only <em>discretely evolving</em> values can be (indirectly) captured, since the imperative paradigm is temporally discrete. In contrast, FRP captures these evolving values <em>directly</em> and has no difficulty with <em>continuously</em> evolving values.</p> <p>FRP is also unusual in that it is concurrent without running afoul of the theoretical &amp; pragmatic rats' nest that plagues imperative concurrency. Semantically, FRP's concurrency is <em>fine-grained</em>, <em>determinate</em>, and <em>continuous</em>. (I'm talking about meaning, not implementation. An implementation may or may not involve concurrency or parallelism.) Semantic determinacy is very important for reasoning, both rigorous and informal. While concurrency adds enormous complexity to imperative programming (due to nondeterministic interleaving), it is effortless in FRP.</p> <p>So, what is FRP? You could have invented it yourself. Start with these ideas:</p> <ul> <li><p>Dynamic/evolving values (i.e., values "over time") are first class values in themselves. You can define them and combine them, pass them into &amp; out of functions. I called these things "behaviors".</p></li> <li><p>Behaviors are built up out of a few primitives, like constant (static) behaviors and time (like a clock), and then with sequential and parallel combination. <em>n</em> behaviors are combined by applying an n-ary function (on static values), "point-wise", i.e., continuously over time.</p></li> <li><p>To account for discrete phenomena, have another type (family) of "events", each of which has a stream (finite or infinite) of occurrences. Each occurrence has an associated time and value.</p></li> <li><p>To come up with the compositional vocabulary out of which all behaviors and events can be built, play with some examples. Keep deconstructing into pieces that are more general/simple.</p></li> <li><p>So that you know you're on solid ground, give the whole model a compositional foundation, using the technique of denotational semantics, which just means that (a) each type has a corresponding simple &amp; precise mathematical type of "meanings", and (b) each primitive and operator has a simple &amp; precise meaning as a function of the meanings of the constituents. <em>Never, ever</em> mix implementation considerations into your exploration process. If this description is gibberish to you, consult (a) <em><a href="http://conal.net/papers/type-class-morphisms" rel="noreferrer">Denotational design with type class morphisms</a></em>, (b) <em><a href="http://conal.net/papers/push-pull-frp" rel="noreferrer">Push-pull functional reactive programming</a></em> (ignoring the implementation bits), and (c) the <a href="http://en.wikibooks.org/wiki/Haskell/Denotational_semantics" rel="noreferrer"><em>Denotational Semantics</em> Haskell wikibooks page</a>. Beware that denotational semantics has two parts, from its two founders Christopher Strachey and Dana Scott: the easier &amp; more useful Strachey part and the harder and less useful (for software design) Scott part.</p></li> </ul> <p>If you stick with these principles, I expect you'll get something more-or-less in the spirit of FRP.</p> <p>Where did I get these principles? In software design, I always ask the same question: "what does it mean?". Denotational semantics gave me a precise framework for this question, and one that fits my aesthetics (unlike operational or axiomatic semantics, both of which leave me unsatisfied). So I asked myself what is behavior? I soon realized that the temporally discrete nature of imperative computation is an accommodation to a particular style of <em>machine</em>, rather than a natural description of behavior itself. The simplest precise description of behavior I can think of is simply "function of (continuous) time", so that's my model. Delightfully, this model handles continuous, deterministic concurrency with ease and grace.</p> <p>It's been quite a challenge to implement this model correctly and efficiently, but that's another story.</p>
{ "question_id": 1028250, "question_date": "2009-06-22T16:41:19.247Z", "question_score": 1147, "tags": "functional-programming|terminology|reactive-programming|frp", "answer_id": 1030631, "answer_date": "2009-06-23T04:31:42.980Z", "answer_score": 930 }
Please answer the following Stack Overflow question: Title: Android "Only the original thread that created a view hierarchy can touch its views." <p>I've built a simple music player in Android. The view for each song contains a SeekBar, implemented like this: </p> <pre><code>public class Song extends Activity implements OnClickListener,Runnable { private SeekBar progress; private MediaPlayer mp; // ... private ServiceConnection onService = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder rawBinder) { appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer progress.setVisibility(SeekBar.VISIBLE); progress.setProgress(0); mp = appService.getMP(); appService.playSong(title); progress.setMax(mp.getDuration()); new Thread(Song.this).start(); } public void onServiceDisconnected(ComponentName classname) { appService = null; } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.song); // ... progress = (SeekBar) findViewById(R.id.progress); // ... } public void run() { int pos = 0; int total = mp.getDuration(); while (mp != null &amp;&amp; pos&lt;total) { try { Thread.sleep(1000); pos = appService.getSongPosition(); } catch (InterruptedException e) { return; } catch (Exception e) { return; } progress.setProgress(pos); } } </code></pre> <p>This works fine. Now I want a timer counting the seconds/minutes of the progress of the song. So I put a <code>TextView</code> in the layout, get it with <code>findViewById()</code> in <code>onCreate()</code>, and put this in <code>run()</code> after <code>progress.setProgress(pos)</code>:</p> <pre><code>String time = String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(pos), TimeUnit.MILLISECONDS.toSeconds(pos), TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes( pos)) ); currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time); </code></pre> <p>But that last line gives me the exception:</p> <blockquote> <p>android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.</p> </blockquote> <p>Yet I'm doing basically the same thing here as I'm doing with the <code>SeekBar</code> - creating the view in <code>onCreate</code>, then touching it in <code>run()</code> - and it doesn't give me this complaint.</p>
<p>You have to move the portion of the background task that updates the UI onto the main thread. There is a simple piece of code for this:</p> <pre><code>runOnUiThread(new Runnable() { @Override public void run() { // Stuff that updates the UI } }); </code></pre> <p>Documentation for <a href="http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)" rel="noreferrer"><code>Activity.runOnUiThread</code></a>.</p> <p>Just nest this inside the method that is running in the background, and then copy paste the code that implements any updates in the middle of the block. Include only the smallest amount of code possible, otherwise you start to defeat the purpose of the background thread.</p>
{ "question_id": 5161951, "question_date": "2011-03-02T00:07:31.160Z", "question_score": 1146, "tags": "android|multithreading", "answer_id": 5162096, "answer_date": "2011-03-02T00:29:05.990Z", "answer_score": 2231 }
Please answer the following Stack Overflow question: Title: What is stdClass in PHP? <p>Please define what <code>stdClass</code> is.</p>
<p><code>stdClass</code> is PHP's generic empty class, kind of like <code>Object</code> in Java or <code>object</code> in Python (<strong>Edit:</strong> but not actually used as universal base class; thanks <em>@Ciaran for</em> <a href="https://stackoverflow.com/a/992654/911182">pointing this out</a>).</p> <p>It is useful for anonymous objects, dynamic properties, etc. </p> <p>An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how <code>json_decode()</code> allows to get an StdClass instance or an associative array. Also but not shown in this example, <code>SoapClient::__soapCall</code> returns an StdClass instance.</p> <pre><code>&lt;?php //Example with StdClass $json = '{ "foo": "bar", "number": 42 }'; $stdInstance = json_decode($json); echo $stdInstance-&gt;foo . PHP_EOL; //"bar" echo $stdInstance-&gt;number . PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'] . PHP_EOL; //"bar" echo $array['number'] . PHP_EOL; //42 </code></pre> <p>See <a href="http://krisjordan.com/dynamic-properties-in-php-with-stdclass" rel="noreferrer">Dynamic Properties in PHP and StdClass</a> for more examples.</p>
{ "question_id": 931407, "question_date": "2009-05-31T05:49:01.493Z", "question_score": 1145, "tags": "php|stdclass", "answer_id": 931419, "answer_date": "2009-05-31T05:55:50.387Z", "answer_score": 846 }
Please answer the following Stack Overflow question: Title: How can I start PostgreSQL server on Mac OS X? <h3>Final update:</h3> <p>I had forgotten to run the <code>initdb</code> command.</p> <hr/> <p>By running this command</p> <pre><code>ps auxwww | grep postgres </code></pre> <p>I see that <code>postgres</code> is not running</p> <pre><code>&gt; ps auxwww | grep postgres remcat 1789 0.0 0.0 2434892 480 s000 R+ 11:28PM 0:00.00 grep postgres </code></pre> <p>This raises the question:</p> <p>How do I start the PostgreSQL server?</p> <p>Update:</p> <pre><code>&gt; pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start server starting sh: /usr/local/var/postgres/server.log: No such file or directory </code></pre> <p>Update 2:</p> <p>The <em>touch</em> was not successful, so I did this instead:</p> <pre><code>&gt; mkdir /usr/local/var/postgres &gt; vi /usr/local/var/postgres/server.log &gt; ls /usr/local/var/postgres/ server.log </code></pre> <p>But when I try to start the Ruby on Rails server, I still see this:</p> <blockquote> <p>Is the server running on host &quot;localhost&quot; and accepting TCP/IP connections on port 5432?</p> </blockquote> <p>Update 3:</p> <pre><code>&gt; pg_ctl -D /usr/local/var/postgres status pg_ctl: no server running </code></pre> <p>Update 4:</p> <p>I found that there <em><strong>wasn't any</strong></em> <em>pg_hba.conf</em> file (only file <em>pg_hba.conf.sample</em>), so I modified the sample and renamed it (to remover the .sample). Here are the contents:</p> <pre><code> # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust </code></pre> <p>But I don't understand this:</p> <pre><code>&gt; pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start server starting &gt; pg_ctl -D /usr/local/var/postgres status pg_ctl: no server running </code></pre> <p>Also:</p> <pre><code>sudo find / -name postgresql.conf find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory </code></pre> <p>Update 5:</p> <pre><code>sudo pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start Password: pg_ctl: cannot be run as root Please log in (using, e.g., &quot;su&quot;) as the (unprivileged) user that will own the server process. </code></pre> <p>Update 6:</p> <p>This seems odd:</p> <pre><code>&gt; egrep 'listen|port' /usr/local/var/postgres/postgresql.conf egrep: /usr/local/var/postgres/postgresql.conf: No such file or directory </code></pre> <p>Though, I did do this:</p> <pre><code>&gt;sudo find / -name &quot;*postgresql.conf*&quot; find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample /usr/share/postgresql/postgresql.conf.sample </code></pre> <p>So I did this:</p> <pre><code>egrep 'listen|port' /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample #listen_addresses = 'localhost' # what IP address(es) to listen on; #port = 5432 # (change requires restart) # supported by the operating system: # %r = remote host and port </code></pre> <p>So I tried this:</p> <pre><code>&gt; cp /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf.sample /usr/local/Cellar/postgresql/9.0.4/share/postgresql/postgresql.conf &gt; cp /usr/share/postgresql/postgresql.conf.sample /usr/share/postgresql/postgresql.conf </code></pre> <p>I am still getting the same &quot;Is the server running?&quot; message.</p>
<p>The <a href="https://brew.sh/" rel="noreferrer">Homebrew</a> package manager includes launchctl plists to start automatically. For more information, run <code>brew info postgres</code>.</p> <h3>Start manually</h3> <p><code>pg_ctl -D /usr/local/var/postgres start</code></p> <h3>Stop manually</h3> <p><code>pg_ctl -D /usr/local/var/postgres stop</code></p> <h3>Start automatically</h3> <p>&quot;To have launchd start postgresql now and restart at login:&quot;</p> <p><code>brew services start postgresql</code></p> <hr /> <p>What is the result of <code>pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start</code>?</p> <p>What is the result of <code>pg_ctl -D /usr/local/var/postgres status</code>?</p> <p>Are there any error messages in the server.log?</p> <p>Make sure tcp localhost connections are enabled in pg_hba.conf:</p> <pre><code># IPv4 local connections: host all all 127.0.0.1/32 trust </code></pre> <p>Check the listen_addresses and port in postgresql.conf:</p> <p><code>egrep 'listen|port' /usr/local/var/postgres/postgresql.conf</code></p> <pre><code>#listen_addresses = 'localhost' # What IP address(es) to listen on; #port = 5432 # (change requires restart) </code></pre> <hr /> <p><strong>Cleaning up</strong></p> <p>PostgreSQL was most likely installed via <a href="https://brew.sh/" rel="noreferrer">Homebrew</a>, <a href="http://www.finkproject.org/" rel="noreferrer">Fink</a>, <a href="http://www.macports.org/" rel="noreferrer">MacPorts</a> or the <a href="http://www.enterprisedb.com/products-services-training/pgdownload#osx" rel="noreferrer">EnterpriseDB</a> installer.</p> <p>Check the output of the following commands to determine which package manager it was installed with:</p> <pre><code>brew &amp;&amp; brew list|grep postgres fink &amp;&amp; fink list|grep postgres port &amp;&amp; port installed|grep postgres </code></pre>
{ "question_id": 7975556, "question_date": "2011-11-02T03:36:43.580Z", "question_score": 1143, "tags": "macos|postgresql|homebrew", "answer_id": 7975660, "answer_date": "2011-11-02T03:55:12.407Z", "answer_score": 2049 }
Please answer the following Stack Overflow question: Title: Global Git ignore <p>I want to set up Git to globally ignore certain files.</p> <p>I have added a <code>.gitignore</code> file to my home directory (<code>/Users/me/</code>) and I have added the following line to it:</p> <pre><code>*.tmproj </code></pre> <p>But it is not ignoring this type of files, any idea what I am doing wrong?</p>
<p>You need to set up your global <code>core.excludesfile</code> configuration file to point to this global ignore file e.g:</p> <p>*<strong>nix or Windows git bash:</strong></p> <pre><code>git config --global core.excludesFile '~/.gitignore' </code></pre> <p><strong>Windows cmd:</strong></p> <pre><code>git config --global core.excludesFile &quot;%USERPROFILE%\.gitignore&quot; </code></pre> <p><strong>Windows PowerShell:</strong></p> <pre><code>git config --global core.excludesFile &quot;$Env:USERPROFILE\.gitignore&quot; </code></pre> <p>For Windows it is set to the location <code>C:\Users\%username%\.gitignore</code>. You can verify that the config value is correct by doing:</p> <pre><code>git config --global core.excludesFile </code></pre> <p>The result should be the expanded path to your user profile's <code>.gitignore</code>. Ensure that the value does not contain the unexpanded <code>%USERPROFILE%</code> string.</p> <p><strong>Important</strong>: The above commands will only set the location of the ignore file that git will use. The file has to still be manually created in that location and populated with the ignore list. (from <a href="https://stackoverflow.com/users/265881/muruge">muruge</a>'s comment)</p> <p>You can read about the command at <a href="https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files#configuring-ignored-files-for-all-repositories-on-your-computer" rel="noreferrer">https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files#configuring-ignored-files-for-all-repositories-on-your-computer</a></p>
{ "question_id": 7335420, "question_date": "2011-09-07T14:16:11.550Z", "question_score": 1143, "tags": "git|global|gitignore", "answer_id": 7335487, "answer_date": "2011-09-07T14:21:09.277Z", "answer_score": 1853 }
Please answer the following Stack Overflow question: Title: How do I pass environment variables to Docker containers? <p>I'm new to Docker, and it's unclear how to access an external database from a container. Is the best way to hard-code in the connection string?</p> <pre><code># Dockerfile ENV DATABASE_URL amazon:rds/connection?string </code></pre>
<p>You can pass environment variables to your containers with the <code>-e</code> flag.</p> <p>An example from a startup script:</p> <pre><code>sudo docker run -d -t -i -e REDIS_NAMESPACE='staging' \ -e POSTGRES_ENV_POSTGRES_PASSWORD='foo' \ -e POSTGRES_ENV_POSTGRES_USER='bar' \ -e POSTGRES_ENV_DB_NAME='mysite_staging' \ -e POSTGRES_PORT_5432_TCP_ADDR='docker-db-1.hidden.us-east-1.rds.amazonaws.com' \ -e SITE_URL='staging.mysite.com' \ -p 80:80 \ --link redis:redis \ --name container_name dockerhub_id/image_name </code></pre> <p>Or, if you don't want to have the value on the command-line where it will be displayed by <code>ps</code>, etc., <code>-e</code> can pull in the value from the current environment if you just give it without the <code>=</code>:</p> <pre><code>sudo PASSWORD='foo' docker run [...] -e PASSWORD [...] </code></pre> <p>If you have many environment variables and especially if they're meant to be secret, you can <a href="https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file">use an env-file</a>:</p> <pre><code>$ docker run --env-file ./env.list ubuntu bash </code></pre> <blockquote> <p>The --env-file flag takes a filename as an argument and expects each line to be in the VAR=VAL format, mimicking the argument passed to --env. Comment lines need only be prefixed with #</p> </blockquote>
{ "question_id": 30494050, "question_date": "2015-05-27T22:17:09.387Z", "question_score": 1141, "tags": "docker|environment-variables|dockerfile", "answer_id": 30494145, "answer_date": "2015-05-27T22:25:07.583Z", "answer_score": 1753 }
Please answer the following Stack Overflow question: Title: How can I represent an 'Enum' in Python? <p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
<p><a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">Enums</a> have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="noreferrer">PEP 435</a>. It has also been <a href="https://pypi.python.org/pypi/enum34" rel="noreferrer">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi.</p> <p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="noreferrer">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you'll need <a href="https://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p> <ul> <li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li> <li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li> </ul> <p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p> <hr /> <pre><code>from enum import Enum # for enum34, or the stdlib version # from aenum import Enum # for the aenum version Animal = Enum('Animal', 'ant bee cat dog') Animal.ant # returns &lt;Animal.ant: 1&gt; Animal['ant'] # returns &lt;Animal.ant: 1&gt; (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) </code></pre> <p>or equivalently:</p> <pre><code>class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 </code></pre> <hr /> <p>In earlier versions, one way of accomplishing enums is:</p> <pre><code>def enum(**enums): return type('Enum', (), enums) </code></pre> <p>which is used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum(ONE=1, TWO=2, THREE='three') &gt;&gt;&gt; Numbers.ONE 1 &gt;&gt;&gt; Numbers.TWO 2 &gt;&gt;&gt; Numbers.THREE 'three' </code></pre> <p>You can also easily support automatic enumeration with something like this:</p> <pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) </code></pre> <p>and used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum('ZERO', 'ONE', 'TWO') &gt;&gt;&gt; Numbers.ZERO 0 &gt;&gt;&gt; Numbers.ONE 1 </code></pre> <p>Support for converting the values back to names can be added this way:</p> <pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) </code></pre> <p>This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a <code>KeyError</code> if the reverse mapping doesn't exist. With the first example:</p> <pre><code>&gt;&gt;&gt; Numbers.reverse_mapping['three'] 'THREE' </code></pre> <hr /> <p>If you are using MyPy another way to express &quot;enums&quot; is with <a href="https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals" rel="noreferrer"><code>typing.Literal</code></a>.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>from typing import Literal #python &gt;=3.8 from typing_extensions import Literal #python 2.7, 3.4-3.7 Animal = Literal['ant', 'bee', 'cat', 'dog'] def hello_animal(animal: Animal): print(f&quot;hello {animal}&quot;) hello_animal('rock') # error hello_animal('bee') # passes </code></pre>
{ "question_id": 36932, "question_date": "2008-08-31T15:55:47.910Z", "question_score": 1141, "tags": "python|python-3.x|enums", "answer_id": 1695250, "answer_date": "2009-11-08T03:15:28.320Z", "answer_score": 2941 }
Please answer the following Stack Overflow question: Title: Propagate all arguments in a Bash shell script <p>I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.</p> <p>For instance, my script name is <code>foo.sh</code> and calls <code>bar.sh</code>.</p> <p>foo.sh:</p> <pre><code>bar $1 $2 $3 $4 </code></pre> <p>How can I do this without explicitly specifying each parameter?</p>
<p>Use <code>&quot;$@&quot;</code> instead of plain <code>$@</code> if you actually wish your parameters to be passed the same.</p> <p>Observe:</p> <pre><code>$ cat no_quotes.sh #!/bin/bash echo_args.sh $@ $ cat quotes.sh #!/bin/bash echo_args.sh &quot;$@&quot; $ cat echo_args.sh #!/bin/bash echo Received: $1 echo Received: $2 echo Received: $3 echo Received: $4 $ ./no_quotes.sh first second Received: first Received: second Received: Received: $ ./no_quotes.sh &quot;one quoted arg&quot; Received: one Received: quoted Received: arg Received: $ ./quotes.sh first second Received: first Received: second Received: Received: $ ./quotes.sh &quot;one quoted arg&quot; Received: one quoted arg Received: Received: Received: </code></pre>
{ "question_id": 4824590, "question_date": "2011-01-28T03:34:04.250Z", "question_score": 1140, "tags": "bash|command-line-arguments", "answer_id": 4824637, "answer_date": "2011-01-28T03:42:43.227Z", "answer_score": 1817 }
Please answer the following Stack Overflow question: Title: How are zlib, gzip and zip related? What do they have in common and how are they different? <p>The compression algorithm used in <em>zlib</em> is essentially the same as that in <em>gzip</em> and <em>zip</em>. What are <em>gzip</em> and <em>zip</em>? How are they different and how are they same?</p>
<p><em>Short form:</em></p> <p><a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT" rel="noreferrer"><code>.zip</code> is an archive format</a> using, usually, the <a href="https://www.rfc-editor.org/rfc/rfc1951" rel="noreferrer">Deflate compression method</a>. The <a href="https://www.rfc-editor.org/rfc/rfc1952" rel="noreferrer"><code>.gz</code> gzip format</a> is for single files, also using the Deflate compression method. Often gzip is used in combination with <a href="http://www.gnu.org/software/tar/manual/html_node/Standard.html" rel="noreferrer">tar to make a compressed archive format</a>, <code>.tar.gz</code>. The <a href="http://zlib.net/" rel="noreferrer">zlib library</a> provides Deflate compression and decompression code for use by zip, gzip, <a href="http://www.w3.org/TR/PNG/" rel="noreferrer">png</a> (which uses the <a href="https://www.rfc-editor.org/rfc/rfc1950" rel="noreferrer">zlib wrapper</a> on deflate data), and many other applications.</p> <p><em>Long form:</em></p> <p>The <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT" rel="noreferrer">ZIP format</a> was developed by Phil Katz as an open format with an open specification, where his implementation, PKZIP, was shareware. It is an archive format that stores files and their directory structure, where each file is individually compressed. The file type is <code>.zip</code>. The files, as well as the directory structure, can optionally be encrypted.</p> <p>The ZIP format supports several compression methods:</p> <pre><code> 0 - The file is stored (no compression) 1 - The file is Shrunk 2 - The file is Reduced with compression factor 1 3 - The file is Reduced with compression factor 2 4 - The file is Reduced with compression factor 3 5 - The file is Reduced with compression factor 4 6 - The file is Imploded 7 - Reserved for Tokenizing compression algorithm 8 - The file is Deflated 9 - Enhanced Deflating using Deflate64(tm) 10 - PKWARE Data Compression Library Imploding (old IBM TERSE) 11 - Reserved by PKWARE 12 - File is compressed using BZIP2 algorithm 13 - Reserved by PKWARE 14 - LZMA 15 - Reserved by PKWARE 16 - IBM z/OS CMPSC Compression 17 - Reserved by PKWARE 18 - File is compressed using IBM TERSE (new) 19 - IBM LZ77 z Architecture 20 - deprecated (use method 93 for zstd) 93 - Zstandard (zstd) Compression 94 - MP3 Compression 95 - XZ Compression 96 - JPEG variant 97 - WavPack compressed data 98 - PPMd version I, Rev 1 99 - AE-x encryption marker (see APPENDIX E) </code></pre> <p>Methods 1 to 7 are historical and are not in use. Methods 9 through 98 are relatively recent additions and are in varying, small amounts of use. The only method in truly widespread use in the ZIP format is method 8, <a href="https://www.rfc-editor.org/rfc/rfc1951" rel="noreferrer">Deflate</a>, and to some smaller extent method 0, which is no compression at all. Virtually every <code>.zip</code> file that you will come across in the wild will use exclusively methods 8 and 0, likely just method 8. (Method 8 also has a means to effectively store the data with no compression and relatively little expansion, and Method 0 cannot be streamed whereas Method 8 can be.)</p> <p>The <a href="http://www.digitalpreservation.gov/formats/fdd/fdd000361.shtml" rel="noreferrer">ISO/IEC 21320-1:2015 standard for file containers</a> is a restricted zip format, such as used in Java archive files (.jar), Office Open XML files (Microsoft Office .docx, .xlsx, .pptx), Office Document Format files (.odt, .ods, .odp), and EPUB files (.epub). That standard limits the compression methods to 0 and 8, as well as other constraints such as no encryption or signatures.</p> <p>Around 1990, the <a href="http://www.info-zip.org/" rel="noreferrer">Info-ZIP group</a> wrote portable, free, open-source implementations of <code>zip</code> and <code>unzip</code> utilities, supporting compression with the Deflate format, and decompression of that and the earlier formats. This greatly expanded the use of the <code>.zip</code> format.</p> <p>In the early '90s, the <a href="https://www.rfc-editor.org/rfc/rfc1952" rel="noreferrer">gzip format</a> was developed as a replacement for the <a href="https://en.wikipedia.org/wiki/Compress" rel="noreferrer">Unix <code>compress</code> utility</a>, derived from the Deflate code in the Info-ZIP utilities. Unix <code>compress</code> was designed to compress a single file or stream, appending a <code>.Z</code> to the file name. <code>compress</code> uses the <a href="https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch" rel="noreferrer">LZW compression algorithm</a>, which at the time was under patent and its free use was in dispute by the patent holders. Though some specific implementations of Deflate were patented by Phil Katz, the format was not, and so it was possible to write a Deflate implementation that did not infringe on any patents. That implementation has not been so challenged in the last 20+ years. The Unix <code>gzip</code> utility was intended as a drop-in replacement for <code>compress</code>, and in fact is able to decompress <code>compress</code>-compressed data (assuming that you were able to parse that sentence). <code>gzip</code> appends a <code>.gz</code> to the file name. <code>gzip</code> uses the Deflate compressed data format, which compresses quite a bit better than Unix <code>compress</code>, has very fast decompression, and adds a CRC-32 as an integrity check for the data. The header format also permits the storage of more information than the <code>compress</code> format allowed, such as the original file name and the file modification time.</p> <p>Though <code>compress</code> only compresses a single file, it was common to use the <code>tar</code> utility to create an archive of files, their attributes, and their directory structure into a single <code>.tar</code> file, and to then compress it with <code>compress</code> to make a <code>.tar.Z</code> file. In fact, the <code>tar</code> utility had and still has an option to do the compression at the same time, instead of having to pipe the output of <code>tar</code> to <code>compress</code>. This all carried forward to the gzip format, and <code>tar</code> has an option to compress directly to the <code>.tar.gz</code> format. The <code>tar.gz</code> format compresses better than the <code>.zip</code> approach, since the compression of a <code>.tar</code> can take advantage of redundancy across files, especially many small files. <code>.tar.gz</code> is the most common archive format in use on Unix due to its very high portability, but there are more effective compression methods in use as well, so you will often see <code>.tar.bz2</code> and <code>.tar.xz</code> archives.</p> <p>Unlike <code>.tar</code>, <code>.zip</code> has a central directory at the end, which provides a list of the contents. That and the separate compression provides random access to the individual entries in a <code>.zip</code> file. A <code>.tar</code> file would have to be decompressed and scanned from start to end in order to build a directory, which is how a <code>.tar</code> file is listed.</p> <p>Shortly after the introduction of gzip, around the mid-1990s, the same patent dispute called into question the free use of the <code>.gif</code> image format, very widely used on bulletin boards and the World Wide Web (a new thing at the time). So a small group created the PNG losslessly compressed image format, with file type <code>.png</code>, to replace <code>.gif</code>. That format also uses the Deflate format for compression, which is applied after filters on the image data expose more of the redundancy. In order to promote widespread usage of the PNG format, two free code libraries were created. <a href="http://www.libpng.org/pub/png/libpng.html" rel="noreferrer">libpng</a> and <a href="http://zlib.net/" rel="noreferrer">zlib</a>. libpng handled all of the features of the PNG format, and zlib provided the compression and decompression code for use by libpng, as well as for other applications. zlib was adapted from the <code>gzip</code> code.</p> <p>All of the mentioned patents have since expired.</p> <p>The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams. Those are: no wrapping at all (&quot;raw&quot; deflate), <a href="https://www.rfc-editor.org/rfc/rfc1950" rel="noreferrer">zlib wrapping</a>, which is used in the PNG format data blocks, and gzip wrapping, to provide gzip routines for the programmer. The main difference between zlib and gzip wrapping is that the zlib wrapping is more compact, six bytes vs. a minimum of 18 bytes for gzip, and the integrity check, Adler-32, runs faster than the CRC-32 that gzip uses. Raw deflate is used by programs that read and write the <code>.zip</code> format, which is another format that wraps around deflate compressed data.</p> <p>zlib is now in wide use for data transmission and storage. For example, most HTTP transactions by servers and browsers compress and decompress the data using zlib, specifically HTTP header <code>Content-Encoding: deflate</code> means <a href="https://en.wikipedia.org/wiki/HTTP_compression#Content-Encoding_tokens" rel="noreferrer">deflate compression method wrapped inside the zlib data format</a>.</p> <p>Different implementations of deflate can result in different compressed output for the same input data, as evidenced by the existence of selectable compression levels that allow trading off compression effectiveness for CPU time. zlib and PKZIP are not the only implementations of deflate compression and decompression. Both the <a href="http://www.7-zip.org/" rel="noreferrer">7-Zip archiving utility</a> and Google's <a href="http://github.com/google/zopfli" rel="noreferrer">zopfli library</a> have the ability to use much more CPU time than zlib in order to squeeze out the last few bits possible when using the deflate format, reducing compressed sizes by a few percent as compared to zlib's highest compression level. The <a href="http://zlib.net/pigz/" rel="noreferrer">pigz utility</a>, a parallel implementation of gzip, includes the option to use zlib (compression levels 1-9) or zopfli (compression level 11), and somewhat mitigates the time impact of using zopfli by splitting the compression of large files over multiple processors and cores.</p>
{ "question_id": 20762094, "question_date": "2013-12-24T13:48:49.957Z", "question_score": 1140, "tags": "compression|zip|gzip|zlib", "answer_id": 20765054, "answer_date": "2013-12-24T18:03:42.173Z", "answer_score": 2946 }
Please answer the following Stack Overflow question: Title: What is the difference between --save and --save-dev? <p>What is the difference between:</p> <pre><code>npm install [package_name] </code></pre> <p>and:</p> <pre><code>npm install [package_name] --save </code></pre> <p>and:</p> <pre><code>npm install [package_name] --save-dev </code></pre> <p>What does this mean? And what is really the effect of <code>--save</code> and <code>-dev</code> keywords?</p>
<p>The difference between <code>--save</code> and <code>--save-dev</code> may not be immediately noticeable if you have tried them both on your own projects. So here are a few examples...</p> <p>Let's say you were building an app that used the <strong><a href="https://www.npmjs.com/package/moment" rel="noreferrer">moment</a></strong> package to parse and display dates. Your app is a scheduler so it really needs this package to run, as in: <strong>cannot run without it</strong>. In this case you would use</p> <pre><code>npm install moment --save </code></pre> <p>This would create a new value in your package.json</p> <pre><code>&quot;dependencies&quot;: { ... &quot;moment&quot;: &quot;^2.17.1&quot; } </code></pre> <p>When you are developing, it really helps to use tools such as test suites and may need <a href="https://www.npmjs.com/package/jasmine-core" rel="noreferrer">jasmine-core</a> and <a href="https://www.npmjs.com/package/karma" rel="noreferrer">karma</a>. In this case you would use</p> <pre><code>npm install jasmine-core --save-dev npm install karma --save-dev </code></pre> <p>This would also create a new value in your package.json</p> <pre><code>&quot;devDependencies&quot;: { ... &quot;jasmine-core&quot;: &quot;^2.5.2&quot;, &quot;karma&quot;: &quot;^1.4.1&quot;, } </code></pre> <p>You do <strong>not need</strong> the test suite to run the app in its normal state, so it is a <code>--save-dev</code> type dependency, nothing more. You can see how if you do not understand what is really happening, it is a bit hard to imagine.</p> <p>Taken directly from NPM docs <a href="https://docs.npmjs.com/files/package.json#dependencies" rel="noreferrer">docs#dependencies</a></p> <blockquote> <p><strong>Dependencies</strong></p> <p>Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string that has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.</p> <p><strong>Please do not put test harnesses or transpilers in your dependencies object. See devDependencies</strong>, below.</p> </blockquote> <p>Even in the docs, it asks you to use <code>--save-dev</code> for modules such as test harnesses.</p>
{ "question_id": 22891211, "question_date": "2014-04-06T07:34:11.083Z", "question_score": 1140, "tags": "node.js|npm|save|package", "answer_id": 42206389, "answer_date": "2017-02-13T14:25:36.920Z", "answer_score": 904 }
Please answer the following Stack Overflow question: Title: Is there a simple way to delete a list element by value? <p>I want to remove a value from a list if it exists in the list (which it may not).</p> <pre><code>a = [1, 2, 3, 4] b = a.index(6) del a[b] print(a) </code></pre> <p>The above gives the error:</p> <pre class="lang-none prettyprint-override"><code>ValueError: list.index(x): x not in list </code></pre> <p>So I have to do this:</p> <pre><code>a = [1, 2, 3, 4] try: b = a.index(6) del a[b] except: pass print(a) </code></pre> <p>But is there not a simpler way to do this?</p>
<p>To remove the <em>first occurrence</em> of an element, use <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="noreferrer"><code>list.remove</code></a>:</p> <pre><code>&gt;&gt;&gt; xs = ['a', 'b', 'c', 'd'] &gt;&gt;&gt; xs.remove('b') &gt;&gt;&gt; print(xs) ['a', 'c', 'd'] </code></pre> <p>To remove <em>all occurrences</em> of an element, use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>:</p> <pre><code>&gt;&gt;&gt; xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b'] &gt;&gt;&gt; xs = [x for x in xs if x != 'b'] &gt;&gt;&gt; print(xs) ['a', 'c', 'd'] </code></pre>
{ "question_id": 2793324, "question_date": "2010-05-08T07:48:28.700Z", "question_score": 1139, "tags": "python|list", "answer_id": 2793341, "answer_date": "2010-05-08T07:56:03.203Z", "answer_score": 1824 }
Please answer the following Stack Overflow question: Title: Can a local variable's memory be accessed outside its scope? <p>I have the following code.</p> <pre><code>#include &lt;iostream&gt; int * foo() { int a = 5; return &amp;a; } int main() { int* p = foo(); std::cout &lt;&lt; *p; *p = 8; std::cout &lt;&lt; *p; } </code></pre> <p>And the code is just running with no runtime exceptions!</p> <p>The output was <code>58</code></p> <p>How can it be? Isn't the memory of a local variable inaccessible outside its function?</p>
<blockquote> <p>How can it be? Isn't the memory of a local variable inaccessible outside its function?</p> </blockquote> <p>You rent a hotel room. You put a book in the top drawer of the bedside table and go to sleep. You check out the next morning, but "forget" to give back your key. You steal the key!</p> <p>A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!</p> <p><strong>How can that be? Aren't the contents of a hotel room drawer inaccessible if you haven't rented the room?</strong></p> <p>Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.</p> <p>The hotel management is not <em>required</em> to remove your book. You didn't make a contract with them that said that if you leave stuff behind, they'll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not <em>required</em> to catch you sneaking in. You didn't make a contract with them that said "if I try to sneak back into my room later, you are required to stop me." Rather, you signed a contract with them that said "I promise not to sneak back into my room later", a contract which <em>you broke</em>.</p> <p>In this situation <strong>anything can happen</strong>. The book can be there -- you got lucky. Someone else's book can be there and yours could be in the hotel's furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around. </p> <p>You don't know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because <em>you</em> chose to break the rules of the system.</p> <p><strong>C++ is not a safe language</strong>. It will cheerfully allow you to break the rules of the system. If you try to do something illegal and foolish like going back into a room you're not authorized to be in and rummaging through a desk that might not even be there anymore, C++ is not going to stop you. Safer languages than C++ solve this problem by restricting your power -- by having much stricter control over keys, for example.</p> <h2>UPDATE</h2> <p>Holy goodness, this answer is getting a lot of attention. (I'm not sure why -- I considered it to be just a "fun" little analogy, but whatever.)</p> <p>I thought it might be germane to update this a bit with a few more technical thoughts.</p> <p>Compilers are in the business of generating code which manages the storage of the data manipulated by that program. There are lots of different ways of generating code to manage memory, but over time two basic techniques have become entrenched. </p> <p>The first is to have some sort of "long lived" storage area where the "lifetime" of each byte in the storage -- that is, the period of time when it is validly associated with some program variable -- cannot be easily predicted ahead of time. The compiler generates calls into a "heap manager" that knows how to dynamically allocate storage when it is needed and reclaim it when it is no longer needed.</p> <p>The second method is to have a “short-lived” storage area where the lifetime of each byte is well known. Here, the lifetimes follow a “nesting” pattern. The longest-lived of these short-lived variables will be allocated before any other short-lived variables, and will be freed last. Shorter-lived variables will be allocated after the longest-lived ones, and will be freed before them. The lifetime of these shorter-lived variables is “nested” within the lifetime of longer-lived ones.</p> <p>Local variables follow the latter pattern; when a method is entered, its local variables come alive. When that method calls another method, the new method's local variables come alive. They'll be dead before the first method's local variables are dead. The relative order of the beginnings and endings of lifetimes of storages associated with local variables can be worked out ahead of time.</p> <p>For this reason, local variables are usually generated as storage on a "stack" data structure, because a stack has the property that the first thing pushed on it is going to be the last thing popped off. </p> <p>It's like the hotel decides to only rent out rooms sequentially, and you can't check out until everyone with a room number higher than you has checked out. </p> <p>So let's think about the stack. In many operating systems you get one stack per thread and the stack is allocated to be a certain fixed size. When you call a method, stuff is pushed onto the stack. If you then pass a pointer to the stack back out of your method, as the original poster does here, that's just a pointer to the middle of some entirely valid million-byte memory block. In our analogy, you check out of the hotel; when you do, you just checked out of the highest-numbered occupied room. If no one else checks in after you, and you go back to your room illegally, all your stuff is guaranteed to still be there <em>in this particular hotel</em>.</p> <p>We use stacks for temporary stores because they are really cheap and easy. An implementation of C++ is not required to use a stack for storage of locals; it could use the heap. It doesn't, because that would make the program slower. </p> <p>An implementation of C++ is not required to leave the garbage you left on the stack untouched so that you can come back for it later illegally; it is perfectly legal for the compiler to generate code that turns back to zero everything in the "room" that you just vacated. It doesn't because again, that would be expensive.</p> <p>An implementation of C++ is not required to ensure that when the stack logically shrinks, the addresses that used to be valid are still mapped into memory. The implementation is allowed to tell the operating system "we're done using this page of stack now. Until I say otherwise, issue an exception that destroys the process if anyone touches the previously-valid stack page". Again, implementations do not actually do that because it is slow and unnecessary.</p> <p>Instead, implementations let you make mistakes and get away with it. Most of the time. Until one day something truly awful goes wrong and the process explodes.</p> <p>This is problematic. There are a lot of rules and it is very easy to break them accidentally. I certainly have many times. And worse, the problem often only surfaces when memory is detected to be corrupt billions of nanoseconds after the corruption happened, when it is very hard to figure out who messed it up.</p> <p>More memory-safe languages solve this problem by restricting your power. In "normal" C# there simply is no way to take the address of a local and return it or store it for later. You can take the address of a local, but the language is cleverly designed so that it is impossible to use it after the lifetime of the local ends. In order to take the address of a local and pass it back, you have to put the compiler in a special "unsafe" mode, <em>and</em> put the word "unsafe" in your program, to call attention to the fact that you are probably doing something dangerous that could be breaking the rules. </p> <p>For further reading:</p> <ul> <li><p>What if C# did allow returning references? Coincidentally that is the subject of today's blog post:</p> <p><a href="https://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/" rel="noreferrer">https://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/</a></p></li> <li><p>Why do we use stacks to manage memory? Are value types in C# always stored on the stack? How does virtual memory work? And many more topics in how the C# memory manager works. Many of these articles are also germane to C++ programmers:</p> <p><a href="https://ericlippert.com/tag/memory-management/" rel="noreferrer">https://ericlippert.com/tag/memory-management/</a></p></li> </ul>
{ "question_id": 6441218, "question_date": "2011-06-22T14:05:48.240Z", "question_score": 1139, "tags": "c++|memory-management|local-variables|dangling-pointer", "answer_id": 6445794, "answer_date": "2011-06-22T20:01:23.010Z", "answer_score": 4967 }
Please answer the following Stack Overflow question: Title: endsWith in JavaScript <p>How can I check if a string ends with a particular character in JavaScript?</p> <p>Example: I have a string </p> <pre><code>var str = "mystring#"; </code></pre> <p>I want to know if that string is ending with <code>#</code>. How can I check it?</p> <ol> <li><p>Is there a <code>endsWith()</code> method in JavaScript?</p></li> <li><p>One solution I have is take the length of the string and get the last character and check it.</p></li> </ol> <p>Is this the best way or there is any other way?</p>
<p><strong>UPDATE (Nov 24th, 2015):</strong></p> <p>This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:</p> <ul> <li><a href="https://stackoverflow.com/users/570040/shauna">Shauna</a> -</li> </ul> <blockquote> <p>Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith</a></p> </blockquote> <ul> <li><a href="https://stackoverflow.com/users/157247/t-j-crowder">T.J. Crowder</a> -</li> </ul> <blockquote> <p>Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple <code>this.substr(-suffix.length) === suffix</code> approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: <a href="https://jsben.ch/OJzlM" rel="nofollow noreferrer">https://jsben.ch/OJzlM</a> And faster across the board when the result is false: <a href="http://jsperf.com/endswith-stackoverflow-when-false" rel="nofollow noreferrer">jsperf.com/endswith-stackoverflow-when-false</a> <strong>Of course, with ES6 adding endsWith, the point is moot. :-)</strong></p> </blockquote> <hr /> <p><strong>ORIGINAL ANSWER:</strong></p> <p>I know this is a year old question... but I need this too and I need it to work cross-browser so... <strong>combining everyone's answer and comments</strong> and simplifying it a bit:</p> <pre><code>String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; </code></pre> <ul> <li>Doesn't create a substring</li> <li>Uses native <code>indexOf</code> function for fastest results</li> <li>Skip unnecessary comparisons using the second parameter of <code>indexOf</code> to skip ahead</li> <li>Works in Internet Explorer</li> <li>NO Regex complications</li> </ul> <hr /> <p>Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:</p> <pre><code>function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } </code></pre> <hr /> <p><strong>EDIT:</strong> As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a <code>typeof</code> check like so:</p> <pre><code>if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } </code></pre>
{ "question_id": 280634, "question_date": "2008-11-11T11:15:32.807Z", "question_score": 1138, "tags": "javascript|string|ends-with", "answer_id": 2548133, "answer_date": "2010-03-30T19:40:46.977Z", "answer_score": 1781 }
Please answer the following Stack Overflow question: Title: How to mock void methods with Mockito <p>How to mock methods with void return type? </p> <p>I implemented an observer pattern but I can't mock it with Mockito because I don't know how.</p> <p>And I tried to find an example on the Internet but didn't succeed.</p> <p>My class looks like this:</p> <pre><code>public class World { List&lt;Listener&gt; listeners; void addListener(Listener item) { listeners.add(item); } void doAction(Action goal,Object obj) { setState("i received"); goal.doAction(obj); setState("i finished"); } private string state; //setter getter state } public class WorldTest implements Listener { @Test public void word{ World w= mock(World.class); w.addListener(this); ... ... } } interface Listener { void doAction(); } </code></pre> <p>The system is not triggered with mock.</p> <p>I want to show the above-mentioned system state. And make assertions according to them.</p>
<p>Take a look at the Mockito <a href="http://javadoc.io/page/org.mockito/mockito-core/latest/org/mockito/Mockito.html#12" rel="noreferrer">API docs</a>. As the linked document mentions (Point # 12) you can use any of the <code>doThrow()</code>,<code>doAnswer()</code>,<code>doNothing()</code>,<code>doReturn()</code> family of methods from Mockito framework to mock void methods.</p> <p>For example,</p> <pre><code>Mockito.doThrow(new Exception()).when(instance).methodName(); </code></pre> <p>or if you want to combine it with follow-up behavior,</p> <pre><code>Mockito.doThrow(new Exception()).doNothing().when(instance).methodName(); </code></pre> <p>Presuming that you are looking at mocking the setter <code>setState(String s)</code> in the class World below is the code uses <code>doAnswer</code> method to mock the <code>setState</code>.</p> <pre><code>World mockWorld = mock(World.class); doAnswer(new Answer&lt;Void&gt;() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); System.out.println(&quot;called with arguments: &quot; + Arrays.toString(args)); return null; } }).when(mockWorld).setState(anyString()); </code></pre>
{ "question_id": 2276271, "question_date": "2010-02-16T20:54:39.500Z", "question_score": 1136, "tags": "java|unit-testing|mocking|mockito|void", "answer_id": 2278221, "answer_date": "2010-02-17T04:02:46.077Z", "answer_score": 1374 }
Please answer the following Stack Overflow question: Title: Getting a random value from a JavaScript array <p>Consider:</p> <pre><code>var myArray = ['January', 'February', 'March']; </code></pre> <p>How can I select a random value from this array using JavaScript?</p>
<p>It's a simple one-liner:</p> <pre><code>const randomElement = array[Math.floor(Math.random() * array.length)]; </code></pre> <p>For example:</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 months = ["January", "February", "March", "April", "May", "June", "July"]; const random = Math.floor(Math.random() * months.length); console.log(random, months[random]);</code></pre> </div> </div> </p>
{ "question_id": 4550505, "question_date": "2010-12-29T00:04:44.470Z", "question_score": 1136, "tags": "javascript|random", "answer_id": 4550514, "answer_date": "2010-12-29T00:06:56.057Z", "answer_score": 2101 }
Please answer the following Stack Overflow question: Title: How to use Git and Dropbox together? <p>Is it possible to use <a href="https://en.wikipedia.org/wiki/Git_%28software%29" rel="nofollow noreferrer">Git</a> and <a href="https://en.wikipedia.org/wiki/Dropbox_%28service%29" rel="nofollow noreferrer">Dropbox</a> together?</p>
<p>I think that Git on Dropbox is great. I use it all the time. I have multiple computers (two at home and one at work) on which I use Dropbox as a central bare repository. Since I don’t want to host it on a public service, and I don’t have access to a server that I can always SSH to, Dropbox takes care of this by syncing in the background (very doing so quickly).</p> <p>Setup is something like this:</p> <pre class="lang-sh prettyprint-override"><code>~/project $ git init ~/project $ git add . ~/project $ git commit -m &quot;first commit&quot; ~/project $ cd ~/Dropbox/git ~/Dropbox/git $ git init --bare project.git ~/Dropbox/git $ cd ~/project ~/project $ git remote add origin ~/Dropbox/git/project.git ~/project $ git push -u origin master </code></pre> <p>From there, you can just clone that <code>~/Dropbox/git/project.git</code> directory (regardless of whether it belongs to your Dropbox account or is shared across multiple accounts) and do all the normal Git operations—they will be synchronized to all your other machines automatically.</p> <p>I wrote a blog post “<a href="http://corrupt.net/2009/08/01/On-Version-Control/" rel="nofollow noreferrer">On Version Control</a>” in which I cover the reasoning behind my environment setup. It’s based on my <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="nofollow noreferrer">Ruby on Rails</a> development experience, but it can be applied to anything, really.</p>
{ "question_id": 1960799, "question_date": "2009-12-25T08:41:51.677Z", "question_score": 1136, "tags": "git|dropbox", "answer_id": 1961515, "answer_date": "2009-12-25T17:10:40.737Z", "answer_score": 1408 }
Please answer the following Stack Overflow question: Title: How to parse XML and get instances of a particular node attribute? <p>I have many rows in XML and I'm trying to get instances of a particular node attribute.</p> <pre class="lang-xml prettyprint-override"><code>&lt;foo&gt; &lt;bar&gt; &lt;type foobar=&quot;1&quot;/&gt; &lt;type foobar=&quot;2&quot;/&gt; &lt;/bar&gt; &lt;/foo&gt; </code></pre> <p>How do I access the values of the attribute <code>foobar</code>? In this example, I want <code>&quot;1&quot;</code> and <code>&quot;2&quot;</code>.</p>
<p>I suggest <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="noreferrer"><code>ElementTree</code></a>. There are other compatible implementations of the same API, such as <a href="https://lxml.de/parsing.html" rel="noreferrer"><code>lxml</code></a>, and <code>cElementTree</code> in the Python standard library itself; but, in this context, what they chiefly add is even more speed -- the ease of programming part depends on the API, which <code>ElementTree</code> defines.</p> <p>First build an Element instance <code>root</code> from the XML, e.g. with the <a href="http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.XML" rel="noreferrer">XML</a> function, or by parsing a file with something like:</p> <pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ET root = ET.parse('thefile.xml').getroot() </code></pre> <p>Or any of the many other ways shown at <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="noreferrer"><code>ElementTree</code></a>. Then do something like:</p> <pre class="lang-py prettyprint-override"><code>for type_tag in root.findall('bar/type'): value = type_tag.get('foobar') print(value) </code></pre> <p>Output:</p> <pre><code>1 2 </code></pre>
{ "question_id": 1912434, "question_date": "2009-12-16T05:09:24.933Z", "question_score": 1135, "tags": "python|xml", "answer_id": 1912483, "answer_date": "2009-12-16T05:21:55.017Z", "answer_score": 892 }
Please answer the following Stack Overflow question: Title: Deserialize JSON into C# dynamic object? <p>Is there a way to deserialize JSON content into a C# dynamic type? It would be nice to skip creating a bunch of classes in order to use the <code>DataContractJsonSerializer</code>.</p>
<p>If you are happy to have a dependency upon the <code>System.Web.Helpers</code> assembly, then you can use the <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json(v=vs.111).aspx" rel="noreferrer"><code>Json</code></a> class:</p> <pre><code>dynamic data = Json.Decode(json); </code></pre> <p>It is included with the MVC framework as an <a href="https://stackoverflow.com/q/8037895/24874">additional download</a> to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.</p> <hr> <p>An alternative deserialisation approach is suggested <a href="http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx" rel="noreferrer">here</a>. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to <code>System.Web.Extensions</code> from your project:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; using System.Linq; using System.Text; using System.Web.Script.Serialization; public sealed class DynamicJsonConverter : JavaScriptConverter { public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } public override IDictionary&lt;string, object&gt; Serialize(object obj, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IEnumerable&lt;Type&gt; SupportedTypes { get { return new ReadOnlyCollection&lt;Type&gt;(new List&lt;Type&gt;(new[] { typeof(object) })); } } #region Nested type: DynamicJsonObject private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary&lt;string, object&gt; _dictionary; public DynamicJsonObject(IDictionary&lt;string, object&gt; dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); _dictionary = dictionary; } public override string ToString() { var sb = new StringBuilder("{"); ToString(sb); return sb.ToString(); } private void ToString(StringBuilder sb) { var firstInDictionary = true; foreach (var pair in _dictionary) { if (!firstInDictionary) sb.Append(","); firstInDictionary = false; var value = pair.Value; var name = pair.Key; if (value is string) { sb.AppendFormat("{0}:\"{1}\"", name, value); } else if (value is IDictionary&lt;string, object&gt;) { new DynamicJsonObject((IDictionary&lt;string, object&gt;)value).ToString(sb); } else if (value is ArrayList) { sb.Append(name + ":["); var firstInArray = true; foreach (var arrayValue in (ArrayList)value) { if (!firstInArray) sb.Append(","); firstInArray = false; if (arrayValue is IDictionary&lt;string, object&gt;) new DynamicJsonObject((IDictionary&lt;string, object&gt;)arrayValue).ToString(sb); else if (arrayValue is string) sb.AppendFormat("\"{0}\"", arrayValue); else sb.AppendFormat("{0}", arrayValue); } sb.Append("]"); } else { sb.AppendFormat("{0}:{1}", name, value); } } sb.Append("}"); } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { if (indexes.Length == 1 &amp;&amp; indexes[0] != null) { if (!_dictionary.TryGetValue(indexes[0].ToString(), out result)) { // return null to avoid exception. caller can check for null this way... result = null; return true; } result = WrapResultObject(result); return true; } return base.TryGetIndex(binder, indexes, out result); } private static object WrapResultObject(object result) { var dictionary = result as IDictionary&lt;string, object&gt;; if (dictionary != null) return new DynamicJsonObject(dictionary); var arrayList = result as ArrayList; if (arrayList != null &amp;&amp; arrayList.Count &gt; 0) { return arrayList[0] is IDictionary&lt;string, object&gt; ? new List&lt;object&gt;(arrayList.Cast&lt;IDictionary&lt;string, object&gt;&gt;().Select(x =&gt; new DynamicJsonObject(x))) : new List&lt;object&gt;(arrayList.Cast&lt;object&gt;()); } return result; } } #endregion } </code></pre> <p>You can use it like this:</p> <pre><code>string json = ...; var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); dynamic obj = serializer.Deserialize(json, typeof(object)); </code></pre> <p>So, given a JSON string:</p> <pre><code>{ "Items":[ { "Name":"Apple", "Price":12.3 }, { "Name":"Grape", "Price":3.21 } ], "Date":"21/11/2010" } </code></pre> <p>The following code will work at runtime:</p> <pre><code>dynamic data = serializer.Deserialize(json, typeof(object)); data.Date; // "21/11/2010" data.Items.Count; // 2 data.Items[0].Name; // "Apple" data.Items[0].Price; // 12.3 (as a decimal) data.Items[1].Name; // "Grape" data.Items[1].Price; // 3.21 (as a decimal) </code></pre>
{ "question_id": 3142495, "question_date": "2010-06-29T16:04:01.637Z", "question_score": 1135, "tags": "c#|.net|json|serialization|dynamic", "answer_id": 3806407, "answer_date": "2010-09-27T17:46:10.193Z", "answer_score": 727 }
Please answer the following Stack Overflow question: Title: Colors in JavaScript console <p>Can Chrome's built-in JavaScript console display colors?</p> <p>I want errors in red, warnings in orange and <code>console.log</code>'s in green. Is that possible?</p>
<p>In Chrome &amp; Firefox (+31) you can add CSS in <code>console.log</code> messages:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>console.log('%c Oh my heavens! ', 'background: #222; color: #bada55');</code></pre> </div> </div> </p> <p><img src="https://i.stack.imgur.com/gvpgF.png" alt="Console color example in Chrome" /></p> <p>The same can be applied for adding multiple CSS to same command. <a href="https://i.stack.imgur.com/DFJBd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DFJBd.png" alt="syntax for multi coloring chrome console messages" /></a></p> <h3>References</h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/console#Usage" rel="noreferrer">MDN: Styling console output</a></li> <li><a href="https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css" rel="noreferrer">Chrome: Console API Reference</a></li> </ul>
{ "question_id": 7505623, "question_date": "2011-09-21T19:36:53.370Z", "question_score": 1135, "tags": "javascript|google-chrome|console|google-chrome-devtools", "answer_id": 13017382, "answer_date": "2012-10-22T18:22:07.213Z", "answer_score": 1738 }
Please answer the following Stack Overflow question: Title: What are the most common Python docstring formats? <p>I have seen a few different styles of writing docstrings in Python, what are the most popular styles?</p>
<h1>Formats</h1> <p>Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on <strong>reStructuredText (reST)</strong>. You can get some information about the main formats in <a href="http://daouzli.com/blog/docstring.html" rel="noreferrer">this blog post</a>.</p> <p>Note that the reST is recommended by the <a href="https://www.python.org/dev/peps/pep-0287" rel="noreferrer">PEP 287</a></p> <p>There follows the main used formats for docstrings.</p> <h2>- Epytext</h2> <p>Historically a <strong>javadoc</strong> like style was prevalent, so it was taken as a base for <a href="http://epydoc.sourceforge.net" rel="noreferrer">Epydoc</a> (with the called <code>Epytext</code> format) to generate documentation.</p> <p>Example:</p> <pre><code>""" This is a javadoc style. @param param1: this is a first param @param param2: this is a second param @return: this is a description of what is returned @raise keyError: raises an exception """ </code></pre> <h2>- reST</h2> <p>Nowadays, the probably more prevalent format is the <strong>reStructuredText</strong> (reST) format that is used by <a href="http://sphinx-doc.org" rel="noreferrer">Sphinx</a> to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.</p> <p>Example:</p> <pre><code>""" This is a reST style. :param param1: this is a first param :param param2: this is a second param :returns: this is a description of what is returned :raises keyError: raises an exception """ </code></pre> <h2>- Google</h2> <p>Google has their own <a href="https://github.com/google/styleguide/blob/gh-pages/pyguide.md#38-comments-and-docstrings" rel="noreferrer">format</a> that is often used. It also can be interpreted by Sphinx (ie. using <a href="https://sphinxcontrib-napoleon.readthedocs.io/en/latest/" rel="noreferrer">Napoleon plugin</a>). </p> <p>Example:</p> <pre><code>""" This is an example of Google style. Args: param1: This is the first param. param2: This is a second param. Returns: This is a description of what is returned. Raises: KeyError: Raises an exception. """ </code></pre> <p>Even <a href="https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html#example-google" rel="noreferrer">more examples</a></p> <h2>- Numpydoc</h2> <p>Note that Numpy recommend to follow their own <a href="https://numpydoc.readthedocs.io/en/latest/" rel="noreferrer">numpydoc</a> based on Google format and usable by Sphinx.</p> <pre><code>""" My numpydoc description of a kind of very exhautive numpydoc format docstring. Parameters ---------- first : array_like the 1st param name `first` second : the 2nd param third : {'value', 'other'}, optional the 3rd param, by default 'value' Returns ------- string a value in a string Raises ------ KeyError when a key error OtherError when an other error """ </code></pre> <h1>Converting/Generating</h1> <p>It is possible to use a tool like <a href="https://github.com/dadadel/pyment" rel="noreferrer">Pyment</a> to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.</p> <p>Note: The examples are taken from the <a href="https://github.com/dadadel/pyment/blob/master/README.rst" rel="noreferrer">Pyment documentation</a></p>
{ "question_id": 3898572, "question_date": "2010-10-10T01:10:44.823Z", "question_score": 1135, "tags": "python|coding-style|documentation|docstring", "answer_id": 24385103, "answer_date": "2014-06-24T11:10:21.110Z", "answer_score": 1390 }
Please answer the following Stack Overflow question: Title: Remove all whitespace in a string <p>I want to eliminate all the whitespace from a string, on both ends, and in between words.</p> <p>I have this Python code:</p> <pre><code>def my_handle(self): sentence = ' hello apple ' sentence.strip() </code></pre> <p>But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?</p>
<p>If you want to remove leading and ending spaces, use <a href="http://docs.python.org/2/library/stdtypes.html#str.strip" rel="noreferrer"><code>str.strip()</code></a>:</p> <pre><code>&gt;&gt;&gt; &quot; hello apple &quot;.strip() 'hello apple' </code></pre> <p>If you want to remove all space characters, use <a href="http://docs.python.org/2/library/stdtypes.html#str.replace" rel="noreferrer"><code>str.replace()</code></a> <em>(NB this only removes the “normal” ASCII space character <code>' ' U+0020</code> but not <a href="https://en.wikipedia.org/wiki/Whitespace_character#Unicode" rel="noreferrer">any other whitespace</a>)</em>:</p> <pre><code>&gt;&gt;&gt; &quot; hello apple &quot;.replace(&quot; &quot;, &quot;&quot;) 'helloapple' </code></pre> <p>If you want to remove duplicated spaces, use <a href="http://docs.python.org/2/library/stdtypes.html#str.split" rel="noreferrer"><code>str.split()</code></a> followed by <code>str.join()</code>:</p> <pre><code>&gt;&gt;&gt; &quot; &quot;.join(&quot; hello apple &quot;.split()) 'hello apple' </code></pre>
{ "question_id": 8270092, "question_date": "2011-11-25T13:51:21.037Z", "question_score": 1134, "tags": "python|trim|removing-whitespace", "answer_id": 8270146, "answer_date": "2011-11-25T13:56:30.797Z", "answer_score": 2184 }
Please answer the following Stack Overflow question: Title: Copy array items into another array <p>I have a JavaScript array <code>dataArray</code> which I want to push into a new array <code>newArray</code>. Except I don't want <code>newArray[0]</code> to be <code>dataArray</code>. I want to push in all the items into the new array:</p> <pre><code>var newArray = []; newArray.pushValues(dataArray1); newArray.pushValues(dataArray2); // ... </code></pre> <p>or even better:</p> <pre><code>var newArray = new Array ( dataArray1.values(), dataArray2.values(), // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself ); </code></pre> <p>So now the new array contains all the values of the individual data arrays. Is there some shorthand like <code>pushValues</code> available so I don't have to iterate over each individual <code>dataArray</code>, adding the items one by one?</p>
<p>Use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer">concat</a> function, like so:</p> <pre><code>var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA.concat(arrayB); </code></pre> <p>The value of <code>newArray</code> will be <code>[1, 2, 3, 4]</code> (<code>arrayA</code> and <code>arrayB</code> remain unchanged; <code>concat</code> creates and returns a new array for the result).</p>
{ "question_id": 4156101, "question_date": "2010-11-11T15:33:18.830Z", "question_score": 1133, "tags": "javascript|arrays", "answer_id": 4156145, "answer_date": "2010-11-11T15:37:48.393Z", "answer_score": 1512 }
Please answer the following Stack Overflow question: Title: How do I check if string contains substring? <p>I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible. </p> <p>The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:</p> <pre><code>$(document).ready(function() { $('select[id="Engraving"]').change(function() { var str = $('select[id="Engraving"] option:selected').text(); if (str == "Yes (+ $6.95)") { $('.engraving').show(); } else { $('.engraving').hide(); } }); }); </code></pre> <p>However I would rather use something like this, which doesn't work:</p> <pre><code>$(document).ready(function() { $('select[id="Engraving"]').change(function() { var str = $('select[id="Engraving"] option:selected').text(); if (str *= "Yes") { $('.engraving').show(); } else { $('.engraving').hide(); } }); }); </code></pre> <p>I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.</p>
<p>Like this:</p> <pre><code>if (str.indexOf(&quot;Yes&quot;) &gt;= 0) </code></pre> <p>...or you can use the tilde operator:</p> <pre><code>if (~str.indexOf(&quot;Yes&quot;)) </code></pre> <p>This works because <code>indexOf()</code> returns <code>-1</code> if the string wasn't found at all.</p> <p>Note that this is case-sensitive.<br /> If you want a case-insensitive search, you can write</p> <pre><code>if (str.toLowerCase().indexOf(&quot;yes&quot;) &gt;= 0) </code></pre> <p>Or:</p> <pre><code>if (/yes/i.test(str)) </code></pre> <p>The latter is a <strong>regular expression</strong> or <strong>regex</strong>.</p> <p>Regex breakdown:</p> <ul> <li><code>/</code> indicates this is a regex</li> <li><code>yes</code> means that the regex will find those exact characters in that exact order</li> <li><code>/</code> ends the regex</li> <li><code>i</code> sets the regex as case-<em>in</em>sensitive</li> <li><code>.test(str)</code> determines if the regular expression matches <code>str</code> To sum it up, it means it will see if it can find the letters <code>y</code>, <code>e</code>, and <code>s</code> in that exact order, case-insensitively, in the variable <code>str</code></li> </ul>
{ "question_id": 3480771, "question_date": "2010-08-13T21:25:54.837Z", "question_score": 1131, "tags": "javascript|jquery|string|substring|contains", "answer_id": 3480785, "answer_date": "2010-08-13T21:28:36.617Z", "answer_score": 2322 }
Please answer the following Stack Overflow question: Title: What's the difference between lists and tuples? <p>What's the difference between tuples/lists and what are their advantages/disadvantages?</p>
<p>Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. <strong>Tuples have structure, lists have order.</strong> </p> <p>Using this distinction makes code more explicit and understandable.</p> <p>One example would be pairs of page and line number to reference locations in a book, e.g.:</p> <pre><code>my_location = (42, 11) # page number, line number </code></pre> <p>You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.</p> <p>There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.</p> <p>There are some interesting articles on this issue, e.g. <a href="http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/" rel="noreferrer">"Python Tuples are Not Just Constant Lists"</a> or <a href="http://news.e-scribe.com/397" rel="noreferrer">"Understanding tuples vs. lists in Python"</a>. The official Python documentation <a href="http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">also mentions this</a></p> <blockquote> <p>"Tuples are immutable, and usually contain an heterogeneous sequence ...".</p> </blockquote> <p>In a statically typed language like <em>Haskell</em> the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.</p> <p>Finally there is the <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple" rel="noreferrer">namedtuple</a> in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.</p>
{ "question_id": 626759, "question_date": "2009-03-09T15:41:25.767Z", "question_score": 1131, "tags": "python|list|tuples", "answer_id": 626871, "answer_date": "2009-03-09T16:02:51.800Z", "answer_score": 1092 }
Please answer the following Stack Overflow question: Title: How can I do Base64 encoding in Node.js? <p>Does Node.js have built-in Base64 encoding yet?</p> <p>The reason why I ask this is that <code>final()</code> from <code>crypto</code> can only output hexadecimal, binary or ASCII data. For example:</p> <pre><code>var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv); var ciph = cipher.update(plaintext, 'utf8', 'hex'); ciph += cipher.final('hex'); var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv); var txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); </code></pre> <p>According to the documentation, <code>update()</code> can output Base64-encoded data. However, <code>final()</code> doesn't support Base64. I tried and it will break.</p> <p>If I do this:</p> <pre><code>var ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('hex'); </code></pre> <p>Then what should I use for decryption? Hexadecimal or Base64?</p> <p>Therefore, I'm looking for a function to Base64-encode my encrypted hexadecimal output.</p>
<p><a href="http://nodejs.org/docs/latest/api/buffer.html" rel="noreferrer">Buffers</a> can be used for taking a string or piece of data and doing Base64 encoding of the result. For example:</p> <pre><code>&gt; console.log(Buffer.from(&quot;Hello World&quot;).toString('base64')); SGVsbG8gV29ybGQ= &gt; console.log(Buffer.from(&quot;SGVsbG8gV29ybGQ=&quot;, 'base64').toString('ascii')) Hello World </code></pre> <p>Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available <code>toString</code> and <code>Buffer</code> constructor encodings are as follows:</p> <blockquote> <p>'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.</p> <p>'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.</p> <p>'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).</p> <p>'base64' - Base64 string encoding.</p> <p>'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.</p> </blockquote>
{ "question_id": 6182315, "question_date": "2011-05-31T02:09:42.377Z", "question_score": 1130, "tags": "node.js|encoding|base64", "answer_id": 6182519, "answer_date": "2011-05-31T02:46:02.100Z", "answer_score": 2506 }
Please answer the following Stack Overflow question: Title: Group By Multiple Columns <p>How can I do GroupBy multiple columns in LINQ</p> <p>Something similar to this in SQL:</p> <pre><code>SELECT * FROM &lt;TableName&gt; GROUP BY &lt;Column1&gt;,&lt;Column2&gt; </code></pre> <p>How can I convert this to LINQ:</p> <pre><code>QuantityBreakdown ( MaterialID int, ProductID int, Quantity float ) INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM(Quantity) FROM @Transactions GROUP BY MaterialID, ProductID </code></pre>
<p>Use an anonymous type.</p> <p>Eg</p> <pre><code>group x by new { x.Column1, x.Column2 } </code></pre>
{ "question_id": 847066, "question_date": "2009-05-11T07:24:39.507Z", "question_score": 1130, "tags": "c#|.net|linq|group-by|aggregate", "answer_id": 847097, "answer_date": "2009-05-11T07:37:04.133Z", "answer_score": 1348 }
Please answer the following Stack Overflow question: Title: Grouping functions (tapply, by, aggregate) and the *apply family <p>Whenever I want to do something "map"py in R, I usually try to use a function in the <code>apply</code> family. </p> <p>However, I've never quite understood the differences between them -- how {<code>sapply</code>, <code>lapply</code>, etc.} apply the function to the input/grouped input, what the output will look like, or even what the input can be -- so I often just go through them all until I get what I want.</p> <p>Can someone explain how to use which one when?</p> <p>My current (probably incorrect/incomplete) understanding is...</p> <ol> <li><p><code>sapply(vec, f)</code>: input is a vector. output is a vector/matrix, where element <code>i</code> is <code>f(vec[i])</code>, giving you a matrix if <code>f</code> has a multi-element output</p></li> <li><p><code>lapply(vec, f)</code>: same as <code>sapply</code>, but output is a list?</p></li> <li><code>apply(matrix, 1/2, f)</code>: input is a matrix. output is a vector, where element <code>i</code> is f(row/col i of the matrix)</li> <li><code>tapply(vector, grouping, f)</code>: output is a matrix/array, where an element in the matrix/array is the value of <code>f</code> at a grouping <code>g</code> of the vector, and <code>g</code> gets pushed to the row/col names</li> <li><code>by(dataframe, grouping, f)</code>: let <code>g</code> be a grouping. apply <code>f</code> to each column of the group/dataframe. pretty print the grouping and the value of <code>f</code> at each column.</li> <li><code>aggregate(matrix, grouping, f)</code>: similar to <code>by</code>, but instead of pretty printing the output, aggregate sticks everything into a dataframe.</li> </ol> <p>Side question: I still haven't learned plyr or reshape -- would <code>plyr</code> or <code>reshape</code> replace all of these entirely?</p>
<p>R has many *apply functions which are ably described in the help files (e.g. <code>?apply</code>). There are enough of them, though, that beginning useRs may have difficulty deciding which one is appropriate for their situation or even remembering them all. They may have a general sense that &quot;I should be using an *apply function here&quot;, but it can be tough to keep them all straight at first.</p> <p>Despite the fact (noted in other answers) that much of the functionality of the *apply family is covered by the extremely popular <code>plyr</code> package, the base functions remain useful and worth knowing.</p> <p>This answer is intended to act as a sort of <strong>signpost</strong> for new useRs to help direct them to the correct *apply function for their particular problem. Note, this is <strong>not</strong> intended to simply regurgitate or replace the R documentation! The hope is that this answer helps you to decide which *apply function suits your situation and then it is up to you to research it further. With one exception, performance differences will not be addressed.</p> <ul> <li><p><strong>apply</strong> - <em>When you want to apply a function to the rows or columns of a matrix (and higher-dimensional analogues); not generally advisable for data frames as it will coerce to a matrix first.</em></p> <pre><code> # Two dimensional matrix M &lt;- matrix(seq(1,16), 4, 4) # apply min to rows apply(M, 1, min) [1] 1 2 3 4 # apply max to columns apply(M, 2, max) [1] 4 8 12 16 # 3 dimensional array M &lt;- array( seq(32), dim = c(4,4,2)) # Apply sum across each M[*, , ] - i.e Sum across 2nd and 3rd dimension apply(M, 1, sum) # Result is one-dimensional [1] 120 128 136 144 # Apply sum across each M[*, *, ] - i.e Sum across 3rd dimension apply(M, c(1,2), sum) # Result is two-dimensional [,1] [,2] [,3] [,4] [1,] 18 26 34 42 [2,] 20 28 36 44 [3,] 22 30 38 46 [4,] 24 32 40 48 </code></pre> <p>If you want row/column means or sums for a 2D matrix, be sure to investigate the highly optimized, lightning-quick <code>colMeans</code>, <code>rowMeans</code>, <code>colSums</code>, <code>rowSums</code>.</p> </li> <li><p><strong>lapply</strong> - <em>When you want to apply a function to each element of a list in turn and get a list back.</em></p> <p>This is the workhorse of many of the other *apply functions. Peel back their code and you will often find <code>lapply</code> underneath.</p> <pre><code> x &lt;- list(a = 1, b = 1:3, c = 10:100) lapply(x, FUN = length) $a [1] 1 $b [1] 3 $c [1] 91 lapply(x, FUN = sum) $a [1] 1 $b [1] 6 $c [1] 5005 </code></pre> </li> <li><p><strong>sapply</strong> - <em>When you want to apply a function to each element of a list in turn, but you want a <strong>vector</strong> back, rather than a list.</em></p> <p>If you find yourself typing <code>unlist(lapply(...))</code>, stop and consider <code>sapply</code>.</p> <pre><code> x &lt;- list(a = 1, b = 1:3, c = 10:100) # Compare with above; a named vector, not a list sapply(x, FUN = length) a b c 1 3 91 sapply(x, FUN = sum) a b c 1 6 5005 </code></pre> <p>In more advanced uses of <code>sapply</code> it will attempt to coerce the result to a multi-dimensional array, if appropriate. For example, if our function returns vectors of the same length, <code>sapply</code> will use them as columns of a matrix:</p> <pre><code> sapply(1:5,function(x) rnorm(3,x)) </code></pre> <p>If our function returns a 2 dimensional matrix, <code>sapply</code> will do essentially the same thing, treating each returned matrix as a single long vector:</p> <pre><code> sapply(1:5,function(x) matrix(x,2,2)) </code></pre> <p>Unless we specify <code>simplify = &quot;array&quot;</code>, in which case it will use the individual matrices to build a multi-dimensional array:</p> <pre><code> sapply(1:5,function(x) matrix(x,2,2), simplify = &quot;array&quot;) </code></pre> <p>Each of these behaviors is of course contingent on our function returning vectors or matrices of the same length or dimension.</p> </li> <li><p><strong>vapply</strong> - <em>When you want to use <code>sapply</code> but perhaps need to squeeze some more speed out of your code or <a href="http://stackoverflow.com/questions/12339650/why-is-vapply-safer-than-sapply/12340888#12340888">want more type safety</a>.</em></p> <p>For <code>vapply</code>, you basically give R an example of what sort of thing your function will return, which can save some time coercing returned values to fit in a single atomic vector.</p> <pre><code> x &lt;- list(a = 1, b = 1:3, c = 10:100) #Note that since the advantage here is mainly speed, this # example is only for illustration. We're telling R that # everything returned by length() should be an integer of # length 1. vapply(x, FUN = length, FUN.VALUE = 0L) a b c 1 3 91 </code></pre> </li> <li><p><strong>mapply</strong> - <em>For when you have several data structures (e.g. vectors, lists) and you want to apply a function to the 1st elements of each, and then the 2nd elements of each, etc., coercing the result to a vector/array as in <code>sapply</code>.</em></p> <p>This is multivariate in the sense that your function must accept multiple arguments.</p> <pre><code> #Sums the 1st elements, the 2nd elements, etc. mapply(sum, 1:5, 1:5, 1:5) [1] 3 6 9 12 15 #To do rep(1,4), rep(2,3), etc. mapply(rep, 1:4, 4:1) [[1]] [1] 1 1 1 1 [[2]] [1] 2 2 2 [[3]] [1] 3 3 [[4]] [1] 4 </code></pre> </li> <li><p><strong>Map</strong> - <em>A wrapper to <code>mapply</code> with <code>SIMPLIFY = FALSE</code>, so it is guaranteed to return a list.</em></p> <pre><code> Map(sum, 1:5, 1:5, 1:5) [[1]] [1] 3 [[2]] [1] 6 [[3]] [1] 9 [[4]] [1] 12 [[5]] [1] 15 </code></pre> </li> <li><p><strong>rapply</strong> - <em>For when you want to apply a function to each element of a <strong>nested list</strong> structure, recursively.</em></p> <p>To give you some idea of how uncommon <code>rapply</code> is, I forgot about it when first posting this answer! Obviously, I'm sure many people use it, but YMMV. <code>rapply</code> is best illustrated with a user-defined function to apply:</p> <pre><code> # Append ! to string, otherwise increment myFun &lt;- function(x){ if(is.character(x)){ return(paste(x,&quot;!&quot;,sep=&quot;&quot;)) } else{ return(x + 1) } } #A nested list structure l &lt;- list(a = list(a1 = &quot;Boo&quot;, b1 = 2, c1 = &quot;Eeek&quot;), b = 3, c = &quot;Yikes&quot;, d = list(a2 = 1, b2 = list(a3 = &quot;Hey&quot;, b3 = 5))) # Result is named vector, coerced to character rapply(l, myFun) # Result is a nested list like l, with values altered rapply(l, myFun, how=&quot;replace&quot;) </code></pre> </li> <li><p><strong>tapply</strong> - <em>For when you want to apply a function to <strong>subsets</strong> of a vector and the subsets are defined by some other vector, usually a factor.</em></p> <p>The black sheep of the *apply family, of sorts. The help file's use of the phrase &quot;ragged array&quot; can be a bit <a href="https://stackoverflow.com/questions/6297201/explain-r-tapply-description/6297396#6297396">confusing</a>, but it is actually quite simple.</p> <p>A vector:</p> <pre><code> x &lt;- 1:20 </code></pre> <p>A factor (of the same length!) defining groups:</p> <pre><code> y &lt;- factor(rep(letters[1:5], each = 4)) </code></pre> <p>Add up the values in <code>x</code> within each subgroup defined by <code>y</code>:</p> <pre><code> tapply(x, y, sum) a b c d e 10 26 42 58 74 </code></pre> <p>More complex examples can be handled where the subgroups are defined by the unique combinations of a list of several factors. <code>tapply</code> is similar in spirit to the split-apply-combine functions that are common in R (<code>aggregate</code>, <code>by</code>, <code>ave</code>, <code>ddply</code>, etc.) Hence its black sheep status.</p> </li> </ul>
{ "question_id": 3505701, "question_date": "2010-08-17T18:31:12.913Z", "question_score": 1130, "tags": "r|lapply|sapply|tapply|r-faq", "answer_id": 7141669, "answer_date": "2011-08-21T22:50:17.290Z", "answer_score": 1420 }
Please answer the following Stack Overflow question: Title: How to escape braces (curly brackets) in a format string in .NET <p>How can brackets be escaped in using <code>string.Format</code>?</p> <p>For example:</p> <pre><code>String val = &quot;1,2,3&quot; String.Format(&quot; foo {{0}}&quot;, val); </code></pre> <p>This example doesn't throw an exception, but it outputs the string <code>foo {0}</code>.</p> <p>Is there a way to escape the brackets?</p>
<p>For you to output <code> foo {1, 2, 3}</code> you have to do something like:</p> <pre><code>string t = &quot;1, 2, 3&quot;; string v = String.Format(&quot; foo {{{0}}}&quot;, t); </code></pre> <p>To output a <code>{</code> you use <code>{{</code> and to output a <code>}</code> you use <code>}}</code>.</p> <p><strong>Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)</strong></p> <p><strong>Escaping brackets: String interpolation $(&quot;&quot;)</strong>. It is new feature in C# 6.0.</p> <pre><code>var inVal = &quot;1, 2, 3&quot;; var outVal = $&quot; foo {{{inVal}}}&quot;; // The output will be: foo {1, 2, 3} </code></pre>
{ "question_id": 91362, "question_date": "2008-09-18T10:04:48.583Z", "question_score": 1130, "tags": "c#|.net|string|parsing|formatting", "answer_id": 91375, "answer_date": "2008-09-18T10:07:35.737Z", "answer_score": 1432 }
Please answer the following Stack Overflow question: Title: jQuery how to find an element based on a data-attribute value? <p>I've got the following scenario:</p> <pre><code>var el = 'li'; </code></pre> <p>and there are 5 <code>&lt;li&gt;</code>'s on the page each with a <code>data-slide=number</code> attribute <em>(number being 1,2,3,4,5 respectively)</em>.</p> <p>I now need to find the currently active slide number which is mapped to <code>var current = $('ul').data(current);</code> and is updated on each slide change.</p> <p>So far my tries have been unsuccessful, trying to construct the selector that would match the current slide:</p> <pre><code>$('ul').find(el+[data-slide=+current+]); </code></pre> <p>does not match/return anything…</p> <p>The reason I can't hardcode the <code>li</code> part is that this is a user accessible variable that can be changed to a different element if required, so it may not always be an <code>li</code>.</p> <p>Any ideas on what I'm missing?</p>
<p>You have to inject the value of <code>current</code> into an <a href="http://api.jquery.com/attribute-equals-selector/" rel="noreferrer">Attribute Equals</a> selector:</p> <pre class="lang-js prettyprint-override"><code>$(&quot;ul&quot;).find(`[data-slide='${current}']`) </code></pre> <p>For older JavaScript environments (<strong>ES5</strong> and earlier):</p> <pre class="lang-js prettyprint-override"><code>$(&quot;ul&quot;).find(&quot;[data-slide='&quot; + current + &quot;']&quot;); </code></pre>
{ "question_id": 4191386, "question_date": "2010-11-16T05:11:28.920Z", "question_score": 1129, "tags": "jquery|jquery-selectors|custom-data-attribute", "answer_id": 4191718, "answer_date": "2010-11-16T06:30:48.540Z", "answer_score": 1686 }
Please answer the following Stack Overflow question: Title: How to install a previous exact version of a NPM package? <p>I used nvm to download node v0.4.10 and installed npm to work with that version of node. </p> <p>I am trying to install express using </p> <pre><code>npm install express -g </code></pre> <p>and I get an error that express requires node version >= 0.5.0. </p> <p>Well, this is odd, since I am following the directions for a node+express+mongodb tutorial <a href="http://howtonode.org/e84d3e8548d86d90eb82878e4d71dc21f4d63b93/express-mongodb" rel="noreferrer">here</a> that used node v0.4.10, so I am assuming express is/was available to node v0.4.10. If my assumption is correct, how do I tell npm to fetch a version that would work with my setup?</p>
<p>If you have to install an older version of a package, just specify it</p> <pre><code>npm install &lt;package&gt;@&lt;version&gt; </code></pre> <p>For example: <code>npm install [email protected]</code></p> <p>You can also add the <code>--save</code> flag to that command to add it to your package.json dependencies, or <code>--save --save-exact</code> flags if you want that exact version specified in your package.json dependencies.</p> <p>The <code>install</code> command is documented here: <a href="https://docs.npmjs.com/cli/install">https://docs.npmjs.com/cli/install</a></p> <p>If you're not sure what versions of a package are available, you can use:</p> <pre><code>npm view &lt;package&gt; versions </code></pre> <p>And <code>npm view</code> can be used for viewing other things about a package too. <a href="https://docs.npmjs.com/cli/view">https://docs.npmjs.com/cli/view</a></p>
{ "question_id": 15890958, "question_date": "2013-04-08T23:44:51.723Z", "question_score": 1129, "tags": "node.js|npm", "answer_id": 15892076, "answer_date": "2013-04-09T02:01:25.773Z", "answer_score": 1881 }
Please answer the following Stack Overflow question: Title: How to install an npm package from GitHub directly <p>Trying to install modules from GitHub results in this error:</p> <blockquote> <p>ENOENT error on package.json.</p> </blockquote> <p>Easily reproduced using express:</p> <p><code>npm install https://github.com/visionmedia/express</code> throws error.</p> <p><code>npm install express </code> works.</p> <p>Why can't I install from GitHub?</p> <p>Here is the console output:</p> <pre><code>npm http GET https://github.com/visionmedia/express.git npm http 200 https://github.com/visionmedia/express.git npm ERR! not a package /home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/tmp.tgz npm ERR! Error: ENOENT, open '/home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/package/package.json' npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;[email protected]&gt; npm ERR! System Linux 3.8.0-23-generic npm ERR! command &quot;/usr/bin/node&quot; &quot;/usr/bin/npm&quot; &quot;install&quot; &quot;https://github.com/visionmedia/express.git&quot; npm ERR! cwd /home/guym/dev_env/projects_GIT/proj/somename npm ERR! node -v v0.10.10 npm ERR! npm -v 1.2.25 npm ERR! path /home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/package/package.json npm ERR! code ENOENT npm ERR! errno 34 npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /home/guym/dev_env/projects_GIT/proj/somename/npm-debug.log npm ERR! not ok code 0 </code></pre>
<p>Because <code>https://github.com/visionmedia/express</code> is the URL of a web page and not an npm module. Use this flavor: <code>git+{url}.git</code></p> <pre class="lang-none prettyprint-override"><code>git+https://github.com/visionmedia/express.git </code></pre> <p>or this flavor if you need SSH:</p> <pre class="lang-none prettyprint-override"><code>git+ssh://[email protected]/visionmedia/express.git </code></pre>
{ "question_id": 17509669, "question_date": "2013-07-07T05:55:03.693Z", "question_score": 1129, "tags": "github|npm|npm-install|node-modules", "answer_id": 17509764, "answer_date": "2013-07-07T06:19:15.943Z", "answer_score": 1454 }
Please answer the following Stack Overflow question: Title: How can I center text (horizontally and vertically) inside a div block? <p>I have a <code>div</code> set to <code>display:block</code> (<code>90px</code> <code>height</code> and <code>width</code>), and I have some text inside.</p> <p>I need the text to be aligned in the center both vertically and horizontally.</p> <p>I have tried <code>text-align:center</code>, but it doesn't do the vertical centering part, so I tried <code>vertical-align:middle</code>, but it didn't work.</p> <p>Any ideas?</p>
<p>If it is one line of text and/or image, then it is easy to do. Just use:</p> <pre><code>text-align: center; vertical-align: middle; line-height: 90px; /* The same as your div height */ </code></pre> <p>That's it. If it can be multiple lines, then it is somewhat more complicated. But there are solutions on <a href="http://pmob.co.uk/" rel="noreferrer">http://pmob.co.uk/</a>. Look for "vertical align".</p> <p>Since they tend to be hacks or adding complicated divs... I usually use a table with a single cell to do it... to make it as simple as possible.</p> <hr> <h1>Update for 2020:</h1> <p>Unless you need make it work on earlier browsers such as Internet Explorer 10, you can use flexbox. It is <a href="https://caniuse.com/#feat=flexbox" rel="noreferrer">widely supported by all current major browsers</a>. Basically, the container needs to be specified as a flex container, together with centering along its main and cross axis:</p> <pre><code>#container { display: flex; justify-content: center; align-items: center; } </code></pre> <p>To specify a fixed width for the child, which is called a "flex item":</p> <pre><code>#content { flex: 0 0 120px; } </code></pre> <p>Example: <a href="http://jsfiddle.net/2woqsef1/1/" rel="noreferrer">http://jsfiddle.net/2woqsef1/1/</a></p> <p>To shrink-wrap the content, it is even simpler: just remove the <code>flex: ...</code> line from the flex item, and it is automatically shrink-wrapped.</p> <p>Example: <a href="http://jsfiddle.net/2woqsef1/2/" rel="noreferrer">http://jsfiddle.net/2woqsef1/2/</a></p> <p>The examples above have been tested on major browsers including MS Edge and Internet Explorer 11.</p> <p>One technical note if you need to customize it: inside of the flex item, since this flex item is not a flex container itself, the old non-flexbox way of CSS works as expected. However, if you add an additional flex item to the current flex container, the two flex items will be horizontally placed. To make them vertically placed, add the <code>flex-direction: column;</code> to the flex container. This is how it works between a flex container and its <strong>immediate</strong> child elements.</p> <p>There is an alternative method of doing the centering: by not specifying <code>center</code> for the distribution on the main and cross axis for the flex container, but instead specify <code>margin: auto</code> on the flex item to take up all extra space in all four directions, and the evenly distributed margins will make the flex item centered in all directions. This works except when there are multiple flex items. Also, this technique works on MS Edge but not on Internet Explorer 11.</p> <hr> <h1>Update for 2016 / 2017:</h1> <p>It can be more commonly done with <code>transform</code>, and it works well even in older browsers such as Internet&nbsp;Explorer&nbsp;10 and Internet&nbsp;Explorer&nbsp;11. It can support multiple lines of text:</p> <pre><code>position: relative; top: 50%; transform: translateY(-50%); </code></pre> <p>Example: <a href="https://jsfiddle.net/wb8u02kL/1/" rel="noreferrer">https://jsfiddle.net/wb8u02kL/1/</a></p> <h2>To shrink-wrap the width:</h2> <p>The solution above used a fixed width for the content area. To use a shrink-wrapped width, use</p> <pre><code>position: relative; float: left; top: 50%; left: 50%; transform: translate(-50%, -50%); </code></pre> <p>Example: <a href="https://jsfiddle.net/wb8u02kL/2/" rel="noreferrer">https://jsfiddle.net/wb8u02kL/2/</a></p> <p>If the support for Internet&nbsp;Explorer&nbsp;10 is needed, then flexbox won't work and the method above and the <code>line-height</code> method would work. Otherwise, flexbox would do the job.</p>
{ "question_id": 5703552, "question_date": "2011-04-18T13:22:47.147Z", "question_score": 1128, "tags": "html|css", "answer_id": 5703632, "answer_date": "2011-04-18T13:29:31.440Z", "answer_score": 1847 }
Please answer the following Stack Overflow question: Title: Should I put #! (shebang) in Python scripts, and what form should it take? <p>Should I put the shebang in my Python scripts? In what form?</p> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python </code></pre> <p>or</p> <pre class="lang-none prettyprint-override"><code>#!/usr/local/bin/python </code></pre> <p>Are these equally portable? Which form is used most?</p> <p><strong><em>Note:</em></strong> the <a href="https://github.com/facebook/tornado" rel="noreferrer">tornado</a> project uses the shebang. On the other hand the <a href="https://www.djangoproject.com/" rel="noreferrer">Django</a> project doesn't.</p>
<p>The shebang line in any script determines the script's ability to be executed like a standalone executable without typing <code>python</code> beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use <em>is</em> important.</p> <p><strong>Correct</strong> usage for (defaults to version 3.latest) <strong>Python 3</strong> scripts is:</p> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python3 </code></pre> <p><strong>Correct</strong> usage for (defaults to version 2.latest) <strong>Python 2</strong> scripts is:</p> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python2 </code></pre> <p>The following <strong>should <em>not</em> be used</strong> (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):</p> <pre class="lang-none prettyprint-override"><code>#!/usr/bin/env python </code></pre> <p>The reason for these recommendations, given in <a href="https://www.python.org/dev/peps/pep-0394/#recommendation" rel="noreferrer" title="PEP 394">PEP 394</a>, is that <code>python</code> can refer either to <code>python2</code> or <code>python3</code> on different systems.</p> <p><strong>Also, do not use:</strong></p> <pre class="lang-none prettyprint-override"><code>#!/usr/local/bin/python </code></pre> <blockquote> <p>&quot;python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail.&quot;</p> </blockquote> <p>―<a href="https://mail.python.org/pipermail/tutor/2007-June/054816.html" rel="noreferrer">&quot;#!/usr/bin/env python&quot; vs &quot;#!/usr/local/bin/python&quot;</a></p>
{ "question_id": 6908143, "question_date": "2011-08-02T06:35:42.583Z", "question_score": 1128, "tags": "python|shell|python-3.x|shebang", "answer_id": 19305076, "answer_date": "2013-10-10T19:58:55.773Z", "answer_score": 1540 }
Please answer the following Stack Overflow question: Title: Assigning default values to shell variables with a single command in bash <p>I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:</p> <pre><code>if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi </code></pre> <p>I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:</p> <pre><code>FOO=${ ${VARIABLE} : 'default' } </code></pre> <p>(though I know that won't work...)</p> <p>Am I crazy, or does something like that exist?</p>
<p>Very close to what you posted, actually. You can use something called <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Bash parameter expansion</a> to accomplish this.</p> <p>To get the assigned value, or <code>default</code> if it's missing:</p> <pre><code>FOO=&quot;${VARIABLE:-default}&quot; # If variable not set or null, use default. # If VARIABLE was unset or null, it still is after this (no assignment done). </code></pre> <p>Or to assign <code>default</code> to <code>VARIABLE</code> at the same time:</p> <pre><code>FOO=&quot;${VARIABLE:=default}&quot; # If variable not set or null, set it to default. </code></pre>
{ "question_id": 2013547, "question_date": "2010-01-06T14:29:31.193Z", "question_score": 1128, "tags": "bash|shell", "answer_id": 2013589, "answer_date": "2010-01-06T14:36:56.187Z", "answer_score": 2022 }
Please answer the following Stack Overflow question: Title: How do I install a Python package with a .whl file? <p>I'm having trouble installing a Python package on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installations). However, only .whl files are available.</p> <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype" rel="noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype</a></p> <p>But how do I install .whl files?</p> <h2>Notes</h2> <ul> <li>I've found <a href="https://wheel.readthedocs.org/en/latest/" rel="noreferrer">documents on wheel</a>, but they don't seem so staightforward in explaining how to install .whl files.</li> <li>This question is a duplicate with <a href="https://stackoverflow.com/questions/27041264/how-to-install-whl-file-in-python-windows">this question</a>, which wasn't directly answered.</li> </ul>
<p>I just used the following which was quite simple. First open a console then cd to where you've downloaded your file like some-package.whl and use</p> <pre><code>pip install some-package.whl </code></pre> <p>Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. If pip is not installed, this page can help: <a href="https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows">How do I install pip on Windows?</a></p> <p><em>Note: for clarification</em><br> If you copy the <code>*.whl</code> file to your local drive (ex. <strong>C:\some-dir\some-file.whl</strong>) use the following command line parameters -- </p> <pre><code>pip install C:/some-dir/some-file.whl </code></pre>
{ "question_id": 27885397, "question_date": "2015-01-11T08:48:34.620Z", "question_score": 1127, "tags": "python|pip|python-wheel|jpype", "answer_id": 27909082, "answer_date": "2015-01-12T19:12:41.927Z", "answer_score": 1344 }
Please answer the following Stack Overflow question: Title: What are "named tuples" in Python? <ul> <li>What are named tuples and how do I use them?</li> <li>When should I use named tuples instead of normal tuples, or vice versa?</li> <li>Are there &quot;named lists&quot; too? (i.e. mutable named tuples)</li> </ul>
<p>Named tuples are basically easy-to-create, lightweight object types. Named tuple instances can be referenced using object-like variable dereferencing or the standard tuple syntax. They can be used similarly to <code>struct</code> or other common record types, except that they are immutable. They were added in Python 2.6 and Python 3.0, although there is a <a href="http://code.activestate.com/recipes/500261/" rel="noreferrer">recipe for implementation in Python 2.4</a>.</p> <p>For example, it is common to represent a point as a tuple <code>(x, y)</code>. This leads to code like the following:</p> <pre><code>pt1 = (1.0, 5.0) pt2 = (2.5, 1.5) from math import sqrt line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2) </code></pre> <p>Using a named tuple it becomes more readable:</p> <pre><code>from collections import namedtuple Point = namedtuple('Point', 'x y') pt1 = Point(1.0, 5.0) pt2 = Point(2.5, 1.5) from math import sqrt line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2) </code></pre> <p>However, named tuples are still backwards compatible with normal tuples, so the following will still work:</p> <pre><code>Point = namedtuple('Point', 'x y') pt1 = Point(1.0, 5.0) pt2 = Point(2.5, 1.5) from math import sqrt # use index referencing line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2) # use tuple unpacking x1, y1 = pt1 </code></pre> <p>Thus, <strong>you should use named tuples instead of tuples anywhere you think object notation will make your code more pythonic and more easily readable</strong>. I personally have started using them to represent very simple value types, particularly when passing them as parameters to functions. It makes the functions more readable, without seeing the context of the tuple packing.</p> <p>Furthermore, <strong>you can also replace ordinary <em>immutable</em> classes that have no functions</strong>, only fields with them. You can even use your named tuple types as base classes:</p> <pre><code>class Point(namedtuple('Point', 'x y')): [...] </code></pre> <p>However, as with tuples, attributes in named tuples are immutable:</p> <pre><code>&gt;&gt;&gt; Point = namedtuple('Point', 'x y') &gt;&gt;&gt; pt1 = Point(1.0, 5.0) &gt;&gt;&gt; pt1.x = 2.0 AttributeError: can't set attribute </code></pre> <p>If you want to be able change the values, you need another type. There is a handy recipe for <a href="http://code.activestate.com/recipes/576555/" rel="noreferrer">mutable recordtypes</a> which allow you to set new values to attributes.</p> <pre><code>&gt;&gt;&gt; from rcdtype import * &gt;&gt;&gt; Point = recordtype('Point', 'x y') &gt;&gt;&gt; pt1 = Point(1.0, 5.0) &gt;&gt;&gt; pt1 = Point(1.0, 5.0) &gt;&gt;&gt; pt1.x = 2.0 &gt;&gt;&gt; print(pt1[0]) 2.0 </code></pre> <p>I am not aware of any form of "named list" that lets you add new fields, however. You may just want to use a dictionary in this situation. Named tuples can be converted to dictionaries using <code>pt1._asdict()</code> which returns <code>{'x': 1.0, 'y': 5.0}</code> and can be operated upon with all the usual dictionary functions. </p> <p>As already noted, you should <a href="http://docs.python.org/py3k/library/collections.html?highlight=namedtuple#collections.namedtuple" rel="noreferrer">check the documentation</a> for more information from which these examples were constructed.</p>
{ "question_id": 2970608, "question_date": "2010-06-03T23:50:16.897Z", "question_score": 1126, "tags": "python|tuples|namedtuple", "answer_id": 2970722, "answer_date": "2010-06-04T00:19:37.743Z", "answer_score": 1417 }
Please answer the following Stack Overflow question: Title: How to initialize all members of an array to the same value? <p>I have a large array in <strong>C</strong> (not <strong>C++</strong> if that makes a difference). I want to initialize all members of the same value.</p> <p>I could swear I once knew a simple way to do this. I could use <code>memset()</code> in my case, but isn't there a way to do this that is built right into the C syntax?</p>
<p>Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.</p> <p>Don't overlook the obvious solution, though:</p> <pre><code>int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; </code></pre> <p>Elements with missing values will be initialized to 0:</p> <pre><code>int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0... </code></pre> <p>So this will initialize all elements to 0:</p> <pre><code>int myArray[10] = { 0 }; // all elements 0 </code></pre> <p>In C++, an empty initialization list will also initialize every element to 0. This is <a href="https://stackoverflow.com/a/17589839">not allowed</a> with C until C23:</p> <pre><code>int myArray[10] = {}; // all elements 0 in C++ and C23 </code></pre> <p>Remember that objects with static storage duration will initialize to 0 if no initializer is specified:</p> <pre><code>static int myArray[10]; // all elements 0 </code></pre> <p>And that &quot;0&quot; doesn't necessarily mean &quot;all-bits-zero&quot;, so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)</p>
{ "question_id": 201101, "question_date": "2008-10-14T13:13:40.783Z", "question_score": 1125, "tags": "c|arrays|initialization|array-initialize", "answer_id": 201116, "answer_date": "2008-10-14T13:17:23.130Z", "answer_score": 1431 }
Please answer the following Stack Overflow question: Title: Does functional programming replace GoF design patterns? <p>Since I started learning <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Objective_Caml" rel="noreferrer">OCaml</a> last year, I've read a huge number of articles which insist that design patterns (especially in Java) are workarounds for the missing features in imperative languages. One article I found <a href="http://www.defmacro.org/ramblings/fp.html" rel="noreferrer">makes a fairly strong claim</a>:</p> <blockquote> <p>Most people I've met have read <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="noreferrer">the Design Patterns book</a> by the Gang of Four (GoF). Any self respecting programmer will tell you that the book is language agnostic and the patterns apply to software engineering in general, regardless of which language you use. This is a noble claim. Unfortunately it is far removed from the truth.</p> <p>Functional languages are extremely expressive. <strong>In a functional language one does not need design patterns because the language is likely so high level, you end up programming in concepts that eliminate design patterns all together.</strong></p> </blockquote> <p>The main features of functional programming (FP) include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.</p> <p>Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml every day, and there are no striking differences between the patterns I use in these languages vs. the patterns I use when I write in Java.</p> <p>Is there any truth to the claim that functional programming eliminates the need for OOP design patterns? If so, could you post or link to an example of a typical OOP design pattern and its functional equivalent?</p>
<p>The blog post you quoted overstates its claim a bit. FP doesn't <em>eliminate</em> the need for design patterns. The term "design patterns" just isn't widely used to describe the same thing in FP languages. But they exist. Functional languages have plenty of best practice rules of the form "when you encounter problem X, use code that looks like Y", which is basically what a design pattern is.</p> <p>However, it's correct that most OOP-specific design patterns are pretty much irrelevant in functional languages.</p> <p>I don't think it should be particularly controversial to say that design patterns <em>in general</em> only exist to patch up shortcomings in the language. And if another language can solve the same problem trivially, that other language won't have need of a design pattern for it. Users of that language may not even be aware that the problem <em>exists</em>, because, well, it's not a problem in that language.</p> <p>Here is what the Gang of Four has to say about this issue:</p> <blockquote> <p>The choice of programming language is important because it influences one's point of view. Our patterns assume Smalltalk/C++-level language features, and that choice determines what can and cannot be implemented easily. If we assumed procedural languages, we might have included design patterns called "Inheritance", "Encapsulation," and "Polymorphism". Similarly, some of our patterns are supported directly by the less common object-oriented languages. CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor. In fact, there are enough differences between Smalltalk and C++ to mean that some patterns can be expressed more easily in one language than the other. (See Iterator for example.)</p> </blockquote> <p>(The above is a quote from the Introduction to the Design Patterns book, page 4, paragraph 3)</p> <blockquote> <p>The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.</p> </blockquote> <p>What is the command pattern, if not an approximation of first-class functions? :) In an FP language, you'd simply pass a function as the argument to another function. In an OOP language, you have to wrap up the function in a class, which you can instantiate and then pass that object to the other function. The effect is the same, but in OOP it's called a design pattern, and it takes a whole lot more code. And what is the abstract factory pattern, if not currying? Pass parameters to a function a bit at a time, to configure what kind of value it spits out when you finally call it.</p> <p>So yes, several GoF design patterns are rendered redundant in FP languages, because more powerful and easier to use alternatives exist.</p> <p>But of course there are still design patterns which are <em>not</em> solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use.)</p> <p>And it works both ways too. As I said, FP has its design patterns too; people just don't usually think of them as such.</p> <p>But you may have run across monads. What are they, if not a design pattern for "dealing with global state"? That's a problem that's so simple in OOP languages that no equivalent design pattern exists there.</p> <p>We don't need a design pattern for "increment a static variable", or "read from that socket", because it's just what you <em>do</em>.</p> <p>Saying a monad is a design pattern is as absurd as saying the Integers with their usual operations and zero element is a design pattern. No, a monad is a <strong>mathematical pattern</strong>, not a design pattern.</p> <p>In (pure) functional languages, side effects and mutable state are impossible, unless you work around it with the monad "design pattern", or any of the other methods for allowing the same thing.</p> <blockquote> <p>Additionally, in functional languages which support OOP (such as F# and OCaml), it seems obvious to me that programmers using these languages would use the same design patterns found available to every other OOP language. In fact, right now I use F# and OCaml everyday, and there are no striking differences between the patterns I use in these languages vs the patterns I use when I write in Java.</p> </blockquote> <p>Perhaps because you're still thinking imperatively? A lot of people, after dealing with imperative languages all their lives, have a hard time giving up on that habit when they try a functional language. (I've seen some pretty funny attempts at F#, where literally <em>every</em> function was just a string of 'let' statements, basically as if you'd taken a C program, and replaced all semicolons with 'let'. :))</p> <p>But another possibility might be that you just haven't realized that you're solving problems trivially which would require design patterns in an OOP language.</p> <p>When you use currying, or pass a function as an argument to another, stop and think about how you'd do that in an OOP language.</p> <blockquote> <p>Is there any truth to the claim that functional programming eliminates the need for OOP design patterns?</p> </blockquote> <p>Yep. :) When you work in a FP language, you no longer need the OOP-specific design patterns. But you still need some general design patterns, like MVC or other non-OOP specific stuff, and you need a couple of new FP-specific "design patterns" instead. All languages have their shortcomings, and design patterns are usually how we work around them.</p> <p>Anyway, you may find it interesting to try your hand at "cleaner" FP languages, like <a href="https://en.wikipedia.org/wiki/ML_(programming_language)" rel="noreferrer">ML</a> (my personal favorite, at least for learning purposes), or <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a>, where you don't have the OOP crutch to fall back on when you're faced with something new.</p> <hr> <p>As expected, a few people objected to my definition of design patterns as "patching up shortcomings in a language", so here's my justification:</p> <p>As already said, most design patterns are specific to one programming paradigm, or sometimes even one specific language. Often, they solve problems that only <em>exist</em> in that paradigm (see monads for FP, or abstract factories for OOP).</p> <p>Why doesn't the abstract factory pattern exist in FP? Because the problem it tries to solve does not exist there.</p> <p>So, if a problem exists in OOP languages, which does not exist in FP languages, then clearly that is a shortcoming of OOP languages. The problem can be solved, but your language does not do so, but requires a bunch of boilerplate code from you to work around it. Ideally, we'd like our programming language to magically make <em>all</em> problems go away. Any problem that is still there is in principle a shortcoming of the language. ;)</p>
{ "question_id": 327955, "question_date": "2008-11-29T20:08:46.620Z", "question_score": 1125, "tags": "oop|design-patterns|functional-programming", "answer_id": 328146, "answer_date": "2008-11-29T23:06:35.450Z", "answer_score": 1154 }
Please answer the following Stack Overflow question: Title: R cannot be resolved - Android error <p>I just downloaded and installed the new Android SDK. I wanted to create a simple application to test drive it.</p> <p>The wizard created this code:</p> <pre><code>package eu.mauriziopz.gps; import android.app.Activity; import android.os.Bundle; public class ggps extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } </code></pre> <p>but <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> gives me the error</p> <blockquote> <p>R cannot be resolved</p> </blockquote> <p>on line</p> <pre><code>setContentView(R.layout.main); </code></pre> <p>Why?</p> <p>PS: I do have an XML file named <code>main.xml</code> under <code>res/layout/</code>.</p>
<p>What Will said was right</p> <blockquote> <p>R is an automatically generated class that holds the constants used to identify your >resources. If you don't have an R.java file (it would be gen/eu.mauriziopz.gps/R.java in >Eclipse with the 1.5 SDK) I would recommend closing and reopening your project or going to >Project > Build all (and selecting "Build Automatically" while there as recommended by >Josef). If that doesn't work than try making a new project, if the problem is recreated than >post here again and we'll go into more detail.</p> </blockquote> <p>but I've found out that there was another problem that was causing the first one. The tools in the SDK directory didn't have the permissions to be executed, so it was like the didn't exist for Eclipse, thus it didn't build the <code>R.java</code> file.</p> <p>So modifying the permission and selecting "Build Automatically" solved the problem.</p>
{ "question_id": 885009, "question_date": "2009-05-19T21:02:20.117Z", "question_score": 1124, "tags": "android|eclipse|compiler-errors|android-resources|android-sdk-tools", "answer_id": 886494, "answer_date": "2009-05-20T06:54:33.817Z", "answer_score": 89 }
Please answer the following Stack Overflow question: Title: Best way to remove an event handler in jQuery? <p>I have an <code>input type="image"</code>. This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this <code>input-image</code> is paired with, I setup an event handler for the <code>input-image</code>. Then when the user clicks the <code>image</code>, they get a little popup to add some notes to the data.</p> <p>My problem is that when a user enters a zero into the text box, I need to disable the <code>input-image</code>'s event handler. I have tried the following, but to no avail.</p> <pre><code>$('#myimage').click(function { return false; }); </code></pre>
<h2>jQuery ≥ 1.7</h2> <p>With jQuery 1.7 onward the event API has been updated, <code>.bind()</code>/<code>.unbind()</code> are still available for backwards compatibility, but the preferred method is using the <a href="http://api.jquery.com/on/" rel="noreferrer">on()</a>/<a href="http://api.jquery.com/off/" rel="noreferrer">off()</a> functions. The below would now be,</p> <pre><code>$('#myimage').click(function() { return false; }); // Adds another click event $('#myimage').off('click'); $('#myimage').on('click.mynamespace', function() { /* Do stuff */ }); $('#myimage').off('click.mynamespace'); </code></pre> <hr> <h2>jQuery &lt; 1.7</h2> <p>In your example code you are simply adding another click event to the image, not overriding the previous one:</p> <pre><code>$('#myimage').click(function() { return false; }); // Adds another click event </code></pre> <p>Both click events will then get fired.</p> <p>As people have said you can use unbind to remove all click events:</p> <pre><code>$('#myimage').unbind('click'); </code></pre> <p>If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:</p> <pre><code>$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ }); </code></pre> <p>and to remove just your event:</p> <pre><code>$('#myimage').unbind('click.mynamespace'); </code></pre>
{ "question_id": 209029, "question_date": "2008-10-16T15:28:47.933Z", "question_score": 1124, "tags": "jquery|html-input", "answer_id": 210345, "answer_date": "2008-10-16T21:13:55.117Z", "answer_score": 1753 }
Please answer the following Stack Overflow question: Title: How do you test that a Python function throws an exception? <p>How does one write a unittest that fails only if a function doesn't throw an expected exception?</p>
<p>Use <a href="http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises" rel="noreferrer"><code>TestCase.assertRaises</code></a> (or <code>TestCase.failUnlessRaises</code>) from the unittest module, for example:</p> <pre><code>import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc) </code></pre>
{ "question_id": 129507, "question_date": "2008-09-24T20:00:35.597Z", "question_score": 1124, "tags": "python|unit-testing|exception", "answer_id": 129522, "answer_date": "2008-09-24T20:02:29.600Z", "answer_score": 924 }
Please answer the following Stack Overflow question: Title: Why use Redux over Facebook Flux? <p>I've read <a href="https://stackoverflow.com/questions/32021763/what-could-be-the-downsides-of-using-redux-instead-of-flux">this answer</a>, <a href="http://redux.js.org/docs/recipes/ReducingBoilerplate.html" rel="noreferrer">reducing boilerplate</a>, looked at few GitHub examples and even tried redux a little bit (todo apps). </p> <p>As I understand, <a href="http://redux.js.org/docs/introduction/Motivation.html" rel="noreferrer">official redux doc motivations</a> provide pros comparing to traditional MVC architectures. BUT it doesn't provide an answer to the question: </p> <p><strong>Why you should use Redux over Facebook Flux?</strong> </p> <p><em>Is that only a question of programming styles: functional vs non-functional? Or the question is in abilities/dev-tools that follow from redux approach? Maybe scaling? Or testing?</em></p> <p><em>Am I right if I say that redux is a flux for people who come from functional languages?</em> </p> <p><strong>To answer this question you may compare the complexity of implementation redux's motivation points on flux vs redux.</strong></p> <p>Here are motivation points from <a href="http://redux.js.org/docs/introduction/Motivation.html" rel="noreferrer">official redux doc motivations</a>:</p> <ol> <li>Handling optimistic updates (<em>as I understand, it hardly depends on 5th point. Is it hard to implement it in facebook flux?</em>)</li> <li>Rendering on the server (<em>facebook flux also can do this. Any benefits comparing to redux?</em>)</li> <li>Fetching data before performing route transitions (<em>Why it can't be achieved in facebook flux? What's the benefits?</em>)</li> <li>Hot reload (<em>It's possible with <a href="http://gaearon.github.io/react-hot-loader/" rel="noreferrer">React Hot Reload</a>. Why do we need redux?</em>)</li> <li>Undo/Redo functionality</li> <li>Any other points? Like persisting state...</li> </ol>
<p>Redux author here! </p> <p>Redux is not <em>that</em> different from Flux. Overall it has same architecture, but Redux is able to cut some complexity corners by using functional composition where Flux uses callback registration.</p> <p>There is not a fundamental difference in Redux, but I find it makes certain abstractions easier, or at least possible to implement, that would be hard or impossible to implement in Flux.</p> <h2>Reducer Composition</h2> <p>Take, for example, pagination. My <a href="https://github.com/gaearon/flux-react-router-example" rel="noreferrer">Flux + React Router example</a> handles pagination, but the code for that is awful. One of the reasons it's awful is that <strong>Flux makes it unnatural to reuse functionality across stores.</strong> If two stores need to handle pagination in response to different actions, they either need to inherit from a common base store (bad! you're locking yourself into a particular design when you use inheritance), or call an externally defined function from within the event handler, which will need to somehow operate on the Flux store's private state. The whole thing is messy (although definitely in the realm of possible).</p> <p>On the other hand, with Redux pagination is natural thanks to reducer composition. It's reducers all the way down, so you can write a <a href="https://github.com/reactjs/redux/blob/ecb1bb453a60408543f5760bba0aa4c767650ba2/examples/real-world/reducers/paginate.js" rel="noreferrer">reducer factory that generates pagination reducers</a> and then <a href="https://github.com/reactjs/redux/blob/ecb1bb453a60408543f5760bba0aa4c767650ba2/examples/real-world/reducers/index.js#L29-L46" rel="noreferrer">use it in your reducer tree</a>. The key to why it's so easy is because <strong>in Flux, stores are flat, but in Redux, reducers can be nested via functional composition, just like React components can be nested.</strong></p> <p>This pattern also enables wonderful features like no-user-code <a href="https://github.com/omnidan/redux-undo" rel="noreferrer">undo/redo</a>. <strong>Can you imagine plugging Undo/Redo into a Flux app being two lines of code? Hardly. With Redux, it is</strong>—again, thanks to reducer composition pattern. I need to highlight there's nothing new about it—this is the pattern pioneered and described in detail in <a href="https://github.com/evancz/elm-architecture-tutorial/" rel="noreferrer">Elm Architecture</a> which was itself influenced by Flux.</p> <h2>Server Rendering</h2> <p>People have been rendering on the server fine with Flux, but seeing that we have 20 Flux libraries each attempting to make server rendering “easier”, perhaps Flux has some rough edges on the server. The truth is Facebook doesn't do much server rendering, so they haven't been very concerned about it, and rely on the ecosystem to make it easier.</p> <p>In traditional Flux, stores are singletons. This means it's hard to separate the data for different requests on the server. Not impossible, but hard. This is why most Flux libraries (as well as the new <a href="https://facebook.github.io/flux/docs/flux-utils.html" rel="noreferrer">Flux Utils</a>) now suggest you use classes instead of singletons, so you can instantiate stores per request.</p> <p>There are still the following problems that you need to solve in Flux (either yourself or with the help of your favorite Flux library such as <a href="https://github.com/acdlite/flummox" rel="noreferrer">Flummox</a> or <a href="https://github.com/goatslacker/alt" rel="noreferrer">Alt</a>):</p> <ul> <li>If stores are classes, how do I create and destroy them with dispatcher per request? When do I register stores?</li> <li>How do I hydrate the data from the stores and later rehydrate it on the client? Do I need to implement special methods for this?</li> </ul> <p>Admittedly Flux frameworks (not vanilla Flux) have solutions to these problems, but I find them overcomplicated. For example, <a href="http://acdlite.github.io/flummox/docs/api/store" rel="noreferrer">Flummox asks you to implement <code>serialize()</code> and <code>deserialize()</code> in your stores</a>. Alt solves this nicer by providing <a href="http://alt.js.org/docs/takeSnapshot/" rel="noreferrer"><code>takeSnapshot()</code></a> that automatically serializes your state in a JSON tree.</p> <p>Redux just goes further: <strong>since there is just a single store (managed by many reducers), you don't need any special API to manage the (re)hydration.</strong> You don't need to “flush” or “hydrate” stores—there's just a single store, and you can read its current state, or create a new store with a new state. Each request gets a separate store instance. <a href="http://redux.js.org/docs/recipes/ServerRendering.html" rel="noreferrer">Read more about server rendering with Redux.</a></p> <p>Again, this is a case of something possible both in Flux and Redux, but Flux libraries solve this problem by introducing a ton of API and conventions, and Redux doesn't even have to solve it because it doesn't have that problem in the first place thanks to conceptual simplicity.</p> <h2>Developer Experience</h2> <p>I didn't actually intend Redux to become a popular Flux library—I wrote it as I was working on my <a href="http://youtube.com/watch?v=xsSnOQynTHs" rel="noreferrer">ReactEurope talk on hot reloading with time travel</a>. I had one main objective: <strong>make it possible to change reducer code on the fly or even “change the past” by crossing out actions, and see the state being recalculated.</strong></p> <p><img src="https://camo.githubusercontent.com/a0d66cf145fe35cbe5fb341494b04f277d5d85dd/687474703a2f2f692e696d6775722e636f6d2f4a34476557304d2e676966" alt=""></p> <p>I haven't seen a single Flux library that is able to do this. React Hot Loader also doesn't let you do this—in fact it breaks if you edit Flux stores because it doesn't know what to do with them.</p> <p>When Redux needs to reload the reducer code, it calls <a href="http://redux.js.org/docs/api/Store.html#replaceReducer" rel="noreferrer"><code>replaceReducer()</code></a>, and the app runs with the new code. In Flux, data and functions are entangled in Flux stores, so you can't “just replace the functions”. Moreover, you'd have to somehow re-register the new versions with the Dispatcher—something Redux doesn't even have.</p> <h2>Ecosystem</h2> <p>Redux has a <a href="https://github.com/xgrommx/awesome-redux" rel="noreferrer">rich and fast-growing ecosystem</a>. This is because it provides a few extension points such as <a href="http://redux.js.org/docs/advanced/Middleware.html" rel="noreferrer">middleware</a>. It was designed with use cases such as <a href="https://github.com/fcomb/redux-logger" rel="noreferrer">logging</a>, support for <a href="https://github.com/acdlite/redux-promise" rel="noreferrer">Promises</a>, <a href="https://github.com/acdlite/redux-rx" rel="noreferrer">Observables</a>, <a href="https://github.com/reactjs/react-router-redux" rel="noreferrer">routing</a>, <a href="https://github.com/leoasis/redux-immutable-state-invariant" rel="noreferrer">immutability dev checks</a>, <a href="https://github.com/elgerlambert/redux-localstorage/" rel="noreferrer">persistence</a>, etc, in mind. Not all of these will turn out to be useful, but it's nice to have access to a set of tools that can be easily combined to work together.</p> <h2>Simplicity</h2> <p>Redux preserves all the benefits of Flux (recording and replaying of actions, unidirectional data flow, dependent mutations) and adds new benefits (easy undo-redo, hot reloading) without introducing Dispatcher and store registration.</p> <p>Keeping it simple is important because it keeps you sane while you implement higher-level abstractions.</p> <p>Unlike most Flux libraries, Redux API surface is tiny. If you remove the developer warnings, comments, and sanity checks, it's <a href="https://gist.github.com/gaearon/ffd88b0e4f00b22c3159" rel="noreferrer">99 lines</a>. There is no tricky async code to debug.</p> <p>You can actually read it and understand all of Redux.</p> <hr> <p>See also <a href="https://stackoverflow.com/a/32916602/458193">my answer on downsides of using Redux compared to Flux</a>.</p>
{ "question_id": 32461229, "question_date": "2015-09-08T15:05:14.610Z", "question_score": 1124, "tags": "javascript|reactjs|reactjs-flux|flux|redux", "answer_id": 32920459, "answer_date": "2015-10-03T08:26:25.950Z", "answer_score": 1953 }
Please answer the following Stack Overflow question: Title: How do I import other Python files? <p>How do I import files in Python? I want to import:</p> <ol> <li>a file (e.g. <code>file.py</code>)</li> <li>a folder</li> <li>a file dynamically at runtime, based on user input</li> <li>one specific part of a file (e.g. a single function)</li> </ol>
<p><a href="https://docs.python.org/3/library/importlib.html#module-importlib" rel="noreferrer"><code>importlib</code></a> was added to Python 3 to programmatically import a module.</p> <pre class="lang-python prettyprint-override"><code>import importlib moduleName = input('Enter module name:') importlib.import_module(moduleName) </code></pre> <p>The .py extension should be removed from <code>moduleName</code>. The function also defines a <code>package</code> argument for relative imports.</p> <p>In python 2.x:</p> <ul> <li>Just <code>import file</code> without the .py extension</li> <li>A folder can be marked as a package, by adding an empty <code>__init__.py</code> file</li> <li>You can use the <code>__import__</code> function, which takes the module name (without extension) as a string extension</li> </ul> <pre class="lang-python prettyprint-override"><code>pmName = input('Enter module name:') pm = __import__(pmName) print(dir(pm)) </code></pre> <p>Type <code>help(__import__)</code> for more details.</p>
{ "question_id": 2349991, "question_date": "2010-02-28T03:40:11.193Z", "question_score": 1122, "tags": "python|python-import|python-module|python-packaging", "answer_id": 2349998, "answer_date": "2010-02-28T03:42:33.213Z", "answer_score": 529 }
Please answer the following Stack Overflow question: Title: Create Git branch with current changes <p>I started working on my <em>master</em> branch thinking that my task would be easy. After a while I realized it would take more work and I want to do all this work in a new branch. </p> <p>How can I create a new branch and take all these changes with me without dirtying <em>master</em>?</p>
<p>If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.<br /> Or, in one command: <strong><code>git checkout -b newBranch</code></strong></p> <p>With <a href="https://stackoverflow.com/a/57066202/6309">Git 2.23+</a> (Q3 2019), the <a href="https://git-scm.com/docs/git-switch" rel="noreferrer">new command <code>git switch</code></a> would create the branch in one line (with the same kind of <code>reset --hard</code>, so <strong>beware of its effect</strong>):</p> <pre><code># First, save your work in progress! git stash # Then, one command to create *and* switch to a new branch git switch -f -c topic/wip HEAD~3 </code></pre> <hr /> <p>Or, as suggested in <a href="https://stackoverflow.com/users/1264830/alia">Alia</a>'s <a href="https://stackoverflow.com/a/73200194/6309">answer</a>, use <a href="https://git-scm.com/docs/git-switch#Documentation/git-switch.txt--m" rel="noreferrer"><code>git switch -m</code></a>, <em>without</em> <code>git stash</code>:</p> <pre><code>git switch -c topic/wip -m </code></pre> <blockquote> <h2><code>--merge</code></h2> <p>If you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context.</p> <p>However, with this option, <strong>a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch</strong>.</p> <p>When a merge conflict happens, the index entries for conflicting paths are left unmerged, and you need to resolve the conflicts and mark the resolved paths with <code>git add</code> (or <code>git rm</code> if the merge should result in deletion of the path).</p> </blockquote> <hr /> <p>As mentioned in the <a href="http://git-scm.com/docs/git-reset#Documentation/git-reset.txt-Undoacommitmakingitatopicbranch" rel="noreferrer"><code>git reset</code> man page</a>:</p> <pre><code>$ git stash # (0) Save your work in progress $ git branch topic/wip # (1) $ git reset --hard HEAD~3 # (2) NOTE: use $git reset --soft HEAD~3 (explanation below) $ git checkout topic/wip # (3) </code></pre> <ol> <li>You have made some commits, but realize they were premature to be in the &quot;<code>master</code>&quot; branch. You want to continue polishing them in a topic branch, so create &quot;<code>topic/wip</code>&quot; branch off of the current <code>HEAD</code>.</li> <li>Rewind the <code>master</code> branch to get rid of those three commits.</li> <li>Switch to &quot;<code>topic/wip</code>&quot; branch and keep working.</li> </ol> <p>Again: new way (since 2019 and Git2.23) to do all that in one command:</p> <pre><code>git switch -f -c topic/wip HEAD~3 </code></pre> <hr /> <p>Note: due to the &quot;destructive&quot; effect of a <code>git reset --hard</code> command (it does resets the index and working tree. Any changes to tracked files in the working tree since <code>&lt;commit&gt;</code> are discarded), I would rather go with:</p> <pre><code>$ git reset --soft HEAD~3 # (2) </code></pre> <p>This would make sure I'm not losing any private file (not added to the index).<br /> The <code>--soft</code> option won't touch the index file nor the working tree at all (but resets the head to <code>&lt;commit&gt;</code>, just like all modes do).</p> <hr />
{ "question_id": 3899627, "question_date": "2010-10-10T08:44:12.917Z", "question_score": 1122, "tags": "git|git-branch", "answer_id": 3899660, "answer_date": "2010-10-10T08:52:37.047Z", "answer_score": 897 }
Please answer the following Stack Overflow question: Title: What is attr_accessor in Ruby? <p>I am having a hard time understanding <code>attr_accessor</code> in <strong>Ruby</strong>.<br> Can someone explain this to me?</p>
<p>Let's say you have a class <code>Person</code>.</p> <pre><code>class Person end person = Person.new person.name # =&gt; no method error </code></pre> <p>Obviously we never defined method <code>name</code>. Let's do that.</p> <pre><code>class Person def name @name # simply returning an instance variable @name end end person = Person.new person.name # =&gt; nil person.name = "Dennis" # =&gt; no method error </code></pre> <p>Aha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called <em>reader</em> and latter is called <em>writer</em>. We didn't create the writer yet so let's do that.</p> <pre><code>class Person def name @name end def name=(str) @name = str end end person = Person.new person.name = 'Dennis' person.name # =&gt; "Dennis" </code></pre> <p>Awesome. Now we can write and read instance variable <code>@name</code> using reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier.</p> <pre><code>class Person attr_reader :name attr_writer :name end </code></pre> <p>Even this can get repetitive. When you want both reader and writer just use accessor!</p> <pre><code>class Person attr_accessor :name end person = Person.new person.name = "Dennis" person.name # =&gt; "Dennis" </code></pre> <p>Works the same way! And guess what: the instance variable <code>@name</code> in our person object will be set just like when we did it manually, so you can use it in other methods.</p> <pre><code>class Person attr_accessor :name def greeting "Hello #{@name}" end end person = Person.new person.name = "Dennis" person.greeting # =&gt; "Hello Dennis" </code></pre> <p>That's it. In order to understand how <code>attr_reader</code>, <code>attr_writer</code>, and <code>attr_accessor</code> methods actually generate methods for you, read other answers, books, ruby docs. </p>
{ "question_id": 4370960, "question_date": "2010-12-06T21:07:06.037Z", "question_score": 1122, "tags": "ruby", "answer_id": 4371458, "answer_date": "2010-12-06T22:11:57.257Z", "answer_score": 2527 }
Please answer the following Stack Overflow question: Title: In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member? <p>When looking at the sourcecode for a tslint rule, I came across the following statement:</p> <pre><code>if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } </code></pre> <p>Notice the <code>!</code> operator after <code>node.parent</code>. Interesting!</p> <p>I first tried compiling the file locally with my currently installed version of TS (1.5.3). The resulting error pointed to the exact location of the bang:</p> <pre><code>$ tsc --noImplicitAny memberAccessRule.ts noPublicModifierRule.ts(57,24): error TS1005: ')' expected. </code></pre> <p>Next I upgraded to the latest TS (2.1.6), which compiled it without issue. So it seems to be feature of TS 2.x. <strong>But</strong> the transpilation ignored the bang completely, resulting in the following JS:</p> <pre><code>if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } </code></pre> <p>My Google fu has thus far failed me. </p> <p><strong><em>What is TS's exclamation mark operator, and how does it work?</em></strong></p>
<p>That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be <code>null</code> or <code>undefined</code> here, so don't complain about the possibility of it being <code>null</code> or <code>undefined</code>." Sometimes the type checker is unable to make that determination itself.</p> <p>It is explained <a href="https://github.com/Microsoft/TypeScript/wiki/What&#39;s-new-in-TypeScript#non-null-assertion-operator" rel="noreferrer">here</a>:</p> <blockquote> <p>A new <code>!</code> post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation <code>x!</code> produces a value of the type of <code>x</code> with <code>null</code> and <code>undefined</code> excluded. Similar to type assertions of the forms <code>&lt;T&gt;x</code> and <code>x as T</code>, the <code>!</code> non-null assertion operator is simply removed in the emitted JavaScript code.</p> </blockquote> <p>I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that <em>the developer is asserting it</em>, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.</p>
{ "question_id": 42273853, "question_date": "2017-02-16T12:22:26.833Z", "question_score": 1122, "tags": "typescript|tslint", "answer_id": 42274019, "answer_date": "2017-02-16T12:29:18.143Z", "answer_score": 1563 }
Please answer the following Stack Overflow question: Title: Is there a regular expression to detect a valid regular expression? <p>Is it possible to detect a valid regular expression with another regular expression? If so please give example code below.</p>
<pre><code>/ ^ # start of string ( # first group start (?: (?:[^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!]|\?&lt;[=!]|\?&gt;)? (?1)?? \) # parenthesis, with recursive content | \(\? (?:R|[+-]?\d+) \) # recursive matching ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content ) # end first group $ # end of string / </code></pre> <p>This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it.</p> <p>Without whitespace and comments:</p> <pre><code>/^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?&lt;[=!]|\?&gt;)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/ </code></pre> <hr> <p>.NET does not support recursion directly. (The <code>(?1)</code> and <code>(?R)</code> constructs.) The recursion would have to be converted to counting balanced groups:</p> <pre><code>^ # start of string (?: (?: [^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!] | \?&lt;[=!] | \?&gt; | \?&lt;[^\W\d]\w*&gt; | \?'[^\W\d]\w*' )? # opening of group (?&lt;N&gt;) # increment counter | \) # closing of group (?&lt;-N&gt;) # decrement counter ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content $ # end of string (?(N)(?!)) # fail if counter is non-zero. </code></pre> <p>Compacted:</p> <pre><code>^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?&lt;[=!]|\?&gt;|\?&lt;[^\W\d]\w*&gt;|\?'[^\W\d]\w*')?(?&lt;N&gt;)|\)(?&lt;-N&gt;))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!)) </code></pre> <p>From the comments:</p> <blockquote> <p>Will this validate substitutions and translations?</p> </blockquote> <p>It will validate just the regex part of substitutions and translations. <code>s/&lt;this part&gt;/.../</code></p> <blockquote> <p>It is not theoretically possible to match all valid regex grammars with a regex. </p> </blockquote> <p>It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more.</p> <blockquote> <p>Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes.</p> </blockquote> <p>"In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions.</p> <blockquote> <p>using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions</p> </blockquote> <p>This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor.</p> <blockquote> <p>Regex itself "is not a regular language and hence cannot be parsed by regular expression..."</p> </blockquote> <p>This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task.</p> <blockquote> <p>I see where you're matching <code>[]()/\</code>. and other special regex characters. Where are you allowing non-special characters? It seems like this will match <code>^(?:[\.]+)$</code>, but not <code>^abcdefg$</code>. That's a valid regex.</p> </blockquote> <p><code>[^?+*{}()[\]\\|]</code> will match any single character, not part of any of the other constructs. This includes both literal (<code>a</code> - <code>z</code>), and certain special characters (<code>^</code>, <code>$</code>, <code>.</code>).</p>
{ "question_id": 172303, "question_date": "2008-10-05T17:07:35.227Z", "question_score": 1122, "tags": "regex", "answer_id": 172316, "answer_date": "2008-10-05T17:15:56.067Z", "answer_score": 1052 }
Please answer the following Stack Overflow question: Title: Format number to always show 2 decimal places <p>I would like to format my numbers to always display 2 decimal places, rounding where applicable.</p> <p>Examples:</p> <pre><code>number display ------ ------- 1 1.00 1.341 1.34 1.345 1.35 </code></pre> <p>I have been using this: </p> <pre><code>parseFloat(num).toFixed(2); </code></pre> <p>But it's displaying <code>1</code> as <code>1</code>, rather than <code>1.00</code>.</p>
<pre><code>(Math.round(num * 100) / 100).toFixed(2); </code></pre> <p><strong>Live Demo</strong></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var num1 = "1"; document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2); var num2 = "1.341"; document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2); var num3 = "1.345"; document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>span { border: 1px solid #000; margin: 5px; padding: 5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;span id="num1"&gt;&lt;/span&gt; &lt;span id="num2"&gt;&lt;/span&gt; &lt;span id="num3"&gt;&lt;/span&gt;</code></pre> </div> </div> </p> <p>Note that it will <strong>round</strong> to 2 decimal places, so the input <code>1.346</code> will return <code>1.35</code>.</p>
{ "question_id": 6134039, "question_date": "2011-05-26T05:22:51.133Z", "question_score": 1121, "tags": "javascript|floating-point|number-formatting", "answer_id": 6134070, "answer_date": "2011-05-26T05:27:34.700Z", "answer_score": 1565 }
Please answer the following Stack Overflow question: Title: Get property value from string using reflection <p>I am trying implement the <a href="http://geekswithblogs.net/shahed/archive/2008/07/24/123998.aspx" rel="noreferrer">Data transformation using Reflection</a><sup>1</sup> example in my code.</p> <p>The <code>GetSourceValue</code> function has a switch comparing various types, but I want to remove these types and properties and have <code>GetSourceValue</code> get the value of the property using only a single string as the parameter. I want to pass a class and property in the string and resolve the value of the property.</p> <p>Is this possible?</p> <p><sup>1</sup> <sub><a href="https://web.archive.org/web/20130815002453/http://msmvps.com/blogs/shahed/archive/2008/07/24/c-reflection-tips-data-transformation-using-reflection.aspx" rel="noreferrer">Web Archive version of original blog post</a></sub></p>
<pre><code> public static object GetPropValue(object src, string propName) { return src.GetType().GetProperty(propName).GetValue(src, null); } </code></pre> <p>Of course, you will want to add validation and whatnot, but that is the gist of it.</p>
{ "question_id": 1196991, "question_date": "2009-07-28T21:58:51.230Z", "question_score": 1121, "tags": "c#|reflection|properties", "answer_id": 1197004, "answer_date": "2009-07-28T22:02:05.437Z", "answer_score": 2152 }
Please answer the following Stack Overflow question: Title: How to make links in a TextView clickable <p>I have the following TextView defined:</p> <pre><code>&lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/txtCredits&quot; android:autoLink=&quot;web&quot; android:id=&quot;@+id/infoTxtCredits&quot; android:layout_centerInParent=&quot;true&quot; android:linksClickable=&quot;true&quot;/&gt; </code></pre> <p>where <code>@string/txtCredits</code> is a string resource that contains <code>&lt;a href=&quot;some site&quot;&gt;Link text&lt;/a&gt;</code>.</p> <p>Android is highlighting the links in the TextView, but they do not respond to clicks. What am I doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?</p> <p>It looks like it has to do with the way I define my string resource.</p> <p>This does not work:</p> <pre><code>&lt;string name=&quot;txtCredits&quot;&gt;&lt;a href=&quot;http://www.google.com&quot;&gt;Google&lt;/a&gt;&lt;/string&gt; </code></pre> <p>But this does:</p> <pre><code>&lt;string name=&quot;txtCredits&quot;&gt;www.google.com&lt;/string&gt; </code></pre> <p>Which is a bummer because I would much rather show a text link than show the full URL.</p>
<p>Buried in the API demos, I found the solution to my problem:</p> <p>File <em>Link.java</em>:</p> <pre><code> // text2 has links specified by putting &lt;a&gt; tags in the string // resource. By default these links will appear but not // respond to user input. To make them active, you need to // call setMovementMethod() on the TextView object. TextView t2 = (TextView) findViewById(R.id.text2); t2.setMovementMethod(LinkMovementMethod.getInstance()); </code></pre> <p>I removed most of the attributes on my TextView to match what was in the demo.</p> <pre><code>&lt;TextView android:id=&quot;@+id/text2&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;@string/txtCredits&quot;/&gt; </code></pre> <p>That solved it. It is pretty difficult to uncover and fix.</p> <p><strong>Important</strong>: Don't forget to remove <code>autoLink=&quot;web&quot;</code> if you are calling <code>setMovementMethod()</code>.</p>
{ "question_id": 2734270, "question_date": "2010-04-29T01:41:54.693Z", "question_score": 1121, "tags": "android|hyperlink|textview|clickable", "answer_id": 2746708, "answer_date": "2010-04-30T18:18:12.503Z", "answer_score": 1325 }
Please answer the following Stack Overflow question: Title: LINQ query on a DataTable <p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p> <pre><code>var results = from myRow in myDataTable where results.Field("RowNo") == 1 select results; </code></pre> <p>This is not allowed. How do I get something like this working?</p> <p>I'm amazed that LINQ queries are not allowed on DataTables!</p>
<p>You can't query against the <code>DataTable</code>'s <em>Rows</em> collection, since <code>DataRowCollection</code> doesn't implement <code>IEnumerable&lt;T&gt;</code>. You need to use the <code>AsEnumerable()</code> extension for <code>DataTable</code>. Like so:</p> <pre><code>var results = from myRow in myDataTable.AsEnumerable() where myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1 select myRow; </code></pre> <p>And as <a href="https://stackoverflow.com/a/10893/5519709">@Keith</a> says, you'll need to add a reference to <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx" rel="noreferrer">System.Data.DataSetExtensions</a></p> <p><code>AsEnumerable()</code> returns <code>IEnumerable&lt;DataRow&gt;</code>. If you need to convert <code>IEnumerable&lt;DataRow&gt;</code> to a <code>DataTable</code>, use the <code>CopyToDataTable()</code> extension.</p> <p>Below is query with Lambda Expression,</p> <pre><code>var result = myDataTable .AsEnumerable() .Where(myRow =&gt; myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1); </code></pre>
{ "question_id": 10855, "question_date": "2008-08-14T10:08:27.123Z", "question_score": 1120, "tags": "c#|.net|linq|datatable|.net-3.5", "answer_id": 11593, "answer_date": "2008-08-14T19:45:01.383Z", "answer_score": 1379 }
Please answer the following Stack Overflow question: Title: How do I use $scope.$watch and $scope.$apply in AngularJS? <p>I don't understand how to use <code>$scope.$watch</code> and <code>$scope.$apply</code>. The official documentation isn't helpful.</p> <p>What I don't understand specifically:</p> <ul> <li>Are they connected to the DOM?</li> <li>How can I update DOM changes to the model?</li> <li>What is the connection point between them?</li> </ul> <p>I tried <a href="http://css.dzone.com/articles/drag-and-drop-angularjs-using" rel="noreferrer">this tutorial</a>, but it takes the understanding of <code>$watch</code> and <code>$apply</code> for granted.</p> <p>What do <code>$apply</code> and <code>$watch</code> do, and how do I use them appropriately?</p>
<p>You need to be aware about how AngularJS works in order to understand it.</p> <h2>Digest cycle and $scope</h2> <p>First and foremost, AngularJS defines a concept of a so-called <strong>digest cycle</strong>. This cycle can be considered as a loop, during which AngularJS checks if there are any changes to all the variables <strong>watched</strong> by all the <code>$scope</code>s. So if you have <code>$scope.myVar</code> defined in your controller and this variable was <strong>marked for being watched</strong>, then you are implicitly telling AngularJS to monitor the changes on <code>myVar</code> in each iteration of the loop.</p> <p>A natural follow-up question would be: Is everything attached to <code>$scope</code> being watched? Fortunately, no. If you would watch for changes to every object in your <code>$scope</code>, then quickly a digest loop would take ages to evaluate and you would quickly run into performance issues. That is why the AngularJS team gave us two ways of declaring some <code>$scope</code> variable as being watched (read below).</p> <h2>$watch helps to listen for $scope changes</h2> <p>There are two ways of declaring a <code>$scope</code> variable as being watched.</p> <ol> <li>By using it in your template via the expression <code>&lt;span&gt;{{myVar}}&lt;/span&gt;</code></li> <li>By adding it manually via the <code>$watch</code> service</li> </ol> <p>Ad 1) This is the most common scenario and I'm sure you've seen it before, but you didn't know that this has created a watch in the background. Yes, it had! Using AngularJS directives (such as <code>ng-repeat</code>) can also create implicit watches.</p> <p>Ad 2) This is how you create your own <strong>watches</strong>. <code>$watch</code> service helps you to run some code when some value attached to the <code>$scope</code> has changed. It is rarely used, but sometimes is helpful. For instance, if you want to run some code each time 'myVar' changes, you could do the following:</p> <pre><code>function MyController($scope) { $scope.myVar = 1; $scope.$watch('myVar', function() { alert('hey, myVar has changed!'); }); $scope.buttonClicked = function() { $scope.myVar = 2; // This will trigger $watch expression to kick in }; } </code></pre> <h2>$apply enables to integrate changes with the digest cycle</h2> <p>You can think of the <strong><code>$apply</code> function as of an integration mechanism</strong>. You see, each time you change some <strong>watched variable attached to the <code>$scope</code></strong> object directly, AngularJS will know that the change has happened. This is because AngularJS already knew to monitor those changes. So if it happens in code managed by the framework, the digest cycle will carry on.</p> <p>However, sometimes you want to <strong>change some value outside of the AngularJS world</strong> and see the changes propagate normally. Consider this - you have a <code>$scope.myVar</code> value which will be modified within a jQuery's <code>$.ajax()</code> handler. This will happen at some point in future. AngularJS can't wait for this to happen, since it hasn't been instructed to wait on jQuery.</p> <p>To tackle this, <code>$apply</code> has been introduced. It lets you start the digestion cycle explicitly. However, you should only use this to migrate some data to AngularJS (integration with other frameworks), but never use this method combined with regular AngularJS code, as AngularJS will throw an error then.</p> <h2>How is all of this related to the DOM?</h2> <p>Well, you should really follow the tutorial again, now that you know all this. The digest cycle will make sure that the UI and the JavaScript code stay synchronised, by evaluating every watcher attached to all <code>$scope</code>s as long as nothing changes. If no more changes happen in the digest loop, then it's considered to be finished.</p> <p>You can attach objects to the <code>$scope</code> object either explicitly in the Controller, or by declaring them in <code>{{expression}}</code> form directly in the view.</p> <p>Further readings:</p> <ul> <li><em><a href="http://teropa.info/blog/2013/11/03/make-your-own-angular-part-1-scopes-and-digest.html" rel="noreferrer">Make Your Own AngularJS, Part 1: Scopes And Digest</a></em></li> </ul>
{ "question_id": 15112584, "question_date": "2013-02-27T12:50:07.783Z", "question_score": 1120, "tags": "angularjs|angularjs-scope", "answer_id": 15113029, "answer_date": "2013-02-27T13:14:33.173Z", "answer_score": 1782 }
Please answer the following Stack Overflow question: Title: Node.js + Nginx - What now? <p>I've set up Node.js and Nginx on my server. Now I want to use it, but, before I start there are 2 questions:</p> <ol> <li>How should they work together? How should I handle the requests?</li> <li><p>There are 2 concepts for a Node.js server, which one is better: </p> <p>a. Create a separate HTTP server for each website that needs it. Then load all JavaScript code at the start of the program, so the code is interpreted once.</p> <p>b. Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.</p></li> </ol> <p>It's not clear for me how to use Node.js correctly.</p>
<p>Nginx works as a front end server, which in this case proxies the requests to a node.js server. Therefore you need to setup an Nginx config file for node.</p> <p>This is what I have done in my Ubuntu box:</p> <p>Create the file <code>yourdomain.example</code> at <code>/etc/nginx/sites-available/</code>:</p> <pre><code>vim /etc/nginx/sites-available/yourdomain.example </code></pre> <p>In it you should have something like:</p> <pre><code># the IP(s) on which your node server is running. I chose port 3000. upstream app_yourdomain { server 127.0.0.1:3000; keepalive 8; } # the nginx server instance server { listen 80; listen [::]:80; server_name yourdomain.example www.yourdomain.example; access_log /var/log/nginx/yourdomain.example.log; # pass the request to the node.js server with the correct headers # and much more can be added, see nginx config options location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://app_yourdomain/; proxy_redirect off; } } </code></pre> <p>If you want Nginx (&gt;= 1.3.13) to handle websocket requests as well, add the following lines in the <code>location /</code> section:</p> <pre><code>proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection &quot;upgrade&quot;; </code></pre> <p>Once you have this setup you must enable the site defined in the config file above:</p> <pre><code>cd /etc/nginx/sites-enabled/ ln -s /etc/nginx/sites-available/yourdomain.example yourdomain.example </code></pre> <p>Create your node server app at <code>/var/www/yourdomain/app.js</code> and run it at <code>localhost:3000</code></p> <pre><code>var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(3000, &quot;127.0.0.1&quot;); console.log('Server running at http://127.0.0.1:3000/'); </code></pre> <p>Test for syntax mistakes:</p> <pre><code>nginx -t </code></pre> <p>Restart Nginx:</p> <pre><code>sudo /etc/init.d/nginx restart </code></pre> <p>Lastly start the node server:</p> <pre><code>cd /var/www/yourdomain/ &amp;&amp; node app.js </code></pre> <p>Now you should see &quot;Hello World&quot; at <code>yourdomain.example</code></p> <p>One last note with to starting the node server: you should use some kind of monitoring system for the node daemon. There is an awesome <a href="http://howtonode.org/deploying-node-upstart-monit" rel="noreferrer">tutorial on node with upstart and monit</a>.</p>
{ "question_id": 5009324, "question_date": "2011-02-15T20:49:02.220Z", "question_score": 1120, "tags": "node.js|nginx|concept", "answer_id": 5015178, "answer_date": "2011-02-16T10:20:53.867Z", "answer_score": 1411 }
Please answer the following Stack Overflow question: Title: What's the difference between OpenID and OAuth? <p>I'm really trying to understand the difference between OpenID and OAuth? Maybe they're two totally separate things?</p>
<p><a href="http://openid.net/" rel="noreferrer">OpenID</a> is about authentication (ie. proving who you are), <a href="http://oauth.net/" rel="noreferrer">OAuth</a> is about authorisation (ie. to grant access to functionality/data/etc.. without having to deal with the original authentication).</p> <p>OAuth could be used in external partner sites to allow access to protected data without them having to re-authenticate a user.</p> <p>The blog post "<a href="http://cakebaker.42dh.com/2008/04/01/openid-versus-oauth-from-the-users-perspective/" rel="noreferrer">OpenID versus OAuth from the user’s perspective</a>" has a simple comparison of the two from the user's perspective and "<a href="http://softwareas.com/oauth-openid-youre-barking-up-the-wrong-tree-if-you-think-theyre-the-same-thing" rel="noreferrer">OAuth-OpenID: You’re Barking Up the Wrong Tree if you Think They’re the Same Thing</a>" has more information about it.</p>
{ "question_id": 1087031, "question_date": "2009-07-06T13:40:02.550Z", "question_score": 1118, "tags": "authentication|oauth|openid-connect|openid", "answer_id": 1087071, "answer_date": "2009-07-06T13:47:07.407Z", "answer_score": 929 }